The personal finance app for everyone (by everyone)
Ruby
Consolidate repository instructions after auditing their history (#3409)
Juan José Mata157daf517692
diff --git a/.cursor/rules/api-endpoint-consistency.mdc b/.cursor/rules/api-endpoint-consistency.mdcindex 75bd06f20a..eaabf80b3b 100644--- a/.cursor/rules/api-endpoint-consistency.mdc+++ b/.cursor/rules/api-endpoint-consistency.mdc@@ -4,43 +4,4 @@ globs: app/controllers/api/v1/**/*.rb, spec/requests/api/v1/**/*.rb, test/controalwaysApply: false----# API endpoint consistency (post-commit checklist)--When adding or modifying API v1 endpoints, ensure the following so behavior, docs, and auth stay consistent.--## 1. Minitest behavioral coverage--- **Location**: `test/controllers/api/v1/{resource}_controller_test.rb`-- **Scope**: All new or changed actions must have Minitest coverage here. Do not rely on rswag specs for behavioral assertions.-- **Pattern**:- - Use `ApiKey.create!` (read and read_write scopes) and `api_headers(api_key)` → `{ "X-Api-Key" => api_key.display_key }`. Do not use OAuth/Bearer in these tests.- - Cover: index/show (and create/update/destroy for write endpoints), read-only key blocking writes (403), invalid params (422), invalid date (422), not found (404), missing auth (401).- - Follow existing API v1 test style: see [valuations_controller_test.rb](mdc:test/controllers/api/v1/valuations_controller_test.rb) and [transactions_controller_test.rb](mdc:test/controllers/api/v1/transactions_controller_test.rb).--## 2. rswag is docs-only--- **Location**: `spec/requests/api/v1/{resource}_spec.rb`-- **Rule**: These specs exist only for OpenAPI generation. Do not add `expect(...)` or `assert_*` (or any behavioral assertions). Use `run_test!` without custom assertion blocks so the spec only documents request/response and regenerates `docs/api/openapi.yaml`.-- **Regenerate**: After edits, run `RAILS_ENV=test bundle exec rake rswag:specs:swaggerize`.--## 3. Same API key auth in all rswag specs--- **Rule**: Every request spec in `spec/requests/api/v1/` must use the same API key auth pattern so generated docs are consistent.-- **Pattern** (match holdings_spec, trades_spec, transactions_spec, etc.):-- ```ruby- let(:api_key) do- key = ApiKey.generate_secure_key- ApiKey.create!(- user: user,- name: 'API Docs Key',- key: key,- scopes: %w[read_write],- source: 'web'- )- end-- let(:'X-Api-Key') { api_key.plain_key }- ```--- Do not use Doorkeeper/OAuth in these specs (no `Doorkeeper::Application`, `Doorkeeper::AccessToken`, or `Authorization: "Bearer ..."`). Use API key only. Note: [valuations_spec.rb](mdc:spec/requests/api/v1/valuations_spec.rb) currently uses OAuth; update it to the API key pattern above when editing that file.+@docs/llm-guides/api-endpoint-consistency.mddiff --git a/.cursor/rules/cursor_rules.mdc b/.cursor/rules/cursor_rules.mdcdeleted file mode 100644index 506d7d326b..0000000000--- a/.cursor/rules/cursor_rules.mdc+++ /dev/null@@ -1,54 +0,0 @@-----description: Guidelines for creating and maintaining Cursor rules to ensure consistency and effectiveness.-globs: .cursor/rules/*.mdc-alwaysApply: true------- **Required Rule Structure:**- ```markdown- ---- description: Clear, one-line description of what the rule enforces- globs: path/to/files/*.ext, other/path/**/*- alwaysApply: boolean- ----- - **Main Points in Bold**- - Sub-points with details- - Examples and explanations- ```--- **File References:**- - Use `[filename](mdc:path/to/file)` ([filename](mdc:filename)) to reference files- - Example: [prisma.mdc](mdc:.cursor/rules/prisma.mdc) for rule references- - Example: [schema.prisma](mdc:prisma/schema.prisma) for code references--- **Code Examples:**- - Use language-specific code blocks- ```typescript- // ✅ DO: Show good examples- const goodExample = true;-- // ❌ DON'T: Show anti-patterns- const badExample = false;- ```--- **Rule Content Guidelines:**- - Start with high-level overview- - Include specific, actionable requirements- - Show examples of correct implementation- - Reference existing code when possible- - Keep rules DRY by referencing other rules--- **Rule Maintenance:**- - Update rules when new patterns emerge- - Add examples from actual codebase- - Remove outdated patterns- - Cross-reference related rules--- **Best Practices:**- - Use bullet points for clarity- - Keep descriptions concise- - Include both DO and DON'T examples- - Reference actual code over theoretical examples- - Use consistent formatting across rules-diff --git a/.cursor/rules/general-rules.mdc b/.cursor/rules/general-rules.mdcindex f9f0537598..440a12f286 100644--- a/.cursor/rules/general-rules.mdc+++ b/.cursor/rules/general-rules.mdc@@ -3,19 +3,5 @@ description: Miscellaneous rules to get the AI to behaveglobs: *alwaysApply: true----# General rules for AI-- Use `Current.user` for the current user. Do NOT use `current_user`.-- Use `Current.family` for the current family. Do NOT use `current_family`.-- Prior to generating any code, carefully read the project conventions and guidelines- - Read [project-design.mdc](mdc:.cursor/rules/project-design.mdc) to understand the codebase- - Read [project-conventions.mdc](mdc:.cursor/rules/project-conventions.mdc) to understand _how_ to write code for the codebase- - Read [ui-ux-design-guidelines.mdc](mdc:.cursor/rules/ui-ux-design-guidelines.mdc) to understand how to implement frontend code specifically-- ActiveRecord migrations must inherit from `ActiveRecord::Migration[7.2]`. Do **not** use version 8.0 yet.--## Prohibited actions--- Do not run `rails server` in your responses.-- Do not run `touch tmp/restart.txt`-- Do not run `rails credentials`-- Do not automatically run migrations\ No newline at end of filediff --git a/.cursor/rules/project-conventions.mdc b/.cursor/rules/project-conventions.mdcdeleted file mode 100644index 46d54ed423..0000000000--- a/.cursor/rules/project-conventions.mdc+++ /dev/null@@ -1,73 +0,0 @@-----description:-globs:-alwaysApply: true-----This rule serves as high-level documentation for how you should write code in this codebase.--## Project Tech Stack--- Web framework: Ruby on Rails- - Minitest + fixtures for testing- - Propshaft for asset pipeline- - Hotwire Turbo/Stimulus for SPA-like UI/UX- - TailwindCSS for styles- - Lucide Icons for icons- - OpenAI for AI chat-- Database: PostgreSQL-- Jobs: Sidekiq + Redis-- External- - Payments: Stripe- - User bank data syncing: Plaid--## Project conventions--These conventions should be used when writing code for the project.--### Convention 1: Minimize dependencies, vanilla Rails is plenty--Dependencies are a natural part of building software, but we aim to minimize them when possible to keep this open-source codebase easy to understand, maintain, and contribute to.--- Push Rails to its limits before adding new dependencies-- When a new dependency is added, there must be a strong technical or business reason to add it-- When adding dependencies, you should favor old and reliable over new and flashy--### Convention 2: Leverage POROs and concerns over "service objects"--This codebase adopts a "skinny controller, fat models" convention. Furthermore, we put almost _everything_ directly in the `app/models/` folder and avoid separate folders for business logic such as `app/services/`.--- Organize large pieces of business logic into Rails concerns and POROs (Plain ole' Ruby Objects)-- While a Rails concern _may_ offer shared functionality (i.e. "duck types"), it can also be a "one-off" concern that is only included in one place for better organization and readability.-- When concerns are used for code organization, they should be organized around the "traits" of a model; not for simply moving code to another spot in the codebase.-- When possible, models should answer questions about themselves—for example, we might have a method, `account.balance_series` that returns a time-series of the account's most recent balances. We prefer this over something more service-like such as `AccountSeries.new(account).call`.--### Convention 3: Leverage Hotwire, write semantic HTML, CSS, and JS, prefer server-side solutions--- Native HTML is always preferred over JS-based components- - Example 1: Use `<dialog>` element for modals instead of creating a custom component- - Example 2: Use `<details><summary>...</summary></details>` for disclosures rather than custom components-- Leverage Turbo frames to break up the page over JS-driven client-side solutions- - Example 1: A good example of turbo frame usage is in [application.html.erb](mdc:app/views/layouts/application.html.erb) where we load [chats_controller.rb](mdc:app/controllers/chats_controller.rb) actions in a turbo frame in the global layout-- Leverage query params in the URL for state over local storage and sessions. If absolutely necessary, utilize the DB for persistent state.-- Use Turbo streams to enhance functionality, but do not solely depend on it-- Format currencies, numbers, dates, and other values server-side, then pass to Stimulus controllers for display only-- Keep client-side code for where it truly shines. For example, @bulk_select_controller.js is a case where server-side solutions would degrade the user experience significantly. When bulk-selecting entries, client-side solutions are the way to go and Stimulus provides the right toolset to achieve this.-- Always use the `icon` helper in [application_helper.rb](mdc:app/helpers/application_helper.rb) for icons. NEVER use `lucide_icon` helper directly.--The Hotwire suite (Turbo/Stimulus) works very well with these native elements and we optimize for this.--### Convention 4: Optimize for simplicitly and clarity--All code should maximize readability and simplicity.--- Prioritize good OOP domain design over performance-- Only focus on performance for critical and global areas of the codebase; otherwise, don't sweat the small stuff.- - Example 1: be mindful of loading large data payloads in global layouts- - Example 2: Avoid N+1 queries--### Convention 5: Use ActiveRecord for complex validations, DB for simple ones, keep business logic out of DB--- Enforce `null` checks, unique indexes, and other simple validations in the DB-- ActiveRecord validations _may_ mirror the DB level ones, but not 100% necessary. These are for convenience when error handling in forms. Always prefer client-side form validation when possible.-- Complex validations and business logic should remain in ActiveRecord-diff --git a/.cursor/rules/project-design.mdc b/.cursor/rules/project-design.mdcindex 0b87e0a4fe..b1bcc3a19e 100644--- a/.cursor/rules/project-design.mdc+++ b/.cursor/rules/project-design.mdc@@ -4,237 +4,4 @@ globs: *alwaysApply: true----This file outlines how the codebase is structured and how data flows through the app.--This is a personal finance application built in Ruby on Rails. The primary domain entities for this app are outlined below. For an authoritative overview of the relationships, [schema.rb](mdc:db/schema.rb) is the source of truth.--## App Modes--The codebase runs in two distinct "modes", dictated by `Rails.application.config.app_mode`, which can be `managed` or `self_hosted`.--- "Managed" - in managed mode, a team operates and manages servers for users-- "Self Hosted" - in self hosted mode, users host the codebase on their own infrastructure, typically through Docker Compose. We have an example [docker-compose.example.yml](mdc:docker-compose.example.yml) file that runs [Dockerfile](mdc:Dockerfile) for this mode.--## Families and Users--- `Family` - all Stripe subscriptions, financial accounts, and the majority of preferences are stored at the [family.rb](mdc:app/models/family.rb) level.-- `User` - all [session.rb](mdc:app/models/session.rb) happen at the [user.rb](mdc:app/models/user.rb) level. A user belongs to a `Family` and can either be an `admin` or a `member`. Typically, a `Family` has a single admin, or "head of household" that manages finances while there will be several `member` users who can see the family's finances from varying perspectives.--## Currency Preference--Each `Family` selects a currency preference. This becomes the "main" currency in which all records are "normalized" to via [exchange_rate.rb](mdc:app/models/exchange_rate.rb) records so that the app can calculate metrics, historical graphs, and other insights in a single family currency.--## Accounts--The center of the app's domain is the [account.rb](mdc:app/models/account.rb). This represents a single financial account that has a `balance` and `currency`. For example, an `Account` could be "Chase Checking", which is a single financial account at Chase Bank. A user could have multiple accounts at a single institution (i.e. "Chase Checking", "Chase Credit Card", "Chase Savings") or an account could be a standalone account, such as "My Home" (a primary residence).--### Accountables--In the app, [account.rb](mdc:app/models/account.rb) is a Rails "delegated type" with the following subtypes (separate DB tables). Each account has a `classification` or either `asset` or `liability`. While the types are a flat hierarchy, below, they have been organized by their classification:--- Asset accountables- - [depository.rb](mdc:app/models/depository.rb) - a typical "bank account" such as a savings or checking account- - [investment.rb](mdc:app/models/investment.rb) - an account that has "holdings" such as a brokerage, 401k, etc.- - [crypto.rb](mdc:app/models/crypto.rb) - an account that tracks the value of one or more crypto holdings- - [property.rb](mdc:app/models/property.rb) - an account that tracks the value of a physical property such as a house or rental property- - [vehicle.rb](mdc:app/models/vehicle.rb) - an account that tracks the value of a vehicle- - [other_asset.rb](mdc:app/models/other_asset.rb) - an asset that cannot be classified by the other account types. For example, "jewelry".-- Liability accountables- - [credit_card.rb](mdc:app/models/credit_card.rb) - an account that tracks the debt owed on a credit card- - [loan.rb](mdc:app/models/loan.rb) - an account that tracks the debt owed on a loan (i.e. mortgage, student loan)- - [other_liability.rb](mdc:app/models/other_liability.rb) - a liability that cannot be classified by the other account types. For example, "IOU to a friend"--### Account Balances--An account [balance.rb](mdc:app/models/account/balance.rb) represents a single balance value for an account on a specific `date`. A series of balance records is generated daily for each account and is how we show a user's historical balance graph.--- For simple accounts like a "Checking Account", the balance represents the amount of cash in the account for a date.-- For a more complex account like "Investment Brokerage", the `balance` represents the combination of the "cash balance" + "holdings value". Each accountable type has different components that make up the "balance", but in all cases, the "balance" represents "How much the account is worth" (when `classification` is `asset`) or "How much is owed on the account" (when `classification` is `liability`)--All balances are calculated daily by [balance_calculator.rb](mdc:app/models/account/balance_calculator.rb).--### Account Holdings--An account [holding.rb](mdc:app/models/holding.rb) applies to [investment.rb](mdc:app/models/investment.rb) type accounts and represents a `qty` of a certain [security.rb](mdc:app/models/security.rb) at a specific `price` on a specific `date`.--For investment accounts with holdings, [base_calculator.rb](mdc:app/models/holding/base_calculator.rb) is used to calculate the daily historical holding quantities and prices, which are then rolled up into a final "Balance" for the account in [base_calculator.rb](mdc:app/models/account/balance/base_calculator.rb).--### Account Entries--An account [entry.rb](mdc:app/models/entry.rb) is also a Rails "delegated type". `Entry` represents any record that _modifies_ an `Account` [balance.rb](mdc:app/models/account/balance.rb) and/or [holding.rb](mdc:app/models/holding.rb). Therefore, every entry must have a `date`, `amount`, and `currency`.--The `amount` of an [entry.rb](mdc:app/models/entry.rb) is a signed value. A _negative_ amount is an "inflow" of money to that account. A _positive_ value is an "outflow" of money from that account. For example:--- A negative amount for a credit card account represents a "payment" to that account, which _reduces_ its balance (since it is a `liability`)-- A negative amount for a checking account represents an "income" to that account, which _increases_ its balance (since it is an `asset`)-- A negative amount for an investment/brokerage trade represents a "sell" transaction, which _increases_ the cash balance of the account--There are 3 entry types, defined as [entryable.rb](mdc:app/models/entryable.rb) records:--- `Valuation` - an account [valuation.rb](mdc:app/models/valuation.rb) is an entry that says, "here is the value of this account on this date". It is an absolute measure of an account value / debt. If there is an `Valuation` of 5,000 for today's date, that means that the account balance will be 5,000 today.-- `Transaction` - an account [transaction.rb](mdc:app/models/transaction.rb) is an entry that alters the account balance by the `amount`. This is the most common type of entry and can be thought of as an "income" or "expense".-- `Trade` - an account [trade.rb](mdc:app/models/trade.rb) is an entry that only applies to an investment account. This represents a "buy" or "sell" of a holding and has a `qty` and `price`.--### Account Transfers--A [transfer.rb](mdc:app/models/transfer.rb) represents a movement of money between two accounts. A transfer has an inflow [transaction.rb](mdc:app/models/transaction.rb) and an outflow [transaction.rb](mdc:app/models/transaction.rb). The codebase auto-matches transfers based on the following criteria:--- Must be from different accounts-- Must be within 4 days of each other-- Must be the same currency-- Must be opposite values--There are two primary forms of a transfer:--- Regular transfer - a normal movement of money between two accounts. For example, "Transfer $500 from Checking account to Brokerage account".-- Debt payment - a special form of transfer where the _receiver_ of funds is a [loan.rb](mdc:app/models/loan.rb) type account.--Regular transfers are typically _excluded_ from income and expense calculations while a debt payment is considered an "expense".--## Plaid Items--A [plaid_item.rb](mdc:app/models/plaid_item.rb) represents a "connection" maintained by our external data provider, Plaid in the "hosted" mode of the app. An "Item" has 1 or more [plaid_account.rb](mdc:app/models/plaid_account.rb) records, which are each associated 1:1 with an internal app [account.rb](mdc:app/models/account.rb).--All relevant metadata about the item and its underlying accounts are stored on [plaid_item.rb](mdc:app/models/plaid_item.rb) and [plaid_account.rb](mdc:app/models/plaid_account.rb), while the "normalized" data is then stored on internal app domain models.--## "Syncs"--The codebase has the concept of a [syncable.rb](mdc:app/models/concerns/syncable.rb), which represents any model which can have its data "synced" in the background. "Syncables" include:--- `Account` - an account "sync" will sync account holdings, balances, and enhance transaction metadata-- `PlaidItem` - a Plaid Item "sync" fetches data from Plaid APIs, normalizes that data, stores it on internal app models, and then finally performs an "Account sync" for each of the underlying accounts created from the Plaid Item.-- `Family` - a Family "sync" loops through the family's Plaid Items and individual Accounts and "syncs" each of them. A family is synced once per day, automatically through [auto_sync.rb](mdc:app/controllers/concerns/auto_sync.rb).--Each "sync" creates a [sync.rb](mdc:app/models/sync.rb) record in the database, which keeps track of the status of the sync, any errors that it encounters, and acts as an "audit table" for synced data.--Below are brief descriptions of each type of sync in more detail.--### Account Syncs--The most important type of sync is the account sync. It is orchestrated by the account's `sync_data` method, which performs a few important tasks:--- Auto-matches transfer records for the account-- Calculates daily [balance.rb](mdc:app/models/account/balance.rb) records for the account from `account.start_date` to `Date.current` using [base_calculator.rb](mdc:app/models/account/balance/base_calculator.rb)- - Balances are dependent on the calculation of [holding.rb](mdc:app/models/holding.rb), which uses [base_calculator.rb](mdc:app/models/account/holding/base_calculator.rb)-- Enriches transaction data if enabled by user--An account sync happens every time an [entry.rb](mdc:app/models/entry.rb) is updated.--### Plaid Item Syncs--A Plaid Item sync is an ETL (extract, transform, load) operation:--1. [plaid_item.rb](mdc:app/models/plaid_item.rb) fetches data from the external Plaid API-2. [plaid_item.rb](mdc:app/models/plaid_item.rb) creates and loads this data to [plaid_account.rb](mdc:app/models/plaid_account.rb) records-3. [plaid_item.rb](mdc:app/models/plaid_item.rb) and [plaid_account.rb](mdc:app/models/plaid_account.rb) transform and load data to [account.rb](mdc:app/models/account.rb) and [entry.rb](mdc:app/models/entry.rb), the internal codebase representations of the data.--### Family Syncs--A family sync happens once daily via [auto_sync.rb](mdc:app/controllers/concerns/auto_sync.rb). A family sync is an "orchestrator" of Account and Plaid Item syncs.--## Data Providers--The codebase utilizes several 3rd party data services to calculate historical account balances, enrich data, and more. Since the app can be run in both "hosted" and "self hosted" mode, this means that data providers are _optional_ for self hosted users and must be configured.--Because of this optionality, data providers must be configured at _runtime_ through [registry.rb](mdc:app/models/provider/registry.rb) utilizing [setting.rb](mdc:app/models/setting.rb) for runtime parameters like API keys:--There are two types of 3rd party data in the codebase:--1. "Concept" data-2. One-off data--### "Concept" data--Since the app is self hostable, users may prefer using different providers for generic data like exchange rates and security prices. When data is generic enough where we can easily swap out different providers, we call it a data "concept".--Each "concept" has an interface defined in the `app/models/provider/concepts` directory.--```-app/models/- exchange_rate/- provided.rb # <- Responsible for selecting the concept provider from the registry- provider.rb # <- Base provider class- provider/- registry.rb <- Defines available providers by concept- concepts/- exchange_rate.rb <- defines the interface required for the exchange rate concept-```--### One-off data--For data that does not fit neatly into a "concept", an interface is not required and the concrete provider may implement ad-hoc methods called directly in code.--## "Provided" Concerns--In general, domain models should not be calling [registry.rb](mdc:app/models/provider/registry.rb) directly. When 3rd party data is required for a domain model, we use the `Provided` concern within that model's namespace. This concern is primarily responsible for:--- Choosing the provider to use for this "concept"-- Providing convenience methods on the model for accessing data--For example, [exchange_rate.rb](mdc:app/models/exchange_rate.rb) has a [provided.rb](mdc:app/models/exchange_rate/provided.rb) concern with the following convenience methods:--```rb-module ExchangeRate::Provided- extend ActiveSupport::Concern-- class_methods do- def provider- registry = Provider::Registry.for_concept(:exchange_rates)- registry.get_provider(:synth)- end-- def find_or_fetch_rate(from:, to:, date: Date.current, cache: true)- # Implementation- end-- def sync_provider_rates(from:, to:, start_date:, end_date: Date.current)- # Implementation- end- end-end-```--This exposes a generic access pattern where the caller does not care _which_ provider has been chosen for the concept of exchange rates and can get a predictable response:--```rb-def access_patterns_example- # Call exchange rate provider directly- ExchangeRate.provider.fetch_exchange_rate(from: "USD", to: "CAD", date: Date.current)-- # Call convenience method- ExchangeRate.sync_provider_rates(from: "USD", to: "CAD", start_date: 2.days.ago.to_date)-end-```--## Concrete provider implementations--Each 3rd party data provider should have a class under the `Provider::` namespace that inherits from `Provider` and returns `with_provider_response`, which will return a `Provider::ProviderResponse` object:--```rb-class ConcreteProvider < Provider- def fetch_some_data- with_provider_response do- ExampleData.new(- example: "data"- )- end- end-end-```--The `with_provider_response` automatically catches provider errors, so concrete provider classes should raise when valid data is not possible:--```rb-class ConcreteProvider < Provider- def fetch_some_data- with_provider_response do- data = nil-- # Raise an error if data cannot be returned- raise ProviderError.new("Could not find the data you need") if data.nil?-- data- end- end-end-```+@docs/llm-guides/architecture.mddiff --git a/.cursor/rules/self_improve.mdc b/.cursor/rules/self_improve.mdcdeleted file mode 100644index 0f95cfa006..0000000000--- a/.cursor/rules/self_improve.mdc+++ /dev/null@@ -1,73 +0,0 @@-----description: Guidelines for continuously improving Cursor rules based on emerging code patterns and best practices.-globs: **/*-alwaysApply: true------- **Rule Improvement Triggers:**- - New code patterns not covered by existing rules- - Repeated similar implementations across files- - Common error patterns that could be prevented- - New libraries or tools being used consistently- - Emerging best practices in the codebase--- **Analysis Process:**- - Compare new code with existing rules- - Identify patterns that should be standardized- - Look for references to external documentation- - Check for consistent error handling patterns- - Monitor test patterns and coverage--- **Rule Updates:**- - **Add New Rules When:**- - A new technology/pattern is used in 3+ files- - Common bugs could be prevented by a rule- - Code reviews repeatedly mention the same feedback- - New security or performance patterns emerge-- - **Modify Existing Rules When:**- - Better examples exist in the codebase- - Additional edge cases are discovered- - Related rules have been updated- - Implementation details have changed--- **Example Pattern Recognition:**- ```typescript- // If you see repeated patterns like:- const data = await prisma.user.findMany({- select: { id: true, email: true },- where: { status: 'ACTIVE' }- });-- // Consider adding to [prisma.mdc](mdc:.cursor/rules/prisma.mdc):- // - Standard select fields- // - Common where conditions- // - Performance optimization patterns- ```--- **Rule Quality Checks:**- - Rules should be actionable and specific- - Examples should come from actual code- - References should be up to date- - Patterns should be consistently enforced--- **Continuous Improvement:**- - Monitor code review comments- - Track common development questions- - Update rules after major refactors- - Add links to relevant documentation- - Cross-reference related rules--- **Rule Deprecation:**- - Mark outdated patterns as deprecated- - Remove rules that no longer apply- - Update references to deprecated rules- - Document migration paths for old patterns--- **Documentation Updates:**- - Keep examples synchronized with code- - Update references to external docs- - Maintain links between related rules- - Document breaking changes--Follow [cursor_rules.mdc](mdc:.cursor/rules/cursor_rules.mdc) for proper rule formatting and structure.diff --git a/.cursor/rules/stimulus_conventions.mdc b/.cursor/rules/stimulus_conventions.mdcindex 58038f0998..35df62d42e 100644--- a/.cursor/rules/stimulus_conventions.mdc+++ b/.cursor/rules/stimulus_conventions.mdc@@ -3,61 +3,5 @@ description:globs:alwaysApply: false----This rule describes how to write Stimulus controllers.-- **Use declarative actions, not imperative event listeners**- - Instead of assigning a Stimulus target and binding it to an event listener in the initializer, always write Controllers + ERB views declaratively by using Stimulus actions in ERB to call methods in the Stimulus JS controller. Below are good vs. bad code.-- BAD code:-- ```js- // BAD!!!! DO NOT DO THIS!!- // Imperative - controller does all the work- export default class extends Controller {- static targets = ["button", "content"]-- connect() {- this.buttonTarget.addEventListener("click", this.toggle.bind(this))- }-- toggle() {- this.contentTarget.classList.toggle("hidden")- this.buttonTarget.textContent = this.contentTarget.classList.contains("hidden") ? "Show" : "Hide"- }- }- ```-- GOOD code:-- ```erb- <!-- Declarative - HTML declares what happens -->-- <div data-controller="toggle">- <button data-action="click->toggle#toggle" data-toggle-target="button">Show</button>- <div data-toggle-target="content" class="hidden">Hello World!</div>- </div>- ```-- ```js- // Declarative - controller just responds- export default class extends Controller {- static targets = ["button", "content"]-- toggle() {- this.contentTarget.classList.toggle("hidden")- this.buttonTarget.textContent = this.contentTarget.classList.contains("hidden") ? "Show" : "Hide"- }- }- ```--- **Keep Stimulus controllers lightweight and simple**- - Always aim for less than 7 controller targets. Any more is a sign of too much complexity.- - Use private methods and expose a clear public API--- **Keep Stimulus controllers focused on what they do best**- - Domain logic does NOT belong in a Stimulus controller- - Stimulus controllers should aim for a single responsibility, or a group of highly related responsibilities- - Make good use of Stimulus's callbacks, actions, targets, values, and classes--- **Component controllers should not be used outside the component**- - If a Stimulus controller is in the app/components directory, it should only be used in its component view. It should not be used anywhere in app/views.+@docs/llm-guides/ui.mddiff --git a/.cursor/rules/testing.mdc b/.cursor/rules/testing.mdcindex caa9c345f3..e0c0b78fe0 100644--- a/.cursor/rules/testing.mdc+++ b/.cursor/rules/testing.mdc@@ -3,84 +3,5 @@ description:globs: test/**alwaysApply: false----Use this rule to learn how to write tests for the codebase.--Due to the open-source nature of this project, we have chosen Minitest + Fixtures for testing to maximize familiarity and predictability.--- **General testing rules**- - Always use Minitest and fixtures for testing, NEVER rspec or factories- - Keep fixtures to a minimum. Most models should have 2-3 fixtures maximum that represent the "base cases" for that model. "Edge cases" should be created on the fly, within the context of the test which it is needed.- - For tests that require a large number of fixture records to be created, use Rails helpers to help create the records needed for the test, then inline the creation. For example, [entries_test_helper.rb](mdc:test/support/entries_test_helper.rb) provides helpers to easily do this.--- **Write minimal, effective tests**- - Use system tests sparingly as they increase the time to complete the test suite- - Only write tests for critical and important code paths- - Write tests as you go, when required- - Take a practical approach to testing. Tests are effective when their presence _significantly increases confidence in the codebase_.-- Below are examples of necessary vs. unnecessary tests:-- ```rb- # GOOD!!- # Necessary test - in this case, we're testing critical domain business logic- test "syncs balances" do- Holding::Syncer.any_instance.expects(:sync_holdings).returns([]).once-- @account.expects(:start_date).returns(2.days.ago.to_date)-- Balance::ForwardCalculator.any_instance.expects(:calculate).returns(- [- Balance.new(date: 1.day.ago.to_date, balance: 1000, cash_balance: 1000, currency: "USD"),- Balance.new(date: Date.current, balance: 1000, cash_balance: 1000, currency: "USD")- ]- )-- assert_difference "@account.balances.count", 2 do- Balance::Syncer.new(@account, strategy: :forward).sync_balances- end- end-- # BAD!!- # Unnecessary test - in this case, this is simply testing ActiveRecord's functionality- test "saves balance" do- balance_record = Balance.new(balance: 100, currency: "USD")-- assert balance_record.save- end- ```--- **Test boundaries correctly**- - Distinguish between commands and query methods. Test output of query methods; test that commands were called with the correct params. See an example below:-- ```rb- class ExampleClass- def do_something- result = 2 + 2-- CustomEventProcessor.process_result(result)-- result- end- end-- class ExampleClass < ActiveSupport::TestCase- test "boundaries are tested correctly" do- result = ExampleClass.new.do_something-- # GOOD - we're only testing that the command was received, not internal implementation details- # The actual tests for CustomEventProcessor belong in a different test suite!- CustomEventProcessor.expects(:process_result).with(4).once-- # GOOD - we're testing the implementation of ExampleClass inside its own test suite- assert_equal 4, result- end- end- ```-- - Never test the implementation details of one class in another classes test suite--- **Stubs and mocks**- - Use `mocha` gem- - Always prefer `OpenStruct` when creating mock instances, or in complex cases, a mock class- - Only mock what's necessary. If you're not testing return values, don't mock a return value.+@docs/llm-guides/testing.mddiff --git a/.cursor/rules/ui-ux-design-guidelines.mdc b/.cursor/rules/ui-ux-design-guidelines.mdcindex 125fc744a5..e1a0631bb4 100644--- a/.cursor/rules/ui-ux-design-guidelines.mdc+++ b/.cursor/rules/ui-ux-design-guidelines.mdc@@ -3,21 +3,5 @@ description: This file describes Sure's design system and how views should be stglobs: app/views/**,app/helpers/**,app/javascript/controllers/**alwaysApply: true----Use the rules below when:--- You are writing HTML-- You are writing CSS-- You are writing styles in a JavaScript Stimulus controller--## Rules for AI (mandatory)--The codebase uses TailwindCSS v4.x (the newest version) with a custom design system defined in [sure-design-system.css](mdc:app/assets/tailwind/sure-design-system.css)--- Always start by referencing [sure-design-system.css](mdc:app/assets/tailwind/sure-design-system.css) to see the base primitives, functional tokens, and component tokens we use in the codebase-- Always prefer using the functional "tokens" defined in @sure-design-system.css when possible.- - Example 1: use `text-primary` rather than `text-white`- - Example 2: use `bg-container` rather than `bg-white`- - Example 3: use `border border-primary` rather than `border border-gray-200`-- Never create new styles in [sure-design-system.css](mdc:app/assets/tailwind/sure-design-system.css) or [application.css](mdc:app/assets/tailwind/application.css) without explicitly receiving permission to do so-- Always generate semantic HTML+@docs/llm-guides/design-system.mddiff --git a/.cursor/rules/view_conventions.mdc b/.cursor/rules/view_conventions.mdcindex 2801cccd49..35c887c4ca 100644--- a/.cursor/rules/view_conventions.mdc+++ b/.cursor/rules/view_conventions.mdc@@ -3,99 +3,5 @@ description:globs: app/views/**,app/javascript/**,app/components/**/*.jsalwaysApply: false----Use this rule to learn how to write ERB views, partials, and Stimulus controllers should be incorporated into them.--- **Component vs. Partial Decision Making**- - **Use ViewComponents when:**- - Element has complex logic or styling patterns- - Element will be reused across multiple views/contexts- - Element needs structured styling with variants/sizes (like buttons, badges)- - Element requires interactive behavior or Stimulus controllers- - Element has configurable slots or complex APIs- - Element needs accessibility features or ARIA support-- - **Use Partials when:**- - Element is primarily static HTML with minimal logic- - Element is used in only one or few specific contexts- - Element is simple template content (like CTAs, static sections)- - Element doesn't need variants, sizes, or complex configuration- - Element is more about content organization than reusable functionality--- **Prefer components over partials**- - If there is a component available for the use case in app/components, use it- - If there is no component, look for a partial- - If there is no partial, decide between component or partial based on the criteria above--- **Examples of Component vs. Partial Usage**- ```erb- <%# Component: Complex, reusable with variants and interactivity %>- <%= render DialogComponent.new(variant: :drawer) do |dialog| %>- <% dialog.with_header(title: "Account Settings") %>- <% dialog.with_body { "Dialog content here" } %>- <% end %>-- <%# Component: Interactive with complex styling options %>- <%= render ButtonComponent.new(text: "Save Changes", variant: "primary", confirm: "Are you sure?") %>-- <%# Component: Reusable with variants %>- <%= render FilledIconComponent.new(icon: "credit-card", variant: :surface) %>-- <%# Partial: Static template content %>- <%= render "shared/logo" %>-- <%# Partial: Simple, context-specific content with basic styling %>- <%= render "shared/trend_change", trend: @account.trend, comparison_label: "vs last month" %>-- <%# Partial: Simple divider/utility %>- <%= render "shared/ruler", classes: "my-4" %>-- <%# Partial: Simple form utility %>- <%= render "shared/form_errors", model: @account %>- ```--- **Keep domain logic out of the views**- ```erb- <%# BAD!!! %>-- <%# This belongs in the component file, not the template file! %>- <% button_classes = { class: "bg-blue-500 hover:bg-blue-600" } %>-- <%= tag.button class: button_classes do %>- Save Account- <% end %>-- <%# GOOD! %>-- <%= tag.button class: computed_button_classes do %>- Save Account- <% end %>- ```--- **Stimulus Integration in Views**- - Always use the **declarative approach** when integrating Stimulus controllers- - The ERB template should declare what happens, the Stimulus controller should respond- - Refer to [stimulus_conventions.mdc](mdc:.cursor/rules/stimulus_conventions.mdc) to learn how to incorporate them into-- GOOD Stimulus controller integration into views:-- ```erb- <!-- Declarative - HTML declares what happens -->-- <div data-controller="toggle">- <button data-action="click->toggle#toggle" data-toggle-target="button">Show</button>- <div data-toggle-target="content" class="hidden">Hello World!</div>- </div>- ```--- **Stimulus Controller Placement Guidelines**- - **Component controllers** (in `app/components/`) should only be used within their component templates- - **Global controllers** (in `app/javascript/controllers/`) can be used across any view- - Pass data from Rails to Stimulus using `data-*-value` attributes, not inline JavaScript- - Use Stimulus targets to reference DOM elements, not manual `getElementById` calls--- **Naming Conventions**- - **Components**: Use `ComponentName` suffix (e.g., `ButtonComponent`, `DialogComponent`, `FilledIconComponent`)- - **Partials**: Use underscore prefix (e.g., `_trend_change.html.erb`, `_form_errors.html.erb`, `_sync_indicator.html.erb`)- - **Shared partials**: Place in `app/views/shared/` directory for reusable content- - **Context-specific partials**: Place in relevant controller view directory (e.g., `accounts/_account_sidebar_tabs.html.erb`)+@docs/llm-guides/ui.mddiff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.mdindex 87726005e1..b9573410c6 100644--- a/.github/copilot-instructions.md+++ b/.github/copilot-instructions.md@@ -1,283 +1,3 @@-----applyTo: '**'------# Copilot instructions (English — concise)--Purpose: provide short, actionable guidance so Copilot suggestions match project conventions.--## Common Development Commands--### Development Server-- `bin/dev` - Start development server (Rails, Sidekiq, Tailwind CSS watcher)-- `bin/rails server` - Start Rails server only-- `bin/rails console` - Open Rails console--### Testing-- `bin/rails test` - Run all tests-- `bin/rails test:db` - Run tests with database reset-- `DISABLE_PARALLELIZATION=true bin/rails test:system` - Run system tests only (use sparingly - they take longer)-- `bin/rails test test/models/account_test.rb` - Run specific test file-- `bin/rails test test/models/account_test.rb:42` - Run specific test at line--### Linting & Formatting-- `bin/rubocop` - Run Ruby linter-- `npm run lint` - Check JavaScript/TypeScript code-- `npm run lint:fix` - Fix JavaScript/TypeScript issues-- `npm run format` - Format JavaScript/TypeScript code-- `bin/brakeman` - Run security analysis--### Database-- `bin/rails db:prepare` - Create and migrate database-- `bin/rails db:migrate` - Run pending migrations-- `bin/rails db:rollback` - Rollback last migration-- `bin/rails db:seed` - Load seed data--### Setup-- `bin/setup` - Initial project setup (installs dependencies, prepares database)--## Pre-PR workflow (run locally before opening PR)-- Tests: bin/rails test (all), DISABLE_PARALLELIZATION=true bin/rails test:system (when applicable)-- Linters: bin/rubocop -f github -a; bundle exec erb_lint ./app/**/*.erb -a-- Security: bin/brakeman --no-pager--## High-Level Architecture--### Application Modes-The app runs in two modes:-- **Managed** (Rails.application.config.app_mode = "managed")-- **Self-hosted** (Rails.application.config.app_mode = "self_hosted")--### Core Domain Model-The application is built around financial data management with these key relationships:-- **User** → has many **Accounts** → has many **Transactions**-- **Account** types: checking, savings, credit cards, investments, crypto, loans, properties-- **Transaction** → belongs to **Category**, can have **Tags** and **Rules**-- **Investment accounts** → have **Holdings** → track **Securities** via **Trades**--### API Architecture-The application provides both internal and external APIs:-- Internal API: Controllers serve JSON via Turbo for SPA-like interactions-- External API: `/api/v1/` namespace with Doorkeeper OAuth and API key authentication-- API responses use Jbuilder templates for JSON rendering.-- Rate limiting via Rack::Attack with configurable limits per API key--### Sync & Import System-Two primary data ingestion methods:-1. **Plaid Integration**: Real-time bank account syncing- - `PlaidItem` manages connections- - `Sync` tracks sync operations- - Background jobs handle data updates-2. **CSV Import**: Manual data import with mapping- - `Import` manages import sessions- - Supports transaction and balance imports- - Custom field mapping with transformation rules--### Background Processing-Sidekiq handles asynchronous tasks:-- Account syncing (`SyncJob`)-- Import processing (`ImportJob`)-- AI chat responses (`AssistantResponseJob`)-- Scheduled maintenance via sidekiq-cron--### Frontend Architecture-- **Hotwire Stack**: Turbo + Stimulus for reactive UI without heavy JavaScript-- **ViewComponents**: Reusable UI components in `app/components/`-- **Stimulus Controllers**: Handle interactivity, organized alongside components-- **Charts**: D3.js for financial visualizations (time series, donut, sankey)-- **Styling**: Tailwind CSS v4.x with custom design system- - Design system defined in `app/assets/tailwind/sure-design-system.css`- - Always use functional tokens (e.g., `text-primary` not `text-white`)- - Prefer semantic HTML elements over JS components- - Use `icon` helper for icons, never `lucide_icon` directly--### Multi-Currency Support-- All monetary values stored in base currency (user's primary currency)-- `Money` objects handle currency conversion and formatting-- Historical exchange rates for accurate reporting--### Security & Authentication-- Session-based auth for web users-- API authentication via:- - OAuth2 (Doorkeeper) for third-party apps- - API keys with JWT tokens for direct API access-- Scoped permissions system for API access-- Strong parameters and CSRF protection throughout--## Key rules-- Project modes: "managed" or "self_hosted".-- Domain: User → Accounts → Transactions. Keep business logic in models, controllers thin.--Authentication & context-- Use Current.user and Current.family (never current_user / current_family).--Testing conventions-- Use Minitest + fixtures (no RSpec, no FactoryBot).-- Use mocha for mocks where needed; VCR for external API tests.--Frontend conventions-- Hotwire-first: Turbo + Stimulus.-- Prefer semantic HTML, Turbo Frames, server-side formatting.-- Use the helper icon for icons (do not use lucide_icon directly).-- Use Tailwind design tokens (text-primary, bg-container, etc.).--Backend & architecture-- Skinny controllers, fat models.-- Prefer built-in Rails patterns; add dependencies only with strong justification.-- Sidekiq for background jobs (e.g., SyncJob, ImportJob, AssistantResponseJob).--API & security-- External API under /api/v1 with Doorkeeper / API keys; respect CSRF and strong params.-- Follow rate limits and auth strategies already in project.--Stimulus & components-- Keep controllers small (< 7 targets); pass data via data-*-value.-- Prefer ViewComponents for reusable or complex UI.--## Component Architecture--### ViewComponent vs Partials Decision Making--**Use ViewComponents when:**-- Element has complex logic or styling patterns-- Element will be reused across multiple views/contexts-- Element needs structured styling with variants/sizes-- Element requires interactive behavior or Stimulus controllers-- Element has configurable slots or complex APIs-- Element needs accessibility features or ARIA support--**Use Partials when:**-- Element is primarily static HTML with minimal logic-- Element is used in only one or few specific contexts-- Element is simple template content-- Element doesn't need variants, sizes, or complex configuration-- Element is more about content organization than reusable functionality--**Component Guidelines:**-- Prefer components over partials when available-- Keep domain logic OUT of view templates-- Logic belongs in component files, not template files--### Stimulus Controller Guidelines--**Declarative Actions (Required):**-```erb-<!-- GOOD: Declarative - HTML declares what happens -->-<div data-controller="toggle">- <button data-action="click->toggle#toggle" data-toggle-target="button">Show</button>- <div data-toggle-target="content" class="hidden">Hello World!</div>-</div>-```--**Controller Best Practices:**-- Keep controllers lightweight and simple (< 7 targets)-- Use private methods and expose clear public API-- Single responsibility or highly related responsibilities-- Component controllers stay in component directory, global controllers in `app/javascript/controllers/`-- Pass data via `data-*-value` attributes, not inline JavaScript--## Testing Philosophy--### General Testing Rules-- **ALWAYS use Minitest + fixtures + Mocha** (NEVER RSpec or FactoryBot)-- Keep fixtures minimal (2-3 per model for base cases)-- Create edge cases on-the-fly within test context-- Use Rails helpers for large fixture creation needs--### Test Quality Guidelines-- **Write minimal, effective tests** - system tests sparingly-- **Only test critical and important code paths**-- **Test boundaries correctly:**- - Commands: test they were called with correct params- - Queries: test output- - Don't test implementation details of other classes--### Testing Examples--```ruby-# GOOD - Testing critical domain business logic-test "syncs balances" do- Holding::Syncer.any_instance.expects(:sync_holdings).returns([]).once- assert_difference "@account.balances.count", 2 do- Balance::Syncer.new(@account, strategy: :forward).sync_balances- end-end--# BAD - Testing ActiveRecord functionality-test "saves balance" do- balance_record = Balance.new(balance: 100, currency: "USD")- assert balance_record.save-end-```--### Stubs and Mocks-- Use `mocha` gem-- Prefer `OpenStruct` for mock instances-- Only mock what's necessary--## Performance Considerations-- Database queries optimized with proper indexes-- N+1 queries prevented via includes/joins-- Background jobs for heavy operations-- Caching strategies for expensive calculations-- Turbo Frames for partial page updates--## Development Workflow-- Feature branches merged to `main`-- Docker support for consistent environments-- Environment variables via `.env` files-- Lookbook for component development (`/design-system`)-- Letter Opener for email preview in development--## Project Conventions--### Convention 1: Minimize Dependencies-- Push Rails to its limits before adding new dependencies-- Strong technical/business reason required for new dependencies-- Favor old and reliable over new and flashy--### Convention 2: Skinny Controllers, Fat Models-- Business logic in `app/models/` folder, avoid `app/services/`-- Use Rails concerns and POROs for organization-- Models should answer questions about themselves: `account.balance_series` not `AccountSeries.new(account).call`--### Convention 3: Hotwire-First Frontend-- **Native HTML preferred over JS components**- - Use `<dialog>` for modals, `<details><summary>` for disclosures- - **Leverage Turbo frames** for page sections over client-side solutions- - **Query params for state** over localStorage/sessions- - **Server-side formatting** for currencies, numbers, dates- - **Always use `icon` helper** in `application_helper.rb`, NEVER `lucide_icon` directly--### Convention 4: Optimize for Simplicity-- Prioritize good OOP domain design over performance-- Focus performance only on critical/global areas (avoid N+1 queries, mindful of global layouts)--### Convention 5: Database vs ActiveRecord Validations-- Simple validations (null checks, unique indexes) in DB-- ActiveRecord validations for convenience in forms (prefer client-side when possible)-- Complex validations and business logic in ActiveRecord--## TailwindCSS Design System--### Design System Rules-- **Always reference `app/assets/tailwind/sure-design-system.css`** for primitives and tokens-- **Use functional tokens** defined in design system:- - `text-primary` instead of `text-white`- - `bg-container` instead of `bg-white`- - `border border-secondary` instead of `border border-gray-200`-- **NEVER create new styles** in design system files without permission-- **Always generate semantic HTML**--Disallowed suggestions / behaviors-- Do NOT propose running system commands in PRs (rails server, rails credentials, touching tmp files, auto-running migrations).-- Avoid adding new global styles to design system without permission.-- Do not produce offensive, dangerous, or non-technical content.--Style for suggestions-- Make changes atomic and testable; explain impact briefly.-- Keep suggestions concise and aligned with existing code.-- Respect existing tests; add tests when changing critical logic.--Notes from repository config-- If .gemini/config.yaml disables automated code_review, still provide clear summaries and fix suggestions in PRs.+Read and follow [AGENTS.md](../AGENTS.md) before working in this repository.+Follow the shared guides linked there when their subjects apply to the task,+including the development checks, architecture, testing, UI, API and provider guides.diff --git a/.junie/guidelines.md b/.junie/guidelines.mdindex 2097634b82..b9573410c6 100644--- a/.junie/guidelines.md+++ b/.junie/guidelines.md@@ -1,799 +1,3 @@-# Sure Project — Junie Guidelines (Persistent Context)--This single file provides optional, persistent context for JetBrains Junie/RubyMine users. It is a direct, verbatim port of the project’s `.cursor/rules/*.mdc` guidelines into one document, with only path normalization for links and cross-references updated to point to sections below. It does not alter or interfere with Cursor/Codex workflows.--Self-hosted emphasis: the Sure project primarily operates in self-hosted mode; if references to managed mode exist in the original text below, they are preserved as-is for accuracy.--------## Original File: .cursor/rules/general-rules.mdc--```markdown-----description: Miscellaneous rules to get the AI to behave-globs: *-alwaysApply: true-----# General rules for AI--- Use `Current.user` for the current user. Do NOT use `current_user`.-- Use `Current.family` for the current family. Do NOT use `current_family`.-- Prior to generating any code, carefully read the project conventions and guidelines- - Read [project-design.mdc](#original-file-cursorrulesproject-designmdc) to understand the codebase- - Read [project-conventions.mdc](#original-file-cursorrulesproject-conventionsmdc) to understand _how_ to write code for the codebase- - Read [ui-ux-design-guidelines.mdc](#original-file-cursorrulesui-ux-design-guidelinesmdc) to understand how to implement frontend code specifically-- ActiveRecord migrations must inherit from `ActiveRecord::Migration[7.2]`. Do **not** use version 8.0 yet.--## Prohibited actions--- Do not run `rails server` in your responses.-- Do not run `touch tmp/restart.txt`-- Do not run `rails credentials`-- Do not automatically run migrations-```--------## Original File: .cursor/rules/project-design.mdc--```markdown-----description: This rule explains the system architecture and data flow of the Rails app-globs: *-alwaysApply: true------This file outlines how the codebase is structured and how data flows through the app.--This is a personal finance application built in Ruby on Rails. The primary domain entities for this app are outlined below. For an authoritative overview of the relationships, [schema.rb](db/schema.rb) is the source of truth.--## App Modes--The codebase runs in two distinct "modes", dictated by `Rails.application.config.app_mode`, which can be `managed` or `self_hosted`.--- "Managed" - in managed mode, a team operates and manages servers for users-- "Self Hosted" - in self hosted mode, users host the codebase on their own infrastructure, typically through Docker Compose. We have an example [docker-compose.example.yml](docker-compose.example.yml) file that runs [Dockerfile](Dockerfile) for this mode.--## Families and Users--- `Family` - all Stripe subscriptions, financial accounts, and the majority of preferences are stored at the [family.rb](app/models/family.rb) level.-- `User` - all [session.rb](app/models/session.rb) happen at the [user.rb](app/models/user.rb) level. A user belongs to a `Family` and can either be an `admin` or a `member`. Typically, a `Family` has a single admin, or "head of household" that manages finances while there will be several `member` users who can see the family's finances from varying perspectives.--## Currency Preference--Each `Family` selects a currency preference. This becomes the "main" currency in which all records are "normalized" to via [exchange_rate.rb](app/models/exchange_rate.rb) records so that the app can calculate metrics, historical graphs, and other insights in a single family currency.--## Accounts--The center of the app's domain is the [account.rb](app/models/account.rb). This represents a single financial account that has a `balance` and `currency`. For example, an `Account` could be "Chase Checking", which is a single financial account at Chase Bank. A user could have multiple accounts at a single institution (i.e. "Chase Checking", "Chase Credit Card", "Chase Savings") or an account could be a standalone account, such as "My Home" (a primary residence).--### Accountables--In the app, [account.rb](app/models/account.rb) is a Rails "delegated type" with the following subtypes (separate DB tables). Each account has a `classification` or either `asset` or `liability`. While the types are a flat hierarchy, below, they have been organized by their classification:--- Asset accountables- - [depository.rb](app/models/depository.rb) - a typical "bank account" such as a savings or checking account- - [investment.rb](app/models/investment.rb) - an account that has "holdings" such as a brokerage, 401k, etc.- - [crypto.rb](app/models/crypto.rb) - an account that tracks the value of one or more crypto holdings- - [property.rb](app/models/property.rb) - an account that tracks the value of a physical property such as a house or rental property- - [vehicle.rb](app/models/vehicle.rb) - an account that tracks the value of a vehicle- - [other_asset.rb](app/models/other_asset.rb) - an asset that cannot be classified by the other account types. For example, "jewelry".-- Liability accountables- - [credit_card.rb](app/models/credit_card.rb) - an account that tracks the debt owed on a credit card- - [loan.rb](app/models/loan.rb) - an account that tracks the debt owed on a loan (i.e. mortgage, student loan)- - [other_liability.rb](app/models/other_liability.rb) - a liability that cannot be classified by the other account types. For example, "IOU to a friend"--### Account Balances--An account [balance.rb](app/models/account/balance.rb) represents a single balance value for an account on a specific `date`. A series of balance records is generated daily for each account and is how we show a user's historical balance graph.--- For simple accounts like a "Checking Account", the balance represents the amount of cash in the account for a date.-- For a more complex account like "Investment Brokerage", the `balance` represents the combination of the "cash balance" + "holdings value". Each accountable type has different components that make up the "balance", but in all cases, the "balance" represents "How much the account is worth" (when `classification` is `asset`) or "How much is owed on the account" (when `classification` is `liability`)--All balances are calculated daily by [balance_calculator.rb](app/models/account/balance_calculator.rb).--### Account Holdings--An account [holding.rb](app/models/holding.rb) applies to [investment.rb](app/models/investment.rb) type accounts and represents a `qty` of a certain [security.rb](app/models/security.rb) at a specific `price` on a specific `date`.--For investment accounts with holdings, [base_calculator.rb](app/models/holding/base_calculator.rb) is used to calculate the daily historical holding quantities and prices, which are then rolled up into a final "Balance" for the account in [base_calculator.rb](app/models/account/balance/base_calculator.rb).--### Account Entries--An account [entry.rb](app/models/entry.rb) is also a Rails "delegated type". `Entry` represents any record that _modifies_ an `Account` [balance.rb](app/models/account/balance.rb) and/or [holding.rb](app/models/holding.rb). Therefore, every entry must have a `date`, `amount`, and `currency`.--The `amount` of an [entry.rb](app/models/entry.rb) is a signed value. A _negative_ amount is an "inflow" of money to that account. A _positive_ value is an "outflow" of money from that account. For example:--- A negative amount for a credit card account represents a "payment" to that account, which _reduces_ its balance (since it is a `liability`)-- A negative amount for a checking account represents an "income" to that account, which _increases_ its balance (since it is an `asset`)-- A negative amount for an investment/brokerage trade represents a "sell" transaction, which _increases_ the cash balance of the account--There are 3 entry types, defined as [entryable.rb](app/models/entryable.rb) records:--- `Valuation` - an account [valuation.rb](app/models/valuation.rb) is an entry that says, "here is the value of this account on this date". It is an absolute measure of an account value / debt. If there is an `Valuation` of 5,000 for today's date, that means that the account balance will be 5,000 today.-- `Transaction` - an account [transaction.rb](app/models/transaction.rb) is an entry that alters the account balance by the `amount`. This is the most common type of entry and can be thought of as an "income" or "expense".-- `Trade` - an account [trade.rb](app/models/trade.rb) is an entry that only applies to an investment account. This represents a "buy" or "sell" of a holding and has a `qty` and `price`.--### Account Transfers--A [transfer.rb](app/models/transfer.rb) represents a movement of money between two accounts. A transfer has an inflow [transaction.rb](app/models/transaction.rb) and an outflow [transaction.rb](app/models/transaction.rb). The codebase auto-matches transfers based on the following criteria:--- Must be from different accounts-- Must be within 4 days of each other-- Must be the same currency-- Must be opposite values--There are two primary forms of a transfer:--- Regular transfer - a normal movement of money between two accounts. For example, "Transfer $500 from Checking account to Brokerage account".-- Debt payment - a special form of transfer where the _receiver_ of funds is a [loan.rb](app/models/loan.rb) type account.--Regular transfers are typically _excluded_ from income and expense calculations while a debt payment is considered an "expense".--## Plaid Items--A [plaid_item.rb](app/models/plaid_item.rb) represents a "connection" maintained by our external data provider, Plaid in the "hosted" mode of the app. An "Item" has 1 or more [plaid_account.rb](app/models/plaid_account.rb) records, which are each associated 1:1 with an internal app [account.rb](app/models/account.rb).--All relevant metadata about the item and its underlying accounts are stored on [plaid_item.rb](app/models/plaid_item.rb) and [plaid_account.rb](app/models/plaid_account.rb), while the "normalized" data is then stored on internal app domain models.--## "Syncs"--The codebase has the concept of a [syncable.rb](app/models/concerns/syncable.rb), which represents any model which can have its data "synced" in the background. "Syncables" include:--- `Account` - an account "sync" will sync account holdings, balances, and enhance transaction metadata-- `PlaidItem` - a Plaid Item "sync" fetches data from Plaid APIs, normalizes that data, stores it on internal app models, and then finally performs an "Account sync" for each of the underlying accounts created from the Plaid Item.-- `Family` - a Family "sync" loops through the family's Plaid Items and individual Accounts and "syncs" each of them. A family is synced once per day, automatically through [auto_sync.rb](app/controllers/concerns/auto_sync.rb).--Each "sync" creates a [sync.rb](app/models/sync.rb) record in the database, which keeps track of the status of the sync, any errors that it encounters, and acts as an "audit table" for synced data.--Below are brief descriptions of each type of sync in more detail.--### Account Syncs--The most important type of sync is the account sync. It is orchestrated by the account's `sync_data` method, which performs a few important tasks:--- Auto-matches transfer records for the account-- Calculates daily [balance.rb](app/models/account/balance.rb) records for the account from `account.start_date` to `Date.current` using [base_calculator.rb](app/models/account/balance/base_calculator.rb)- - Balances are dependent on the calculation of [holding.rb](app/models/holding.rb), which uses [base_calculator.rb](app/models/account/holding/base_calculator.rb)-- Enriches transaction data if enabled by user--An account sync happens every time an [entry.rb](app/models/entry.rb) is updated.--### Plaid Item Syncs--A Plaid Item sync is an ETL (extract, transform, load) operation:--1. [plaid_item.rb](app/models/plaid_item.rb) fetches data from the external Plaid API-2. [plaid_item.rb](app/models/plaid_item.rb) creates and loads this data to [plaid_account.rb](app/models/plaid_account.rb) records-3. [plaid_item.rb](app/models/plaid_item.rb) and [plaid_account.rb](app/models/plaid_account.rb) transform and load data to [account.rb](app/models/account.rb) and [entry.rb](app/models/entry.rb), the internal codebase representations of the data.--### Family Syncs--A family sync happens once daily via [auto_sync.rb](app/controllers/concerns/auto_sync.rb). A family sync is an "orchestrator" of Account and Plaid Item syncs.--## Data Providers--The codebase utilizes several 3rd party data services to calculate historical account balances, enrich data, and more. Since the app can be run in both "hosted" and "self hosted" mode, this means that data providers are _optional_ for self hosted users and must be configured.--Because of this optionality, data providers must be configured at _runtime_ through [registry.rb](app/models/provider/registry.rb) utilizing [setting.rb](app/models/setting.rb) for runtime parameters like API keys:--There are two types of 3rd party data in the codebase:--1. "Concept" data-2. One-off data--### "Concept" data--Since the app is self hostable, users may prefer using different providers for generic data like exchange rates and security prices. When data is generic enough where we can easily swap out different providers, we call it a data "concept".--Each "concept" has an interface defined in the `app/models/provider/concepts` directory.--```plain-app/models/- exchange_rate/- provided.rb # <- Responsible for selecting the concept provider from the registry- provider.rb # <- Base provider class- provider/- registry.rb <- Defines available providers by concept- concepts/- exchange_rate.rb <- defines the interface required for the exchange rate concept-```--### One-off data--For data that does not fit neatly into a "concept", an interface is not required and the concrete provider may implement ad-hoc methods called directly in code.--## "Provided" Concerns--In general, domain models should not be calling [registry.rb](app/models/provider/registry.rb) directly. When 3rd party data is required for a domain model, we use the `Provided` concern within that model's namespace. This concern is primarily responsible for:--- Choosing the provider to use for this "concept"-- Providing convenience methods on the model for accessing data--For example, [exchange_rate.rb](app/models/exchange_rate.rb) has a [provided.rb](app/models/exchange_rate/provided.rb) concern with the following convenience methods:--```rb-module ExchangeRate::Provided- extend ActiveSupport::Concern-- class_methods do- def provider- registry = Provider::Registry.for_concept(:exchange_rates)- registry.get_provider(:synth)- end-- def find_or_fetch_rate(from:, to:, date: Date.current, cache: true)- # Implementation- end-- def sync_provider_rates(from:, to:, start_date:, end_date: Date.current)- # Implementation- end- end-end-```--This exposes a generic access pattern where the caller does not care _which_ provider has been chosen for the concept of exchange rates and can get a predictable response:--```rb-def access_patterns_example- # Call exchange rate provider directly- ExchangeRate.provider.fetch_exchange_rate(from: "USD", to: "CAD", date: Date.current)-- # Call convenience method- ExchangeRate.sync_provider_rates(from: "USD", to: "CAD", start_date: 2.days.ago.to_date)-end-```--## Concrete provider implementations--Each 3rd party data provider should have a class under the `Provider::` namespace that inherits from `Provider` and returns `with_provider_response`, which will return a `Provider::ProviderResponse` object:--```rb-class ConcreteProvider < Provider- def fetch_some_data- with_provider_response do- ExampleData.new(- example: "data"- )- end- end-end-```--The `with_provider_response` automatically catches provider errors, so concrete provider classes should raise when valid data is not possible:--```rb-class ConcreteProvider < Provider- def fetch_some_data- with_provider_response do- data = nil-- # Raise an error if data cannot be returned- raise ProviderError.new("Could not find the data you need") if data.nil?-- data- end- end-end-```-```-------## Original File: .cursor/rules/project-conventions.mdc--```markdown-----description:-globs:-alwaysApply: true-----This rule serves as high-level documentation for how you should write code in this codebase.--## Project Tech Stack--- Web framework: Ruby on Rails- - Minitest + fixtures for testing- - Propshaft for asset pipeline- - Hotwire Turbo/Stimulus for SPA-like UI/UX- - TailwindCSS for styles- - Lucide Icons for icons- - OpenAI for AI chat-- Database: PostgreSQL-- Jobs: Sidekiq + Redis-- External- - Payments: Stripe- - User bank data syncing: Plaid--## Project conventions--These conventions should be used when writing code for the project.--### Convention 1: Minimize dependencies, vanilla Rails is plenty--Dependencies are a natural part of building software, but we aim to minimize them when possible to keep this open-source codebase easy to understand, maintain, and contribute to.--- Push Rails to its limits before adding new dependencies-- When a new dependency is added, there must be a strong technical or business reason to add it-- When adding dependencies, you should favor old and reliable over new and flashy--### Convention 2: Leverage POROs and concerns over "service objects"--This codebase adopts a "skinny controller, fat models" convention. Furthermore, we put almost _everything_ directly in the `app/models/` folder and avoid separate folders for business logic such as `app/services/`.--- Organize large pieces of business logic into Rails concerns and POROs (Plain ole' Ruby Objects)-- While a Rails concern _may_ offer shared functionality (i.e. "duck types"), it can also be a "one-off" concern that is only included in one place for better organization and readability.-- When concerns are used for code organization, they should be organized around the "traits" of a model; not for simply moving code to another spot in the codebase.-- When possible, models should answer questions about themselves—for example, we might have a method, `account.balance_series` that returns a time-series of the account's most recent balances. We prefer this over something more service-like such as `AccountSeries.new(account).call`.--### Convention 3: Leverage Hotwire, write semantic HTML, CSS, and JS, prefer server-side solutions--- Native HTML is always preferred over JS-based components- - Example 1: Use `<dialog>` element for modals instead of creating a custom component- - Example 2: Use `<details><summary>...</summary></details>` for disclosures rather than custom components-- Leverage Turbo frames to break up the page over JS-driven client-side solutions- - Example 1: A good example of turbo frame usage is in [application.html.erb](app/views/layouts/application.html.erb) where we load [chats_controller.rb](app/controllers/chats_controller.rb) actions in a turbo frame in the global layout-- Leverage query params in the URL for state over local storage and sessions. If absolutely necessary, utilize the DB for persistent state.-- Use Turbo streams to enhance functionality, but do not solely depend on it-- Format currencies, numbers, dates, and other values server-side, then pass to Stimulus controllers for display only-- Keep client-side code for where it truly shines. For example, @bulk_select_controller.js is a case where server-side solutions would degrade the user experience significantly. When bulk-selecting entries, client-side solutions are the way to go and Stimulus provides the right toolset to achieve this.-- Always use the `icon` helper in [application_helper.rb](app/helpers/application_helper.rb) for icons. NEVER use `lucide_icon` helper directly.--The Hotwire suite (Turbo/Stimulus) works very well with these native elements and we optimize for this.--### Convention 4: Optimize for simplicitly and clarity--All code should maximize readability and simplicity.--- Prioritize good OOP domain design over performance-- Only focus on performance for critical and global areas of the codebase; otherwise, don't sweat the small stuff.- - Example 1: be mindful of loading large data payloads in global layouts- - Example 2: Avoid N+1 queries--### Convention 5: Use ActiveRecord for complex validations, DB for simple ones, keep business logic out of DB--- Enforce `null` checks, unique indexes, and other simple validations in the DB-- ActiveRecord validations _may_ mirror the DB level ones, but not 100% necessary. These are for convenience when error handling in forms. Always prefer client-side form validation when possible.-- Complex validations and business logic should remain in ActiveRecord-```-------## Original File: .cursor/rules/testing.mdc--```markdown-----description:-globs: test/**-alwaysApply: false-----Use this rule to learn how to write tests for the codebase.--Due to the open-source nature of this project, we have chosen Minitest + Fixtures for testing to maximize familiarity and predictability.--- **General testing rules**- - Always use Minitest and fixtures for testing, NEVER rspec or factories- - Keep fixtures to a minimum. Most models should have 2-3 fixtures maximum that represent the "base cases" for that model. "Edge cases" should be created on the fly, within the context of the test which it is needed.- - For tests that require a large number of fixture records to be created, use Rails helpers to help create the records needed for the test, then inline the creation. For example, [entries_test_helper.rb](test/support/entries_test_helper.rb) provides helpers to easily do this.--- **Write minimal, effective tests**- - Use system tests sparingly as they increase the time to complete the test suite- - Only write tests for critical and important code paths- - Write tests as you go, when required- - Take a practical approach to testing. Tests are effective when their presence _significantly increases confidence in the codebase_.-- Below are examples of necessary vs. unnecessary tests:-- ```rb- # GOOD!!- # Necessary test - in this case, we're testing critical domain business logic- test "syncs balances" do- Holding::Syncer.any_instance.expects(:sync_holdings).returns([]).once-- @account.expects(:start_date).returns(2.days.ago.to_date)-- Balance::ForwardCalculator.any_instance.expects(:calculate).returns(- [- Balance.new(date: 1.day.ago.to_date, balance: 1000, cash_balance: 1000, currency: "USD"),- Balance.new(date: Date.current, balance: 1000, cash_balance: 1000, currency: "USD")- ]- )-- assert_difference "@account.balances.count", 2 do- Balance::Syncer.new(@account, strategy: :forward).sync_balances- end- end-- # BAD!!- # Unnecessary test - in this case, this is simply testing ActiveRecord's functionality- test "saves balance" do- balance_record = Balance.new(balance: 100, currency: "USD")-- assert balance_record.save- end- ```--- **Test boundaries correctly**- - Distinguish between commands and query methods. Test output of query methods; test that commands were called with the correct params. See an example below:-- ```rb- class ExampleClass- def do_something- result = 2 + 2-- CustomEventProcessor.process_result(result)-- result- end- end-- class ExampleClass < ActiveSupport::TestCase- test "boundaries are tested correctly" do- result = ExampleClass.new.do_something-- # GOOD - we're only testing that the command was received, not internal implementation details- # The actual tests for CustomEventProcessor belong in a different test suite!- CustomEventProcessor.expects(:process_result).with(4).once-- # GOOD - we're testing the implementation of ExampleClass inside its own test suite- assert_equal 4, result- end- end- ```-- - Never test the implementation details of one class in another classes test suite--- **Stubs and mocks**- - Use `mocha` gem- - Always prefer `OpenStruct` when creating mock instances, or in complex cases, a mock class- - Only mock what's necessary. If you're not testing return values, don't mock a return value.-```-------## Original File: .cursor/rules/ui-ux-design-guidelines.mdc--```markdown-----description: This file describes Sure's design system and how views should be styled-globs: app/views/**,app/helpers/**,app/javascript/controllers/**-alwaysApply: true-----Use the rules below when:--- You are writing HTML-- You are writing CSS-- You are writing styles in a JavaScript Stimulus controller--## Rules for AI (mandatory)--The codebase uses TailwindCSS v4.x (the newest version) with a custom design system defined in [sure-design-system.css](app/assets/tailwind/sure-design-system.css)--- Always start by referencing [sure-design-system.css](app/assets/tailwind/sure-design-system.css) to see the base primitives, functional tokens, and component tokens we use in the codebase-- Always prefer using the functional "tokens" defined in @sure-design-system.css when possible.- - Example 1: use `text-primary` rather than `text-white`- - Example 2: use `bg-container` rather than `bg-white`- - Example 3: use `border border-primary` rather than `border border-gray-200`-- Never create new styles in [sure-design-system.css](app/assets/tailwind/sure-design-system.css) or [application.css](app/assets/tailwind/application.css) without explicitly receiving permission to do so-- Always generate semantic HTML-```-------## Original File: .cursor/rules/stimulus_conventions.mdc--```markdown-----description:-globs:-alwaysApply: false-----This rule describes how to write Stimulus controllers.--- **Use declarative actions, not imperative event listeners**- - Instead of assigning a Stimulus target and binding it to an event listener in the initializer, always write Controllers + ERB views declaratively by using Stimulus actions in ERB to call methods in the Stimulus JS controller. Below are good vs. bad code.-- BAD code:-- ```js- // BAD!!!! DO NOT DO THIS!!- // Imperative - controller does all the work- export default class extends Controller {- static targets = ["button", "content"]-- connect() {- this.buttonTarget.addEventListener("click", this.toggle.bind(this))- }-- toggle() {- this.contentTarget.classList.toggle("hidden")- this.buttonTarget.textContent = this.contentTarget.classList.contains("hidden") ? "Show" : "Hide"- }- }- ```-- GOOD code:-- ```erb- <!-- Declarative - HTML declares what happens -->-- <div data-controller="toggle">- <button data-action="click->toggle#toggle" data-toggle-target="button">Show</button>- <div data-toggle-target="content" class="hidden">Hello World!</div>- </div>- ```-- ```js- // Declarative - controller just responds- export default class extends Controller {- static targets = ["button", "content"]-- toggle() {- this.contentTarget.classList.toggle("hidden")- this.buttonTarget.textContent = this.contentTarget.classList.contains("hidden") ? "Show" : "Hide"- }- }- ```--- **Keep Stimulus controllers lightweight and simple**- - Always aim for less than 7 controller targets. Any more is a sign of too much complexity.- - Use private methods and expose a clear public API--- **Keep Stimulus controllers focused on what they do best**- - Domain logic does NOT belong in a Stimulus controller- - Stimulus controllers should aim for a single responsibility, or a group of highly related responsibilities- - Make good use of Stimulus's callbacks, actions, targets, values, and classes--- **Component controllers should not be used outside the component**- - If a Stimulus controller is in the app/components directory, it should only be used in its component view. It should not be used anywhere in app/views.-```-------## Original File: .cursor/rules/view_conventions.mdc--```-----description:-globs: app/views/**,app/javascript/**,app/components/**/*.js-alwaysApply: false-----Use this rule to learn how to write ERB views, partials, and Stimulus controllers should be incorporated into them.--- **Component vs. Partial Decision Making**- - **Use ViewComponents when:**- - Element has complex logic or styling patterns- - Element will be reused across multiple views/contexts- - Element needs structured styling with variants/sizes (like buttons, badges)- - Element requires interactive behavior or Stimulus controllers- - Element has configurable slots or complex APIs- - Element needs accessibility features or ARIA support-- - **Use Partials when:**- - Element is primarily static HTML with minimal logic- - Element is used in only one or few specific contexts- - Element is simple template content (like CTAs, static sections)- - Element doesn't need variants, sizes, or complex configuration- - Element is more about content organization than reusable functionality--- **Prefer components over partials**- - If there is a component available for the use case in app/components, use it- - If there is no component, look for a partial- - If there is no partial, decide between component or partial based on the criteria above--- **Examples of Component vs. Partial Usage**- ```erb- <%# Component: Complex, reusable with variants and interactivity %>- <%= render DialogComponent.new(variant: :drawer) do |dialog| %>- <% dialog.with_header(title: "Account Settings") %>- <% dialog.with_body { "Dialog content here" } %>- <% end %>-- <%# Component: Interactive with complex styling options %>- <%= render ButtonComponent.new(text: "Save Changes", variant: "primary", confirm: "Are you sure?") %>-- <%# Component: Reusable with variants %>- <%= render FilledIconComponent.new(icon: "credit-card", variant: :surface) %>-- <%# Partial: Static template content %>- <%= render "shared/logo" %>-- <%# Partial: Simple, context-specific content with basic styling %>- <%= render "shared/trend_change", trend: @account.trend, comparison_label: "vs last month" %>-- <%# Partial: Simple divider/utility %>- <%= render "shared/ruler", classes: "my-4" %>-- <%# Partial: Simple form utility %>- <%= render "shared/form_errors", model: @account %>- ```--- **Keep domain logic out of the views**- ```erb- <%# BAD!!! %>-- <%# This belongs in the component file, not the template file! %>- <% button_classes = { class: "bg-blue-500 hover:bg-blue-600" } %>-- <%= tag.button class: button_classes do %>- Save Account- <% end %>-- <%# GOOD! %>-- <%= tag.button class: computed_button_classes do %>- Save Account- <% end %>- ```--- **Stimulus Integration in Views**- - Always use the **declarative approach** when integrating Stimulus controllers- - The ERB template should declare what happens, the Stimulus controller should respond- - Refer to [stimulus_conventions.mdc](#original-file-cursorrulesstimulus_conventionsmdc) to learn how to incorporate them into-- GOOD Stimulus controller integration into views:-- ```erb- <!-- Declarative - HTML declares what happens -->-- <div data-controller="toggle">- <button data-action="click->toggle#toggle" data-toggle-target="button">Show</button>- <div data-toggle-target="content" class="hidden">Hello World!</div>- </div>- ```--- **Stimulus Controller Placement Guidelines**- - **Component controllers** (in `app/components/`) should only be used within their component templates- - **Global controllers** (in `app/javascript/controllers/`) can be used across any view- - Pass data from Rails to Stimulus using `data-*-value` attributes, not inline JavaScript- - Use Stimulus targets to reference DOM elements, not manual `getElementById` calls--- **Naming Conventions**- - **Components**: Use `ComponentName` suffix (e.g., `ButtonComponent`, `DialogComponent`, `FilledIconComponent`)- - **Partials**: Use underscore prefix (e.g., `_trend_change.html.erb`, `_form_errors.html.erb`, `_sync_indicator.html.erb`)- - **Shared partials**: Place in `app/views/shared/` directory for reusable content- - **Context-specific partials**: Place in relevant controller view directory (e.g., `accounts/_account_sidebar_tabs.html.erb`)-```-------## Original File: .cursor/rules/cursor_rules.mdc--```-----description: Guidelines for creating and maintaining Cursor rules to ensure consistency and effectiveness.-globs: .cursor/rules/*.mdc-alwaysApply: true------- **Required Rule Structure:**- ```markdown- ---- description: Clear, one-line description of what the rule enforces- globs: path/to/files/*.ext, other/path/**/*- alwaysApply: boolean- ----- - **Main Points in Bold**- - Sub-points with details- - Examples and explanations- ```--- **File References:**- - Use `[filename](mdc:path/to/file)` ([filename](mdc:filename)) to reference files- - Example: [prisma.mdc](.cursor/rules/prisma.mdc) for rule references- - Example: [schema.prisma](prisma/schema.prisma) for code references--- **Code Examples:**- - Use language-specific code blocks- ```typescript- // ✅ DO: Show good examples- const goodExample = true;-- // ❌ DON'T: Show anti-patterns- const badExample = false;- ```--- **Rule Content Guidelines:**- - Start with high-level overview- - Include specific, actionable requirements- - Show examples of correct implementation- - Reference existing code when possible- - Keep rules DRY by referencing other rules--- **Rule Maintenance:**- - Update rules when new patterns emerge- - Add examples from actual codebase- - Remove outdated patterns- - Cross-reference related rules--- **Best Practices:**- - Use bullet points for clarity- - Keep descriptions concise- - Include both DO and DON'T examples- - Reference actual code over theoretical examples- - Use consistent formatting across rules-```-------## Original File: .cursor/rules/self_improve.mdc--```-----description: Guidelines for continuously improving Cursor rules based on emerging code patterns and best practices.-globs: **/*-alwaysApply: true------- **Rule Improvement Triggers:**- - New code patterns not covered by existing rules- - Repeated similar implementations across files- - Common error patterns that could be prevented- - New libraries or tools being used consistently- - Emerging best practices in the codebase--- **Analysis Process:**- - Compare new code with existing rules- - Identify patterns that should be standardized- - Look for references to external documentation- - Check for consistent error handling patterns- - Monitor test patterns and coverage--- **Rule Updates:**- - **Add New Rules When:**- - A new technology/pattern is used in 3+ files- - Common bugs could be prevented by a rule- - Code reviews repeatedly mention the same feedback- - New security or performance patterns emerge-- - **Modify Existing Rules When:**- - Better examples exist in the codebase- - Additional edge cases are discovered- - Related rules have been updated- - Implementation details have changed--- **Example Pattern Recognition:**- ```typescript- // If you see repeated patterns like:- const data = await prisma.user.findMany({- select: { id: true, email: true },- where: { status: 'ACTIVE' }- });-- // Consider adding to [prisma.mdc](.cursor/rules/prisma.mdc):- // - Standard select fields- // - Common where conditions- // - Performance optimization patterns- ```--- **Rule Quality Checks:**- - Rules should be actionable and specific- - Examples should come from actual code- - References should be up to date- - Patterns should be consistently enforced--- **Continuous Improvement:**- - Monitor code review comments- - Track common development questions- - Update rules after major refactors- - Add links to relevant documentation- - Cross-reference related rules--- **Rule Deprecation:**- - Mark outdated patterns as deprecated- - Remove rules that no longer apply- - Update references to deprecated rules- - Document migration paths for old patterns--- **Documentation Updates:**- - Keep examples synchronized with code- - Update references to external docs- - Maintain links between related rules- - Document breaking changes--Follow [cursor_rules.mdc](#original-file-cursorrulescursor_rulesmdc) for proper rule formatting and structure.-```+Read and follow [AGENTS.md](../AGENTS.md) before working in this repository.+Follow the shared guides linked there when their subjects apply to the task,+including the development checks, architecture, testing, UI, API and provider guides.diff --git a/AGENTS.md b/AGENTS.mdindex 399375924e..372e7c75ea 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,103 +1,43 @@-# Repository Guidelines+# Repository guidance-## Project Structure & Module Organization-- Code: `app/` (Rails MVC, services, jobs, mailers, components), JS in `app/javascript/`, styles/assets in `app/assets/` (Tailwind, images, fonts).-- Config: `config/`, environment examples in `.env.local.example` and `.env.test.example`.-- Data: `db/` (migrations, seeds), fixtures in `test/fixtures/`.-- Tests: `test/` mirroring `app/` (e.g., `test/models/*_test.rb`).-- Tooling: `bin/` (project scripts), `docs/` (guides), `public/` (static), `lib/` (shared libs).+## Working in the repository-## Build, Test, and Development Commands-- Setup: `cp .env.local.example .env.local && bin/setup` — install deps, set DB, prepare app.-- Run app: `bin/dev` — starts Rails server and asset/watchers via `Procfile.dev`.-- Test suite: `bin/rails test` — run all Minitest tests; add `TEST=test/models/user_test.rb` to target a file.-- Lint Ruby: `bin/rubocop` — style checks; add `-A` to auto-correct safe cops.-- Lint/format JS/CSS: `npm run lint` and `npm run format` — uses Biome.-- Security scan: `bin/brakeman` — static analysis for common Rails issues.+- Read [architecture and conventions](docs/llm-guides/architecture.md) before changing code, and the relevant [task guides](docs/llm-guides/README.md).+- Rails code lives in `app/`; keep business logic in models, concerns and POROs, with thin controllers. JavaScript is in `app/javascript/`, components in `app/components/`, assets in `app/assets/`, and configuration in `config/`.+- Minitest tests mirror `app/` under `test/`; fixtures are in `test/fixtures/`. Migrations and schema are in `db/`, scripts in `bin/`, shared libraries in `lib/`.+- Use `Current.user` and `Current.family`, never `current_user` or `current_family`. Preserve family tenancy and existing authorization boundaries.+- Prefer built-in Rails patterns and established dependencies. New dependencies need a strong technical or business reason. Keep changes focused, readable and consistent with nearby code.+- Ruby uses two-space indentation, `snake_case` methods/variables and `CamelCase` classes. JavaScript uses `lowerCamelCase` variables/functions and `PascalCase` classes; follow Biome. Keep domain logic out of ERB.+- Never commit secrets; use environment variables and `.env.local` for local configuration.+- Do not start `rails server`, touch `tmp/restart.txt`, run `rails credentials`, or automatically run migrations. Setup and database commands in the [development guide](docs/llm-guides/development.md) are for explicitly requested environment work.+- New migrations use the current Rails migration version; leave historical migration versions intact.-## Coding Style & Naming Conventions-- Ruby: 2-space indent, `snake_case` for methods/vars, `CamelCase` for classes/modules. Follow Rails conventions for folders and file names.-- Views: ERB checked by `erb-lint` (see `.erb_lint.yml`). Avoid heavy logic in views; prefer helpers/components.-- JavaScript: `lowerCamelCase` for vars/functions, `PascalCase` for classes/components. Let Biome format code.-- Commit small, cohesive changes; keep diffs focused.+## Tests and pull requests-## Testing Guidelines-- Framework: Minitest (Rails). Name files `*_test.rb` and mirror `app/` structure.-- Run: `bin/rails test` locally and ensure green before pushing.-- Fixtures/VCR: Use `test/fixtures` and existing VCR cassettes for HTTP. Prefer unit tests plus focused integration tests.+- Use Minitest and fixtures for behavioral tests, with Mocha and VCR where needed. RSpec/rswag is for OpenAPI documentation only. Follow the [testing guide](docs/llm-guides/testing.md).+- Run `bin/rails test` and ensure it is green before pushing. Before opening a PR, run **all** checks in the [pre-PR checklist](docs/llm-guides/development.md#before-opening-a-pull-request): full Rails tests, applicable system tests, Ruby and ERB lint, Biome and Brakeman. Only create the PR when all required checks pass.+- Commits use imperative subjects of at most 72 characters, with rationale and issue references where relevant. Target `main` with small, cohesive changes.+- PRs explain the problem, resulting behavior and validation; link issues and include screenshots for UI changes and migration notes when applicable. Ensure CI passes and the branch is up to date before requesting review; see [CONTRIBUTING.md](CONTRIBUTING.md).-## Commit & Pull Request Guidelines-- Commits: Imperative subject ≤ 72 chars (e.g., "Add account balance validation"). Include rationale in body and reference issues (`#123`).-- PRs: Clear description, linked issues, screenshots for UI changes, and migration notes if applicable. Ensure CI passes, tests added/updated, and `rubocop`/Biome are clean.+## UI changes-## Security & Configuration Tips-- Never commit secrets. Start from `.env.local.example`; use `.env.local` for development only.-- Run `bin/brakeman` before major PRs. Prefer environment variables over hard-coded values.+When touching ERB, view components or CSS, follow the [design system guide](docs/llm-guides/design-system.md):-## API Development Guidelines+- Use functional tokens from `app/assets/tailwind/sure-design-system.css`, such as `bg-container`, `text-primary`, `border-primary`, `bg-warning/10` and `text-destructive`. No raw Tailwind palette classes or hex literals.+- Check `app/components/DS/` first for alerts, badges, buttons, disclosures, dialogs and inputs. Use existing `DS::*` primitives.+- If the same hand-built shape appears at least twice in a diff with no DS equivalent, propose a new `DS::*` primitive before the second copy lands.+- Use the `icon` helper, never `lucide_icon` directly; no raw SVG outside DS primitives. Use `t()` for user-facing strings and scale tokens instead of arbitrary pixel values when a scale token fits.+- Adding styles to `app/assets/tailwind/sure-design-system.css` or `app/assets/tailwind/application.css` requires explicit permission.+- Reviewers escalate DS reuse and repeated-shape violations to close/rewrite; token and icon/SVG/localization/scale violations are request-changes.-### OpenAPI Documentation (MANDATORY)-When adding or modifying API endpoints in `app/controllers/api/v1/`, you **MUST** create or update corresponding OpenAPI request specs for **DOCUMENTATION ONLY**:+## API changes-1. **Location**: `spec/requests/api/v1/{resource}_spec.rb`-2. **Framework**: RSpec with rswag for OpenAPI generation-3. **Schemas**: Define reusable schemas in `spec/swagger_helper.rb`-4. **Generated Docs**: `docs/api/openapi.yaml`-5. **Regenerate**: Run `RAILS_ENV=test bundle exec rake rswag:specs:swaggerize` after changes+Adding or modifying `app/controllers/api/v1/` endpoints requires Minitest behavioral coverage and corresponding **documentation-only** rswag specs in `spec/requests/api/v1/`. Reusable schemas belong in `spec/swagger_helper.rb`; regenerate `docs/api/openapi.yaml` with `RAILS_ENV=test bundle exec rake rswag:specs:swaggerize` after changes.-### Post-commit API consistency (LLM checklist)-After every API endpoint commit, ensure: (1) **Minitest** behavioral coverage in `test/controllers/api/v1/{resource}_controller_test.rb` (no behavioral assertions in rswag); (2) **rswag** remains docs-only (no `expect`/`assert_*` in `spec/requests/api/v1/`); (3) **rswag auth** uses the same API key pattern everywhere (`X-Api-Key`, not OAuth/Bearer). Full checklist: [.cursor/rules/api-endpoint-consistency.mdc](.cursor/rules/api-endpoint-consistency.mdc).+**Post-commit API consistency:** after every API endpoint commit, follow the [API checklist](docs/llm-guides/api-endpoint-consistency.md): Minitest coverage, no behavioral assertions in rswag, and the shared `X-Api-Key` authentication pattern in those tests/specs.-## Design System Hygiene (UI PRs)+## Provider and feature work-When a PR touches `.erb`, view components, or `.css`:--1. **Tokens, not palette.** Use functional tokens from `app/assets/tailwind/sure-design-system.css` (`bg-warning/10`, `text-destructive`, `bg-container`, `text-primary`, `border-primary`). No raw Tailwind palette (`bg-blue-50`, `text-red-500`, hex literals).-2. **Reach for `DS::*` first.** Check `app/components/DS/` (`DS::Alert`, `DS::Button`, `DS::Disclosure`, `DS::Dialog`, `DS::Menu`, etc.) before writing an alert, badge, button, disclosure, dialog, or input shape.-3. **Two copies → lift to DS.** Same hand-rolled shape ≥2× in a diff with no DS equivalent → propose a new `DS::*` primitive before the second copy lands.-4. **Conventions.** Use the `icon` helper (never `lucide_icon` directly), no raw SVG outside DS primitives, user-facing strings via `t()`, avoid arbitrary `*-[Npx]` values when a scale token fits.--Reviewers escalate violations of (2)–(3) to close/rewrite; (1) and (4) are request-changes.--## Securities Providers--If you need to add a new securities price provider (Tiingo, EODHD, Binance-style crypto, etc.), see [adding-a-securities-provider.md](./docs/llm-guides/adding-a-securities-provider.md) for the full walkthrough — provider class, registry wiring, MIC handling, settings UI, locales, and tests.--## Debug Logging for Provider Syncs--When a provider sync/import path hits a recoverable error or suspicious partial response that support may need to inspect later, prefer `DebugLogEntry.capture(...)` over `Rails.logger.*`.--- Record support-relevant diagnostics in the debug log so they surface in the super-admin-friendly `/settings/debug` UI.-- Include `category`, `level`, `message`, `source`, `provider_key`, and useful structured `metadata`.-- Attach `family` and `account_provider` when available so support can filter and trace the affected connection.-- Reserve raw Rails logging for low-value local noise; anything operators may need should go to the debug log.--## Providers: Pending Transactions and FX Metadata (SimpleFIN/Plaid/Lunchflow)--- Pending detection- - SimpleFIN: pending when provider sends `pending: true`, or when `posted` is blank/0 and `transacted_at` is present.- - Plaid: pending when Plaid sends `pending: true` (stored at `transaction.extra["plaid"]["pending"]` for bank/credit transactions imported via `PlaidEntry::Processor`).- - Lunchflow: pending when API returns `isPending: true` in transaction response (stored at `transaction.extra["lunchflow"]["pending"]`).-- Storage (extras)- - Provider metadata lives on `Transaction#extra`, namespaced (e.g., `extra["simplefin"]["pending"]`).- - SimpleFIN FX: `extra["simplefin"]["fx_from"]`, `extra["simplefin"]["fx_date"]`.-- UI- - Shows a small “Pending” badge when `transaction.pending?` is true.-- Variability- - Some providers don’t expose pendings; in that case nothing is shown.-- Configuration (default-off)- - SimpleFIN runtime toggles live in `config/initializers/simplefin.rb` via `Rails.configuration.x.simplefin.*`.- - Lunchflow runtime toggles live in `config/initializers/lunchflow.rb` via `Rails.configuration.x.lunchflow.*`.- - ENV-backed keys:- - `SIMPLEFIN_INCLUDE_PENDING=1` (forces `pending=1` on SimpleFIN fetches when caller didn’t specify a `pending:` arg)- - `SIMPLEFIN_DEBUG_RAW=1` (logs raw payload returned by SimpleFIN)- - `LUNCHFLOW_INCLUDE_PENDING=1` (forces `include_pending=true` on Lunchflow API requests)- - `LUNCHFLOW_DEBUG_RAW=1` (logs raw payload returned by Lunchflow)--### Provider support notes--- SimpleFIN: supports pending + FX metadata; stored under `extra["simplefin"]`.-- Plaid: supports pending when the upstream Plaid payload includes `pending: true`; stored under `extra["plaid"]`.-- Plaid investments: investment transactions currently do not store pending metadata.-- Lunchflow: supports pending via `include_pending` query parameter; stored under `extra["lunchflow"]`.-- Manual/CSV imports: no pending concept.+- Read [provider sync guidance](docs/llm-guides/providers.md) when changing imports, pending transactions, FX metadata or diagnostics. Use `DebugLogEntry.capture(...)` for support-relevant failures and partial responses, with provider/source metadata and family/account-provider context where available.+- For securities providers, follow [adding a securities provider](docs/llm-guides/adding-a-securities-provider.md).+- For feature rollout, follow [preview-feature gating](docs/llm-guides/gating-a-preview-feature.md); for goals, read the [Goals guide](docs/llm-guides/goals.md).diff --git a/CLAUDE.md b/CLAUDE.mdindex a1da3b7bb2..43c994c2d3 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,393 +1 @@-# CLAUDE.md--This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.--## Common Development Commands--### Development Server-- `bin/dev` - Start development server (Rails, Sidekiq, Tailwind CSS watcher)-- `bin/rails server` - Start Rails server only-- `bin/rails console` - Open Rails console--### Testing-- `bin/rails test` - Run all tests-- `bin/rails test:db` - Run tests with database reset-- `DISABLE_PARALLELIZATION=true bin/rails test:system` - Run system tests only (use sparingly - they take longer)-- `bin/rails test test/models/account_test.rb` - Run specific test file-- `bin/rails test test/models/account_test.rb:42` - Run specific test at line--#### System Tests in the Dev Container-When running inside the Dev Container, the `SELENIUM_REMOTE_URL` environment variable is automatically set to the bundled `selenium/standalone-chromium` service. System tests will connect to that remote browser — no local Chrome installation is required.--```bash-DISABLE_PARALLELIZATION=true bin/rails test:system-```--To watch the browser live, open `http://localhost:7900` or `http://localhost:4444` in your host browser (password: `secret`).--### Linting & Formatting-- `bin/rubocop` - Run Ruby linter-- `npm run lint` - Check JavaScript/TypeScript code-- `npm run lint:fix` - Fix JavaScript/TypeScript issues-- `npm run format` - Format JavaScript/TypeScript code-- `bin/brakeman` - Run security analysis--### Database-- `bin/rails db:prepare` - Create and migrate database-- `bin/rails db:migrate` - Run pending migrations-- `bin/rails db:rollback` - Rollback last migration-- `bin/rails db:seed` - Load seed data--### Setup-- `bin/setup` - Initial project setup (installs dependencies, prepares database)--## Pre-Pull Request CI Workflow--ALWAYS run these commands before opening a pull request:--1. **Tests** (Required):- - `bin/rails test` - Run all tests (always required)- - `DISABLE_PARALLELIZATION=true bin/rails test:system` - Run system tests (only when applicable, they take longer)--2. **Linting** (Required):- - `bin/rubocop -f github -a` - Ruby linting with auto-correct- - `bundle exec erb_lint ./app/**/*.erb -a` - ERB linting with auto-correct--3. **Security** (Required):- - `bin/brakeman --no-pager` - Security analysis--Only proceed with pull request creation if ALL checks pass.--## General Development Rules--### Authentication Context-- Use `Current.user` for the current user. Do NOT use `current_user`.-- Use `Current.family` for the current family. Do NOT use `current_family`.--### Development Guidelines-- Carefully read project conventions and guidelines before generating any code.-- Do not run `rails server` in your responses-- Do not run `touch tmp/restart.txt`-- Do not run `rails credentials`-- Do not automatically run migrations--## High-Level Architecture--### Application Modes-The codebase runs in two distinct modes:-- **Managed**: A team operates and manages servers for users (Rails.application.config.app_mode = "managed")-- **Self Hosted**: Users host the codebase on their own infrastructure, typically through Docker Compose (Rails.application.config.app_mode = "self_hosted")--### Core Domain Model-The application is built around financial data management with these key relationships:-- **User** → has many **Accounts** → has many **Transactions**-- **Account** types: checking, savings, credit cards, investments, crypto, loans, properties-- **Transaction** → belongs to **Category**, can have **Tags** and **Rules**-- **Investment accounts** → have **Holdings** → track **Securities** via **Trades**--### API Architecture-The application provides both internal and external APIs:-- Internal API: Controllers serve JSON via Turbo for SPA-like interactions-- External API: `/api/v1/` namespace with Doorkeeper OAuth and API key authentication-- API responses use Jbuilder templates for JSON rendering-- Rate limiting via Rack Attack with configurable limits per API key-- **OpenAPI Documentation**: All API endpoints MUST have corresponding OpenAPI specs in `spec/requests/api/` using rswag. See `docs/api/openapi.yaml` for the generated documentation.--### Sync & Import System-Two primary data ingestion methods:-1. **Plaid Integration**: Real-time bank account syncing- - `PlaidItem` manages connections- - `Sync` tracks sync operations- - Background jobs handle data updates-2. **CSV Import**: Manual data import with mapping- - `Import` manages import sessions- - Supports transaction and balance imports- - Custom field mapping with transformation rules--### Provider Integrations: Pending Transactions and FX (SimpleFIN/Plaid)--- Detection- - SimpleFIN: pending via `pending: true` or `posted` blank/0 + `transacted_at`.- - Plaid: pending via Plaid `pending: true` (stored at `extra["plaid"]["pending"]` for bank/credit transactions imported via `PlaidEntry::Processor`).-- Storage: provider data on `Transaction#extra` (e.g., `extra["simplefin"]["pending"]`; FX uses `fx_from`, `fx_date`).-- UI: "Pending" badge when `transaction.pending?` is true; no badge if provider omits pendings.-- Configuration (default-on for pending)- - SimpleFIN: `config/initializers/simplefin.rb` via `Rails.configuration.x.simplefin.*`.- - Plaid: `config/initializers/plaid_config.rb` via `Rails.configuration.x.plaid.*`.- - Pending transactions are fetched by default and handled via reconciliation/filtering.- - Set `SIMPLEFIN_INCLUDE_PENDING=0` to disable pending fetching for SimpleFIN.- - Set `PLAID_INCLUDE_PENDING=0` to disable pending fetching for Plaid.- - Set `SIMPLEFIN_DEBUG_RAW=1` to enable raw payload debug logging.- - Set `UP_DEBUG_RAW=1` to enable raw Up payload debug logging. DEV-ONLY: the dump contains PII and is gated to local environments, so it never logs in managed/production.--Provider support notes:-- SimpleFIN: supports pending + FX metadata (stored under `extra["simplefin"]`).-- Plaid: supports pending when the upstream Plaid payload includes `pending: true` (stored under `extra["plaid"]`).-- Plaid investments: investment transactions currently do not store pending metadata.-- Lunchflow: does not currently store pending metadata.--### Background Processing-Sidekiq handles asynchronous tasks:-- Account syncing (`SyncJob`)-- Import processing (`ImportJob`)-- AI chat responses (`AssistantResponseJob`)-- Scheduled maintenance via sidekiq-cron--### Debug Logging for Provider Syncs-- Prefer `DebugLogEntry.capture(...)` over `Rails.logger.*` for provider sync/import failures, partial responses, and other support-relevant diagnostics.-- Record support-relevant incidents in the super-admin `/settings/debug` UI rather than leaving them only in raw application logs.-- Include `category`, `level`, `message`, `source`, `provider_key`, and structured `metadata`.-- Attach `family` and `account_provider` whenever possible so support can filter to the affected provider connection.--### Frontend Architecture-- **Hotwire Stack**: Turbo + Stimulus for reactive UI without heavy JavaScript-- **ViewComponents**: Reusable UI components in `app/components/`-- **Stimulus Controllers**: Handle interactivity, organized alongside components-- **Charts**: D3.js for financial visualizations (time series, donut, sankey)-- **Styling**: Tailwind CSS v4.x with custom design system- - Design system defined in `app/assets/tailwind/sure-design-system.css`- - Always use functional tokens (e.g., `text-primary` not `text-white`)- - Prefer semantic HTML elements over JS components- - Use `icon` helper for icons, never `lucide_icon` directly-- **i18n**: All user-facing strings must use localization (i18n). Update locale files for each new or changed element.--### Internationalization (i18n) Guidelines-- **Key Organization**: Use hierarchical keys by feature: `accounts.index.title`, `transactions.form.amount_label`-- **Translation Helper**: Always use `t()` helper for user-facing strings-- **Interpolation**: Use for dynamic content: `t("users.greeting", name: user.name)`-- **Pluralization**: Use Rails pluralization: `t("transactions.count", count: @transactions.count)`-- **Locale Files**: Update `config/locales/en.yml` for new strings-- **Missing Translations**: Configure to raise errors in development for missing keys--### Multi-Currency Support-- All monetary values stored in base currency (user's primary currency)-- `Money` objects handle currency conversion and formatting-- Historical exchange rates for accurate reporting--### Security & Authentication-- Session-based auth for web users-- API authentication via:- - OAuth2 (Doorkeeper) for third-party apps- - API keys with JWT tokens for direct API access-- Scoped permissions system for API access-- Strong parameters and CSRF protection throughout--### Testing Philosophy-- Comprehensive test coverage using Rails' built-in Minitest-- Fixtures for test data (avoid FactoryBot)-- Keep fixtures minimal (2-3 per model for base cases)-- VCR for external API testing-- System tests for critical user flows (use sparingly)-- Test helpers in `test/support/` for common scenarios-- Only test critical code paths that significantly increase confidence-- Write tests as you go, when required-- **API Endpoints require OpenAPI specs** in `spec/requests/api/` for documentation purposes ONLY, not test (uses RSpec + rswag)--### Performance Considerations-- Database queries optimized with proper indexes-- N+1 queries prevented via includes/joins-- Background jobs for heavy operations-- Caching strategies for expensive calculations-- Turbo Frames for partial page updates--### Development Workflow-- Feature branches merged to `main`-- Docker support for consistent environments-- Environment variables via `.env` files-- Lookbook for component development (`/lookbook`)-- Letter Opener for email preview in development--## Project Conventions--### Convention 1: Minimize Dependencies-- Push Rails to its limits before adding new dependencies-- Strong technical/business reason required for new dependencies-- Favor old and reliable over new and flashy--### Convention 2: Skinny Controllers, Fat Models-- Business logic in `app/models/` folder, avoid `app/services/`-- Use Rails concerns and POROs for organization-- Models should answer questions about themselves: `account.balance_series` not `AccountSeries.new(account).call`--### Convention 3: Hotwire-First Frontend-- **Native HTML preferred over JS components**- - Use `<dialog>` for modals, `<details><summary>` for disclosures-- **Leverage Turbo frames** for page sections over client-side solutions-- **Query params for state** over localStorage/sessions-- **Server-side formatting** for currencies, numbers, dates-- **Always use `icon` helper** in `application_helper.rb`, NEVER `lucide_icon` directly--### Convention 4: Optimize for Simplicity-- Prioritize good OOP domain design over performance-- Focus performance only on critical/global areas (avoid N+1 queries, mindful of global layouts)--### Convention 5: Database vs ActiveRecord Validations-- Simple validations (null checks, unique indexes) in DB-- ActiveRecord validations for convenience in forms (prefer client-side when possible)-- Complex validations and business logic in ActiveRecord--## TailwindCSS Design System--### Design System Rules-- **Always reference `app/assets/tailwind/sure-design-system.css`** for primitives and tokens-- **Use functional tokens** defined in design system:- - `text-primary` instead of `text-white`- - `bg-container` instead of `bg-white`- - `border border-primary` instead of `border border-gray-200`-- **NEVER create new styles** in design system files without permission-- **Always generate semantic HTML**--## Component Architecture--### ViewComponent vs Partials Decision Making--**Use ViewComponents when:**-- Element has complex logic or styling patterns-- Element will be reused across multiple views/contexts-- Element needs structured styling with variants/sizes-- Element requires interactive behavior or Stimulus controllers-- Element has configurable slots or complex APIs-- Element needs accessibility features or ARIA support--**Use Partials when:**-- Element is primarily static HTML with minimal logic-- Element is used in only one or few specific contexts-- Element is simple template content-- Element doesn't need variants, sizes, or complex configuration-- Element is more about content organization than reusable functionality--**Component Guidelines:**-- Prefer components over partials when available-- Keep domain logic OUT of view templates-- Logic belongs in component files, not template files--### Stimulus Controller Guidelines--**Declarative Actions (Required):**-```erb-<!-- GOOD: Declarative - HTML declares what happens -->-<div data-controller="toggle">- <button data-action="click->toggle#toggle" data-toggle-target="button">- <%= t("components.transaction_details.show_details") %>- </button>- <div data-toggle-target="content" class="hidden">- <p><%= t("components.transaction_details.amount_label") %>: <%= @transaction.amount %></p>- <p><%= t("components.transaction_details.date_label") %>: <%= @transaction.date %></p>- <p><%= t("components.transaction_details.category_label") %>: <%= @transaction.category.name %></p>- </div>-</div>-```--**Example locale file structure (config/locales/en.yml):**-```yaml-en:- components:- transaction_details:- show_details: "Show Details"- hide_details: "Hide Details"- amount_label: "Amount"- date_label: "Date"- category_label: "Category"-```--**i18n Best Practices:**-- Organize keys by feature/component: `components.transaction_details.show_details`-- Use descriptive key names that indicate purpose: `show_details` not `button`-- Group related translations together in the same namespace-- Use interpolation for dynamic content: `t("users.welcome", name: user.name)`-- Always update locale files when adding new user-facing strings--**Controller Best Practices:**-- Keep controllers lightweight and simple (< 7 targets)-- Use private methods and expose clear public API-- Single responsibility or highly related responsibilities-- Component controllers stay in component directory, global controllers in `app/javascript/controllers/`-- Pass data via `data-*-value` attributes, not inline JavaScript--## Testing Philosophy--### General Testing Rules-- **ALWAYS use Minitest + fixtures** (NEVER RSpec or factories)-- Keep fixtures minimal (2-3 per model for base cases)-- Create edge cases on-the-fly within test context-- Use Rails helpers for large fixture creation needs--### Test Quality Guidelines-- **Write minimal, effective tests** - system tests sparingly-- **Only test critical and important code paths**-- **Test boundaries correctly:**- - Commands: test they were called with correct params- - Queries: test output- - Don't test implementation details of other classes--### Testing Examples--```ruby-# GOOD - Testing critical domain business logic-test "syncs balances" do- Holding::Syncer.any_instance.expects(:sync_holdings).returns([]).once- assert_difference "@account.balances.count", 2 do- Balance::Syncer.new(@account, strategy: :forward).sync_balances- end-end--# BAD - Testing ActiveRecord functionality-test "saves balance" do- balance_record = Balance.new(balance: 100, currency: "USD")- assert balance_record.save-end-```--### Stubs and Mocks-- Use `mocha` gem-- Prefer `OpenStruct` for mock instances-- Only mock what's necessary--## API Development Guidelines--### OpenAPI Documentation (MANDATORY)-When adding or modifying API endpoints in `app/controllers/api/v1/`, you **MUST** create or update corresponding OpenAPI request specs:--1. **Location**: `spec/requests/api/v1/{resource}_spec.rb`-2. **Framework**: RSpec with rswag for OpenAPI generation-3. **Schemas**: Define reusable schemas in `spec/swagger_helper.rb`-4. **Generated Docs**: `docs/api/openapi.yaml`--**Example structure for a new API endpoint:**-```ruby-# spec/requests/api/v1/widgets_spec.rb-require 'swagger_helper'--RSpec.describe 'API V1 Widgets', type: :request do- path '/api/v1/widgets' do- get 'List widgets' do- tags 'Widgets'- security [ { apiKeyAuth: [] } ]- produces 'application/json'-- response '200', 'widgets listed' do- schema '$ref' => '#/components/schemas/WidgetCollection'- run_test!- end- end- end-end-```--**Regenerate OpenAPI docs after changes:**-```bash-RAILS_ENV=test bundle exec rake rswag:specs:swaggerize-```--### Post-commit API consistency (issue #944)-After every API endpoint commit, ensure:--1. **Minitest behavioral coverage** — Add or update tests in `test/controllers/api/v1/{resource}_controller_test.rb`. Use API key and `api_headers` (X-Api-Key). Cover index/show, CRUD where relevant, 401/403/422/404. Do not rely on rswag for behavioral assertions.--2. **rswag docs-only** — Do not add `expect(...)` or `assert_*` in `spec/requests/api/v1/`. Use `run_test!` only so specs document request/response and regenerate `docs/api/openapi.yaml`.--3. **Same API key auth in rswag** — Every request spec in `spec/requests/api/v1/` must use the same API key pattern (`ApiKey.generate_secure_key`, `ApiKey.create!(...)`, `let(:'X-Api-Key') { api_key.plain_key }`). Do not use Doorkeeper/OAuth in those specs so generated docs stay consistent.--Full checklist and pattern: [.cursor/rules/api-endpoint-consistency.mdc](.cursor/rules/api-endpoint-consistency.mdc).--To verify the implementation: `ruby test/support/verify_api_endpoint_consistency.rb`. To scan the current APIs for violations: `ruby test/support/verify_api_endpoint_consistency.rb --compliance`.\ No newline at end of filediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex a97e19f33e..90a80c9853 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -4,8 +4,8 @@ It means so much that you're interested in contributing to Sure! Seriously. Than## House Rules-- Before contributing, familiarize yourself with our project conventions. You should read through our [Project Conventions Rule](https://github.com/we-promise/sure/blob/main/.cursor/rules/project-conventions.mdc), which is intended for LLMs, but is also an excellent primer on how we write code for Sure.-- While totally optional, consider using Cursor + VSCode as it will automatically apply our project conventions to your code via the `.cursor/rules` directory.+- Before contributing, read the [repository guidance](AGENTS.md) and [architecture and conventions](docs/llm-guides/architecture.md). Detailed [task guides](docs/llm-guides/README.md) cover testing, UI, APIs and providers.+- Coding-assistant setup is optional; see the [supported instruction adapters](docs/llm-guides/harness-adapters.md).- Before contributing, please check if it already exists in [issues](https://github.com/we-promise/sure/issues) or [PRs](https://github.com/we-promise/sure/pulls)- Given the speed at which we're moving on the codebase, we don't assign issues or "give" issues to anyone.- When multiple PRs are submitted for the same issue, we take the one that most succinctly & efficiently solves a given problem and stays within the scope of work.diff --git a/app/models/provider/simplefin.rb b/app/models/provider/simplefin.rbindex 39a0d88988..786a933e04 100644--- a/app/models/provider/simplefin.rb+++ b/app/models/provider/simplefin.rb@@ -1,9 +1,10 @@class Provider::Simplefin# Pending: some institutions do not return pending transactions even with `pending=1`.- # This is provider variability (not a bug). For troubleshooting, you can set- # `SIMPLEFIN_INCLUDE_PENDING=1` and/or `SIMPLEFIN_DEBUG_RAW=1` (both default-off).- # These are centralized in `Rails.configuration.x.simplefin.*` via- # `config/initializers/simplefin.rb`.+ # This is provider variability (not a bug). The importer resolves pending inclusion+ # from its explicit argument, SIMPLEFIN_INCLUDE_PENDING, or Setting.syncs_include_pending+ # (default-on without overrides), then passes pending: to this client.+ # SIMPLEFIN_DEBUG_RAW=1 enables raw payload logging (default-off); environment+ # configuration lives in config/initializers/simplefin.rb.include HTTPartyextend SslConfigurablediff --git a/docs/llm-guides/README.md b/docs/llm-guides/README.mdnew file mode 100644index 0000000000..9c234e72e1--- /dev/null+++ b/docs/llm-guides/README.md@@ -0,0 +1,32 @@+# Development guides++Start with [repository guidance](../../AGENTS.md), then read the guide for the work+being changed. These guides hold the detailed conventions and procedures.++| Task | Guide |+| --- | --- |+| Understand the domain and write Rails code | [Architecture and conventions](architecture.md) |+| Set up an environment, run checks or prepare a PR | [Development and verification](development.md) |+| Write behavioral tests and fixtures | [Testing](testing.md) |+| Change design tokens or `DS::*` primitives | [Design system](design-system.md) |+| Change views, components, CSS, Stimulus or localization | [UI](ui.md) |+| Add or modify an API v1 endpoint | [API endpoint consistency](api-endpoint-consistency.md) |+| Change provider imports, pending/FX metadata or diagnostics | [Provider sync guidance](providers.md) |+| Add a securities price provider | [Provider walkthrough](adding-a-securities-provider.md) |+| Gate or release a preview feature | [Preview-feature gating](gating-a-preview-feature.md) |+| Change goals, pledges or reconciliation | [Goals](goals.md) |++## External wealth integration++[Wealth history with an external agent harness](wealth-agent-harness.md) describes+Sure's read-only tool interface and the boundary with an external wealth system.+The [wealth blueprint](wealth-blueprint.md) is reference architecture for that+separate system. Its working-memory files, private document vault and operating+protocol apply to that external project, not to every change in this repository.++## Instruction maintenance++[Harness adapters](harness-adapters.md) documents discovery, supported imports,+scoped loading and legacy helpers. The [preservation map](instruction-preservation-map.md)+records the inventory, history, dispositions and intentional policy decisions for+the consolidation; it is an audit record rather than additional coding policy.diff --git a/docs/llm-guides/api-endpoint-consistency.md b/docs/llm-guides/api-endpoint-consistency.mdnew file mode 100644index 0000000000..9742c8f3bf--- /dev/null+++ b/docs/llm-guides/api-endpoint-consistency.md@@ -0,0 +1,56 @@+# API endpoint consistency (post-commit checklist)++When adding or modifying API v1 endpoints, follow this checklist after every API endpoint commit so behavior, docs, and auth stay consistent. Runtime endpoints also support OAuth; the API-key-only requirement below applies to the behavioral test and documentation patterns.++## 1. Minitest behavioral coverage++- **Location**: `test/controllers/api/v1/{resource}_controller_test.rb`+- **Scope**: All new or changed actions must have Minitest coverage here. Do not rely on rswag specs for behavioral assertions.+- **Pattern**:+ - Use `ApiKey.create!` (read and read_write scopes) and `api_headers(api_key)` → `{ "X-Api-Key" => api_key.display_key }`. Do not use OAuth/Bearer in these tests.+ - Cover: index/show (and create/update/destroy for write endpoints), read-only key blocking writes (403), invalid params (422), invalid date (422), not found (404), missing auth (401).+ - Follow existing API v1 test style: see [valuations_controller_test.rb](../../test/controllers/api/v1/valuations_controller_test.rb) and [transactions_controller_test.rb](../../test/controllers/api/v1/transactions_controller_test.rb).++## 2. rswag is docs-only++- **Location**: `spec/requests/api/v1/{resource}_spec.rb`+- **Rule**: These specs exist only for OpenAPI generation. Do not add `expect(...)` or `assert_*` (or any behavioral assertions). Use `run_test!` without custom assertion blocks so the spec only documents request/response and regenerates `docs/api/openapi.yaml`.+- **Regenerate**: After edits, run `RAILS_ENV=test bundle exec rake rswag:specs:swaggerize`.++## 3. Same API key auth in all rswag specs++- **Rule**: Every request spec in `spec/requests/api/v1/` must use the same API key auth pattern so generated docs are consistent.+- **Pattern** (match holdings_spec, trades_spec, transactions_spec, etc.):++ ```ruby+ let(:api_key) do+ key = ApiKey.generate_secure_key+ ApiKey.create!(+ user: user,+ name: 'API Docs Key',+ key: key,+ scopes: %w[read_write],+ source: 'web'+ )+ end++ let(:'X-Api-Key') { api_key.plain_key }+ ```++- Do not use Doorkeeper/OAuth in these specs (no `Doorkeeper::Application`, `Doorkeeper::AccessToken`, or `Authorization: "Bearer ..."`). Use API key only.++## OpenAPI schemas and verification++Adding or modifying an API endpoint requires corresponding documentation specs.+Define reusable schemas in [`spec/swagger_helper.rb`](../../spec/swagger_helper.rb).+Generated documentation lives in [`docs/api/openapi.yaml`](../api/openapi.yaml).++Verify the guidance without booting Rails:++```sh+ruby test/support/verify_api_endpoint_consistency.rb+ruby test/support/verify_api_endpoint_consistency.rb --compliance+```++The second command reports existing API compliance issues; its inventory is not a+replacement for running the behavioral tests or regenerating OpenAPI documentation.diff --git a/docs/llm-guides/architecture.md b/docs/llm-guides/architecture.mdnew file mode 100644index 0000000000..e2c82188b8--- /dev/null+++ b/docs/llm-guides/architecture.md@@ -0,0 +1,144 @@+# Architecture and development conventions++Read the relevant models and [schema](../../db/schema.rb) before changing domain+behavior. The application supports `managed` and `self_hosted` modes through+`Rails.application.config.app_mode`; see [application configuration](../../config/application.rb).+Provider availability can differ between installations.++## Design conventions++- Push built-in Rails functionality before adding dependencies. A new dependency+ needs a strong technical or business reason; favor established, reliable tools.+- Keep controllers thin and business logic in `app/models/`, organized with POROs+ and concerns rather than introducing service-object directories. A concern may+ serve one model, but organize it around a model trait rather than merely moving+ code elsewhere. Prefer `account.balance_series` to `AccountSeries.new(account).call`.+- Optimize for clear object design and readability. Focus performance work on+ critical paths and shared surfaces: avoid N+1 queries and loading large payloads+ in global layouts; use indexes, eager loading, background jobs and caching where+ they address a real cost.+- Put simple constraints such as null checks and uniqueness in the database.+ ActiveRecord may mirror them for form error handling; prefer client-side form+ validation where possible. Keep complex validation and business logic in Ruby.+- Use semantic HTML and Hotwire, server-side formatting and URL state. Detailed+ component, Turbo, Stimulus and design-system rules are in [UI guidance](ui.md).++## Families, users and currencies++[Family](../../app/models/family.rb) owns financial accounts, users, subscriptions+and many preferences. [User](../../app/models/user.rb) belongs to a family;+[Session](../../app/models/session.rb) belongs to a user. Roles include guest,+member, admin and super admin. Accounts also have an optional user owner and+sharing rules, so family membership alone does not describe every user's access.+Use [Current.user and Current.family](../../app/models/current.rb), and the existing+account-access scopes for the surface being changed.++An [Account](../../app/models/account.rb) has its own balance and currency.+[Entries](../../app/models/entry.rb), [balances](../../app/models/balance.rb) and+[holdings](../../app/models/holding.rb) also retain currencies. The family's+preferred currency is used to normalize reports; it does not mean every stored+amount is already in that currency. [Money](../../lib/money.rb) handles monetary+operations and formatting, with [ExchangeRate](../../app/models/exchange_rate.rb)+and its [Provided concern](../../app/models/exchange_rate/provided.rb) supplying+dated conversion rates.++## Accounts, balances and entries++Account uses a delegated `accountable` type. The supported types are defined in+[Accountable](../../app/models/concerns/accountable.rb): asset types `Depository`,+`Investment`, `Crypto`, `Property`, `Vehicle`, `OtherAsset`; liability types+`CreditCard`, `Loan`, `OtherLiability`.++A daily balance records what an asset is worth or what is owed on a liability.+For a depository account this is cash; for an investment account it includes cash+and holdings value. A holding records an account's quantity and price of a+[Security](../../app/models/security.rb) on a date. [Balance::Materializer](../../app/models/balance/materializer.rb)+materializes holdings through [Holding::Materializer](../../app/models/holding/materializer.rb)+before calculating balance history.++Entry delegates to one of the three [Entryable types](../../app/models/entryable.rb),+with a date, amount and currency:++- [Valuation](../../app/models/valuation.rb) is an absolute account value or debt+ at a date, not an income or expense.+- [Transaction](../../app/models/transaction.rb) changes the account balance and+ can have a category, merchant and tags; rules can enrich or classify it.+- [Trade](../../app/models/trade.rb) represents a security movement with quantity+ and price, including buys and sells.++For cash movements, **negative entry amounts are inflows; positive amounts are+outflows**. A negative checking transaction increases cash; a negative credit-card+transaction is a payment that reduces debt. A sale's negative entry amount+increases investment-account cash. Do not apply movement signs to an absolute+valuation or confuse cash direction with asset/liability balance direction.++## Transfers++[Transfer](../../app/models/transfer.rb) pairs an inflow and outflow transaction+between different accounts in the same family. Same-currency amounts must be equal+and opposite. [Family::AutoTransferMatchable](../../app/models/family/auto_transfer_matchable.rb)+normally searches a four-day window and also supports cross-currency candidates+using dated exchange rates and a tolerance. Confirmed transfers permit a+thirty-day date difference; do not assume every transfer is a same-currency,+four-day match.++The destination determines the outflow's kind: loan payment, credit-card payment,+investment contribution or ordinary funds movement. In [Transaction's budget+classification](../../app/models/transaction.rb), funds movement and credit-card+payments are excluded, while loan payments and investment contributions count as+expenses. Preserve these distinctions rather than treating every transfer as+excluded from income/expense reporting.++## Ingestion and background work++Provider connections such as [PlaidItem](../../app/models/plaid_item.rb) hold+connection metadata and provider account payloads; processors normalize them into+internal accounts and entries through [Account::ProviderImportAdapter](../../app/models/account/provider_import_adapter.rb).+[AccountProvider](../../app/models/account_provider.rb) connects accounts to+provider records. [Import](../../app/models/import.rb) supports manual import+sessions, including CSV mapping and transformations. Plaid is one of many supported+provider integrations.++[Syncable](../../app/models/concerns/syncable.rb) schedules background syncs and+[Sync](../../app/models/sync.rb) records their state, hierarchy and errors.+[Account::Syncer](../../app/models/account/syncer.rb) imports market data,+materializes history (reverse for linked accounts, forward for manual accounts),+applies provider balance overrides and matches transfers after sync.+[Family::Syncer](../../app/models/family/syncer.rb) schedules all eligible Syncable+`*_items` associations plus manual accounts, then matches transfers and applies+active rules. Entry-changing workflows call `Entry#sync_account_later`; inspect+the calling workflow rather than assuming every save schedules a full sync.++[AutoSync](../../app/controllers/concerns/auto_sync.rb) can request a family sync+on login once per date when the family enables it and has active accounts.+[AutoSyncScheduler](../../app/services/auto_sync_scheduler.rb) and the+[Sidekiq schedule](../../config/schedule.yml) handle scheduled work. Sidekiq also+runs [SyncJob](../../app/jobs/sync_job.rb), [ImportJob](../../app/jobs/import_job.rb)+and [AssistantResponseJob](../../app/jobs/assistant_response_job.rb).++## Provider interfaces and APIs++Interchangeable provider concepts are registered at runtime through+[Provider::Registry](../../app/models/provider/registry.rb) and+[Setting](../../app/models/setting.rb), with environment overrides where supported.+Interfaces live in `app/models/provider/*_concept.rb`, including+[SecurityConcept](../../app/models/provider/security_concept.rb) and+[ExchangeRateConcept](../../app/models/provider/exchange_rate_concept.rb).+One-off integrations can expose concrete methods without inventing a shared+concept. Domain models should normally select providers through their `Provided`+concerns rather than calling the registry throughout business logic.++Concept providers inherit from [Provider](../../app/models/provider.rb) and use+`with_provider_response` to return `Provider::Response` (`success?`, `data`,+`error`). Raise when valid data cannot be produced inside that wrapper; it+converts failures into the response contract. See [provider guidance](providers.md)+and [adding a securities provider](adding-a-securities-provider.md) for details.++Web interaction uses Turbo/Stimulus with server-rendered views. External+`/api/v1` endpoints support separate Doorkeeper OAuth and `X-Api-Key`+authentication; API keys are opaque keys, not JWTs. The [API base controller](../../app/controllers/api/v1/base_controller.rb)+sets current context, skips session CSRF checks and applies API-key rate limits.+Preserve the existing authentication, scope and strong-parameter behavior. Follow+the [API consistency guide](api-endpoint-consistency.md) for behavioral tests and+documentation-only rswag specs; its API-key convention does not remove runtime+OAuth support.diff --git a/docs/llm-guides/design-system.md b/docs/llm-guides/design-system.mdnew file mode 100644index 0000000000..4548f3f78c--- /dev/null+++ b/docs/llm-guides/design-system.md@@ -0,0 +1,22 @@+# Design system++Consult [`app/assets/tailwind/sure-design-system.css`](../../app/assets/tailwind/sure-design-system.css)+and existing [`DS::*` components](../../app/components/DS/) before building UI.++- Use functional tokens: `text-primary`, `bg-container`, `border-primary`,+ `bg-warning/10`, `text-destructive`. Do not use raw palette classes or hex literals.+- Reach for `DS::Alert`, `DS::Button`, `DS::Disclosure`, `DS::Dialog`, `DS::Menu`+ and other existing primitives before making an alert, badge, button, disclosure,+ dialog or input shape.+- If a diff contains the same hand-built shape at least twice and no DS equivalent+ exists, propose a new DS primitive before introducing the second copy.+- Use the `icon` helper from [`ApplicationHelper`](../../app/helpers/application_helper.rb),+ never `lucide_icon` directly. Raw SVG belongs only inside DS primitives.+- Use scale tokens rather than arbitrary pixel values when a scale token fits.+- Do not add new styles to `sure-design-system.css` or+ [`application.css`](../../app/assets/tailwind/application.css) without explicit permission.+- Reviewers escalate DS reuse and repeated-shape violations to close/rewrite.+ Token, icon/SVG, localization and scale violations are request-changes.++For templates, Hotwire, Stimulus and localization guidance, see the+[UI guide](ui.md).diff --git a/docs/llm-guides/development.md b/docs/llm-guides/development.mdnew file mode 100644index 0000000000..642bb40adb--- /dev/null+++ b/docs/llm-guides/development.md@@ -0,0 +1,67 @@+# Development and verification++## Environment and commands++Use the Ruby version in [`.ruby-version`](../../.ruby-version) and dependencies in+[`Gemfile`](../../Gemfile) / [`package.json`](../../package.json).+[CONTRIBUTING.md](../../CONTRIBUTING.md) describes local and devcontainer setup.+Start environment configuration from [`.env.local.example`](../../.env.local.example)+and [`.env.test.example`](../../.env.test.example); never commit secrets or local credentials.++These are command references, not permission to start servers, restart the app,+edit credentials or automatically migrate a database. Run setup/database operations+only when that environment work has been explicitly requested. In particular,+`bin/setup` prepares the database and restarts the app; it is not a read-only check.++| Task | Command |+| --- | --- |+| Initial setup | `cp .env.local.example .env.local` (only if the file does not exist), then `bin/setup` |+| Development processes | `bin/dev` (Rails, Sidekiq, Tailwind watcher) |+| Rails console | `bin/rails console` |+| Database preparation / migration | `bin/rails db:prepare` / `bin/rails db:migrate` |+| Database rollback / seed | `bin/rails db:rollback` / `bin/rails db:seed` |+| Full behavioral suite | `bin/rails test` |+| One file / test at a line | `bin/rails test test/models/account_test.rb` / `bin/rails test test/models/account_test.rb:42` |+| Reset test database and test | `bin/rails test:db` (database-changing task) |+| System tests | `DISABLE_PARALLELIZATION=true bin/rails test:system` |+| Ruby lint | `bin/rubocop` |+| Safe Ruby autocorrection | `bin/rubocop -a` (`-A` also enables unsafe corrections) |+| JavaScript/TypeScript lint / fix | `npm run lint` / `npm run lint:fix` |+| Biome formatting check / fix | `npm run format:check` / `npm run format` |+| Security analysis | `bin/brakeman --no-pager` |++Lookbook is mounted at `/design-system` outside production; see+[`config/routes.rb`](../../config/routes.rb). Letter Opener supports development+email previews. Use Docker/devcontainers where useful for consistent environments.++## Before opening a pull request++Run these checks locally before **every** PR. All required checks must pass before+PR creation; the full suite is also required to be green before pushing.++1. `bin/rails test` — the full Minitest suite is always required.+2. `DISABLE_PARALLELIZATION=true bin/rails test:system` — required when system tests+ are applicable to the change; keep system-test additions focused on critical flows.+3. `bin/rubocop -f github -a` — Ruby lint with safe autocorrection.+4. `bundle exec erb_lint ./app/**/*.erb -a` — ERB lint with autocorrection.+5. `npm run lint` — keep Biome clean. Use `npm run format:check` for formatting+ changes and `npm run format` when corrections are needed.+6. `bin/brakeman --no-pager` — security analysis for every PR.++Inspect autocorrections before committing; keep the diff focused. Record checks+and any failures accurately. Focused tests help during development but do not+replace the required full pre-PR suite.++CI has its own executable definition in [`.github/workflows/ci.yml`](../../.github/workflows/ci.yml)+and callers. Its unit and system jobs are separate; CI runs system tests even though+the local checklist makes them conditional on applicability. Local ERB lint is an+existing additional requirement. Passing local checks does not replace the+[contributor requirement](../../CONTRIBUTING.md#making-a-pull-request) for green+GitHub checks and an up-to-date branch before requesting review.++## System tests in a devcontainer++The [devcontainer configuration](../../.devcontainer/docker-compose.yml) includes+Selenium Chromium and sets `SELENIUM_REMOTE_URL`; no local Chrome is needed there.+Run `DISABLE_PARALLELIZATION=true bin/rails test:system`. Watch the browser at+`http://localhost:7900` or `http://localhost:4444` (development password: `secret`).diff --git a/docs/llm-guides/harness-adapters.md b/docs/llm-guides/harness-adapters.mdnew file mode 100644index 0000000000..3481c20b7b--- /dev/null+++ b/docs/llm-guides/harness-adapters.md@@ -0,0 +1,123 @@+# Instruction adapters and maintenance++[AGENTS.md](../../AGENTS.md) contains the shared repository requirements and links+to detailed guides. Harness entry points load or direct readers to that guidance.+The [preservation map](instruction-preservation-map.md) records the sources,+history and intentional policy decisions behind this structure.++## Supported entry points++| Harness | Repository entry point | Loading behavior |+| --- | --- | --- |+| AGENTS-compatible tools | [AGENTS.md](../../AGENTS.md) | Read the root instructions and applicable linked guides. |+| Claude Code | [CLAUDE.md](../../CLAUDE.md) | Native `@AGENTS.md` import loads the canonical file at session start. |+| Cursor | [AGENTS.md](../../AGENTS.md), [project rules](../../.cursor/rules/) | Root guidance is supported natively; retained `.mdc` rules include shared guides with `@` references and preserve their existing applicability. |+| GitHub Copilot | [copilot-instructions.md](../../.github/copilot-instructions.md) | Repository-wide instructions explicitly direct the agent to read AGENTS and its applicable guides. |+| Junie | [AGENTS.md](../../AGENTS.md), [legacy guidelines](../../.junie/guidelines.md) | Current Junie discovers root AGENTS; the legacy entry point directs older clients to the same guidance. |+| Gemini Code Assist on GitHub | [config.yaml](../../.gemini/config.yaml) | Existing review configuration is retained unchanged; this is configuration, not an instruction adapter. |++Claude documents `@AGENTS.md` as an import from `CLAUDE.md`. Relative imports+resolve from the importing file. Using the import keeps both files ordinary text+files, including on Windows. [Claude Code memory documentation](https://code.claude.com/docs/en/memory#agentsmd)++Cursor supports root and nested `AGENTS.md` files. Project rules require the+`.mdc` extension, frontmatter and `@` file references to include shared content.+The adapters below use repository-root paths. [Cursor rules documentation](https://cursor.com/docs/rules)++Copilot's support for agent instruction files varies across GitHub, CLI and IDE+features. Keep its repository-wide entry point rather than relying on universal+`AGENTS.md` discovery. Its explicit read/follow link is an instruction to the+agent, not a claim that every Copilot surface automatically expands Markdown+links. Copilot CLI separately supports `@` relative-file imports in+`copilot-instructions.md`, `AGENTS.md` and `CLAUDE.md`.+[Copilot support matrix](https://docs.github.com/en/copilot/reference/custom-instructions-support),+[Copilot CLI instruction imports](https://docs.github.com/en/copilot/how-tos/copilot-cli/customize-copilot/add-custom-instructions)++Current Junie checks `.junie/AGENTS.md` first, then root `AGENTS.md`, then the+legacy `.junie/guidelines.md` or guidelines directory. Do not introduce a separate+`.junie/AGENTS.md` copy: it would take precedence over the shared root file. The+legacy adapter uses an explicit read/follow link rather than an undocumented+import directive. [Junie guidelines and memory](https://junie.jetbrains.com/docs/guidelines-and-memory.html)++Gemini Code Assist's `.gemini/config.yaml` controls GitHub review behavior. Its+`code_review.disable: true`, summary settings, severity threshold and ignore+patterns are preserved. Code Assist supports `.gemini/styleguide.md` for review+instructions, but this repository has no such file and this consolidation does+not add one. [Gemini Code Assist repository configuration](https://docs.cloud.google.com/gemini/docs/code-review/customize-repo-review)++Gemini CLI is a separate integration: it uses `GEMINI.md`, supports `@` imports,+and can change context filenames through `context.fileName` in `settings.json`.+There is no tracked Gemini CLI context configuration here; the review YAML does+not configure it. [Gemini CLI context documentation](https://geminicli.com/docs/cli/gemini-md/)++## Cursor applicability retained++These are the existing frontmatter values. `alwaysApply: true` retains global+loading even where a rule also lists globs. Empty description and globs on the+Stimulus rule preserve manual availability; adding either could change discovery.++| Rule | Shared content | `globs` | `alwaysApply` |+| --- | --- | --- | --- |+| [general-rules.mdc](../../.cursor/rules/general-rules.mdc) | [AGENTS.md](../../AGENTS.md) | `*` | `true` |+| [project-design.mdc](../../.cursor/rules/project-design.mdc) | [Architecture](architecture.md) | `*` | `true` |+| [testing.mdc](../../.cursor/rules/testing.mdc) | [Testing](testing.md) | `test/**` | `false` |+| [view_conventions.mdc](../../.cursor/rules/view_conventions.mdc) | [UI](ui.md) | `app/views/**,app/javascript/**,app/components/**/*.js` | `false` |+| [stimulus_conventions.mdc](../../.cursor/rules/stimulus_conventions.mdc) | [UI](ui.md) | empty | `false` |+| [ui-ux-design-guidelines.mdc](../../.cursor/rules/ui-ux-design-guidelines.mdc) | [Design system](design-system.md) | `app/views/**,app/helpers/**,app/javascript/controllers/**` | `true` |+| [api-endpoint-consistency.mdc](../../.cursor/rules/api-endpoint-consistency.mdc) | [API endpoint consistency](api-endpoint-consistency.md) | `app/controllers/api/v1/**/*.rb, spec/requests/api/v1/**/*.rb, test/controllers/api/v1/**/*.rb` | `false` |++The former `project-conventions.mdc` content now lives with architecture guidance;+the always-on architecture adapter keeps those conventions available. The generic+`cursor_rules.mdc` template and automatic `self_improve.mdc` rule-generation+trigger are retired, as recorded in the preservation map.++## Maintaining guidance++- Put common requirements in AGENTS and detailed explanations, examples and+ procedures in the appropriate shared guide. Keep adapters limited to loading+ and routing guidance.+- Update guidance when code, a workflow or a reviewed requirement changes.+ Verify examples against current files; keep links accurate and remove resolved+ temporary advice with an explanation in the change description.+- Review parallel entry points before changing a rule. Record intentional changes+ to mandatory checks, permission requirements or harness applicability explicitly.+- Change existing shared guidance before adding a new document or rule. Repeated+ code alone is not a trigger to generate more harness-specific policy files.+- When editing an adapter, verify its target and applicable loading syntax.+ Compare complete Cursor metadata values, rather than accepting substring+ matches that permit extra globs or duplicate values. The existing+ [API checker](../../test/support/verify_api_endpoint_consistency.rb) protects+ the API guide and its scoped adapter.++## Skills considered++[Adding a securities provider](adding-a-securities-provider.md) and+[gating a preview feature](gating-a-preview-feature.md) are bounded, repeatable+workflows and therefore plausible skill candidates. Skills have real ecosystem+support: both Copilot and Junie document the open format and shared+`.agents/skills/` locations.+[Copilot customization reference](https://docs.github.com/en/copilot/reference/customization-cheat-sheet),+[Junie agent skills](https://junie.jetbrains.com/docs/agent-skills.html)++No skill wrapper is introduced. The shared guides already make these procedures+available across harnesses; the repository also has+[Rails provider generators](../../lib/generators/provider/). A wrapper would add+another discovery and maintenance layer without a demonstrated invocation,+template-packaging or execution benefit. The wealth guides describe product+integration and operation, not a repository coding skill.++## Legacy helpers and local context++[bin/update_structure.sh](../../bin/update_structure.sh) is an optional generated+tree helper. Its ignored `.cursor/rules/structure.mdc` output is not a shared+policy source. The existing script writes `alwaysApply` to a different path and+then overwrites its generated header; repairing the generator is separate work.+The ignored `agent.mdc`, `dev_workflow.mdc` and `taskmaster.mdc` paths likewise+remain local/generated context.++[bin/codex-env](../../bin/codex-env) is a legacy Linux environment bootstrap,+not the standard setup procedure or a skill. It installs system packages,+changes PostgreSQL authentication, and can comment out the Ruby requirement+and mark Gemfiles assume-unchanged when versions differ. It remains unchanged;+use the maintained [development guide](development.md) for repository setup and+checks.diff --git a/docs/llm-guides/instruction-preservation-map.md b/docs/llm-guides/instruction-preservation-map.mdnew file mode 100644index 0000000000..c4fd1339c7--- /dev/null+++ b/docs/llm-guides/instruction-preservation-map.md@@ -0,0 +1,177 @@+# Instruction consolidation: preservation map++This map was written before the instruction rewrite, against `main` at+`947fe8327c6eac31f218d350b8dd5f865d5036fc` (2026-09-06 UTC).+The new branch starts there. [PR #3403](https://github.com/we-promise/sure/pull/3403)+is reference material only; none of its commits are in this branch's ancestry.+This document records the migration decision, not additional operating rules.++## Inventory and disposition++The inventory covers tracked files, references to instruction files, ignored generated+instruction paths, and deleted/renamed sources in reachable `main` history. Personal+instructions outside this repository are outside the consolidation.++| Source on main | Disposition | What survives / why |+| --- | --- | --- |+| `AGENTS.md` (uppercase; no separate `Agents.md`) | Preserve, shorten | Canonical repository rules, required checks, design-system enforcement, API obligations; detailed material moves to shared guides. |+| `CLAUDE.md` | Thin adapter | Native `@AGENTS.md` import; commands, testing, architecture and UI guidance move to shared docs. Strict pre-PR gate survives. |+| `.github/copilot-instructions.md` | Thin adapter | Explicit link to canonical guidance and relevant shared guides; remove duplicated prose and inapplicable `applyTo` frontmatter. |+| `.junie/guidelines.md` | Thin adapter | Retain legacy discovery path with a link to canonical guidance; the frozen nine-rule copy is no longer maintained separately. |+| `.gemini/config.yaml` | Preserve unchanged | Gemini Code Assist review configuration, including disabled reviews, summary settings, severity and ignore patterns. It is not Gemini CLI context. No new Gemini integration is introduced. |+| `.cursor/rules/general-rules.mdc` | Thin always-on adapter | Canonical entry point; operational restrictions and current-user/family conventions survive. |+| `.cursor/rules/project-conventions.mdc` | Move, retire duplicate | Model/PORO/concern design, dependency discipline, Hotwire, simplicity and validation conventions move to `architecture.md`. |+| `.cursor/rules/project-design.mdc` | Thin adapter | Architecture/data-flow guide; retain always-on loading. Correct verified stale descriptions. |+| `.cursor/rules/testing.mdc` | Thin scoped adapter | `testing.md`; retain `test/**` scope. |+| `.cursor/rules/view_conventions.mdc` | Thin scoped adapter | `ui.md`; retain view/JavaScript/component-JavaScript scopes. |+| `.cursor/rules/stimulus_conventions.mdc` | Thin adapter | `ui.md`; retain manual rule availability. |+| `.cursor/rules/ui-ux-design-guidelines.mdc` | Thin always-on adapter | `design-system.md` (split from `ui.md` so the always-on adapter stays design-only); preserve global design restrictions and explicit permission requirement for new global styles. |+| `.cursor/rules/api-endpoint-consistency.mdc` | Thin scoped adapter | Shared API checklist; retain exactly the three API v1 scopes and `alwaysApply: false`. |+| `.cursor/rules/cursor_rules.mdc` | Retire generic template | Cursor rule format/loading reference belongs in `harness-adapters.md`; Prisma examples do not describe this Rails app. |+| `.cursor/rules/self_improve.mdc` | Retire automatic trigger | Keep guidance maintenance advice in `harness-adapters.md`; intentionally stop always-on instructions to generate new rules when patterns occur in three files. |+| `docs/llm-guides/adding-a-securities-provider.md` | Preserve in place | Detailed repeatable provider workflow, registry, MIC/currency handling, configuration, UI/locales and verification. |+| `docs/llm-guides/gating-a-preview-feature.md` | Preserve in place | Feature gate and rollout workflow. |+| `docs/llm-guides/goals.md` | Preserve in place | Goals domain, reconciliation, statuses and data guidance. |+| `docs/llm-guides/wealth-agent-harness.md` | Preserve in place | Product integration boundary, read-only tools, provenance and monthly runbook. Not repository-wide coding policy. |+| `docs/llm-guides/wealth-blueprint.md` | Preserve in place | Reference architecture for an external wealth/tax project, including its own operating protocol. Its working-memory instructions do not redefine this repository's root files. |+| `CONTRIBUTING.md` | Update entry links | House rules, contribution workflow and CI review gate remain; replace vendor-specific convention link. |+| `bin/update_structure.sh` and ignored `.cursor/rules/structure.mdc` | Preserve, document legacy status | Optional generated tree helper, not a policy source. Existing generator defects are separate from this consolidation. |+| `bin/codex-env` | Preserve, document legacy status | Linux environment bootstrap, not repo guidance or a skill; it changes system auth and can mask Ruby-version mismatches. Do not promote it as the standard setup. |+| Ignored editor, agent, MCP and generated-workflow paths in `.gitignore` | Preserve exclusions | Local/generated context, not tracked shared policy; complete categories are listed below. |+| `test/api_endpoint_consistency_rule_test.rb`, `test/support/verify_api_endpoint_consistency.rb` | Update existing checks | Check the shared API guide and adapter reference/scopes instead of requiring full policy prose inside Cursor. Keep compliance scanning. |+| `.github/workflows/*`, `.github/ISSUE_TEMPLATE/*`, `.github/DISCUSSION_TEMPLATE/*`, `.rubocop.yml`, `.erb_lint.yml`, `biome.json`, `.editorconfig`, `.devcontainer/*`, `.env*.example`, `package.json`, `Gemfile`, `.ruby-version` | Preserve | Executable checks, contributor templates, style and environment configuration; useful evidence, not replacement prose to copy into adapters. |+| `app/models/assistant/**`, provider LLM prompt implementations, settings for AI prompts, `app/models/eval/**`, `db/eval_data/*.yml`, `test/models/eval/**`, `lib/tasks/evals.rake`, `.github/workflows/llm-evals.yml`, `docs/hosting/ai.md`, `docs/hosting/mcp.md` | Preserve | Runtime product behavior, evals and user-facing integration documentation; no prompt or application behavior changes. |+| Comments in fixtures/migrations referring to `CLAUDE.md` | Preserve | Historical attribution, not active instruction entry points; unnecessary application/fixture churn is avoided. |++No tracked `GEMINI.md`, nested `AGENTS.md`, `SKILL.md`, `.claude/`, `.codex/`,+`.agents/skills/`, Windsurf, Cline, Aider, Roo or Continue instruction source exists at+the audited base. Historical sources and deleted files are recorded below.++The ignored instruction/configuration categories in [`.gitignore`](../../.gitignore)+are legacy editor rules (`.cursorrules`, `.windsurfrules`, `*.roo*`); generated+Cursor rules (`structure.mdc`, `agent.mdc`, `dev_workflow.mdc`, `taskmaster.mdc`);+local Claude/Codex state (`.claude/settings.local.json`, `.claude_settings.json`,+`.codex`); Auto Claude state (`.auto-claude/`, `.auto-claude-security.json`,+`.auto-claude-status`, `.security-key`, `logs/security/`); Taskmaster state+(`.taskmaster/`, `.taskmasterconfig`, `tasks.json`); MCP configuration+(`*.mcp.json`, `.cursor/mcp.json`, `.playwright-mcp`); and generated workflow+material (`docs/superpowers/`, `scripts/`). These are exclusion patterns, not+claims that any contributor's ignored files exist or contain shared policy.++## Preservation by subject++| Subject | Destination | Decision |+| --- | --- | --- |+| Setup, daily commands, prohibited server/restart/credentials/automatic migration actions | `AGENTS.md`, `development.md` | Preserve restrictions; setup/migration commands are references for explicitly requested environment work. |+| Pre-PR tests, ERB/Ruby lint, security, applicable system tests, clean Biome and CI | `AGENTS.md`, `development.md` | Adopt the existing strict Claude gate globally; explicitly stronger for other entry points (see below). |+| Dependency restraint, model-owned business logic, concerns, database vs model validations, performance tradeoffs | `architecture.md` | Preserve, including traits-based concerns and avoiding N+1/global-layout overhead. |+| Family ownership, account/entry delegated types, amounts, valuations/trades, transfers, syncs, provider concepts/Provided concerns | `architecture.md` | Preserve concepts; update names/paths and qualify claims using current code. |+| Minitest/fixtures/Mocha/OpenStruct, minimal fixtures, edge cases, VCR, commands vs queries, sparing system tests | `testing.md` | Preserve; RSpec remains an explicit documentation-only exception. |+| Functional tokens, DS-first, repeated-shape extraction and reviewer severity | `AGENTS.md`, `design-system.md` | Preserve every requirement and escalation level. |+| Permission for new global styles, semantic HTML, Turbo/query state, ViewComponent vs partial, declarative Stimulus, <7-target aim, localization/accessibility | `ui.md` | Preserve; replace obsolete examples and hardcoded UI text. |+| API behavioral coverage, errors/scopes, docs-only rswag, API-key pattern, regeneration after changes and checklist after commits | `api-endpoint-consistency.md` | Preserve; remove already-resolved OAuth TODO only. Runtime OAuth support remains. |+| Provider diagnostics, namespaced extras, pending/FX, defaults/precedence, raw payload privacy | `providers.md` | Preserve obligations and Up local-only privacy restriction; correct descriptions of current behavior. |++## Intentional policy decisions++1. **Pre-PR gate becomes uniform and therefore stronger for some harnesses.**+ Claude required all Rails tests, applicable system tests, RuboCop with safe+ autocorrection, ERB lint with autocorrection and Brakeman before *every* PR,+ with creation allowed only when all checks pass. Copilot copied the check list.+ AGENTS required green tests before pushing and clean Ruby/Biome but Brakeman+ only before major PRs; Cursor/Junie lacked the same explicit creation gate.+ Preserve the strict gate and AGENTS' additional Biome requirement in canonical+ guidance. Do not silently substitute focused tests, changed-file lint or+ merely reporting failures for that gate. CI configuration is unchanged.+2. **Retire the Rails 7.2-only migration restriction.** It explicitly prohibited+ 8.0 in older Cursor/Junie instructions; current Rails is 8.1. New migrations+ follow the current Rails version, while historical migration superclass+ versions stay intact. This is a deliberate removal of a version-era constraint.+3. **Retire automatic rule proliferation.** The `self_improve` rule's three-file+ trigger is removed. Maintain shared guidance when relevant; do not create+ duplicate harness-specific policies as a side effect of ordinary coding.+4. **Use current UI conventions and the established rswag exception.** Remove+ old hardcoded-string advice, obsolete component examples and blanket no-RSpec+ phrasing that conflicts with later mandatory OpenAPI documentation policy.+ No permission or design-review requirement is relaxed. Setup/database command+ references are explicitly limited to requested environment work: this makes+ the existing no-automatic-migrations restriction explicit for setup and related+ database tasks, rather than treating command listings as standing authorization.+5. **No skills introduced.** Provider addition and preview gating are genuine+ repeatable workflow candidates, but existing shared guides already serve every+ supported harness, and Rails provider generators already exist in+ `lib/generators/provider/`. There is no demonstrated invocation, packaging or+ execution benefit that warrants a skill wrapper for this change. Runtime wealth+ operating protocols are not repository coding skills.++## History reviewed++Review window: 2025-09-01 through 2026-09-06 UTC (more than one year), plus+earlier introductions to explain inherited policy. The audit used `git ls-files`+for the base inventory, repository-wide reference searches, and `git log` rooted+at the fixed base commit with `--since-as-filter='2025-09-01T00:00:00Z'`,+`--until='2026-09-07T00:00:00Z'`, and `--name-status`, followed by patch inspection.+Deleted/renamed files were checked with `--diff-filter=DR`. All parent ancestry+was included; neither `--first-parent` nor `--all` defined the policy baseline.+Dates below are **committer dates normalized to UTC**, obtained with+`TZ=UTC git show --date=format-local:%Y-%m-%d --format='%h %cd %s'`.+PR #3403's diff and review comments were inspected separately, not merged or+cherry-picked. Its [9f44bee07](https://github.com/we-promise/sure/commit/9f44bee07) commit is not an ancestor of the audited base.++| Date | Commit | Evolution and consequence |+| --- | --- | --- |+| 2025-02-04 | [2a338eb01](https://github.com/we-promise/sure/commit/2a338eb01) | Cursor architecture/conventions introduced; contributor guidance points readers there. |+| 2025-03-28 | [2f6b11c18](https://github.com/we-promise/sure/commit/2f6b11c18) | General AI rules and the generated Cursor structure helper introduced. |+| 2025-05-26 | [07ca33f2f](https://github.com/we-promise/sure/commit/07ca33f2f) | Taskmaster scaffolding adds generic Cursor-rule authoring and self-improvement templates. |+| 2025-06-17 | [b803ddac9](https://github.com/we-promise/sure/commit/b803ddac9) | CLAUDE introduced alongside API v1 work. |+| 2025-06-20 | [fcf14f5f2](https://github.com/we-promise/sure/commit/fcf14f5f2) | Claude's explicit all-checks-pass pre-PR gate introduced; still present at base. |+| 2025-08-15 | [fb6e094f7](https://github.com/we-promise/sure/commit/fb6e094f7) | Gemini Code Assist reviews explicitly disabled; settings unchanged since. |+| 2025-08-27 | [c99335147](https://github.com/we-promise/sure/commit/c99335147) | AGENTS introduces a shorter, different checklist; not evidence of repealing Claude's gate. |+| 2025-09-16 | [e00599516](https://github.com/we-promise/sure/commit/e00599516) | Context file updates; parallel instruction maintenance continues. |+| 2025-09-20 | [60f54f9ba](https://github.com/we-promise/sure/commit/60f54f9ba) | Copilot gets another substantial copy, including pre-PR commands. |+| 2025-09-21 | [2892ebb2f](https://github.com/we-promise/sure/commit/2892ebb2f) | Codex Linux environment helper added. |+| 2025-09-23 | [7245dd79a](https://github.com/we-promise/sure/commit/7245dd79a) | Cursor cleanup adds the temporary Rails 7.2-only migration restriction. |+| 2025-10-28 | [391011628](https://github.com/we-promise/sure/commit/391011628) | Claude switches from temporary hardcoded English advice to mandatory localization. |+| 2025-11-14 | [972648b66](https://github.com/we-promise/sure/commit/972648b66) | Codex helper updated for Ruby 3.4.7; not a portable runtime contract. |+| 2025-11-16 | [066fdf4ed](https://github.com/we-promise/sure/commit/066fdf4ed) | Junie copies nine Cursor rules; later source changes do not automatically reach the copy. |+| 2025-12-19 | [664c6c2b7](https://github.com/we-promise/sure/commit/664c6c2b7) | SimpleFIN/Plaid pending + FX guidance added. |+| 2026-01-10 | [3658e812a](https://github.com/we-promise/sure/commit/3658e812a) | Pending defaults/reconciliation change; Claude updated while AGENTS retains default-off prose. |+| 2026-01-22 | [3f5fff27e](https://github.com/we-promise/sure/commit/3f5fff27e) | Lunchflow pending support reaches AGENTS; Claude's unsupported claim persists. |+| 2026-01-30 | [9f5fdd4d1](https://github.com/we-promise/sure/commit/9f5fdd4d1) | Mandatory rswag documentation exception added. |+| 2026-02-10 | [8fcd2912c](https://github.com/we-promise/sure/commit/8fcd2912c) | Post-commit API behavioral/docs/auth checklist and verification introduced. |+| 2026-03-16 | [a0b1029ba](https://github.com/we-promise/sure/commit/a0b1029ba) | Contributor guide documents automated Pipelock security scanning. |+| 2026-04-06 | [616c363b3](https://github.com/we-promise/sure/commit/616c363b3) | Devcontainer Selenium guidance added. |+| 2026-04-10 | [0aca297e9](https://github.com/we-promise/sure/commit/0aca297e9) | Securities-provider shared guide added. |+| 2026-05-01 | [e250d266e](https://github.com/we-promise/sure/commit/e250d266e) | Design-token source evolves; link to current design system. |+| 2026-05-10 | [712d6baca](https://github.com/we-promise/sure/commit/712d6baca) | AGENTS adds DS reuse and reviewer escalation policy, absent from old copies. |+| 2026-05-18/19 | [5249842c7](https://github.com/we-promise/sure/commit/5249842c7), [e8ce28648](https://github.com/we-promise/sure/commit/e8ce28648) | Beta gating guide introduced, then deleted and replaced with the preview guide. |+| 2026-06-02 | [3508f7058](https://github.com/we-promise/sure/commit/3508f7058) | Goals guide introduced. |+| 2026-06-14 | [88343002d](https://github.com/we-promise/sure/commit/88343002d) | Rails 7.2 → 8.1 upgrade supersedes the old migration-version prohibition. |+| 2026-06-15 | [08bfd4377](https://github.com/we-promise/sure/commit/08bfd4377) | Support-relevant provider diagnostics required in DebugLogEntry. |+| 2026-06-20 | [dc2a565b6](https://github.com/we-promise/sure/commit/dc2a565b6) | Up raw logging privacy constraint added to Claude. |+| 2026-07-26 | [375dd060d](https://github.com/we-promise/sure/commit/375dd060d) | Preview gate guide updated for insights. |+| 2026-08-04 | [efb7cc393](https://github.com/we-promise/sure/commit/efb7cc393) | Wealth blueprint and external agent harness docs added; preserve their separate product scope. |+| 2026-08-16 | [acf4cb201](https://github.com/we-promise/sure/commit/acf4cb201) | Goals deletion semantics updated; preserve current guide. |++The only deleted instruction source in the scoped main-history window is+`docs/llm-guides/gating-a-beta-feature.md`, replaced by the preview guide in+[e8ce28648](https://github.com/we-promise/sure/commit/e8ce28648). Other local refs expose `.cursor/rules/localization.mdc`,+`docs/llm-guides/rails-provider-generator.md`, and earlier+`patrimonial-agent-harness.md` / `patrimonial-blueprint.md` names, but those file+histories are not reachable from the audited main base. They are not resurrected+as main policy; the wealth-named guides entered main directly in [efb7cc393](https://github.com/we-promise/sure/commit/efb7cc393).++## Factual corrections, not product changes++| Stale description | Current source evidence |+| --- | --- |+| User-owned accounts; all values stored in a user's base currency | [Account](../../app/models/account.rb) belongs to `Family`; both accounts and [entries](../../app/models/entry.rb) require their own currency. |+| Nested provider concepts and old balance-calculator paths | [Provider registry](../../app/models/provider/registry.rb), [exchange-rate concept](../../app/models/provider/exchange_rate_concept.rb), [security concept](../../app/models/provider/security_concept.rb), and [account syncer](../../app/models/account/syncer.rb) show the current classes and `Balance::Materializer` flow. |+| Lookbook at `/lookbook`; API keys described as JWT tokens | [Routes](../../config/routes.rb) mount Lookbook at `/design-system`; [ApiKey](../../app/models/api_key.rb) generates random hexadecimal keys. |+| SimpleFIN infers pending from a blank posted date | [SimplefinEntry::Processor.pending?](../../app/models/simplefin_entry/processor.rb) requires explicit epoch zero plus a positive transaction timestamp when no explicit pending flag is set. |+| Blanket pending defaults; Lunchflow does not store pending metadata | Initializers for [SimpleFIN](../../config/initializers/simplefin.rb), [Plaid](../../config/initializers/plaid_config.rb), and [Lunchflow](../../config/initializers/lunchflow.rb), the [SimpleFIN importer](../../app/models/simplefin_item/importer.rb), and [Lunchflow processor](../../app/models/lunchflow_entry/processor.rb) distinguish provider defaults, import-layer overrides and stored metadata. |+| Valuations rswag spec still needs OAuth replaced | [valuations_spec.rb](../../spec/requests/api/v1/valuations_spec.rb) already creates an API key and supplies `X-Api-Key`. |+| New migrations must remain Rails 7.2 | [Gemfile](../../Gemfile) requires Rails 8.1; upgrade commit [88343002d](https://github.com/we-promise/sure/commit/88343002d) provides the historical transition. |++No application code or runtime configuration changes are needed to correct these+descriptions. The shared guides link to the implementation for future verification.diff --git a/docs/llm-guides/providers.md b/docs/llm-guides/providers.mdnew file mode 100644index 0000000000..aaed306f59--- /dev/null+++ b/docs/llm-guides/providers.md@@ -0,0 +1,82 @@+# Provider integration guidance++Read [architecture](architecture.md) for provider concepts, runtime registry+selection and `Provided` concerns. For a new securities price provider, follow+[the complete workflow](adding-a-securities-provider.md), including response+types, MIC mapping, currency handling, settings encryption, UI, locales and tests.++## Support diagnostics++When a provider sync/import path encounters a recoverable error, suspicious partial+response or other support-relevant incident, prefer+[`DebugLogEntry.capture`](../../app/models/debug_log_entry.rb) over `Rails.logger.*`+so operators can inspect it in the super-admin `/settings/debug` UI.++- Include `category`, `level`, `message`, `source`, `provider_key` and useful+ structured `metadata`.+- Attach `family` and `account_provider` whenever available so support can filter+ and trace the affected connection. Account/user associations can add context.+- Reserve raw Rails logging for low-value local noise; incidents operators need+ to investigate belong in the debug log.++## Pending transactions and FX metadata++Store provider metadata on `Transaction#extra` under the provider namespace.+[`Transaction#pending?` and pending scopes](../../app/models/transaction.rb) share+`PENDING_PROVIDERS`; that constant is the current list of supported namespaces,+including providers beyond the three described below. The UI shows a Pending+badge when `transaction.pending?` is true. A provider that supplies no pending+metadata produces no badge; manual/CSV imports have no pending concept.++| Provider | Detection and storage |+| --- | --- |+| SimpleFIN | [`SimplefinEntry::Processor.pending?`](../../app/models/simplefin_entry/processor.rb) accepts an explicitly truthy `pending` flag, or `posted` equal to numeric `0` or string `"0"` with a present, positive `transacted_at` timestamp. A blank/missing `posted` value does **not** imply pending. Writes `extra["simplefin"]["pending"]` as true or false so a posted update clears stale pending metadata. |+| Plaid | [`PlaidEntry::Processor`](../../app/models/plaid_entry/processor.rb) stores bank/credit transaction `pending` and `pending_transaction_id` under `extra["plaid"]`; the linking ID supports pending-to-posted reconciliation. The investment transaction processor does not store pending metadata. |+| Lunchflow | [`LunchflowEntry::Processor`](../../app/models/lunchflow_entry/processor.rb) stores the boolean-cast `isPending` value under `extra["lunchflow"]["pending"]` when the upstream key is present. |++SimpleFIN additionally stores `extra["simplefin"]["fx_from"]` when transaction and+account currencies differ, and `fx_date` from the transacted date with posted-date+fallback. Preserve these namespaced fields and the existing conversion behavior.++Pending inclusion is provider- and layer-specific:++- **SimpleFIN:** the [initializer](../../config/initializers/simplefin.rb) defaults+ `config.x.simplefin.include_pending` to true. The+ [importer](../../app/models/simplefin_item/importer.rb) resolves an explicit+ `pending:` argument first, then a present `SIMPLEFIN_INCLUDE_PENDING` environment+ value, then `Setting.syncs_include_pending`. The entry processor also checks the+ environment/Setting choice before importing cached pending payloads.+ `SIMPLEFIN_INCLUDE_PENDING=0` disables the environment-controlled path.+ The [low-level provider](../../app/models/provider/simplefin.rb) does not resolve+ these settings: it adds `pending=1` only for a truthy argument, and otherwise+ omits the parameter. Do not send `pending=0`; bridges can interpret its presence+ as inclusion.+- **Plaid:** the [initializer](../../config/initializers/plaid_config.rb) defaults+ `config.x.plaid.include_pending` to true. The [transaction processor](../../app/models/plaid_account/transactions/processor.rb)+ uses a present `PLAID_INCLUDE_PENDING` environment value before+ `Setting.syncs_include_pending`; `PLAID_INCLUDE_PENDING=0` filters pending+ records out. This is processing-time filtering, not a pending query flag on the+ [Plaid sync request](../../app/models/provider/plaid.rb).+- **Shared SimpleFIN/Plaid setting:** [`Setting.syncs_include_pending`](../../app/models/setting.rb)+ defaults true with both environment variables absent. Its initial default is+ computed from both provider environment values; a persisted runtime setting can+ differ. Do not infer effective importer behavior from an initializer alone.+- **Lunchflow:** the [initializer](../../config/initializers/lunchflow.rb) defaults+ `config.x.lunchflow.include_pending` to false. Set `LUNCHFLOW_INCLUDE_PENDING=1`+ to enable it. The [importer](../../app/models/lunchflow_item/importer.rb) passes+ that configuration as `include_pending:`. A direct [provider call](../../app/models/provider/lunchflow.rb)+ defaults the argument to false and adds `include_pending=true` only when enabled;+ it does not consult the shared SimpleFIN/Plaid setting.++## Raw payload debugging++Raw debugging is default-off. `SIMPLEFIN_DEBUG_RAW=1` and+`LUNCHFLOW_DEBUG_RAW=1` enable their importers' raw response logging through+`Rails.configuration.x.simplefin.debug_raw` and+`Rails.configuration.x.lunchflow.debug_raw` respectively.++`UP_DEBUG_RAW=1` enables [Up's debug configuration](../../config/initializers/up.rb),+but its [importer](../../app/models/up_item/importer.rb) logs raw transactions only+when `Rails.env.local?` is also true. The dump contains PII: preserve this local-only+guard and do not enable raw Up dumps in managed/production. This guard is specific+to Up; the SimpleFIN and Lunchflow flags do not provide the same environment gate.diff --git a/docs/llm-guides/testing.md b/docs/llm-guides/testing.mdnew file mode 100644index 0000000000..f277ffa911--- /dev/null+++ b/docs/llm-guides/testing.md@@ -0,0 +1,39 @@+# Testing++Use Rails Minitest and fixtures for behavioral tests; do not introduce RSpec+behavioral tests or factories. RSpec/rswag is the explicit exception for+[OpenAPI documentation only](api-endpoint-consistency.md).++- Mirror `app/` under `test/` and name files `*_test.rb`.+- Keep fixtures small: normally two or three per model representing base cases.+ Create edge cases within the test that needs them. Use Rails helpers for large+ data sets, such as [`EntriesTestHelper`](../../test/support/entries_test_helper.rb).+- Write tests while implementing critical behavior. Prefer unit tests plus focused+ integration tests; use system tests sparingly for critical user flows.+- Test code paths that significantly increase confidence. Do not add tests merely+ to verify ActiveRecord's built-in persistence or duplicate another class's tests.+- Respect class boundaries: verify query outputs and that commands receive the+ correct arguments. Do not inspect another class's internal implementation.+- Use Mocha for stubs/mocks. Prefer `OpenStruct` for mock instances, or a small mock+ class for complex cases. Only mock what the test needs; do not stub return values+ that are irrelevant to the behavior under test.+- Use VCR for external API calls and existing cassettes in `test/vcr_cassettes/`.+ Keep credentials out of recordings; filters and shared setup live in+ [`test/test_helper.rb`](../../test/test_helper.rb).++For example, when testing an orchestrator, set the command expectation before+calling the subject, then check the subject's returned result:++```ruby+test "passes the result to the processor" do+ CustomEventProcessor.expects(:process_result).with(4).once++ assert_equal 4, ExampleClass.new.do_something+end+```++This illustrates a test boundary; it does not prescribe new classes. Follow existing+model/controller tests for real fixtures and API setup.++Use the commands and full [pre-PR checklist](development.md#before-opening-a-pull-request).+API changes also require the [post-commit consistency checklist](api-endpoint-consistency.md).diff --git a/docs/llm-guides/ui.md b/docs/llm-guides/ui.mdnew file mode 100644index 0000000000..03d577e6a5--- /dev/null+++ b/docs/llm-guides/ui.md@@ -0,0 +1,54 @@+# Views, components and interaction++Design tokens, `DS::*` reuse and reviewer severity live in the+[design system guide](design-system.md), which is also the always-on Cursor+design adapter. This guide covers templates, Hotwire, Stimulus and localization.++## Hotwire and templates++Prefer semantic native HTML, including `<dialog>` and `<details><summary>`, using+existing DS wrappers where available. Use Turbo Frames for page sections. Turbo+Streams should enhance functionality, not be its sole dependency.++Keep state in URL query parameters before reaching for local storage or sessions;+use the database when persistent state is necessary. Format money, numbers and+dates server-side and pass display values to Stimulus. Client-side behavior is+appropriate for interactions such as bulk selection where server round trips would+hurt usability.++Use an existing component first, then an existing partial. Create a ViewComponent+for reusable or complex styling/logic, variants/sizes, interaction, slots or a+configurable API, and accessibility/ARIA behavior. Use partials for mostly static,+simple or context-specific template content. Keep domain logic out of ERB; compute+presentation logic in helpers or component Ruby files.++Follow the names of nearby components, including the `DS::*` namespace; do not+impose the obsolete `ButtonComponent`/`DialogComponent` examples on this design+system. Partials use an underscore prefix; shared partials live in+`app/views/shared/`, context-specific partials under their controller's views.++## Stimulus++- Declare actions in HTML (`data-action="click->toggle#toggle"`) rather than+ imperatively registering event listeners in controller initialization.+- Keep controllers focused on one responsibility or tightly related responsibilities;+ domain logic belongs on the server.+- Aim for fewer than seven targets. Use private helpers and a clear public API,+ with Stimulus callbacks, actions, targets, values and classes.+- Controllers in `app/components/` belong only to their component templates;+ global controllers in `app/javascript/controllers/` may be shared across views.+- Pass data through `data-*-value` attributes rather than inline JavaScript. Use+ Stimulus targets rather than manual `getElementById` lookups.++## Localization++Use `t()` for all user-facing strings and update the corresponding locale files+under `config/locales/`. Follow the feature's existing locale organization; there+is no requirement to put every new key in a single `en.yml`.++Use descriptive, hierarchical keys such as `accounts.index.title` and+`components.transaction_details.show_details`. Group related keys together; use+interpolation (`t("users.greeting", name: user.name)`) and Rails pluralization+(`t("transactions.count", count: count)`) for dynamic text. Keep examples localized+too. Configure missing translations to raise during development; do not assume that this option is currently enabled in the+checked-in environment configuration.diff --git a/test/api_endpoint_consistency_rule_test.rb b/test/api_endpoint_consistency_rule_test.rbindex 8169ebed31..b255b5dadc 100644--- a/test/api_endpoint_consistency_rule_test.rb+++ b/test/api_endpoint_consistency_rule_test.rb@@ -1,13 +1,15 @@# frozen_string_literal: true-# Verifies the API endpoint consistency implementation (issue #944): rule file and AGENTS.md.+# Verifies the shared API checklist and its canonical/scoped entry points (issue #944).# If Rails fails to load (e.g. Sidekiq::Throttled), run the standalone script instead:# ruby test/support/verify_api_endpoint_consistency.rbrequire "test_helper"+require "yaml"class ApiEndpointConsistencyRuleTest < ActiveSupport::TestCaseRULE_PATH = ".cursor/rules/api-endpoint-consistency.mdc"+ GUIDE_PATH = "docs/llm-guides/api-endpoint-consistency.md"AGENTS_PATH = "AGENTS.md"def root@@ -18,23 +20,33 @@ class ApiEndpointConsistencyRuleTest < ActiveSupport::TestCaseassert File.exist?(root.join(RULE_PATH)), "Expected #{RULE_PATH} to exist"end- test "rule has globs for API v1 paths" do- content = File.read(root.join(RULE_PATH))- assert_includes content, "app/controllers/api/v1"- assert_includes content, "spec/requests/api/v1"- assert_includes content, "test/controllers/api/v1"+ test "rule preserves exact API v1 applicability and imports shared guide" do+ content = File.read(root.join(RULE_PATH), encoding: "UTF-8")+ frontmatter = content.match(/\A---\r?\n(?<yaml>.*?)\r?\n---\r?\n(?<body>.*)\z/m)+ assert frontmatter, "Expected frontmatter at the start of the rule"+ keys = YAML.parse(frontmatter[:yaml]).root.children.each_slice(2).map { |key, _value| key.value }+ assert_equal %w[alwaysApply description globs], keys.sort+ metadata = YAML.safe_load(frontmatter[:yaml])++ assert_equal false, metadata.fetch("alwaysApply")+ assert_equal [+ "app/controllers/api/v1/**/*.rb",+ "spec/requests/api/v1/**/*.rb",+ "test/controllers/api/v1/**/*.rb"+ ], metadata.fetch("globs").split(",").map(&:strip)+ assert_equal "@#{GUIDE_PATH}", frontmatter[:body].stripend- test "rule includes Minitest behavioral coverage section" do- content = File.read(root.join(RULE_PATH))+ test "shared guide includes Minitest behavioral coverage section" do+ content = File.read(root.join(GUIDE_PATH), encoding: "UTF-8")assert_includes content, "Minitest behavioral coverage"assert_includes content, "test/controllers/api/v1/{resource}_controller_test.rb"assert_includes content, "api_headers"assert_includes content, "X-Api-Key"end- test "rule includes rswag docs-only section" do- content = File.read(root.join(RULE_PATH))+ test "shared guide includes rswag docs-only section" do+ content = File.read(root.join(GUIDE_PATH), encoding: "UTF-8")assert_includes content, "rswag is docs-only"assert_includes content, "expect"assert_includes content, "assert_"@@ -42,8 +54,8 @@ class ApiEndpointConsistencyRuleTest < ActiveSupport::TestCaseassert_includes content, "rswag:specs:swaggerize"end- test "rule includes same API key auth section" do- content = File.read(root.join(RULE_PATH))+ test "shared guide includes same API key auth section" do+ content = File.read(root.join(GUIDE_PATH), encoding: "UTF-8")assert_includes content, "Same API key auth"assert_includes content, "ApiKey.generate_secure_key"assert_includes content, "plain_key"@@ -52,9 +64,9 @@ class ApiEndpointConsistencyRuleTest < ActiveSupport::TestCasetest "AGENTS.md references post-commit API consistency" doassert File.exist?(root.join(AGENTS_PATH)), "Expected #{AGENTS_PATH} to exist"- content = File.read(root.join(AGENTS_PATH))+ content = File.read(root.join(AGENTS_PATH), encoding: "UTF-8")assert_includes content, "Post-commit API consistency"- assert_includes content, "api-endpoint-consistency.mdc"+ assert_includes content, GUIDE_PATHassert_includes content, "Minitest"assert_includes content, "rswag"assert_includes content, "X-Api-Key"diff --git a/test/support/verify_api_endpoint_consistency.rb b/test/support/verify_api_endpoint_consistency.rbindex a4dae297bf..df4ba8e4f6 100644--- a/test/support/verify_api_endpoint_consistency.rb+++ b/test/support/verify_api_endpoint_consistency.rb@@ -8,12 +8,14 @@# (rswag specs using OAuth instead of API key, missing Minitest for API controllers,# rswag specs with expect/assert).+require "yaml"+def project_rootdir = File.dirname(File.expand_path(__FILE__))loop do- return dir if File.exist?(File.join(dir, "AGENTS.md")) && File.directory?(File.join(dir, ".cursor", "rules"))+ return dir if File.exist?(File.join(dir, "AGENTS.md")) && File.directory?(File.join(dir, "docs", "llm-guides"))parent = File.dirname(dir)- raise "Could not find project root (AGENTS.md + .cursor/rules)" if parent == dir+ raise "Could not find project root (AGENTS.md + docs/llm-guides)" if parent == dirdir = parentendend@@ -28,35 +30,49 @@ endroot = project_rootrule_path = File.join(root, ".cursor", "rules", "api-endpoint-consistency.mdc")+guide_path = File.join(root, "docs", "llm-guides", "api-endpoint-consistency.md")agents_path = File.join(root, "AGENTS.md")assert File.exist?(rule_path), "Rule file should exist at #{rule_path}"-rule_content = File.read(rule_path)--assert_includes rule_content, "app/controllers/api/v1", "Rule must have glob for app/controllers/api/v1"-assert_includes rule_content, "spec/requests/api/v1", "Rule must have glob for spec/requests/api/v1"-assert_includes rule_content, "test/controllers/api/v1", "Rule must have glob for test/controllers/api/v1"-assert_includes rule_content, "Minitest behavioral coverage", "Rule must include Minitest section"-assert_includes rule_content, "test/controllers/api/v1/{resource}_controller_test.rb", "Rule must specify Minitest location"-assert_includes rule_content, "api_headers", "Rule must mention api_headers"-assert_includes rule_content, "X-Api-Key", "Rule must mention X-Api-Key"-assert_includes rule_content, "rswag is docs-only", "Rule must include rswag docs-only section"-assert_includes rule_content, "run_test!", "Rule must mention run_test!"-assert_includes rule_content, "rswag:specs:swaggerize", "Rule must mention swaggerize task"-assert_includes rule_content, "Same API key auth", "Rule must include API key auth section"-assert_includes rule_content, "ApiKey.generate_secure_key", "Rule must show API key pattern"-assert_includes rule_content, "plain_key", "Rule must mention plain_key"-assert_includes rule_content, "Doorkeeper", "Rule must mention Doorkeeper (to avoid OAuth in specs)"+rule_content = File.read(rule_path, encoding: "UTF-8")++frontmatter = rule_content.match(/\A---\r?\n(?<yaml>.*?)\r?\n---\r?\n(?<body>.*)\z/m)+assert frontmatter, "Rule must start with YAML frontmatter"+keys = YAML.parse(frontmatter[:yaml]).root.children.each_slice(2).map { |key, _value| key.value }+assert keys.sort == %w[alwaysApply description globs], "Rule must have exactly one description, globs and alwaysApply key"+metadata = YAML.safe_load(frontmatter[:yaml])+expected_globs = [+ "app/controllers/api/v1/**/*.rb",+ "spec/requests/api/v1/**/*.rb",+ "test/controllers/api/v1/**/*.rb"+]+assert metadata.fetch("globs").split(",").map(&:strip) == expected_globs, "Rule must retain exactly the API v1 globs"+assert metadata.fetch("alwaysApply") == false, "Rule must remain scoped, not always applied"+assert frontmatter[:body].strip == "@docs/llm-guides/api-endpoint-consistency.md", "Rule must import shared checklist"+assert File.exist?(guide_path), "Shared checklist should exist at #{guide_path}"+guide_content = File.read(guide_path, encoding: "UTF-8")++assert_includes guide_content, "Minitest behavioral coverage", "Shared checklist must include Minitest section"+assert_includes guide_content, "test/controllers/api/v1/{resource}_controller_test.rb", "Shared checklist must specify Minitest location"+assert_includes guide_content, "api_headers", "Shared checklist must mention api_headers"+assert_includes guide_content, "X-Api-Key", "Shared checklist must mention X-Api-Key"+assert_includes guide_content, "rswag is docs-only", "Shared checklist must include rswag docs-only section"+assert_includes guide_content, "run_test!", "Shared checklist must mention run_test!"+assert_includes guide_content, "rswag:specs:swaggerize", "Shared checklist must mention swaggerize task"+assert_includes guide_content, "Same API key auth", "Shared checklist must include API key auth section"+assert_includes guide_content, "ApiKey.generate_secure_key", "Shared checklist must show API key pattern"+assert_includes guide_content, "plain_key", "Shared checklist must mention plain_key"+assert_includes guide_content, "Doorkeeper", "Shared checklist must mention Doorkeeper (to avoid OAuth in specs)"assert File.exist?(agents_path), "AGENTS.md should exist"-agents_content = File.read(agents_path)+agents_content = File.read(agents_path, encoding: "UTF-8")assert_includes agents_content, "Post-commit API consistency", "AGENTS.md must reference post-commit checklist"-assert_includes agents_content, "api-endpoint-consistency.mdc", "AGENTS.md must link to rule file"+assert_includes agents_content, "docs/llm-guides/api-endpoint-consistency.md", "AGENTS.md must link to shared checklist"assert_includes agents_content, "Minitest", "AGENTS.md must mention Minitest"assert_includes agents_content, "rswag", "AGENTS.md must mention rswag"assert_includes agents_content, "X-Api-Key", "AGENTS.md must mention X-Api-Key"-puts "OK: API endpoint consistency implementation verified (rule + AGENTS.md)."+puts "OK: API endpoint consistency implementation verified (shared checklist + scoped adapter + AGENTS.md)."if ARGV.include?("--compliance")puts "\n--- Compliance check (current APIs) ---"@@ -72,7 +88,7 @@ if ARGV.include?("--compliance")Dir.glob(File.join(spec_dir, "*_spec.rb")).each do |path|basename = File.basename(path, "_spec.rb")next if basename == "auth"- content = File.read(path)+ content = File.read(path, encoding: "UTF-8")if content.include?("Doorkeeper") || content.include?("Bearer") || content.include?("access_token")rswag_oauth << "#{basename}_spec.rb"end