155 Commits
Author SHA1 Message Date
Juan José Mata 84cab87370 Unify the provider connection lifecycle for Brex, Lunch Flow, and Mercury (#6049)
## Summary

Brex, Lunch Flow, and Mercury each maintained their own connection
setup, account linking, and sync lifecycle. This PR moves those three
providers onto shared Rails models, controllers, and view components.
Account-provider adapters declare their connections in one place, which
supplies the lists used by Bank Sync, the Accounts page, and the
connection-status API. The `provider:family` generator now builds on the
same kit.

This brings the 56 reviewed changes from [stack
#5268](https://github.com/we-promise/sure/stack/5268) onto `main`, in
their original order. Refs #5003.

## Behavior to review

- Brex, Lunch Flow, and Mercury share the account-selection and setup
flows. Account cards and post-setup Turbo updates respect the viewer’s
account access, including for family admins.
- Editing a Lunch Flow connection keeps its stored API key out of the
rendered form. A blank secret on edit preserves the existing credential.
- Mercury validates every transaction page before saving the account’s
fetch. Malformed pages, repeated full pages, and page limits leave the
stored transactions intact and retain the retry date. A successful
explicit window that starts later also preserves the earlier retry date.
Both Lunch Flow and Mercury honor an explicit sync start date.
- Linking an existing account requires ownership or a full-control
share. Link submissions recheck the upstream account list, and rotating
credentials isolates in-flight discovery results. Settings panels show
connection-wide counts only when the admin can see all linked accounts.
- Stored accounts remain available during a setup refresh outage.
Generated investment providers offer Crypto with wallet and exchange
subtypes. Each subtype picker has its own accessible label, and its
blank choice is keyboard-selectable.
- Sync statistics count linked and unlinked accounts in a single query.
Lunch Flow reports balance-refresh failures separately from
transaction-fetch failures.
- `GET /api/v1/provider_connections` lists providers alphabetically by
key. Connections within a provider retain their order.

## Database migration

Apply
`20261201120000_add_transactions_sync_start_date_to_mercury_accounts`
during deployment. This adds one nullable date to each Mercury account.
The importer initializes it on the next fetch from that account’s
previous sync history, so deployment requires no backfill.

## Screenshots

The Brex account-setup prompt from
[#5232](https://github.com/we-promise/sure/pull/5232) illustrates the
shared card. The [Lunch Flow credential
form](https://github.com/we-promise/sure/pull/5257) and [Mercury setup
dialogs](https://github.com/we-promise/sure/pull/5261) have additional
comparisons.

| Before | After |
| --- | --- |
| ![Previous Brex account-setup
prompt](https://raw.githubusercontent.com/jaysbeekay/sure/4bd2a47ac77b166369e45169be1000638fd95be1/card-setup-needed-before.png)
| ![Updated Brex account-setup
prompt](https://raw.githubusercontent.com/jaysbeekay/sure/4bd2a47ac77b166369e45169be1000638fd95be1/card-setup-needed-after.png)
|

## Validation

- Verified that all 56 rebased commits preserve the reviewed stack order
and that each commit’s files match the corresponding changes applied to
`main` at `5f31a17f5`.
- After the review fixes, `bin/rails test` completed with 20,204 tests,
121,912 assertions, nine skips, and zero failures or errors.
- The full browser suite passed on the rebased stack (532 tests). The
provider account setup browser test also passed after the review fixes,
including keyboard clearing and submitting the selected subtype.
- RuboCop, ERB lint, Biome, Brakeman, and the dependency audit passed.

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Unifies the connection lifecycle for Brex, Lunch Flow, and Mercury on
shared provider-kit infrastructure: models, controllers, account flows,
syncers, and view components. Connection declarations on each provider
adapter now drive the provider lists in Bank Sync, the Accounts page,
and the connection-status API; the `provider:family` generator emits the
same kit. No database migration is needed.

**Behavior changes**
- Mercury now pages through transactions instead of importing only the
first page; Lunch Flow and Mercury honor an explicit sync start date.
- An open redirect via protocol-relative `return_to` paths is closed for
Lunch Flow and Mercury.
- Lunch Flow's panel no longer renders the stored API key into the page
HTML; a blank secret on edit preserves the stored credential.
- Linking several accounts is transactional, unsupported account types
are refused, and setup accepts subtypes only for the chosen account
type.
- Failed syncs are reported once to Sentry, tagged with both connection
and sync ids; swallowed Brex import failures now appear in the debug
log.
- `GET /api/v1/provider_connections` lists providers alphabetically by
key.

<sup>Written for commit c41bdd95d5.
Summary will update on new commits.</sup>

<a
href="https://cubic.dev/pr/we-promise/sure/pull/6049?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/we-promise/sure/6049?returnTo=https%3A%2F%2Fgithub.com%2Fwe-promise%2Fsure%2Fpull%2F6049&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

- **New Features**
- Added guided account selection and setup for provider connections,
including account-type and subtype choices.
- Lunch Flow and Mercury connections now support choosing a transaction
import start date.
- Added clearer connection status, sync summaries, and troubleshooting
details for provider errors.

- **Improvements**
- Provider settings and account lists now reflect connection details,
with account visibility respecting access.
  - Blank connection names receive a localized default.
- Large Mercury transaction imports handle pagination and duplicate
records more reliably.

- **Bug Fixes**
  - Unnamed provider accounts can’t be selected for linking.
  - Keyboard selection now works for options with empty values.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-12-02 11:00:18 -08:00
Chris Werner Rau 402ae5b627 fix: keep CSV formula escaping injective and consistent across export files (#4853)
## Problem

Upstream main now escapes formula-leading text in the export CSVs
through `CsvSanitizer` (#1943). Three gaps remain:

- The escape is not injective: `=x` and `'=x` both become `'=x`. Because
imports never strip the quote, two rules, categories or merchants with
those names collapse into one on re-import, and `RuleImport` replaces
the earlier rule.
- A cell holding a locale separator (for example `Food;=1+1`) is
unquoted, so a spreadsheet using that separator splits it and the part
after the separator starts an unescaped cell.
- `rules.csv` operands carry raw category, merchant and tag names inside
the JSON `conditions` and `actions`, while `categories.csv`,
`merchants.csv` and `transactions.csv` carry the escaped spelling. An
import then creates a second record for the same name.

## Behavior

- `CsvSanitizer` adds one more apostrophe when a value already starts
with apostrophes before a trigger character: `=x` exports as `'=x`,
`'=x` as `''=x`. Plain numbers and ordinary text are unchanged.
- The data export and the reports transactions export write every cell
quoted (`force_quotes: true`). This changes the quoting of all cells and
headers in those files; parsed values are identical.
- Rule operand names in `rules.csv` go through the same escape, so one
name is spelled the same in every CSV. `all.ndjson` and `value_ref` stay
raw. No import-side stripping.

## Known limits

- Full-width prefixes and a leading space are not covered and not
verified in spreadsheet clients.
- A guarded value keeps its visible `'` after re-import (a CSV does not
identify itself as a Sure export).
- The CSV writer in `assistant/function/import_bank_statement.rb`, the
import template and the currently unreachable XLSX generator in
`ReportsController` are not guarded.

## Validation

- Red first: the five new tests (injectivity, locale-separator quoting,
reports quoting, committed rule import, rule operand consistency) fail
on upstream main and pass here.
- Full `bin/rails test` run before the final test-assertion fix: only
the header-quoting assertion in the existing CSV test failed; updated
it, then re-ran the sanitizer, exporter, reports controller and import
tests (178 runs, 0 failures).
- `bin/rubocop`: no offenses. `bin/brakeman --no-pager`: no warnings.
- Run in podman only.
2026-11-25 19:14:57 -08:00
David Gil 9089ccb84d security: CORS allow-list instead of a wildcard, DNS rebinding protection behind ALLOWED_HOSTS (#1944)
Cut down to the two pieces that still apply.

## Scope

- **CORS allowed every origin.** `origins "*"` let any site on the
internet read what `/api`, `/oauth` and `/sessions` answer. Credentials
were never forwarded, so this was not a session leak, but it was an open
door on everything those endpoints return without one. The allow-list
comes from `ALLOWED_ORIGINS`, falling back to `APP_DOMAIN`. With neither
set the list is empty, no `Access-Control-Allow-Origin` header is sent,
and browsers apply their own same-origin default. Native mobile clients
send no `Origin` header and are unaffected either way. The resource list
stays `/api`, `/oauth` and `/sessions`: `/mcp` and the OAuth discovery
endpoints never sent CORS headers, and the desktop app and the PWA load
the instance itself, so their requests are same-origin.
- **Host authorization was commented out**, so the app answered to any
`Host` header. Setting `ALLOWED_HOSTS` turns DNS-rebinding protection
on, and `APP_DOMAIN`, if set, is added to the list so the public name
doesn't have to be written twice. `APP_DOMAIN` alone does not turn it
on: operators set it for outgoing mail, and the same instance is often
reached over a LAN address, a Tailscale name, a tunnel or Pipelock.
Without `ALLOWED_HOSTS` nothing changes from today, so an upgrade can't
lock anyone out of their own instance. `/up` is excluded whenever the
list is active, so container probes keep passing. The Docker and Helm
docs list the names to add, including the one Pipelock uses to reach the
app.

## What was dropped

Three of the original seven are already on main, in better shape than
this PR had them: Sidekiq Web fails closed and its route is behind a
super-admin constraint, and Lookbook is no longer mounted in production.

The CSP work is out. #3246 does the same thing more completely, with a
per-inline-script nonce audit and a Permissions-Policy, and two open PRs
writing the same policy helps nobody. The violation-report endpoint went
with it, since a `report_uri` without a policy reports nothing.

`config.require_master_key = true` is out because it would stop
self-hosted instances from booting. The shipped image bundles a
`credentials.yml.enc` whose key belongs to upstream and is never
distributed, and neither the compose file nor `.env.example` defines
`RAILS_MASTER_KEY`, so the first credentials access at boot would raise.
Self-hosted runtime secrets come from the environment.

Moving `rack-mini-profiler` to the development group is out. It reads
like a production exposure but is not one: the gem's railtie sets
`authorization_mode = :allow_authorized` outside development and test,
and nothing in this app ever calls `authorize_request`, so the profiler
never renders in production.

## Note on matching

The origin comparison is equality rather than a prefix, so
`https://app.example.com.evil.test` does not pass for
`https://app.example.com`. Operator-supplied values are normalized
first: a URL pasted from an address bar carries a trailing slash and
mixed case, and `APP_DOMAIN` is documented as a bare domain but people
put a full URL in it, which the WebAuthn initializer already works
around.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Security**
- Restricted browser cross-origin requests to explicitly configured
origins; wildcard CORS responses are no longer returned.
  - Added exact matching for origin scheme, host, and port.
- Added optional host authorization using `APP_DOMAIN` or
`ALLOWED_HOSTS`, while keeping health checks accessible.
  - Added a startup warning when host restrictions are not configured.

- **Documentation**
- Added Docker hosting guidance for configuring allowed origins and
hosts, including security behavior and environment variables.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-24 16:43:06 -08:00
Yong Cong SinandClaude Opus 5.5 901d141deb Drop the Investment Contributions category from plain transfer legs (#4799)
## Summary

A transfer leg whose kind is `funds_movement` or `cc_payment` is meant
to be uncategorized (`Transaction::UNCATEGORIZED_EXCLUDED_KINDS`).
`Transfer#update_investment_contribution!(false)` leaves it that way,
but other paths changed the kind and kept the **Investment
Contributions** category of the old kind, so those transfers still
showed under that category:

- `Transfer::InvestmentKindReconciler` rewrites the kind with
`update_columns`, which skips callbacks.
- `Account::ProviderImportAdapter` gave a leg labelled "Contribution"
the category even when its matched transfer made it a `funds_movement`
leg (a broker deposit matched to a bank transfer).
- Any later save that moved a leg to a plain transfer kind
(`Transfer#confirm!` on the inflow, a re-sync deriving the kind from its
transfer) kept the category.

Now:
- `Transaction.drop_stale_contribution_categories!(scope)` clears the
category from the plain-transfer legs of a scope that still carry it
without a lock of the user's. A lock an automatic categorizer set itself
(the AI, which locks every category it assigns, or Bayes with
`lock_results`) counts as no lock while the category is still the value
it set; one the user has changed since keeps its lock. Clearing such a
category also removes that lock and the categorizer's claim (the AI's
enrichment, Bayes's `locked_by_bayes` flag), so the leg is left as if
never categorized and a later choice of the same category is the user's.
Built on `Transaction.reassign_category!`, it rechecks each row under
`FOR UPDATE` and touches exactly the entries it cleared, so a category
or lock a user sets meanwhile is not overwritten.
- A save that moves a leg to a plain transfer kind runs it for that leg
afterwards, unless the same save set the category. It checks the row in
the database rather than the record's copy, which may predate a category
a categorizer set after it was loaded. Any other category stays.
- The reconciler runs it with the kind it rewrites (`update_columns`
skips callbacks).
- The import adapter assigns it only while the leg's kind is
`investment_contribution`.
- `Family::AutoCategorizer` leaves plain transfer legs out, as
`Family#bayes_categorize_uncategorized` does, so the AI cannot put back
a category the cleanup removed.
- `data_migration:clear_stale_contribution_categories` (`DRY_RUN`,
`FAMILY_ID`, `BATCH_SIZE`) runs it over rows already left that way, read
and written in batches of 1,000 by default, each its own transaction, so
a large cleanup neither loads every id nor holds every row's lock at
once. It reports how many it cleared and is idempotent.
- A category chosen in the transfer editor is saved under the row lock
and locked as the user's, as one set on the transaction itself is, so
neither the cleanup nor a sync treats it as stale. Choosing it also
drops the automatic categorizers' claim on it, so it stays the user's
even where it is the value the AI or Bayes had set. The task's notes say
to run `reconcile_investment_transfer_kinds` first: it gives a leg
stored with a stale plain-transfer kind its contribution kind back,
which takes it, and any older unlocked editor choice on it, out of the
cleanup's scope.

Related: #3766 (the category left on an outflow after a confirmed
investment transfer is *rejected*, whose legs go back to `standard`) is
a different case and stays open. That one cannot tell an auto-assigned
category from one the user chose, whereas here the leg's new kind is one
that carries no category at all.

## Flow

```mermaid
flowchart TD
    R["Reconciler rewrites the kind<br/>(update_columns)"] --> D
    V["A save changes the kind<br/>(confirm, re-sync)"] --> SS(["Same save set<br/>the category?"])
    SS -- yes --> K0["Kept"]
    SS -- no --> D
    M["Cleanup task<br/>(rows already stale)"] --> D
    D["drop_stale_contribution_categories!"] --> Q(["Investment<br/>Contributions?"])
    Q -- "another category" --> K1["Kept"]
    Q -- yes --> L(["Locked?"])
    L -- "by the user" --> K2["Kept"]
    L -- "no lock, or the AI's<br/>or Bayes' own lock" --> C["Cleared, with that lock<br/>and the categorizer's claim"]
```

Only legs of a plain transfer kind (`funds_movement`, `cc_payment`) are
in scope; an automatic categorizer's lock counts only while the category
is still the value it set.

What stops the category coming back:

```mermaid
flowchart LR
    I["Provider import labels a leg<br/>Contribution"] --> IK{"Leg's kind is<br/>investment_contribution?"}
    IK -- yes --> A1["Gets the category"]
    IK -- "no (matched as a plain transfer)" --> A2["Left uncategorized"]
    AC["AI auto-categorize"] --> A3["Skips plain transfer legs,<br/>as Bayes already does"]
    TE["Category chosen in<br/>the transfer editor"] --> A4["Saved under the row lock, locked as the user's,<br/>automatic claims dropped, so the cleanup keeps it"]
```

## Tests

- `TransactionTest`: "a leg that becomes a plain transfer loses the
Investment Contributions category"; "a leg that becomes a plain transfer
keeps the Investment Contributions category a rule set" (a category a
rule of the user's set and still holds is theirs, as rules don't lock;
fails without the change); "a plain transfer leg keeps a category the
user locked, set in the same save, or another category";
"with_stale_contribution_category finds unlocked plain transfer legs
with the category"; "with_stale_contribution_category counts an
automatic categorizer's lock as no lock"; "a leg that becomes a plain
transfer loses an Investment Contributions category an automatic
categorizer locked" (the AI's and Bayes' locks cleared, a later choice
of the user's kept; both fail without the change); "clearing an
automatic categorizer's category drops its lock and claim with it"; "a
copy loaded before a categorizer set the category still has it cleared";
"a leg becoming a plain transfer keeps a category set after its copy was
loaded" (fails with a before-save clear);
"drop_stale_contribution_categories! clears unlocked stale legs and
touches their entries".
- `ClearStaleContributionCategoriesTaskTest`: the dry run counts and
clears nothing; the real run clears and reports the count;
`BATCH_SIZE=1` makes one call per batch and clears both legs across the
batches; `FAMILY_ID` clears only that family's legs.
- `Family::AutoCategorizerTest`: "leaves plain transfer legs
uncategorized" (fails without the change); "leaves a leg that became a
plain transfer after it was selected uncategorized": each AI result is
applied under the row's lock and skipped if the row has meanwhile become
a plain-transfer kind or gained a category (fails without the recheck).
- `Family::BayesCategorizerTest`: "a leg that became a plain transfer
after it was selected stays uncategorized": Bayes results are applied
under the row's lock with the same kind and category recheck as the AI's
(fails without the recheck).
- `DataEnrichmentTest`: "drop_metadata_flag! removes only that key, and
only from the scope". The helper now clears Bayes's lock flag for both
`Transaction.drop_automatic_category_claims!` and
`Family#unlock_own_locks`.
- `Transfer::InvestmentKindReconcilerTest`: "drops the Investment
Contributions category of a leg it makes a plain transfer".
- `TransfersControllerTest`: "a category chosen in the transfer editor
is locked as the user's"; "a category re-chosen in the transfer editor
stays the user's where the AI had set it"; "a different category chosen
in the transfer editor keeps the AI's superseded suggestion" (dropping a
claim leaves a superseded AI suggestion in place, so it stays in the AI
history filter). The four tests added last each fail without their
change.
- `Account::ProviderImportAdapterTest`: "a broker deposit labelled as a
contribution keeps no category once matched as a plain transfer leg".
- `bin/rubocop` on changed files: no offenses. `bin/brakeman`: no
warnings.
- Full suite, on main d3e3206d5: 15,836 runs, 0 failures, 0 errors, 9
skips. `bin/brakeman`: no warnings.
- Rebased onto main 6aa8cf218 (2026-11-21): the AI categorizer's scope
keeps main's rule that excluded transactions are never sent, and still
leaves plain transfer kinds out; `transaction_test.rb` keeps main's tag
tests beside this PR's. Full suite (`--all`) 18,162 runs, 0 failures, 9
skips.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Stops plain transfer legs (`funds_movement`, `cc_payment`) from keeping
the Investment Contributions category their old kind gave them, so they
no longer show under that category. The category is now cleared whenever
a leg becomes a plain transfer unless the user locked it, a rule set it,
an automatic categorizer owns it, or the same save set it.

Clearing a category also drops the automatic categorizer's lock and
claim (the AI's enrichment, Bayes's `locked_by_bayes` flag), leaving the
leg as if never categorized. The cleanup rechecks each row under the row
lock, so a category or lock a user sets meanwhile is never overwritten.

- A save moving a leg to a plain transfer rechecks the row in the
database rather than the record's copy; the reconciler clears the
category alongside the rewritten kind since `update_columns` skips
callbacks.
- The import adapter assigns the category only while the kind is
`investment_contribution`.
- `Family::AutoCategorizer` and Bayes recheck under the row lock and
skip plain-transfer legs, so neither puts the category back.
- A category chosen in the transfer editor is saved under the row lock
and locked as the user's.
- `data_migration:clear_stale_contribution_categories` (`DRY_RUN`,
`FAMILY_ID`, `BATCH_SIZE`) clears stale rows in bounded, idempotent
batches.
- The rejected-investment case in #3766 stays open: it cannot
distinguish an auto-assigned category from a user-chosen one.

<sup>Written for commit 2c0f575486.
Summary will update on new commits.</sup>

<a
href="https://cubic.dev/pr/we-promise/sure/pull/4799?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Transactions identified as plain transfers no longer receive the
Investment Contributions category by default.
* When a transaction changes from an investment contribution to a plain
transfer, its unlocked Investment Contributions category is cleared.
Locked categories and categories changed at the same time are preserved.
* Re-importing a broker transaction confirmed as a plain transfer no
longer restores the Investment Contributions category.
* Corrected transfer categories remain consistent when an investment
transfer is reconciled as a plain transfer.
* Categories selected in the transfer editor are now retained as locked
choices.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 23:51:43 -08:00
7033725a43 Keep SSO identity blocks across a SECRET_KEY_BASE change and finish the rotation guide (#5225)
Closes #3233

Most of #3233 already landed with #3190, #3221 and #4936
(`docs/hosting/encryption.md`, `security:backfill_encryption` with the
`ACTIVE_RECORD_ENCRYPTION_PREVIOUS_*` variables,
`security:rotate_setting_secrets`). This PR closes the remaining gaps.

## Problem

1. **A key rotation silently lifts SSO identity blocks.** When a super
admin permanently removes a user, `SsoIdentityBlock` stores an HMAC of
the IdP subject id, keyed with `Rails.application.key_generator`, which
is derived from `SECRET_KEY_BASE`. The rotation guide tells operators to
change `SECRET_KEY_BASE`. After that, no stored digest matches, so every
block is gone and a removed user can sign in or be re-created via SSO
again (web callback, account linking/JIT, mobile SSO). The subject id
itself is not stored, so the digests cannot be recomputed. Reproduced on
`main` with a test that stubs a new key generator.
2. **Only one public `SECRET_KEY_BASE` is detected.**
`KNOWN_COMPROMISED_SECRET_KEY_BASES` only knew the old compose default.
These are just as public and trigger no warning: `secret-value` from
`.env.example`, the literal `$(openssl rand -hex 64)` that the Hetzner
guide writes into `.env` (Compose does not run it), and the placeholders
in the Docker, PetHost and Helm guides.
3. **The rotation guide was missing** how to find the old value once
`compose.yml` has been replaced, what a new `SECRET_KEY_BASE`
invalidates, and how to roll back.

## Changes

- `SsoIdentityBlock`: new blocks store the subject id with Active Record
encryption (`encrypts :uid, deterministic: true`). The rotation backfill
re-encrypts it like every other column, so blocks no longer depend on
`SECRET_KEY_BASE`. Without Active Record encryption the model keeps
writing digests as before. For one release new blocks also keep writing
`uid_digest`, so the previous release (an image rollback, or old
processes during a rolling deploy) still sees them; lookups prefer the
encrypted uid. The digest column can be dropped in a later release.
- Migration `MoveSsoIdentityBlocksToActiveRecordEncryption` adds `uid`
(unique per provider) and `legacy_digest_key`. Every existing digest row
gets the HMAC key it was made with, stored encrypted, so legacy blocks
keep matching after a `SECRET_KEY_BASE` change. `down` restores digests
for new rows. It raises `IrreversibleMigration` instead of lifting
blocks when `SECRET_KEY_BASE` changed since `up` or the encryption keys
are missing.
- Lookup: the encrypted uid first, then legacy digests, with one
decryption of the shared stored key. An unreadable stored key is logged
and skipped, so it cannot turn every SSO login into a 500.
- `BACKFILL_MANIFEST`: `sso_identity_blocks` now also covers `uid` and
`legacy_digest_key`. `CURRENT_BACKFILL_VERSION` goes from 10 to 11 with
its digest.
- `KNOWN_COMPROMISED_SECRET_KEY_BASES`: five more public values. The
boot warnings and the settings warning (en, id, zh-CN) now say "publicly
known value" instead of "compose default".
- `docs/hosting/encryption.md`: finding the old value with `docker
inspect` (works without a Compose file and on a stopped container,
unlike `docker compose exec ... printenv`), what a new `SECRET_KEY_BASE`
invalidates (sessions, reset and confirmation links, bill calendar
links, connection flows in progress), and a rollback section.

## Design note

The subject id is now stored encrypted (recoverable with the Active
Record keys, like emails and tokens) instead of as a one-way digest. A
keyed digest would need a key of its own, and any key derived from
`SECRET_KEY_BASE` breaks on rotation. Keeping everything on Active
Record encryption means one key set, one rotation path and one backfill.

## Notes for reviewers

- Bumping `CURRENT_BACKFILL_VERSION` turns the plaintext fallback back
on for installs that already completed a backfill, until they rerun
`bin/rails security:backfill_encryption`. The manifest-digest test
requires the bump. #3833 also bumps the version, so whichever PR lands
second takes the next number.
- Known limitations: digest rows written while Active Record encryption
is not configured still depend on `SECRET_KEY_BASE`, as before. While
`ACTIVE_RECORD_ENCRYPTION_PREVIOUS_*` are set, Rails writes and queries
deterministic attributes with the oldest scheme, so encrypted lookups
(emails, and now blocks) miss rows the backfill already moved. The guide
and the boot log already say to unset them before starting the app.
- #3787 also edits `docs/hosting/docker.md`. This PR only changes one
sentence there.

## Validation

- New tests: model (encrypted path, legacy rows with and without a
stored key, survival of a `SECRET_KEY_BASE` change, unreadable stored
key, path without encryption), migration (`up` keeps legacy blocks
across a key change, `down` keeps new blocks, `down` refuses after a key
change, `down`/`up` restores the schema), detection of the public
values. The rotation tests fail on `main`.
- Related suites green: SSO blocks, migration, encryption config,
backfill, admin, sessions, OIDC accounts, API auth, OIDC identity,
security settings.
- Full suite green apart from environment-only AI/proxy tests. Rubocop
clean, Brakeman without warnings.
- Every place that checks a block goes through
`SsoIdentityBlock.blocked?` / `find_block`: web SSO callback, account
linking/JIT, mobile SSO, identity creation, removal, demo refresh. Admin
unblock and the backfill were checked as well.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Keeps SSO identity blocks of permanently removed users intact across a
`SECRET_KEY_BASE` rotation, so removed users can no longer silently
regain access when operators follow the rotation guide. Also warns about
more publicly known `SECRET_KEY_BASE` values and finishes the rotation
guide.

- New blocks store the IdP subject id encrypted with Active Record
encryption and still write the legacy digest, so the previous release
(after an image rollback or during a rolling deploy) keeps seeing them;
legacy digest rows get the HMAC key they were made with, stored
encrypted, so they keep matching after a key change.
- Each stored legacy key is read on its own: if no block matches while
some key is unreadable, `blocked?` fails closed, so one corrupt row
cannot hide blocks under readable keys or let a removed user log in.
- Rolling back after a `SECRET_KEY_BASE` change, or when a stored
subject id or key does not decrypt, raises `IrreversibleMigration`
instead of lifting blocks; `down` recomputes digests for encrypted rows.
- Adds five more publicly known `SECRET_KEY_BASE` values
(`.env.example`, hosting guide placeholders) to the boot and settings
warnings.
- Extends `docs/hosting/encryption.md` with how to recover the old value
from a stopped container or Rails credentials, what a new key
invalidates (sessions, reset links, bill calendar links, in-progress
connection flows), a restart before rollback, rollback steps that
restore the keys matching the chosen backup, and rotating provider API
keys and tokens when the old key was publicly known or leaked.
- Bumps `CURRENT_BACKFILL_VERSION` to 13 (main shipped 11 for the Enable
Banking IBAN); installs that already backfilled must rerun `bin/rails
security:backfill_encryption` to cover the new fields.

**Migration**

- Requires a `SECRET_KEY_BASE` change to happen together with
`security:backfill_encryption`; installs without Active Record
encryption keys keep writing digests as before.

<sup>Written for commit 6c859be989.
Summary will update on new commits.</sup>

<a
href="https://cubic.dev/pr/we-promise/sure/pull/5225?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Security**
* SSO identity blocks now store encrypted subject identifiers when
encryption is available, while retaining support for legacy records and
environments without encryption. Blocks remain matchable after
secret-key rotation, and duplicate blocks are avoided.
* Security warnings now cover more publicly known secrets and
placeholders.
* **Documentation**
* Expanded encryption key rotation guidance with Docker troubleshooting,
details about affected data, backup precautions, and rollback steps.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: SureBot <sure-bot@we-promise.com>
2026-11-19 16:02:44 -08:00
Chris KnutesonandClaude Opus 5.5 92a6732293 Add browser push notifications for insights and budget warnings (#4705)
Browser users of self-hosted Sure cannot receive the insight
notifications available through the native apps. This adds
standards-based Web Push behind the existing per-user preview toggle,
with separate device registration and an optional switch for Sure's
existing near-limit budget insights.

Registration is bound to the signed-in browser session. Delivery
rechecks account visibility, preferences, insight state and material
version; lock-screen text stays generic. Canonical endpoint identity
preserves ownership checks across equivalent URL spellings. Registration
is limited to 20 browser subscriptions per user, with request limits of
10 registrations and two diagnostic sends per minute per user; each
device also retains its 30-second diagnostic cooldown. Existing devices
can renew or move sessions at the subscription limit.

An atomic delivery ledger captures event-time recipients, deduplicates
material versions and recovers interrupted enqueueing. Provider attempts
and leases survive worker recovery; provider I/O holds no database
locks. Temporary VAPID configuration outages preserve pending work.
Browser actions and polling ignore responses from superseded or
disconnected controller lifecycles, and notification clicks fall back to
opening a window when navigation fails. The maintained `web-push` gem
handles encryption and VAPID signing.

One migration creates browser subscriptions and the shared delivery
ledger and adds the insight notification version. Operators configure
the same `WEB_PUSH_VAPID_PUBLIC_KEY`, `WEB_PUSH_VAPID_PRIVATE_KEY` and
`WEB_PUSH_VAPID_SUBJECT` on web and worker processes. Setup, supported
destinations, iPhone Home Screen steps and delivery-status limits are
documented in `docs/hosting/push-notifications.md`.

Validated `b24cb216a` on our homelab runners: [full validation
run](https://github.com/ctkadvisors/sure/actions/runs/44563867477). Head
`867b2f5cf` adds today's rebase (web push credentials move to backfill
version 12 after #5357 took 11) and reorders two index lines in
`schema.rb`; a [focused
run](https://github.com/ctkadvisors/sure/actions/runs/44573442012)
covers it.

- Full Rails suite: 17,842 tests, 111,092 assertions, zero
failures/errors, 10 skips.
- Full browser suite: 438 tests, 2,431 assertions, zero
failures/errors/skips.
- Encryption coverage: 509 tests, 3,220 assertions, zero
failures/errors/skips.
- All 25 Web Push JavaScript tests, RuboCop, ERB lint, Biome, and
Brakeman passed.

The review regressions cover per-user limits with concurrent
registration, equivalent endpoint identities, combined preference saves,
device deletion during insight recording, configuration outages,
material metadata version changes, deferred connection/action/poll
responses, and notification-click navigation. GPT-6 Astra re-reviewed
the corrections and found no remaining blocking findings.

I also deployed the reviewed backport to a self-hosted installation and
exercised Firefox registration, diagnostic delivery, disabling,
re-registration, and another diagnostic delivery. Both sends reached
provider acceptance on their first attempt; the budget preference
persisted. Notification presentation and tap behavior on a physical
iPhone remain unverified. Provider acceptance is not presented as proof
of display.

AI assistance: OpenAI Codex produced the implementation and supporting
tests. GPT-6 Astra performed additional adversarial reviews. Claude Code
made the 2026-11-19 changes below. Validation results are reported
separately.

Related to [#3248](https://github.com/we-promise/sure/issues/3248): this
adds a browser delivery channel for existing insights. It does not
implement the proposed payment-at-risk generator. Near-limit budget
warnings are a separate, explicit opt-in and default off.

<img width="429" height="344" alt="Browser notification controls with
opt-in budget warnings"
src="https://github.com/user-attachments/assets/e41e5479-960a-4611-a36a-2e20313d39ba"
/>


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* Added browser and installed-app push notifications for eligible
insights, with options to enable, disable, and test notifications.
  * Added an optional budget-warning notification setting.
* Push settings are available when preview features are enabled.
Notifications are tied to the current session and stop when it expires
or is revoked.
  * Selecting a notification opens the insights page.
* **Documentation**
* Added setup and usage guidance for configuring and testing push
notifications.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

## Push channels (review rounds 2026-11-16 to 11-19)

One policy, one delivery record, one job, an adapter per channel.

- `Insight#notifies?(user)` is the policy every channel reads:
high-priority insights, plus near-limit (medium) `budget_at_risk`
warnings for users who opt in. APNs keeps main's behavior and gains the
opt-in.
- `PushDelivery` (`push_deliveries`, polymorphic over the subscription)
is the one delivery record: one row per subscription and insight
version, written in the insight's save transaction, claimed before
provider IO, five provider attempts across retries and recovery.
Diagnostic test sends use the same table with `insight_id` NULL and
expire after 15 minutes.
- `DeliverInsightNotificationJob` delivers every row through the
channel's `deliver(delivery)`. `PushSubscription` (APNs) and
`WebPushSubscription` are the adapters; a new channel is one
subscription model added to `PushDelivery::CHANNELS`.
- `GenerateInsightsJob` matches main apart from the
`notification_version` bump. `Insight` records recipients in
`after_save` and enqueues them in `after_commit`.
- `RecoverPushDeliveriesJob` retries failed enqueues and abandoned
claims every 15 minutes instead of at the next daily generation.
Delivery runs on `high_priority`, not behind the nightly fan-out on
`scheduled`.
- The session foreign key cascades, so
`DemoFamilyRefreshJob#retire_old_family!` is no longer blocked by a
browser subscription.
- The jwt bump from 2.10.3 to 3.3.0 (pulled by `web-push`) is tested on
both consumers: Plaid webhook verification and the Enable Banking
request token (RS256 signature checked with OpenSSL).

### Scale limits

- Recording takes a row lock on each eligible subscription inside the
insight's save transaction, which runs inside the family's generation
advisory lock at the 6:00 UTC run. Families without a configured channel
skip it. `test/integration/push_delivery_concurrency_test.rb` covers
registration against a late 410 and concurrent registration at the
device cap; device deletion during recording is covered in
`test/jobs/generate_insights_job_test.rb`.
- The fan-out is not paced. One family's run enqueues one job per
eligible subscription. A provider 429 spends one of the row's five
attempts with backoff; nothing spreads sends across families yet.

### Not in this PR

- Rule emails stay on `NotificationDelivery`; their dedup key is rule x
transaction, not subscription x insight version.
- action_push_native as the APNs adapter (and FCM through it).
- Pacing the morning fan-out per provider.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 12:38:55 -08:00
GFRandClaude Opus 5.5 bdd3f9540a Encrypt the Enable Banking account IBAN at rest (#5357)
## What this PR does

Encrypts `enable_banking_accounts.iban` at rest. The column held the
linked bank account's IBAN in plain text, while the raw payloads next to
it were already encrypted.

- `EnableBankingAccount` declares `encrypts :iban` without determinism,
like `FioAccount#iban`. No code looks the IBAN up by value; the setup
and account selection views only show its last four characters.
- The encryption backfill manifest covers the column (backfill version
11), so `security:backfill_encryption` encrypts existing rows.

This came out of the review of the IBAN series (#3510): encrypting this
column is independent of the rest and small enough to land on its own.

## Validation

- Full Rails test suite green locally, CI green.
- Backfill manifest digest test updated.


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Encrypts the Enable Banking account IBAN at rest so the linked bank
account's IBAN is no longer stored in plain text alongside the
already-encrypted payloads.

- Uses non-deterministic encryption, like `FioAccount#iban`, since no
code looks up the IBAN by value.
- Bumps the encryption backfill manifest to version 11, so
`security:backfill_encryption` encrypts existing rows.

<sup>Written for commit d691971857.
Summary will update on new commits.</sup>

<a
href="https://cubic.dev/pr/we-promise/sure/pull/5357?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Security**
* IBANs for Enable Banking accounts are now encrypted when encryption is
configured.
* Existing account IBANs are included in the encryption backfill and
remain readable after conversion.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 07:52:28 -08:00
jaysbeekay 4bdfd6d7e3 Let a family tag a security with its own tags (#5294)
Part of #3494

Replaces #4410, which was opened from a fork branch. Its CodeRabbit
history stays there (four threads, all resolved).

**What:** makes `Security` a taggable, so a household can group
securities with its own tags ("pension", "speculative"). It has one
writer, `Security#set_tags_for(family, tag_ids)`, which replaces that
family's tags on the security and leaves every other family's alone. It
reads the family's tags under a share lock.
**Why:** classification columns live on a row every family holding the
instrument shares, so they can't hold a grouping that means something to
one household.
**Start reading:** `Security#set_tags_for` and `#tags_for` in
`app/models/security.rb`.
**Key tests** (`test/models/security/tags_test.rb`, 15 tests):
- "set_tags_for leaves another family's tags on the security alone"
- "a tag belonging to another family is not attached"
- "the security has no family-blind tag writer"
- "a family's data reset removes its security tags and keeps another
family's"

**Behaviour change:** none for users. This is the model only, with no UI
and no migration (`taggings` is already polymorphic).

**Stack:** top of the taggings stack (2 of 2), on #5293 (taggings unique
index). GitHub shows only this slice's diff.
**Size:** +50 / −0 outside tests (4 commits), 313 lines with tests.
**Re-cut onto current `main`:** the three model commits replay cleanly.
#4410 also carried three commits that refused malformed tag ids in the
transactions API (`5cedcc868`, `6a2aab984`, `95e78308b`). `main`'s
transactions API now does this itself (`malformed_tag_ids?` and
`unknown_tag_ids?`), and #4410's own merge with `main` had already taken
`main`'s controller. Those commits are therefore folded into one
test-only commit, `Pin the transactions API's refusal of malformed tag
ids`. Its tests run against `main`'s controller and are the same tests
#4410 carried. The final tree equals #4410's own changes applied to the
new #5293.
**Fork pre-flight:** jaysbeekay/sure#537. Same commits: the fork's
`up/security-taggable` is at this head.

<details>
<summary>Full description and evidence, carried from #4410</summary>

Commit SHAs, "Updated" notes and merge notes below refer to the branch
as it was on #4410, before this re-cut.

## Summary

The classification columns on `securities` (asset class, sub-class,
sector, region) live on a row that every family holding the instrument
shares, so they cannot hold a grouping that means something to one
household only, such as "pension", "kids' fund" or "speculative". `tags`
already carries `family_id` and `taggings` is already polymorphic, but
only `Transaction` is a taggable.

This makes `Security` a taggable too, with one writer that keeps the
edit inside the family that made it.

## What changed

**`app/models/security.rb`**
- `has_many :taggings, as: :taggable, dependent: :destroy` and `has_many
:tags, through: :taggings`.
- `Security#set_tags_for(family, tag_ids)`: replaces `family`'s tags on
the security and leaves every other family's alone.

**`app/models/tag.rb`**
- `has_many :securities, through: :taggings, source: :taggable,
source_type: "Security"`, mirroring the existing `transactions`.

### Tenancy: why the writer is not `security.tags = ...`

A security is global, a tag is per family. `security.tags` therefore
spans every family that has tagged the instrument, and the obvious
writers are wrong in two ways:

```ruby
security.tags = family.tags.where(id: tag_ids)  # deletes other families' taggings
security.tag_ids = tag_ids                      # attaches a tag the family does not own
```

The first destroys another household's data. The second discloses:
attaching a tag this family does not own would put that tag's name on an
instrument other families hold. `set_tags_for` resolves ids only through
`family.tags` (an id from another family, or an unknown id, is ignored),
removes only taggings whose tag belongs to `family`, and creates only
the missing ones. Each failure mode has its own test.

Reading one family's tags is `security.tags.where(family: family)`.
Nothing reads `security.tags` yet; the association comment says which
form to use.

`with_lock` serialises edits to one security. With #4081's unique index,
two concurrent saves of the same tag would otherwise fail one of them on
the index rather than both succeed. The lock reloads the record, so an
association the caller had already loaded does not keep a removed tag.

**Left out:** any UI or controller action (held for the UI phase),
tagging a `Holding` (a holding row is a per-date snapshot, so a tag on
it would be lost on the next materialisation), per-account tagging of
one instrument, allocation by tag, and export/import of security tags
(`Family::DataExporter` exports transaction tag ids only; unchanged).

## Demo data

No change to demo data or seeds.

## Migration notes

None. No migration and no schema change: `taggings.taggable_type` is a
free string, and #4081's index already keys on it.

## Verification

- New tests: `test/models/security/tags_test.rb` (11 tests): attach and
reach from the tag, another family's tag not attached, another family's
tags survive an edit, an empty selection clears only this family's, a
tag left out is removed and the kept tagging row is untouched, a
repeated id keeps the one existing row, already loaded associations
reflect the write, destroying a tag, destroying a security, merging two
tags on the same security, and a family data reset.
- **Fail-first.** Against #4081's head without this change: 11 runs, 11
errors, each `NoMethodError` on `set_tags_for`, `taggings` or `tags` for
`Security`.
- **Mutations**, each applied alone to the committed change,
`test/models/security/tags_test.rb` run, then reverted:

| Mutation | Caught by |
| --- | --- |
| Naive `self.tags = family.tags.where(id: wanted)` | "leaves another
family's tags on the security alone", "an empty selection clears this
family's tags but not another family's" |
| Ids resolved through `Tag` instead of `family.tags` | "a tag belonging
to another family is not attached" |
| `mine` taken from `Tag` (removal not scoped to the family) | "leaves
another family's tags...", "an empty selection clears..." |
| No removal of deselected tags | "a tag left out of the selection is
removed...", "an empty selection clears...", "already loaded
associations..." |
| Remove all of the family's taggings and recreate | "a tag left out ...
the kept one is untouched", "re-submitting the same tag keeps the one
existing tagging" |
| Create every wanted id, no check for existing | the same two tests
(`RecordNotUnique` from #4081's index) |
| Bare transaction instead of `with_lock` | "already loaded associations
reflect the write without a reload" |
| Drop `dependent: :destroy` on `Security#taggings` | "destroying a
security removes its taggings and keeps the tags" |
| Drop `Tag#securities` | "set_tags_for attaches the family's tag and
the tag reaches the security" |

The merge and reset tests pin existing code (`Tag#replace_and_destroy!`
from #4081, `Family::FinancialDataReset`) against the new taggable type;
they are regression coverage, not fail-first evidence for this change.
The concurrency half of `with_lock` is not exercised by a test.

- Neighbouring suites (`test/models/security/tags_test.rb`,
`security_test.rb`, `tag_test.rb`, `tagging_test.rb`): 50 runs, 0
failures.
- Full `bin/rails test` on this branch (Ruby 3.4.9): 11858 runs, 54621
assertions, 0 failures, 0 errors, 34 skips, at `6cf322131`.
- `bin/rubocop` on the changed files: no offenses. `bin/brakeman`: no
warnings. No ERB changed.
- Merges cleanly with current `main` (`git merge-tree`).

## Blast radius

**Who else hits these lines, and what do they pass?** `set_tags_for` is
new and has no caller yet. The associations add a second taggable type
to the readers of `taggings`:

- `Tag#replace_and_destroy!` moves `taggings` with no type filter, so
merging two tags now moves security taggings too. That is intended. With
#4081, a security already carrying both tags keeps one tagging instead
of gaining a duplicate; tested.
- `Tag has_many :taggings, dependent: :destroy`, and `Family has_many
:tags, dependent: :destroy`, so deleting a tag or a family removes its
security taggings.
- `Family::FinancialDataReset` scopes taggings as `Tagging.where(tag_id:
tag_scope.select(:id))`, so a reset removes that family's security
taggings and leaves other families' on the same security; tested.
- `Demo::DataCleaner` (`Security.destroy_all`) and
`lib/tasks/securities.rake` (`security.destroy!`) now also remove the
security's taggings, through `dependent: :destroy`.

**What else reads what this changes the reading of?** `grep -rn
"taggings\|Tagging\|taggable" app/ lib/`:
- `Rule::ConditionFilter::TransactionTag` filters `taggable_type:
"Transaction"`; unaffected.
- `ReportsController` joins taggings from the transaction side;
unaffected.
- `Family::DataImporter` and `QifImport` create taggings on transactions
only; unaffected.
- `Family::DataExporter` reads `transaction.tags` / `tag_ids`; security
tags are not exported (left out above).

</details>

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Makes `Security` a taggable so a family can group securities with its
own tags, such as "pension" or "speculative". No UI, no migration, and
no behavior change for users.

- Adds `Security#set_tags_for(family, tag_ids)`, which replaces only
that family's tags on the shared security row, leaves every other
family's alone, and refuses an unsaved security.
- Reads the wanted tags under a share lock inside the security row lock
so a concurrent tag deletion cannot fail the insert.
- Reads a family's tags via `Security#tags_for(family)`; the
family-blind `tags`, `tags=`, `tag_ids` and `tag_ids=` accessors are
deliberately absent.
- Adds `Tag#securities` as a read-only query, so `set_tags_for` stays
the only tag writer.
- Adds `Security#move_taggings_to!` and calls it from
`securities:deduplicate`, so deduplicating securities moves a
duplicate's tags onto the canonical row instead of destroying them.
- Pins the transactions API's refusal of malformed tag ids (validation
failed, tags unchanged) with tests against `main`'s existing controller
behavior.

<sup>Written for commit 0f6ab2b9e0.
Summary will update on new commits.</sup>

<a
href="https://cubic.dev/pr/we-promise/sure/pull/5294?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/we-promise/sure/5294?returnTo=https%3A%2F%2Fgithub.com%2Fwe-promise%2Fsure%2Fpull%2F5294&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Security tags are managed separately for each family, so updating or
clearing one family’s tags preserves tags belonging to others.
* Invalid tag identifiers and unsupported tag input formats are rejected
without changing existing tags or creating transaction entries.
* Supported clearing inputs continue to remove the selected family’s
tags.
* Tags are preserved when duplicate securities are consolidated,
including when the canonical security already has the same tag.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-18 23:38:42 -08:00
David GilandJuan José Mata 3c8106ff32 security: unsafe chat markdown, constantize on params, LIKE wildcards, CSV formula injection (#1943)
Four injection fixes, merged with current main.

## Scope

- **Unsafe HTML in chat markdown (CWE-79).** The `markdown` helper
renders both user and assistant chat messages. Redcarpet passed raw HTML
through and the result was marked `html_safe`, so `<script>` or `<img
onerror>` in a message ran in the viewer's session. Chats are per user,
so this does not reach other family members directly. The ways in are
assistant replies (model output that bank-feed text such as transaction
or merchant names can steer), messages written through the API, and a
super admin impersonating the user. Two layers, both needed:
`filter_html` drops raw HTML in the input (`div`, `span` and `class`
must stay allowed for footnotes and code blocks, so without it a message
could still cover the app with `<div class="fixed inset-0">`), and a
`sanitize` allow-list drops `javascript:` and `data:` targets in links
the renderer builds itself, which `filter_html` never sees.
- **`constantize` on request params (CWE-470).**
`Import::MappingsController` took both the mapping class and the target
class from params, so any constant in the app could be resolved and have
class methods and constants looked up on it (`type: "Family"` raised
`uninitialized constant Family::CREATE_NEW_KEY`). The mapping row
already declares its target, so neither comes from params now, and the
form no longer posts those fields. `AccountImport` did the same with a
user-supplied mapping value and now goes through
`Accountable.from_type`.
- **LIKE wildcards in the API search.** The search term went into an
`ILIKE` pattern unescaped, so searching for `%` returned every
transaction in the family. It now goes through `sanitize_sql_like`, like
every other search path in the app.
- **CSV formula injection (CWE-1236).** Account, transaction, category,
merchant and rule names, notes, tickers and subtypes reached exported
spreadsheets unescaped. `CsvSanitizer` holds the escape in one place.
`Family::DataExporter` routes its writer through it instead of picking
columns, so a column added later can't go out unescaped. Plain numbers
are left alone, so negative amounts stay numeric. The reports CSV
escapes its category column only, because its amount cells are formatted
money such as `-$42.00`. Imports read values as written, so a user's own
leading quote (`'+44 Taxis`) survives; NDJSON is not escaped and stays
the lossless round-trip.

## Dropped

- `return_to` sanitization in `StoreLocation` and `AccountableResource`:
already on main, with one shared helper.
- The `ORDER BY` change in `ReportsController`: `sort_direction` is
already limited to `asc`/`desc`, so there was nothing to inject.
- The changelog / release-notes sanitize: that HTML comes from GitHub's
markdown API for a hard-coded repository and GitHub already sanitizes
it. Defence in depth only.
- The escape on the XLSX report generator: it has no route and `caxlsx`
is not bundled.

## Tests

Each guard has a test that fails when the guard is removed: markdown raw
HTML and link schemes, mapping target and create-new handling, the
`AccountImport` type allow-list, literal `%` in the API search, every
exported CSV including merchants and both reports sections, negative
numbers staying numeric, and imports keeping a leading apostrophe.

---------

Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
2026-11-17 22:45:23 -08:00
Guillermo Tomás Fernández MartínandClaude Opus 5 a963ca694d fix(balance): stop freezing mid-day provider readings as waypoints (#3519)
## Problem

Linked accounts accumulate one "Manual balance update" entry per day.
Several Enable Banking users reported it on Discord (BBVA, Sabadell,
N26). The visible entries are the symptom; the corrupted history behind
them is the bug. This fixes #3291

On every sync, `Account::CurrentBalanceManager` saves the
provider-reported balance as a `current_anchor` valuation dated today.
On the next day's sync, `preserve_anchor_as_reconciliation_if_stale`
converted yesterday's anchor into a `reconciliation` and renamed it,
which renders as "Manual balance update" for depository accounts.

The problem is timing. That anchor holds whatever the provider reported
at the moment the sync ran — the default auto-sync runs at **02:22** —
but `Balance::ReverseCalculator:34` treats a reconciliation as that
day's **closing** balance and hard-resets end-of-day to it. Any
transaction that posts later the same day lands on the wrong side of the
waypoint, and every balance before that date shifts.

```
Day 1, 02:22 sync   bank says 100        →  current_anchor(Day 1, 100)
Day 1, afternoon    two payments of −20 post, both dated Day 1
                    the account really closes Day 1 at 60
Day 2, 02:22 sync   the payments import
                    Day 1's anchor is frozen as a waypoint of 100
                    a new anchor is created for Day 2 at 60
```

Working backwards from Day 2:

| date | closing | opening | why |
|---|---|---|---|
| Day 2 | 60 | 60 | anchor, nothing posted today |
| Day 1 | **100** | **140** | reset to the waypoint, then the −40
reversed back out of it |

Day 1 closes at 100 when the bank closed it at 60. Day 0 inherits 140.
Everything earlier is inflated by 40.

## What this changes

We keep #1663 because when a provider gives incomplete transaction
history (as reported in #1492, #1484) we need the anchor. This PR adds a
refinement on when the anchor has to be there.

The rotation could not be made conditional where it stood, because
**every processor set the balance before importing transactions**. At
the moment the old code rotated the anchor, the entries that would
explain the move had not landed yet. Therefore, in this PR we change the
ordering so that each processor now anchors the reported balance
**after** its import:

| Processor | Before | After |
|---|---|---|
| `plaid_account` | `process_account!` (anchors) → transactions →
investments → liabilities | `process_account!` → transactions →
investments → liabilities → **anchor** |
| `enable_banking_account` | `process_account!` (anchors) → transactions
| `process_account!` → transactions → **anchor** |
| `coinstats_account` | holdings → `process_account!` (anchors) →
transactions | holdings → `process_account!` → transactions → **anchor**
|
| `redbark_account` | `update_account_balance` (anchors) → transactions
| `update_account_balance` → transactions → **anchor** |
| `sophtron_account` | `process_account!` (anchors) → transactions |
`process_account!` → transactions → **anchor** |
| `indexa_capital_account`, `snaptrade_account`, `questrade_account` |
`update_account_balance` (anchors) → holdings → activities |
`update_account_balance` → holdings → activities → **anchor** |
| `ibkr_account`, `trade_republic_account`, `trading212_account` |
`update_account_balance!` (anchors) → holdings → activities |
`update_account_balance!` → holdings → activities → **anchor** |

Each balance-update step now **returns** the balance it computed instead
of anchoring inline, and `process` passes that value to
`set_current_balance` once the import is done. No processor holds the
balance in instance state. The same change is applied to
`lib/generators/provider/family/templates/account_processor.rb.tt`, so
new providers are generated with the correct ordering and a comment
stating it as a contract.

With the ledger complete, `set_current_balance_for_linked_account`
judges the standing anchor at the point it would overwrite it:

- the imported transactions **explain** the move to today's reading →
the anchor carries nothing they don't already carry, so it moves forward
in place (date *and* amount), exactly like a same-day update;
- they **don't** → the provider knew something the ledger doesn't, so it
is preserved as a reconciliation waypoint and a fresh anchor is created
for today.

```
expected = older + (asset? ? -net : net)
```

Steady state for a healthy linked cash account: **one** `current_anchor`
row, the live one, and **zero** system-generated "Manual balance update"
rows.

### Feature flag

The judge-on-write behavior is gated on `BALANCE_REUSE_EXPLAINED_ANCHOR`
(default off). With the flag unset, every stale anchor is preserved as a
reconciliation waypoint, matching current `main`. Enabling it opts an
installation into the new behavior. See [Linked-account balance
anchoring](docs/hosting/balance-anchors.md) for rollout and rollback.

### Scope

Restricted to `:cash` accounts. For `:investment` the reported total
moves with market prices and trades only shift cash ↔ holdings, so the
identity means nothing; those accounts keep today's behaviour.
Mixed-currency windows bail rather than guess an FX rate.

Only this account's own system-created anchors are ever touched: `kind:
"current_anchor"` is written in exactly one place, so a user's
reconciliation can never be reached. `Entry`'s date-uniqueness
validation (scoped to `[account_id, entryable_type]`) means an account
holds at most one valuation per date, so the promote path can never
collide.

## Rollout and rollback

`BALANCE_REUSE_EXPLAINED_ANCHOR` is documented in the production
`.env.example` and defaults to off. Enabling it can revise historical
chart values on the first reverse sync and overwrites explained anchors
in place; disabling the flag or reverting the code cannot recover an
observation that was overwritten while enabled. Existing reconciliation
rows are retained, and there is no automatic repair migration because
the schema cannot distinguish a sync-created waypoint from a genuine
user reconciliation. See [Linked-account balance
anchoring](docs/hosting/balance-anchors.md).

## Known residuals

- The single live `current_anchor` is still visible in the activity feed
as "Current balance", because `current_anchor` is not filtered anywhere
in `app/views`, `app/components`, `app/controllers` or `app/helpers`.
- `ledger_explains?` returns `false` on any entry whose currency differs
from the account's, so an account with occasional foreign-currency
transactions lands in the preserve branch more often than it should.
- Plaid reports `balances.current` including pending for credit-type
accounts (`plaid_account/processor.rb:130`), while `ledger_explains?`
uses `excluding_pending` to match the calculators. Those accounts will
more often land in the preserve branch.
- A pending row claimed in place keeps its original `created_at`.
`ledger_explains?` therefore treats it as already included in the anchor
even when the provider balance excluded pending. For those providers an
explained move can still be preserved as a waypoint. This is a known
limitation; it needs a financial-change boundary or provider
pending-basis metadata.
- Legacy duplicate `current_anchor` rows are not normalized. The newest
row is selected deterministically, but older rows remain.

## Validation

`bin/rails test` (full suite): **16,410 runs, 105,132 assertions, 0
failures, 0 errors, 9 skips**.

`test/models/account/current_balance_manager_test.rb` includes both
arnau scenarios: a late-posted same-day transaction moves the stale
anchor forward, and a pending row claimed in place pins the known
watermark limitation.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Bug Fixes**
* Current balances are now anchored after transactions, holdings, and
activities finish importing, improving sync accuracy.
* Failed or incomplete imports no longer update balance anchors or
create reconciliation waypoints.
* Balance waypoints are preserved when ledger activity cannot explain a
provider-reported change or currencies do not match.
* Explained changes update existing waypoints without unnecessary
reconciliation entries.
* Improved handling for liabilities, multi-day gaps, repeated same-day
syncs, duplicate entries, and pre-existing balance activity.

* **Tests**
* Expanded coverage for balance anchoring, reconciliation behavior, and
sync ordering across supported account types.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-11-17 13:57:40 -08:00
Josh SandersandClaude Opus 5.5 992bfdcd88 AI plumbing 2b: routing and consent (#4774)
> **Part 2b of the AI plumbing series, stacked: 2a (#4773) → 2b (#4774)
→ 2c (#4775) → 2d (#4765) → 2e (#4771).** Merge them in that order. This
branch contains the parts before it, so its diff shows their commits
until they merge; this part is its last 19 commits (not counting
merges). Compare 2b alone:
[`feat/ai-2a-transports...feat/ai-2b-routing`](https://github.com/josh-sanders/sure/compare/feat/ai-2a-transports...feat/ai-2b-routing).

Part 2b of the AI plumbing redesign proposed in #4440. Split out of
#4765, which held 2a to 2d and now holds 2d only. Implementation plan:

[`pr-2b-routing-and-consent.md`](https://github.com/josh-sanders/sure/blob/proposal/v0.8-ai-workflow-reviews/docs/proposals/v0.8/pr-2b-routing-and-consent.md);
its place in the series is in

[§19](https://github.com/josh-sanders/sure/blob/proposal/v0.8-ai-workflow-reviews/docs/proposals/v0.8/ai-plumbing-redesign.md#19-delivery).

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


## Problem

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

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

## What this adds

```mermaid
flowchart TB
  ENV[("ENV + Setting<br/>(today's values)")] --> LEC["Ai::LegacyEnvConfig<br/>§4.5 table, today's resolvers"]
  LEC --> CFG["Ai::Config.current<br/>endpoints, models, routes per feature"]
  CFG --> R["Ai::Router#resolve(feature)"]
  RT["Ai::Routes::MATRIX<br/>lane, needs, consent, sends"] --> R
  CON["Ai::Consent<br/>the user's AI switch (chat, bills)"] --> R
  R --> AV["Ai.available? / Ai.availability / Ai.plan"]
  AV --> G["requires_ai<br/>smart fill, smart configure, merchants#enhance"]
  AV --> V["Enhance button, rule actions, document upload,<br/>MCP tool list, PDF job, document search"]
  CFG --> VS["VectorStore: store, embedding server, model"]
  CFG --> AH["AiHealth::Probe endpoints"]
```

```mermaid
flowchart LR
  F["feature"] --> L{"routes listed?"}
  L -- no --> NC[":not_configured"]
  L -- yes --> C{"Ai::Consent"}
  C -- denied --> UD[":user_disabled"]
  C -- ok --> K{"a model meets the feature's needs?"}
  K -- no --> CM[":capability_missing"]
  K -- yes --> P["Ai::Plan (ordered routes)"]
```

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

## Reviewer guide

Read in this order:

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

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

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

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

**Worth a look:**

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

## Upgrade notes

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

## Still on old code

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

## Validation

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

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

## Review on this PR

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

## Merged forward

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

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_016zAWUV2Sxn9CgsmcUqojAZ




<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:52:44 -08:00
GFRandClaude Sonnet 5 9d09a48af6 security: close remaining plaintext-storage gaps found while auditing #3142 (#3190)
**Bottom of a stack:** #3190 → #3833 → #4945. This merge with main also
sets the rotation's previous schemes on
`ActiveRecord::Encryption.config` directly: the backfill-completion
check from #3221 snapshots the engine config before that line runs, so
setting only the Rails config left a key rotation without any previous
scheme.

## Why a separate PR

#3189 fixes the `encryption_ready?` gating bug itself. While auditing
every place that bug could touch (per the issue thread, security
deserves a thorough pass, not just the two spots originally reported), I
found several **related but distinct** gaps that fixing the gating check
alone does not close. Splitting these out so the critical fix (#3189)
can be reviewed and merged fast on its own.

## What's in this PR

1. **Three models had no encryption wired up at all** (not a gating bug
— no `encrypts` call existed in the first place):
`IndexaCapitalAccount`, `SophtronAccount`, `OnchainWalletAccount` now
encrypt their raw provider payloads, matching every structurally
identical sibling `*Account` model.
2. **`IndexaCapitalItem#username`/`#document`** (a login-credential pair
used by one of its two auth modes — `document` is very likely a national
ID/tax document number for KYC) had no `encrypts` call. Now encrypted.
3. **Eight `Item` models encrypted their credentials but not
`raw_payload`/`raw_institution_payload`**, unlike every sibling provider
that does: Brex, Coinbase, Binance, CoinStats, Mercury, IndexaCapital,
Sophtron, SnapTrade.
4. **`lib/tasks/security_backfill.rake`** (the task operators run to
re-encrypt data written before encryption was correctly configured) only
covered 16 of the now-50 affected models. Extended to cover every
provider item/account, plus `ApiKey`, `SsoProvider`, `SsoIdentityBlock`.
Without this, upgrading past #3189 would leave previously-plaintext data
for roughly half the affected models with no remediation path at all.
5. **`compose.example.yml`/`compose.example.ai.yml` shipped an
identical, hardcoded, *working* default `SECRET_KEY_BASE`.** Since
Active Record's encryption keys are deterministically derived from
`SECRET_KEY_BASE` when not set explicitly, any default install that
never overrode it in `.env` ends up with encryption keys — and
session/cookie-signing secrets — that are publicly computable straight
from this repo. Removed the default: compose now fails fast with a clear
message if `SECRET_KEY_BASE` isn't set. Also added the
`ACTIVE_RECORD_ENCRYPTION_*` passthrough these files were missing (same
gap as #2388 — folded in here rather than duplicating it, feel free to
close that one in favor of this if maintainers agree).
`docs/hosting/docker.md` updated to match: setting `SECRET_KEY_BASE` is
no longer presented as an optional/skippable step, and a new section
documents running the backfill task after an encryption-related update.

## A pre-existing bug found along the way

Adding a read/update test for the newly-encrypted `IndexaCapitalAccount`
surfaced a latent bug: `test/fixtures/indexa_capital_accounts.yml` seeds
`raw_payload`/`raw_holdings_payload`/`raw_activities_payload` as literal
`{}`/`[]`. Once those columns are encrypted,
`config.active_record.encryption.encrypt_fixtures` double-encodes empty
Hash/Array fixture values for jsonb columns, so reading them back raises
`ActiveRecord::Encryption::Errors::Decryption`.

This isn't new — `SnaptradeAccount`'s fixture has the identical
`{}`/`[]` pattern and is silently broken the same way
(`SnaptradeAccount.first.raw_payload` raises identically on `main`
today); its test suite just never happens to read that field on a
fixture-loaded record. Fixed `indexa_capital_accounts.yml` to use `nil`
instead, which resolves it. Left `SnaptradeAccount`'s pre-existing
instance of this out of scope here since it's unrelated to this PR's
changes — happy to file a follow-up issue if useful.

## Testing

- `bin/rails test` on all changed models/tasks: 153 runs, 368
assertions, 0 failures.
- `bin/rubocop`: 24 files, no offenses.
- `bin/brakeman --no-pager`: 0 errors, 0 security warnings.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Security**
- Expanded encryption coverage for sensitive provider credentials and
financial data.
  - Added warnings for compromised default secret keys.
  - Encryption warnings now recognize automatically generated keys.

- **Configuration**
  - Self-hosted deployments must provide `SECRET_KEY_BASE`.
  - Added optional encryption key settings.

- **Maintenance**
  - Added tools and guidance for re-encrypting existing data.
  - Legacy unencrypted data remains readable during migration.
  - Improved authentication during encryption migrations.

- **Documentation**
  - Updated Docker hosting and encryption migration instructions.

- **Tests**
- Added coverage for encryption, warnings, authentication, and
backfills.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-12 12:33:21 -08:00
1e2003afec security: gate plaintext encryption fallback behind a backfill-completion flag (#3221)
Closes #3214.

Builds on #3189 (merge that first). Independent of #3190.

## Background

`config/initializers/active_record_encryption.rb` unconditionally sets
`support_unencrypted_data = true` and `extend_queries = true` so
self-hosted installs with pre-existing plaintext data (on the ~50 models
#3190 covers) don't crash on boot before running `bin/rails
security:backfill_encryption`. The problem, flagged by CodeRabbit on
#3189 and tracked as #3214: these settings stay on forever, even after
the backfill has fully completed. A plaintext value landing in an
encrypted column later — a bug, a bad migration, a manual DB edit —
would be silently accepted instead of raising, defeating the integrity
guarantee encryption is supposed to provide.

## What this PR does

1. **Versioned completion flag**
(`Setting.encryption_backfill_completed_version`,
`app/models/setting.rb`) — a DB-backed setting so it persists across
processes/deploys and is readable at boot, before the backfill task has
necessarily ever run.
2. **`ActiveRecordEncryptionConfig::CURRENT_BACKFILL_VERSION` +
`.backfill_completed?`** (`lib/active_record_encryption_config.rb`) —
compares the stored version against the current one, so a *future*
expansion of the backfill task's model coverage (bumping the constant)
correctly puts installs that completed an older, narrower backfill back
into "not complete" until they re-run the task. Defaults to `false`
(fallback stays enabled) if the `settings` table can't be read yet —
fresh installs, pre-migration boots, DB errors.
3. **`lib/tasks/security_backfill.rake`** now sets the flag, but only on
a clean (zero-failure), non-dry-run completion — a partial failure must
not disable the fallback for models that still have unreadable plaintext
rows.
4. **`config/initializers/active_record_encryption.rb`** now gates both
settings on `ActiveRecordEncryptionConfig.backfill_completed?` instead
of leaving them unconditionally on.
5. **`config/initializers/encryption_warning.rb`** gets a third
boot-time `[SECURITY]` warning branch (alongside "not configured" and
"compromised default key") for "configured but backfill not completed
yet," reusing the existing operator-facing warning pattern rather than
adding new UI.

## Testing

- New coverage in `test/lib/active_record_encryption_config_test.rb`
(real `Setting` read/write round-trips for `backfill_completed?`, plus
the DB-unreachable rescue path) and
`test/lib/tasks/security_backfill_test.rb` (clean run sets the flag; dry
run and a run with failures don't).
- `test/initializers/active_record_encryption_test.rb` updated with a
comment explaining why the existing assertions still hold (initializer
runs once at boot in the "not completed" state the test suite always
starts in; the gating logic itself is covered separately since
re-running the initializer per-test isn't possible).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Security**
* Expanded encryption coverage for sensitive credentials and provider
data.
* Improved compatibility during encryption migration and strengthened
configuration checks.

* **Bug Fixes**
* Prevented misleading encryption warnings for supported self-hosted
configurations.
  * Improved reporting when encryption backfills encounter failures.

* **New Features**
  * Added encryption backfill tracking and broader coverage.
* Added safer handling for incomplete or compromised encryption
settings.

* **Documentation**
* Clarified required Docker environment settings and documented
encryption backfill procedures.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: jaysbeekay <46616837+jaysbeekay@users.noreply.github.com>
2026-11-12 10:46:46 -08:00
GFRandClaude 303bfe4211 Encrypt every table in the backfill and document adding keys to an instance with data (#4936)
Closes #2422

## Problem

Since #3189, a self-hosted instance without its own keys encrypts with
keys derived from `SECRET_KEY_BASE`. Rows written before that stay
plaintext until `security:backfill_encryption` converts them. Several
gaps remain on main:

- **The backfill misses most tables.** It works from a hand-kept list of
20 tables, but 60 tables declare `encrypts`. Kraken, Coinbase and
SnapTrade items, API keys, SSO providers, Wise, IBKR and others are
missing. A run reports `ok: true` and leaves those rows plaintext.
- **The backfill can destroy data.** With `support_unencrypted_data` on,
a value encrypted with keys the instance doesn't have reads back as the
raw envelope string, and the task encrypts that string again. The
original value is lost. This happens, for example, after adding your own
keys to an instance whose data uses the derived ones, which is #2422.
Plaintext jsonb objects with a `"p"` key also crash the run with
`NoMethodError`, because Rails reads them as envelopes.
- **Keys in `.env` have no effect with Docker.** `compose.example.yml`
and `compose.example.ai.yml` don't pass `ACTIVE_RECORD_ENCRYPTION_*` to
the containers. The settings that `docs/hosting/encryption.md` and the
in-app guide describe never reach the app.
- **No guide covers #2422.** Adding keys to an instance with data
changes its keys. Data already encrypted with the derived keys can't be
read with new ones and has to be rotated. Data that is still plaintext
can be converted directly. Nothing tells an operator which case they are
in.

## Changes

- **`security:backfill_encryption`**:
- Finds every model that declares `encrypts` at runtime instead of using
the list.
- Session columns go through the same path. IP digests run separately as
`session_ip_digests` and only touch rows that need one.
- Refuses values that still hold a complete Rails encryption envelope
(string or jsonb object) instead of encrypting them again. This applies
to the dry run and the real run.
- Falls back to the raw value when the getter raises on envelope-like
plaintext.
- Reports a top-level `failed_count`, and returns `ok: false` with exit
status 1 when any row fails.
- **Compose examples**: forward the three keys as `${VAR:-}`. An empty
value counts as unset, so installs without keys keep the derived ones.
- **Docs** (`docs/hosting/docker.md`, new section "Encrypting sensitive
data"):
  - Where the keys come from, and how to set your own on a new instance.
- Converting rows stored before encryption with the current keys: take a
named backup, stop `web` and `worker`, run the dry run, convert with
`docker compose run --rm web`, then start and check.
- Switching an existing instance to your own keys. A dry run with the
new keys shows whether any data is encrypted with the old ones. If none
is, the data is converted directly. If some is, the guide sends the
operator to the rotation procedure in `encryption.md` instead.
- An undo path via the named backup, recovery steps for operators who
already added keys, and a warning for keys that were sitting unused in
`.env`.
- `.env.example` and the in-app guide link now point to the new section.

## Related pull requests and merge order

Several open PRs touch the same task, the same files or the same topic:

- #3221 adds a completion flag that turns the plaintext fallback off
once the backfill has run. It also adds a manifest of encrypted columns
(`BACKFILL_MANIFEST`), with a test that keeps it in sync with the
`encrypts` declarations.
- #3190 adds key rotation to the task, including keys derived from a
previous `SECRET_KEY_BASE`. It already carries the #3221 manifest.
- #3833 encrypts `DebugLogEntry` metadata and adds it to the backfill.
- #2388 forwards the same three variables in the compose examples. This
PR includes that change.
- #3583 adds `SsoProvider` to the old list. Runtime discovery covers it
here.
- #2679 and #4887 document the same topic in other places.

#3221, #3190 and #3833 are mine, and I'll bring them up to date in this
order:

1. **This PR first.** It is the smallest of the group, adds no migration
or setting, and fixes the coverage and double-encryption problems on
main today.
2. **#3221 next.** The task loop then switches to its manifest, which
the completion flag needs at boot. It keeps the refusal, the raw-value
fallback and `failed_count` from this PR. I test-merged the two branches
this way, and the encryption tests with keys (445 runs) and the full
suite (15654 runs) pass.
3. **#3190 after #3221**, since it builds on the same manifest. Once it
is in, the "Switching an existing instance to your own keys" section can
point to its rotation task instead of the manual steps in
`encryption.md`.
4. **#3833 at any point.** On top of this PR it needs no list entry.
After #3221 it needs a manifest entry and a version bump.

If #2388 or #3583 is merged first, it touches the same lines and the
conflict is trivial to resolve.

## Tests

- `test/lib/tasks/security_backfill_test.rb` (these fail on main):
  - Checks coverage against every `encrypts` line in `app/models`.
- Converts a plaintext value in every encrypted column of every table
and checks that it is stored as an envelope and decrypts to the
original.
- Checks a rerun, the refusal of foreign ciphertext in string and jsonb
columns (including the dry run and the exit status), envelope-like
plaintext, and session user agents and IP digests.
- The full `bin/rails test` (15675 runs) and the encryption tests with
keys pass. Rubocop, Brakeman and erb_lint are clean.
- End to end, with an image built from this branch and the new compose
file, starting from an instance created with the current release and
demo data (all plaintext):
- After the update, new writes such as session user agents are encrypted
with the derived keys, and older rows stay plaintext.
- Converting with the current keys: the dry run lists 61 entries with
`failed_count` 0, and the conversion and a rerun report `ok: true`. The
database then holds envelopes, and sign-in and the dashboard,
transaction, account and provider pages work.
- Switching to your own keys once data uses the derived keys: the dry
run refuses the derived-key session row (`failed_count` 1, exit status
1), and removing the keys again leaves the instance working.
- Switching to your own keys right after the update, before anything is
written with the derived keys: the dry run reports 0, and after the
conversion the app runs with the new keys and everything decrypts.
  - The undo path restores the plaintext instance from the named backup.
- Adding keys without converting reproduces the silent damage:
derived-key values read back as raw envelopes.

## Not included

The docs don't describe running the conversion with the app online. With
`web` and `worker` stopped, nothing writes while rows change keys.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixes the encryption backfill so it covers every encrypted table and
refuses rows encrypted with keys the instance doesn't have, instead of
double-encrypting and losing the original value, and documents how to
add your own encryption keys to an instance that already has data.

The task previously converted only 20 hand-listed tables while 60
declare `encrypts`, and ciphertext no configured key can decrypt read
back as its raw envelope and got encrypted again. It now finds encrypted
models at runtime, sends session user agents through the same path,
reports session IP digests as `session_ip_digests`, and returns `ok:
false` with exit status 1 when any row fails.

**Docs**
- New "Encrypting sensitive data" section in `docs/hosting/docker.md`
covers setting keys on a new instance, converting plaintext rows with
the current keys, and switching an existing instance to your own keys.
- When the dry run with new keys shows data encrypted with the
previously derived keys, the guide has you remove the keys and keep the
derived ones; the manual rotation isn't described because the example
compose files can't provide the required initializer.
- The compose example files now forward the three
`ACTIVE_RECORD_ENCRYPTION_*` variables, so keys in `.env` reach the
containers.
- `.env.example` and the in-app encryption guide link to the new
section.

Tests assert coverage against every `encrypts` declaration in
`app/models` and convert a plaintext row in every encrypted column of
every table.

<sup>Written for commit aa2218e41a.
Summary will update on new commits.</sup>

<a
href="https://cubic.dev/pr/we-promise/sure/pull/4936?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Documentation**
* Expanded the Docker hosting guide with instructions for configuring
and backing up encryption keys, handling existing data, and converting
legacy unencrypted data.
* Updated encryption guidance links and clarified the effects of adding
keys to an instance with existing data.
* **Configuration**
* Added optional encryption key settings to the example Docker
configurations, with guidance on setting them together.
* **Improvements**
* Enhanced the data backfill task to cover encrypted fields across
models, identify undecryptable values without changing them, and report
failures.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-12 07:31:03 -08:00
Artem Danilov 70647cb11c Move LLM prices to a config file refreshed on release (#4666)
Follow-up to #4638, as suggested in [the review
comment](https://github.com/we-promise/sure/pull/4638#issuecomment-6561918619):
move the prices out of `app/models/llm_usage.rb` into a config file that
a GitHub workflow can update on every release.

## Problem

`LlmUsage::PRICING` was a Ruby hash. Every provider price change or new
model needed a hand-written code PR. When nobody wrote one, new models
showed **N/A** on the LLM usage screen (Opus 5.5 before #4638).

## Resulting behavior

**Config file.** `config/llm_pricing.yml` holds the same rows, one model
per line. The family and tier fallbacks (`claude-opus`, `gpt-sol`, …)
and the `gpt-5.6` alias are now YAML aliases of the row they copy, not
duplicate numbers. `LlmUsage` loads the file into the unchanged
`PRICING` / `PRICING_VERIFIED_ON` constants, so lookups, providers'
order and costs are identical. I checked that the loaded hash, including
key order, equals the old constant. No call sites change.

**Updater.** `bin/update_llm_pricing` (logic in
`lib/llm_pricing_updater.rb`, stdlib only) reads [LiteLLM's price
list](https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json)
and:
- rewrites a listed row only when its prices changed. The edit happens
in place, so comments, anchors and aliases survive. It maps input,
output, Anthropic cache-read (only when not 0.1x input) and the
`*_above_<N>k_tokens` long-context tier.
- adds new Claude (`claude-opus-6`) and GPT tier (`gpt-6.2-sol`)
releases, which are exactly the models the fallbacks would otherwise
only estimate. Dated snapshots and `-4-0` aliases are skipped.
- accepts only entries from the matching LiteLLM provider (`openai`,
`anthropic`, `gemini/…`), with finite, non-negative, sane numbers. It
rejects an entry with a partial long-context tier, or an Anthropic entry
without a cache-read price. It keeps a configured long-context tier that
LiteLLM doesn't list, and reports those rows as left unchanged. It
refuses to write a file that no longer loads.
- prints a Markdown summary: what changed, what was added, and which
rows LiteLLM lacks.

**Workflow.** `.github/workflows/llm-pricing.yml` (**Refresh LLM
pricing**) runs on `v*` tags and on demand, on `we-promise/sure` only.
When the file changes and no refresh PR from this repository is open, it
force-pushes `automation/refresh-llm-pricing`, opens a PR with that
summary, and dispatches `pr.yml`, like the version-bump flow in
`publish.yml`, because PRs opened with `GITHUB_TOKEN` don't trigger CI.
While a refresh PR is open, later runs skip with a warning, so a review
in progress is never rewritten. A failed PR lookup fails the run. The
job runs on `ubuntu-24.04` like `ci.yml`. `verified_on` is never bumped
automatically. The PR body asks the reviewer to check the changes
against the official pages first.

A dry run against today's LiteLLM list changes one row: it adds a 272K
long-context tier to `gpt-5.6-cyber`, which OpenAI's page does not list.
That is the kind of thing the PR review is for. It adds no models. It
reports 6 rows LiteLLM lacks: `o1-mini`, `gemini-3.1-pro`,
`gemini-3-flash`, `claude-opus-4`, `claude-opus-4-1`, `claude-sonnet-4`.

`docs/hosting/ai.md` points at the config file and describes the
workflow.

## Notes for maintainers

- The workflow needs the existing "Allow GitHub Actions to create and
approve pull requests" setting, which `publish.yml` already relies on.
- LiteLLM is a third-party list. Today it matches the official Claude
and OpenAI prices to the cent, but it can lag. The workflow therefore
only proposes changes and never merges them.

## Validation

- `bin/rails test test/lib test/models/llm_usage_test.rb
test/models/provider
test/controllers/settings/llm_usages_controller_test.rb`: green. New
`LlmPricingUpdaterTest` covers in-place rewrites with comments and
aliases, adding releases while skipping snapshots, aliases, other
providers and non-tier IDs, rejecting bad source data, and that the
bundled config round-trips unchanged when LiteLLM agrees with it.
- `bin/rubocop`: no offenses. `bin/brakeman`: 0 warnings. `actionlint`
(with shellcheck) on the new workflow: clean. No UI, ERB or JS changes.

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Follow-up to #4638: moves LLM pricing from a Ruby hash in `LlmUsage`
into `config/llm_pricing.yml`, refreshed by a new GitHub workflow so
provider price changes and new model releases no longer need
hand-written code PRs.

**Behavior**
- `PRICING` and `PRICING_VERIFIED_ON` load from the YAML file; lookups,
fallbacks, costs, and the LLM usage screen are unchanged.
- `bin/update_llm_pricing` reads LiteLLM's price list, rewrites changed
rows in place (comments, anchors, aliases, and trailing comments
containing braces survive), adds new Claude and GPT tier releases, and
prints a Markdown summary.
- It validates source data, refuses to write a file that no longer
loads, and leaves unchanged any row with a partial long-context tier, a
reviewed tier LiteLLM lacks, or an Anthropic entry without a valid
cache-read price, reporting them as missing.

**Workflow**
- **Refresh LLM pricing** runs on `v*` tags and on demand. If the file
changes and no refresh PR from this repository is open, it force-pushes
`automation/refresh-llm-pricing` and opens a PR with that summary, then
dispatches `pr.yml` (PRs opened with `GITHUB_TOKEN` don't trigger CI).
- While a refresh PR is open, later runs skip with a warning. The lookup
uses `gh pr list`, so an API error fails the run instead of
force-pushing over a review. It never merges, keeps `verified_on`
manual, and asks reviewers to check changes against provider pricing
pages.
- Requires the existing "Allow GitHub Actions to create and approve pull
requests" setting that `publish.yml` already relies on.

<sup>Written for commit a2ce5a0b24.
Summary will update on new commits.</sup>

<a
href="https://cubic.dev/pr/we-promise/sure/pull/4666?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* LLM usage pricing lists rates for supported OpenAI, Google, and
Anthropic models, including applicable long-context and cache rates.
* Pricing can be refreshed on releases or on demand using LiteLLM’s
published prices. When prices change, a review pull request is opened;
automatic refresh skips if one is already open.
* Pricing updates can include newly listed eligible GPT and Claude
models while retaining reviewed rates when source data is incomplete.
* **Documentation**
* Cloud Costs guidance explains where listed prices and their
verification date come from and how to review pricing updates, including
checking provider pricing pages and model-family fallbacks.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-11 23:14:00 -08:00
ce7e26a3de fix(security): use ready? instead of explicitly_configured? for encryption gating (#3189)
Fixes #3142.

## What

`ActiveRecordEncryptionConfig.explicitly_configured?` only recognizes
explicit `ACTIVE_RECORD_ENCRYPTION_*` env vars or Rails credentials. It
ignores the documented self-hosted fallback where keys are auto-derived
from `SECRET_KEY_BASE` and loaded into
`Rails.application.config.active_record.encryption` at boot
(`runtime_configured?`). `ActiveRecordEncryptionConfig.ready?` (`=
explicitly_configured? || runtime_configured?`) already covers both
cases correctly, but was never called anywhere in the app.

Every `encrypts :field if encryption_ready?` declaration runs once at
class-load time. On self-hosted installs relying on the auto-generation
fallback (i.e. never set the three env vars explicitly — the documented
default path), `encryption_ready?` incorrectly returned `false`, so
**every one of those `encrypts` calls was silently skipped**. Sensitive
fields (provider API tokens/keys, MFA secrets, PII) were stored as
plain, unencrypted attributes despite Rails' encryption machinery being
genuinely configured and ready to use. This is more than the UI warning
the issue title suggests — it's a data-at-rest encryption bug.

## Changes

- `Encryptable#encryption_ready?` (used by 42 models),
`Settings::SecuritiesController`'s warning banner, the boot-time
`[SECURITY]` log warning, and `Settings::ProvidersController`'s warning
banner now all check `.ready?` instead of `.explicitly_configured?`.
- `CoinstatsItem`, `IndexaCapitalItem`, `MercuryItem`, `SnaptradeItem`,
and `SophtronItem` each hand-rolled their own copy of the identical
broken check instead of using the `Encryptable` concern — a fix to the
concern alone would not have fixed these 5. Refactored to `include
Encryptable` (same pattern as #1339), which fixes the bug and removes
the duplication.
- Added a regression test at each affected call site for the specific
scenario that was previously untested: `explicitly_configured?` false
but `runtime_configured?` true (the auto-generated-keys case).

No CI/test-env changes were needed to exercise the fix:
`config/environments/test.rb` already hardcodes a working encryption
config, so `runtime_configured?` (and now `ready?`) is already `true` in
the test suite — the round-trip `encrypts` tests now actually run
instead of being silently skipped.

## Operational note for self-hosted operators

Any data written while running under this bug was stored as plaintext.
After upgrading, preview with `bin/rails security:backfill_encryption`
(dry run by default), then encrypt previously-plaintext rows with
`DRY_RUN=false bin/rails security:backfill_encryption`. For key rotation
— including the deterministic-attribute migration the backfill cannot
perform — see `docs/hosting/encryption.md`. A follow-up PR will extend
that task's model coverage (currently 16 of the 47 affected models) and
close a few structural gaps (a few models with no encryption wired up at
all).

## Since review (2026-11-10)

Addressing jjmata's three P2 findings (commits `9a2fb6c4e`,
`56e06bf04`):

- **Boot priority restored**: the initializer's partial-credentials
rejection now skips when the ENV set is complete
(`ActiveRecordEncryptionConfig.reject_partial_credentials?`), so
complete `ACTIVE_RECORD_ENCRYPTION_*` vars plus a stale/partial
credentials block boots again, per the documented ENV-first priority.
The combination is covered by new tests in
`test/lib/active_record_encryption_config_test.rb`.
- **Remediation command actually writes**: the boot warning prescribes
the plain dry-run preview plus the explicit `DRY_RUN=false bin/rails
security:backfill_encryption` write pass (the task defaults to dry run).
- **Rotation procedure handles deterministic attributes**: the warning
no longer recommends retiring a compromised scheme via the backfill
alone — Rails re-serializes deterministic ("fixed") attributes under the
oldest configured scheme, so the backfill leaves those columns
(`User.email`, `otp_secret`, provider tokens, …) under the compromised
key. New `docs/hosting/encryption.md` documents the full four-step
procedure (previous-scheme setup → preview + write backfill →
per-attribute decrypt-and-rewrite under the current scheme with strict
new-key-only verification → retirement); the rake task's scope note
carries the same caveat. Automated rotation tooling remains tracked in
#3233.

No local test run for these two commits (no Ruby toolchain on the
machine they were prepared on) — CI on `56e06bf04` is the check.

## Testing

- `bin/rails test` on the changed files and their controllers/models: 93
runs, 196 assertions, 0 failures, 0 errors, 0 skips.
- `bin/rubocop`: 17 files inspected, no offenses.
- `bin/brakeman --no-pager`: 0 errors, 0 security warnings.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Bug Fixes**
- Self-hosted installations using runtime-generated encryption keys no
longer display incorrect warnings.
- Legacy unencrypted data remains readable during encryption backfill,
including supported deterministic lookups.
- Encryption readiness is recognized consistently across settings and
integrations.

- **Security**
- Sensitive integration credentials are encrypted whenever encryption is
available.
- Known compromised keys now trigger warnings and safe rotation
guidance.
- Incomplete encryption configuration is detected and reported clearly.

- **Tests**
- Added coverage for encryption configuration, warnings, legacy data
access, and encrypted credentials.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: jaysbeekay <46616837+jaysbeekay@users.noreply.github.com>
2026-11-11 20:23:44 -08:00
kevin 84ce906406 fix(money): use the en-IE locale key when formatting euros (#4921)
The EUR punctuation override in `Money::Formatting` was keyed as
`:en_IE`, but the Irish English locale in this app is `en-IE`
(`config/locales/defaults/en-IE.yml` and the language picker).

Euro's own defaults use European grouping (`1.234,50`). The `:en`
override already switches that to `1,234.50`. Because the Irish key
never matched, `Money.new(1234.5, "EUR").format` in `en-IE` kept the
European punctuation instead of the English grouping used in the locale
file.

This updates the comparison to `:"en-IE"` and keeps `:en_IE` as well. A
test asserts that euros in `en-IE` format as `€1,234.50`.

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixes euro formatting in Irish English (`en-IE`) so amounts use English
grouping (`€1,234.50`) instead of the currency's European punctuation
(`1.234,50`).

The EUR override previously matched only `:en_IE`, which never fired; it
now accepts both `:"en-IE"` and `:en_IE`.

<sup>Written for commit 5928544772.
Summary will update on new commits.</sup>

<a
href="https://cubic.dev/pr/we-promise/sure/pull/4921?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* EUR amounts formatted with the `en-IE` locale now use comma grouping
and a period decimal separator.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-11 18:46:00 -08:00
Shibu M a5ebdca537 Add Indian number grouping for INR and Indian locales (#4680)
## Summary

Adds South Asian (lakh/crore) digit grouping for amounts in Indian
locales **and** for the INR currency, so Indian users see
`₹12,34,567.89` instead of `₹1,234,567.89` without changing any setting.


## Activation

Grouping is applied when **either** condition is true:

- the currency is `INR`, **or**
- the locale is one of `en-IN`, `en-IND`, `hi`, `hi-IN`, `mr-IN`, `ta`,
`te`, `bn`, `gu`, `kn`, `ml`, `pa`.

## Overrides

`indian_grouping:` changes digit grouping only. The currency symbol,
precision and symbol placement still come from the currency and locale.

```ruby
# INR defaults to Indian grouping
Money.new(100_000, :inr).format                         # => "₹1,00,000.00"
Money.new(100_000, :inr).format(indian_grouping: false) # => "₹100,000.00"

# Any other currency defaults to Western grouping and can opt in
Money.new(100_000, :usd).format                         # => "$100,000.00"
Money.new(100_000, :usd).format(indian_grouping: true)  # => "$1,00,000.00"
```

Explicit `true`/`false` wins; `nil` falls back to the currency/locale
rule.

## Implementation

### `lib/money/formatting.rb`

- Adds `INDIAN_GROUPING_CURRENCIES` (`INR`), an expanded
`INDIAN_LOCALES`, and `INDIAN_DELIMITER_PATTERN`.
- Resolves grouping once in `format_options`, after the currency and
locale defaults. Every caller inherits it: web views, `format_money`,
exports, mailers and API `formatted` strings.
- Adds `format(indian_grouping:)` with explicit `true` / `false` / `nil`
semantics.
- Removes the previous Indian branch from `locale_options`, so there is
a single source of truth.

### `test/lib/money_test.rb`

- Adds coverage for zero, units, thousands, lakh, crore, multi-crore,
negatives, `precision: 0`, HTML-entity units, locale triggers (including
non-INR currencies), and the opt-out/opt-in.

## Notes

- No database changes, no migrations, no UI changes.
- Existing locale output is unchanged for every non-Indian
currency/locale. Symbol placement, precision and currency casing stay as
they were; only digit grouping changes.
- INR currency defaults are respected (`delimiter: ","`, `separator:
"."`, symbol before the number). Under a locale with different
separators (e.g. German), the locale separators are kept and only the
grouping changes.
- This is the foundation for **#4681** (per-user
Language/International/Indian/European override) and **#4682** (mobile
consumes the resolved rules). #4681 is stacked on this branch.

## Testing

- `bin/rails test test/lib/money_test.rb` — **47 runs, 670 assertions, 0
failures**
- `bin/rails test test/lib test/helpers
test/controllers/api/v1/accounts_controller_test.rb` — **343 runs, 1897
assertions, 0 failures**
- `bundle exec rubocop lib/money/formatting.rb test/lib/money_test.rb` —
**no offenses**

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* Currency formatting supports Indian-style lakh and crore digit
grouping, enabled by default for INR and listed Indian locales. A
formatting option can override the default.
* Indian grouping uses commas and decimal points; other currencies and
custom currency units can also use this grouping.
* Formatting honors an explicitly requested locale, including its
currency display and decimal precision, while preserving
caller-specified precision and significant-digit options.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-11-11 14:32:40 -08:00
GFRandClaude Opus 5.5 59e6b5293d Encrypt the remaining provider identifiers at rest (#4336)
* Encrypt the remaining provider identifiers at rest

Enable Banking stored the account IBAN and the user's IP address in
plaintext, Akahu the full bank account number and (in institution
metadata) the account holder's name, and Lunch Flow its holdings payload,
while the fields next to them were already encrypted.

- Encrypt EnableBankingAccount#iban, EnableBankingItem#last_psu_ip,
  AkahuAccount#formatted_account and LunchflowAccount#raw_holdings_payload.
- Stop copying the account number and holder into Akahu
  institution_metadata and strip both keys from existing rows.
- Encrypt plaintext already stored in those columns during the deploy,
  since the Enable Banking and Lunch Flow syncs read them and would raise
  on plaintext otherwise.
- List the columns in security:backfill_encryption for instances that
  configure keys later.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Keep pre-encryption rows readable and leave the IBAN to its own PR

- EnableBankingAccount#iban is already encrypted, deterministically, by
  the open IBAN foundation work; a second, non-deterministic encrypts here
  would make the column unreadable once both land. Drop it from this PR.
- Mark the three remaining attributes support_unencrypted_data: true, so
  a plaintext value written by a process still on old code, or stored on
  an instance that configures keys later, stays readable instead of
  raising. The migration still encrypts the existing rows at rest.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Make the provider identifier migration safe to race and roll back

The encryption migration now updates a row only while it still holds
the value it read, so a sync that writes in between is not overwritten
with the stale value. Its down step decrypts the values back to
plaintext, so code from before this release can read them after a
rollback.

Adds tests for an already encrypted jsonb payload, the race, the down
step, and Akahu metadata that carries only one of the two keys.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Commit each row of the identifier migration on its own

Without disable_ddl_transaction! the whole data migration ran in one
transaction, so every updated row stayed locked until the end and a
sync writing the same row had to wait. Rows already encrypted are
skipped, so a rerun after a partial run is safe.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Share one rewrite loop between encrypt and decrypt

encrypt_plaintext and decrypt_ciphertext repeated the per-row loop:
read the value, skip it unless it is in the expected state, write it
back only if it is unchanged. They only differed in that state and in
the update. rewrite_stored_values now holds the loop and the guard
against overwriting a newer value; the two methods just supply the
update. No change in behaviour.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Encrypt each backfill row under a row lock

The backfill read a row, then wrote the encrypted copy with
update_columns. A write in between, such as a new last_psu_ip or
DataCleanerJob clearing it, was overwritten with the stale value. Reading
and writing under the row lock keeps the newer value; a row deleted in
between is skipped.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-10 13:14:11 -08:00
jaysbeekay 0c4411e15e Add a per-account repair for split SnapTrade securities (#4404)
* Add a per-account repair for split SnapTrade securities

Before #3999 a SnapTrade position's holdings and trades could land on
different Security rows of one ticker, so the holding shows no cost
basis. #3999 keeps the position on the row it holds, which keeps an
existing split in place.

snaptrade:repair_split_securities moves one account's trades and its
SnapTrade or provider-less holdings onto the row held_security_for
returns (the one the next sync resolves to), keeps one holding per date
and currency without summing, and re-materializes. It is a dry run
unless DRY_RUN=false, refuses a live run that would leave price gaps on
the target unless ALLOW_PRICE_GAPS=true names one account, and never
destroys a Security or moves a price.

Refs #4025

* Stamp the moved trades and their entries in the split repair

Report caches key on Family#entries_cache_version, the latest entry
updated_at. The repair moved trades with update_all, which touches no
entry, so a figure cached before the repair could keep grouping those
trades under the old security row. The moved trades and their entries
now get the same updated_at as the moved holdings.

Raised as an audit-trail nit in the fork pre-flight's light review; the
cache key is why it matters.

* Skip cross-exchange tickers and unmatched splits in split repair

Review findings on the split security repair:

- Rows were grouped by ticker alone, so two real listings of one ticker
  (SHOP on XNYS and XTSE) were merged. Security uniqueness is scoped to
  exchange_operating_mic. A row's exchange is now its operating MIC, else
  its exchange_mic, canonicalised; a ticker whose rows name more than one
  exchange is skipped and listed in #conflicts. A row with no exchange
  fits any group, which keeps the SnapTrade-created row in the split case.
- Trades moved onto a target that lacks a source row's Security::Split
  replayed without it, because the holding calculators load splits by
  security_id. Each result now reports unmatched_split_dates, and a live
  run refuses the account (no override) when any are present. A split
  only the target carries is left as is.
- A failed live run is rolled back and now recorded with
  DebugLogEntry.capture (provider_sync_error, snaptrade, account and
  account provider). Refusals are expected outcomes and are not logged.
- The rake task logs each failure with its backtrace and exits non-zero
  when any account failed. Its output names each row's exchange and
  security name, the source splits the target lacks, and the skipped
  conflicting tickers.

Siblings checked: split_tickers is the only grouping; held_security_for,
target_for and price_gap_dates read the grouped ids unchanged. Both
refusals share a Refused base so the rake task handles them alike.

* Say whether a split repair failure was rolled back

The repair's transaction has committed by the time the rake task looks
up the securities and prints the results, so an error while reporting
was announced as "failed, rolled back" on an account whose repair had
gone through. A dry run writes nothing at all, so a rollback was never
the right word for it either.

The task now notes when SplitSecurityRepair#run has returned and says
which happened: rolled back, nothing written, or repair applied but
reporting failed. The closing abort no longer claims every failed
account was rolled back. The exit status is unchanged.

* Report the SnapTrade snapshots a split repair drops

When the target row and a source row both hold a SnapTrade snapshot for
the same date and currency, the repair keeps the target's and deletes
the source's, with its provider cost basis. Re-materialization rebuilds
qty and amount from trades but not a provider cost basis, and nothing
said which snapshots a live run would discard.

Result gains dropped_snapshots, [date, cost_basis] for each dropped
holding that is SnapTrade's own (a dropped calculated row is rebuilt
from trades and is not listed), and the rake task prints them. The
choice of which row survives is unchanged.

The rake task also now says "not a SnapTrade-linked account" for an id
that is not linked, rather than "no split securities", which read as a
clean account.

Tests: two snapshots on one date keep the target's and report the
dropped one with its cost basis; a dropped calculated row is not
reported; the rake dry run lists the dropped snapshots; the rake task
names an unlinked account.

* Roll back a split repair raced by a sync; exit non-zero on refusal

The repair plans its holding moves and drops before the transaction
opens, so a holding a sync adds to a source row in that window was left
behind while the trades moved, re-splitting the position. Trades are
read inside apply, but one added after that read had the same effect.
After applying, the repair now checks that no repairable holding and no
trade remains on any source row, and raises ConcurrentChange to roll
back if one does. Locking the account would not help: neither the sync
nor the materializer takes that lock.

The rake task now exits non-zero when a live repair is refused, listing
refused accounts beside failed ones, and aborts rather than returning
when ALLOW_PRICE_GAPS is set without an account id.

The tests use the shared with_env_overrides helper in place of a local
copy, and a price-gap test's comment now matches its prices.

Siblings checked: holdings another provider owns stay on their row by
design and are not counted by the check; the dry run never applies, so
it is unchanged; the reporting-failure path already adds to failures.

* Hold off SnapTrade syncs while a split repair applies

Review found that refuse_concurrent_change! only narrows the race with
SnapTrade syncing: a sync resolves each position's security before it
writes, so one running alongside the repair could still write to a
source row after the check and leave the position split.

The live transaction now first locks the SnapTrade connection and
account rows. Syncable#sync_later creates a sync under that same row
lock, so no new sync on either can start until the repair commits. A
writer already under way is refused (SyncInProgress, a Refused, so it
is reported as "refused, nothing written" and not logged as a failure):
an incomplete sync on the connection or the account, or a pending
activities fetch, which writes trades outside a Sync record. The syncer
itself is unchanged.

Siblings checked: every SnapTrade sync path goes through sync_later
(controllers, sync_later_with_follow_up, the follow-up job, the family
syncer); account syncs that re-materialize holdings also go through it;
SnaptradeActivitiesFetchJob is covered by activities_fetch_pending,
which only a sync's importer sets. refuse_concurrent_change! stays for
rows committed between planning and the lock.

* Assert each split repair refusal's own reason

Every SyncInProgress message ends "run it again once the sync has
finished", so matching /sync/i passed whichever writer the repair had
detected. Each refusal case now asserts its full message, naming the
connection sync, the account sync or the activities fetch.

Swapping the connection and account reasons in hold_off_syncs! fails
three cases, and relabelling the activities-fetch reason fails the
fourth; both passed under the old assertion.

* Flag SnapTrade activities fetch before queueing it

On a fresh account with no activities, the importer queued
SnaptradeActivitiesFetchJob and only then set activities_fetch_pending.
If that update! raised, the job was already queued with the flag false,
so nothing outside the job chain (the item's syncing state, the split
repair's hold-off check) could see a fetch was coming.

Set the flag first, as QuestradeItem::Importer already does. The job
does not read the flag before working; it only clears it on every exit
path. If the enqueue itself fails after the flag is set, SyncCleanerJob
clears a flag stuck for six hours, and until then the repair refuses,
which is the safe direction.

Siblings checked: this is the only place that queues
SnaptradeActivitiesFetchJob outside the job's own retry, and the only
SnapTrade write of the flag to true. Questrade and the provider
generator template already set the flag before queueing.

* Clear the SnapTrade fetch flag when queueing the fetch fails

The importer sets activities_fetch_pending before queueing
SnaptradeActivitiesFetchJob, so the job never runs unflagged. If the
enqueue then failed, nothing cleared the flag: no job existed to clear
it, and SyncCleanerJob only clears one stuck for six hours. Until then
the item showed as syncing and the split repair refused to run.

Clear the flag when perform_later raises (then re-raise), and when it
returns false, which is how Active Job reports an adapter's
EnqueueError. Inside a transaction the enqueue is deferred to commit
(enqueue_after_transaction_commit), where a failure can't be seen here;
SyncCleanerJob stays the backstop for that case.

Siblings: QuestradeItem::Importer sets its flag the same way and has
the same gap; it is outside this change.

* Log a refused SnapTrade fetch enqueue to the debug log

A refused enqueue raises nothing, so the Rails log line was the only
trace of it. Record it with DebugLogEntry.capture instead, with the
family and the account's provider link, so support sees it in
/settings/debug as the other SnapTrade sync diagnostics do.
2026-11-07 22:00:24 +01:00
596562ff75 Add a per-connection sync frequency (#4718)
* Add a per-connection sync frequency

Every connection is synced once a day by the family sync. Connections
differ in what a sync costs (Plaid bills per transactions refresh, banks
rate-limit, an exchange API key is cheap to poll), so a shorter cadence
belongs on the connection, not in a global setting.

A SyncSchedule row (polymorphic to the provider item, one per connection)
holds the interval and the next run. SyncScheduledItemsJob ticks every 15
minutes and syncs whatever has come due, asking Plaid to refresh first as
every other sync entry point does. It skips items outside their class's
`syncable` scope, drops schedules whose item or provider is gone, and
records a failed start in the debug log. Runs are aligned to multiples
of the interval from midnight UTC so they land on the same clock times
every day. The daily sync and the hourly CoinStats job are unchanged.

Admins (or, for per-connection providers, the owning member) set the
interval from a "Sync frequency" entry in each connection card's menu on
the accounts page; "Usual sync only" removes it. The entry is left out
for anyone else and for a connection being deleted.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Add sync frequency to generated provider cards

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
2026-11-07 03:26:11 +01:00
57fbd23cce Format money without resolving number_to_currency options per call (#4690)
number_to_currency builds its options on every call: three nested converters
each run I18n lookups and hash merges. Money#format always passes unit,
precision, delimiter, separator and format, so the only settings it still
reads from I18n are significant, strip_insignificant_zeros, round_mode and
delimiter_pattern. The fast path reads those once per call and builds the
same string; locales that set significant digits or stripped zeros (pl, hu,
nb, ...) and calls with other options keep using number_to_currency.

Co-authored-by: Nikolay Kopylov <nkopylov@kranushealth.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 08:12:26 +01:00
Sure Admin (bot)andSureBot 3ce2afd73b Adopt CalVer release tagging with SemVer compatibility alias (#4539)
* Adopt canonical CalVer releases with compatibility aliases

* Inline CalVer checks and remove legacy release machinery

* Generate release version metadata during packaging

* Rename the release version wrapper to Calver

* Start CalVer with the 0.7.7 alpha.2 release

Move the temporary compatibility bridge to the next release train. Support exact prerelease aliases in image and chart publication without assigning aliases to untagged builds. Keep the canonical date explicit and document setting it on the actual release day.

* Use date-only CalVer alpha and stable release names

* Remove fixed CalVer dates from release configuration

* Replace stale SemVer terminology in chart releases

* Preserve mobile release versions and gate TestFlight tags

* Use dated CalVer tags for nightly Docker builds

* Pause floating Docker channel tags during CalVer validation

* Address CalVer release review findings

---------

Co-authored-by: SureBot <sure-bot@we-promise.com>
2026-11-02 06:58:25 +01:00
Yong Cong Sin 5ed9103303 Add TrueLayer provider for UK open banking (#4164) 2026-10-31 18:12:39 -07:00
Yong Cong SinandClaude Opus 5.5 7919230ab0 Keep the provider lists sorted with a custom cop (#4459)
DataEnrichment's and ProviderMerchant's source enums, Transaction::PENDING_PROVIDERS
and Family::FinancialDataReset::PROVIDER_ITEM_ASSOCIATIONS grew by appending, so
each new provider landed at the end and two branches adding providers conflicted
there. Their order means nothing (they are looked up by key or filtered), so they
are now alphabetical.

A repository cop, Sure/SortedList (lib/rubocop/cop/sure/sorted_list.rb, loaded
from .rubocop.yml), keeps them that way: a hash's keys, or an array's elements,
must be in alphabetical order when the line above the literal is the comment
`# sorted`, and the four lists carry it. Any other list can opt in the same way.
lib/rubocop is kept out of autoloading, as it defines RuboCop's own namespace.

The provider generator inserted a new source at the end of both enums, which the
cop would then reject. It now inserts it before the first source that sorts after
it, on a line of its own in a multi-line hash, and still appends one that sorts
last.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 23:42:18 -07:00
f4613626fa Update demo assistant banner to credit Vercel AI Gateway (#4295)
* Update demo assistant banner to credit Vercel AI Gateway

* Revise English demo assistant disclosure copy

* Track daily assistant and Sidekiq installation activity

* Unify daily usage event capture

Share daily usage capture across web, assistant, and Sidekiq hooks while preserving user-local and installation-UTC counting. Keep all event names in one allowlist and update regression coverage.

Validation: 11 collector and middleware tests pass in a database-free harness; Ruby lint and Brakeman pass. The full Rails suite cannot start because local PostgreSQL is unavailable.

* Skip web usage context when capture is disabled

Check shared daily-usage eligibility before resolving family timezone and visitor IP. This avoids duplicate invalid-timezone warnings when analytics is disabled or Rails uses a null cache, while keeping installation events independent of the Rails cache.

Add regression coverage for disabled collection and null-cache eligibility. The database-free unit and request-guard checks and Ruby lint pass; local full Rails tests are blocked by unavailable PostgreSQL.

* Align demo banner translations with the English disclosure

* Track daily MCP tool execution activity

Capture mcp_call_served_daily through DailyUsage before an authenticated, permitted MCP tool executes. Reuse installation-scoped UTC claims and the shared feedback project without sending tool names, arguments, results, or user metadata.

Cover OAuth and environment-token calls, tool errors, excluded requests, daily identity and Redis claim independence. Offline collector/dispatch tests, Ruby lint and Brakeman pass; local full Rails tests cannot connect to PostgreSQL.

* Rename daily usage collector to Usage

Keep existing daily event semantics while allowing the collector name to accommodate future time horizons. Update runtime call sites, test filenames, and documented references.

* Generalize usage tracking class names

* Remove extra whitespace

---------

Co-authored-by: SureBot <sure-bot@we-promise.com>
Co-authored-by: Local Review <local-review@example.invalid>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Juan José Mata <jjmata@jjmata.com>
2026-10-29 22:20:01 -07:00
Alessandro PogliaghiandSureBot 5695e56a5b chore(langfuse): migrate tracing and experiments to v4 (#3625)
* chore(langfuse): migrate tracing and experiments to v4

* Update health tests for Langfuse tracing migration

---------

Co-authored-by: SureBot <sure-bot@we-promise.com>
2026-10-21 23:56:46 +02:00
Will Wilson 1888ccef9c Detect autopay from explicit descriptor wording (#3624)
* Detect autopay from explicit descriptor wording

Bill-type charges (utilities, insurance, mortgage) always defaulted
to autopay: false regardless of any signal, so a directly-debited
bill still landed on the needs-action list. Descriptors banks stamp
autopay onto (AUTOPAY, AUTO PAY, AUTODRAFT, AUTO-DEBIT, etc.) are a
direct signal from the biller, so match them explicitly and trust
that over the bill_type-based default.

* Drop ambiguous autopay markers and backfill autopay

"AUTO PAY" and "AUTO PMT" on a car loan or auto policy descriptor read
as "automobile payment" as easily as "automatic payment". A false match
takes the bill off the needs-action list without anyone seeing it. A
miss leaves it on the list, where the user can switch autopay on. Keep
only the compound and debit/draft forms, which have no automobile
reading.

recurring:classify_existing skipped series that stayed a plain bill
with no category, so bills detected before this change never picked up
autopay from their descriptor. The task now also updates those series
when the classifier finds autopay wording. The identifier's
claimed-series refresh still leaves autopay alone, because it is
user-editable and detection does not reclassify after creation.
2026-10-21 23:31:18 +02:00
Sure Admin (bot)andSureBot df06937c98 Reuse shared frame redirects in provider controllers and generator (#4281)
* Reuse shared frame redirects in provider controllers and generator

Follow up on #4275 using the shared helper introduced in #4278. Remove the five copied implementations and make generated account-entry paths escape Turbo frames without losing alerts.

Cover the generated controller response contract and the browser-level Kraken modal exit.

* Remove redundant concern include from provider generator

---------

Co-authored-by: SureBot <sure-bot@we-promise.com>
2026-10-17 18:47:05 -07:00
GFRandClaude Opus 5.5 2ea59b48ed Encrypt SnapTrade account_number (#3832)
* Encrypt SnapTrade account_number, backfill via security:backfill_encryption

account_number was the last unencrypted identifier column across the
provider account models; snaptrade_account_id (used for all live API
calls) is unaffected, and the setup view already masks the display
(•••1234). Non-deterministic, matching the fio_account.rb :iban
convention — never looked up by value.

* Test that the backfill encrypts SnapTrade account numbers

The model-level test writes through the encrypted setter, so dropping
:account_number from the security:backfill_encryption field list would
have left every test green. Run the task against a plaintext row and
assert the column is ciphertext afterwards.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-17 18:43:23 -07:00
jaysbeekay 148b007b66 Generate plain ERB from the provider view templates (#4099)
* Generate plain ERB from the provider view templates

The item card, setup accounts and select existing account templates
wrapped every ERB tag in a Ruby string, escaped with <%%=. Thor renders
a template once, so the generated view kept the wrapper as live ERB:
the card failed to compile, because Action View read the wrapper text as
its strict locals, and the other views referenced file_name, which does
not exist in a view.

Use Thor's own escape instead, so <%%= ... %> becomes the view's tag and
<%= file_name %> is filled in by the generator. The rendered views are
unchanged otherwise.

panel.html.erb.tt still builds its tags as strings, but with a single
<%=, which Thor evaluates, so it already emits plain ERB.

Rebased onto upstream main after #4048, which gave the card a
visible_accounts: local. Its lines are converted the same way, and the
test #4048 added now asserts the plain ERB it generates instead of the
string-built line, whose #{file_name} reached the output unfilled. The
render test passes visible_accounts: and asserts the card lists the
accounts it is given rather than every account on the item.

* Refuse string-built closing tags in generated provider views

assert_plain_erb looked only for "<" +, the opening half of the old
templates' string-built tags. They built closing tags with "%" + ">"
as well. A string-built closer that ends a multi-line tag already
breaks the compiled Ruby, so the parse check catches it, but one
standing alone still parses and renders a stray %> as text.

The check now refuses both halves. The new test feeds it an opener, a
multi-line closer and a standalone closer; the standalone one passed
the old check.

* Render generated views at the app's own path in generator tests

render_generated_view wrote each view under a generated/ prefix, so the
item card's relative keys resolved as generated.redbark_items.* rather
than redbark_items.*. Missing translations render a placeholder in
test instead of raising, so the test passed with six of them, and could
not catch a key the app does not define.

The view is now written at its app path, in a directory prepended to
the view paths, so it renders instead of Redbark's own, and every render
asserts there is no missing translation. With the prefix restored the
item card test fails on six missing generated.redbark_items keys.

* Refuse a tag built from one string in the plain ERB check

The check refused "<" + and "%" + ">", but a whole tag built as a
string, <%= "<%" + "= t(\".title\") %" + "" + ">" %>, passed it and
rendered the ERB source as text. It now refuses any string literal that
opens a tag ("<%" or "<" +) and any concatenation that closes one
(%" + ">"), with either quote style.

The three generated templates still pass. New cases: the reviewer's
whole-tag string, a single-quoted standalone closer, and two openers
whose closer is split by an empty string, so each alternative is pinned.
2026-10-15 20:28:49 +02:00
GFRandClaude Opus 5.5 e1b3f42317 Stop Money from silently mixing currencies (#4219)
* Stop Money from silently mixing currencies

Money#+, #-, #/ (Money / Money) and #<=> took the right operand's bare
amount and labelled the result with the left operand's currency, so
200 USD - 180 EUR returned 20 USD without any error or log line.

They now check the currencies. Development and test raise
Money::CurrencyMismatchError; production reports the mismatch through
Rails.error and a warn log, once per call site, and keeps the old
result so no page starts failing. Amounts in different currencies are
not equal, without raising.

All fixtures are USD, so the suite never mixed currencies. A new
integration test runs syncs, transfer matching, insight generators,
assistant read functions, the main pages and the API for a family that
mixes EUR, GBP and USD and asserts that no mismatch is reported. A
control test triggers a known mismatch directly, so it keeps working
once the remaining call site on the trade page is fixed.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Keep reporting mismatches once the report memory is full

After 500 distinct mismatch keys per process, new mismatches were no
longer reported, so a long-running process could go quiet. Start the
memory over instead; a known call site may then be reported once more.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-15 15:46:42 +02:00
GFRandClaude Opus 5.5 92d8ee5248 feat(rules): run rules in a fixed order with "stop processing" (#4013)
* Run rules in a fixed order with "stop processing"

After every sync each active rule ran as its own background job, in
parallel and in no particular order, so when two rules set the same
field the result could change from one sync to the next.

Rules now run from top to bottom in an order the user sets by
dragging. For each transaction and field the highest matching rule
wins; tags are still added by every matching rule. A new "Stop
processing further rules" switch keeps rules further down from
touching the transactions a rule matched.

- Add rules.position and rules.stop_processing (reversible migration;
  existing rules are numbered by name).
- Add Rule::Runner, which runs a family's rules serially under an
  advisory lock and tracks claimed attributes and stopped ids.
- Enqueue one ApplyRulesJob per family after sync instead of one
  RuleJob per rule.
- Show the list in run order with drag handles and a "Stop" badge;
  share the reports page's sortable controller.
- Carry position and stop_processing through NDJSON export/import
  and expose them read-only in the API.

* Reload the sortable list after a failed save with no newer order

A network error on the last pending save left the list showing an
order that was never saved. Reload it like a rejected save does,
unless a newer order is still queued.

* Let rule actions that cannot change anything claim no field

A rule above whose action can never apply, such as a category or
merchant that was deleted or a blank name, still claimed the field and
kept the rules below from setting it. Executors now report whether a
value is actionable, and only actionable actions reserve their field.

* Use the renamed matching_scope in Rule#matches_transaction?

* Serialize rule position assignment per family

assign_next_position read MAX(position) and wrote +1 without a lock or
unique constraint, so two rules created at the same time could share a
position and silently fall back to the created_at/id tie-break. Take a
transaction-scoped advisory lock per family before reading the max; a
real two-connection test reproduces the duplicate without it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Run rules:apply_all in one Rule::Runner pass

The task still applied each rule through RuleJob.perform_now. Every call
built its own Runner and re-matched all rules above it, so N rules cost
O(N^2) match queries. When a sync held the family lock, retry_on LockBusy
quietly re-enqueued the job and the task still printed "done".

Run all rules in a single Runner pass, like ApplyAllRulesJob, print each
rule's run status, and exit non-zero when the family lock is busy or a
rule failed.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Pin rule actions to the matched ids and guard broken actions

Review follow-ups for the ordered rule runner:

- Every action of a rule now works on the transaction ids matched before
  the first action runs. The scope used to re-check the conditions, so a
  rule that renames and then categorizes could claim the category for
  transactions its own rename had hidden from the category action.
- Reading an action's claims is guarded per action. An action whose type
  cannot be resolved (e.g. from an import) claims nothing instead of
  aborting the remaining rules of the family.
- Single-rule apply: the comments now say that rules above are matched
  against the current data, not executed first, instead of promising the
  same result as the full run.
- The reorder handle uses DS::Button (icon variant) instead of a
  hand-built button.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Run the active rules above an applied rule first

"Apply rule" only matched the rules above it against the current data,
so it could differ from the full run when a rule above changes a field
the applied rule's conditions read (e.g. a rename followed by a
categorization). The runner now executes the active rules above the
requested rules in order and stops after the last requested rule, so a
single apply gives the same result as its turn in the full run.

- ignore_attribute_locks only applies to the requested rules; the rules
  above respect locks as in the scheduled run.
- RuleJob fails only when the applied rule fails. A failing rule above
  is recorded as a failed RuleRun, since a retry would re-run all rules
  above as well.
- The confirm dialog says how many active rules above run first.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-12 23:23:51 +02:00
jaysbeekay 808cd25f5f Show a member only the provider accounts shared with them (#4048)
* Show a member only the provider accounts shared with them

A provider card on /accounts is admitted for a member as soon as one of
its accounts is shared with them (visible_provider_items), but the card
partials then listed every account on the connection, with names and
balances. The index now passes each card the accounts this viewer may
see (AccountsController#visible_card_accounts); admins still see all.

- Each *_item partial takes a visible_accounts local, defaulting to
  item.accounts so other callers render as before.
- ProviderSyncSummary takes show_account_details:, so a partially
  shared member sees counts, not the other accounts' names.
- SimpleFIN, Sophtron and SnapTrade gate their institution and
  brokerage lines the same way.
- trading212's inline Current.user filter moves to the same local, so
  the card no longer raises when rendered without a viewer.
- The provider generator's item partial and index section follow suit.

The family-wide card broadcasts on sync completion are removed in a
separate change.

Part of #3630

* Hide stale-rate warnings and Trade Republic totals for other accounts

A card now lists only the viewer's accounts, but two parts of it still
read every account on the connection:

- The Kraken, CoinSpot and Binance stale-rate warnings iterated every
  stale account. They now only cover the visible ones.
- Trade Republic's data-quality panel (positions, events, expenses,
  reconciliation) totals every account. It is shown only to a viewer
  who can see them all.

The card guard test now also checks the on-chain wallet card, which is
rendered by name from the controller's already-filtered card.

* Require visible_accounts on every provider card

Each card declared visible_accounts with a default of item.accounts, so
any render that left the local out listed every account on the
connection. The cards now require it (strict locals, no default), and a
render that forgets it raises ActionView::StrictLocalsError instead of
showing accounts the viewer may not see. The generator's card template
does the same.

Every render site now passes visible_accounts explicitly:

- Accounts index, by viewer (unchanged): the 24 cards in
  app/views/accounts/index.html.erb, and the generator's index section,
  pass visible_card_accounts(item).
- Admin-only turbo_stream responses (require_admin!), full accounts,
  with a comment saying so:
  binance_items_controller.rb:152, :243
  brex_items/account_setups_controller.rb:65
  coinbase_items_controller.rb:176, :260
  enable_banking_items_controller.rb:504
  lunchflow_items_controller.rb:643
  mercury_items_controller.rb:641
  simplefin_items_controller.rb:341, :491
  sophtron_items_controller.rb:476, :632
- Family-stream broadcasts, full accounts, as before. These broadcasts
  are removed in a separate change; until then they keep their current
  output rather than raising inside sync:
  the sync_complete_event.rb of akahu, binance, coinbase, coinspot,
  coinstats, enable_banking, fio, ibkr, indexa_capital, kraken,
  lunchflow, mercury, monobank, plaid, redbark, simplefin, snaptrade,
  sophtron, trade_republic, trading212, up and wise;
  simplefin_item/syncer.rb:186; simplefin_item/balances_only_job.rb:29;
  questrade_activities_fetch_job.rb:126 and
  indexa_capital_activities_fetch_job.rb:36, which relied on Turbo's
  implicit item local and now pass both locals; and the generator's
  activities_fetch_job.rb.tt.

The on-chain wallet's _onchain_wallet_item is its Settings row, not an
accounts card, and is unchanged.

ProviderItemCardsTest now renders every card without visible_accounts
and expects the missing-local error, scans app/ and lib/ for every
render of a card partial and requires visible_accounts in each, and
rejects rendering a card by model. Cards are found by file name, so a
new card is checked without being listed.

* Update card guards for broadcasts removed upstream

#4046 removed every provider card broadcast from sync completions, jobs
and the SimpleFIN syncer, so the render-site scan now finds only the 12
admin-only controller responses, and the generator's job template sends
the toast instead of the card. The scan's floor drops from 39 to 12, and
the generator test asserts the job does not render the card, since no
other test covers that template.

* Reword Trading212 card test comment after #4046

The card is no longer rendered outside a request: #4046 removed the sync
broadcasts. The test still guards that the card takes its accounts only
from visible_accounts, never from Current.user; say that instead.
2026-10-11 23:47:46 +02:00
jaysbeekay bdb280b3bd Stop broadcasting provider cards to the whole family (#4046)
* Stop broadcasting provider cards to the whole family

Each provider's SyncCompleteEvent re-rendered its card and broadcast it
on the family Turbo stream. Every member subscribes to that stream, the
render has no viewer to filter for, and the card lists every account on
the connection, so a member received accounts not shared with them and
had a filtered card replaced by the full one.

The card broadcasts are removed from the provider events, the SimpleFIN
syncer and balances job, and the Questrade and Indexa activity jobs.
The family sync toast, which already makes each browser re-fetch its
own page, carries the update; Kraken, CoinSpot, the on-chain wallet and
the two activity jobs send it in place of the card. The on-chain event
also stops sending the settings wallet row, which names every address.
The provider generator's activities job template follows suit.

Siblings left for later: Account::SyncCompleteEvent still broadcasts
account rows, and several controllers rebuild the manual accounts list.

Closes #3630

* Cover the providers without fixtures in the broadcast test

Akahu, Coinbase, CoinStats, Sophtron and Up have no fixtures, so the
sweep skipped their events. Each is now built with only the attributes
its validations need, so every provider event that lost its card
broadcast is checked.
2026-10-10 20:44:27 +02:00
Oscar Maciel Caamal Cetina bd783290e4 fix: Preserve MXN separators in Spanish locale (#3651)
Keep MXN's native US-style number separators when formatting Spanish UI values while preserving existing locale-aware behavior for all other currencies.
2026-10-10 16:13:01 +02:00
33bc802958 Share one pending predicate, and classify investment cash movements in one place (#3557)
* Align provider SQL pending checks with model semantics

* Build correlated pending SQL lazily

* Build pending SQL without a boot-time connection

* Share one false-value list across pending SQL builders

Review on #146 noted that pending_sql quoted the false values through
the connection while PENDING_CHECK_SQL quoted them by hand, so a value
with special characters could diverge between the two. Both now read
PENDING_FLAG_FALSE_VALUES_SQL, built from the constant without a
database connection, and a test pins it to the adapter's quoting.

The rake test helper header no longer cites an unrelated issue or
describes a migration this change does not make, and the restore test
loads its task at file scope as the helper documents.

* Decide Monobank's stale pending prune the way Transaction#pending? does

The Monobank processor was the one provider read still casting the
stored flag with ::boolean. PostgreSQL raises on a value it cannot
parse ("maybe"), which aborts the whole prune on that sync, and it
disagrees with Transaction#pending? on values like "off". It now uses
Transaction.pending_sql scoped to monobank, as Akahu and Up already do.

Monobank itself writes a JSON boolean, which both rules classify alike,
so only a malformed flag changes behaviour.

The test helper that listed pending entries used the same cast; it now
reads the shared predicate, and a new test prunes a malformed flag,
keeps a false one and keeps a current hold. Without the fix it fails
with PG::InvalidTextRepresentation.

* Read pending provider metadata through one predicate

The import adapter decided pending three times with a raw Hash#dig on a
provider namespace: once on the incoming payload, and twice on a stored
flag when a booked version reuses a pending entry's external_id. dig
raises TypeError on a provider key holding a scalar, and all three reads
sit inside Account.transaction with no rescue between them and the
caller, so one malformed namespace aborted the whole import rather than
skipping that provider. Transaction#pending? was given exactly this
guard earlier in this branch; the adapter never got it, so the invariant
this branch is named for had three exceptions left.

Transaction.pending_extra? is that decision over a metadata hash rather
than a record, and #pending? now delegates to it, so there is one
implementation for a record, for an incoming payload and, in the same
terms, for pending_sql.

The two stored-flag reads also tested the value for truthiness with no
cast, so a flag of "false" read as pending where #pending? reads it as
not pending, and the booked sync deleted a flag that was never set. They
now read the same cast as everything else.

Four tests cover the three sites: a malformed namespace in the incoming
payload, in a stored flag on the same-external-id path and on the
user-modified path, and a stored "false" left alone by a booked sync.
Each raised TypeError or cleared the flag before this change.

Refs we-promise/sure#3557

* State the leading-AND contract on pending_providers_sql

The method returns `"AND #{not_pending_sql(...)}"`, and the doc comment
said nothing about that. All three callers -- FamilyStats, CategoryStats
and ScopedTransactionsQuery -- interpolate it after their own AND
clauses, so the prefix is load-bearing; used as the first condition in a
WHERE it produces `WHERE AND NOT (...)`, a syntax error.

Comment only, and it names not_pending_sql as the form to use in that
position so the next raw-SQL author does not have to read the body to
find out.

* Classify every investment cash movement in one place

`balances.cash_inflows` does not distinguish an external deposit from a
dividend landing in cash, so nothing downstream can tell money the
investor PUT IN from money the investments EARNED. A time-weighted
return cannot be read off balances until something can: a deposit
belongs in the denominator, a dividend belongs in the numerator, and
counting one as the other misstates the return in opposite directions.

Portfolio::FlowClassifier answers that for one entry, or for a set of
entry ids in one query, with the same rules either way. Five classes --
external_inflow, external_outflow, income, fee, internal -- decided by
the activity label on the Trade or Transaction, the transfer's
counterpart, and whether that counterpart is inside the scope being
measured. A position journalled between two accounts you own is
internal, and moves nothing; the same journal to an account outside the
scope is external, because from the scope's point of view it left.

Both paths share one definition of pending, one label table and one set
of rules -- LABEL_RULES is the table, and a label added to
Transaction::ACTIVITY_LABELS without a rule fails the test that compares
the two, so the classifier cannot silently drop a new label into
whatever its else-branch happens to be.

Nothing calls it yet. The return series that does follows as its own PR.

22 runs, 239 assertions, 0 failures; the full suite is 9269 runs, 0
failures. Three mutations checked: stopping the SQL path from skipping
pending rows, stopping the Ruby path from doing the same, and calling an
in-scope security journal external.

(cherry picked from commit 94dd187336)

* Read a NULL excluded flag as live on a security transfer's opposite leg

entries.excluded is nullable. #classify treats a NULL as live
(excluded? is false) and so does the SQL CASE, but the lookup for a
Transfer trade's opposite leg filtered on `excluded = false`, which
drops NULL rows, so an in-scope position move with a NULL-flagged leg
was classified as an external flow in both forms.

Filter with IS NOT TRUE in the Ruby and SQL lookups alike. An
explicitly excluded leg still does not count.

(cherry picked from commit dab9694b7b)

* Count stale pending for review before the exclusion hides it

The sync ran exclude_and_track_stale_pending before
track_stale_unmatched_pending. Both decide "pending" with
Transaction.pending_sql, and the tracker counts only entries still
`excluded: false`, so the exclusion had already marked every row the
tracker would have counted. "N pending transactions need manual review"
in the sync summary was therefore always absent, whatever the account
held -- and it stays absent under the old order in the new test, which
reports nil rather than 2.

Both steps now sit behind one caller, review_and_exclude_stale_pending,
which owns the order and says why it matters, and the test drives that
caller rather than either step alone.

Raised by a review of #3617's pre-flight: the earlier test called the
tracker directly, so it asserted a count the real sync could not reach.

(cherry picked from commit 8d2492901d)

* State the flow classifier's caller contract: signed sums and family scoping

Income and fee are classified by label alone, so a margin-interest charge is
income with a positive amount and a fee rebate is a fee with a negative one.
The class comment now says a caller must sum signed amounts per class, and
that neither #classify nor #classify_ids filters by family.

A new test pins the sign-blind rule in both the Ruby and SQL forms for a
transaction and a trade, so a later sign-aware change has to be deliberate.

(cherry picked from commit 4c0f3a404e)

* Drop the contract-gate claim this branch cannot back

The classifier, its tests and the flow test helper all pointed at
docs/portfolio/methodology.md, config/portfolio_contract_tests.yml and
portfolio:verify_contract_coverage. None of the three exists here: they
are fork-side, and this branch is cut from upstream main. A reader
following the pointer found nothing, and the promised drift check --
rename a test and the gate names the row that lost its evidence -- could
not run.

The comments now say what is true on this branch: the contract is stated
in full at the top of Portfolio::FlowClassifier, one test per rule, and
each helper names the provider whose storage shape it reproduces.

(cherry picked from commit ae94ba5fed)

* Let the link outrank the label on a transfer inside the scope

A Contribution or Withdrawal label used to decide an entry's class on its
own. When both legs of a linked Transfer sat inside the measured scope and
a provider had labelled them, the movement read as an external outflow
leaving the portfolio and an external inflow arriving from outside it --
twice over, once per leg, on money that never left.

The label says what the borrower meant; the Transfer row records where the
money went. Both forms now resolve the counterpart first for an :external
label, exactly as they already did for a :transfer one, and fall back to
the same direction as before when there is no link or the counterpart is
out of scope. An unlinked Contribution is unchanged, which is what keeps
this a precedence fix rather than a label the classifier stopped reading.

Both the Ruby and the SQL form were reverted in turn against the new test
and each was caught.

(cherry picked from commit 239b48e0d3)

* Read SimpleFIN pending flags through Transaction.pending_sql in rake tasks

pending_cleanup and pending_list compared the raw flag with 'true', so an
unknown string such as "maybe" was treated as posted by the cleanup and left
out of the list, disagreeing with Transaction#pending?. Use pending_sql and
not_pending_sql scoped to simplefin; genuine true/false/absent flags behave
as before. Tests cover "maybe", "no" (pending) and "off" (a Rails false).

---------

Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
2026-10-10 15:55:50 +02:00
GFRandClaude Opus 5.5 7e1d93613f Fix investment-transfer follow-ups from #3719 (#4064)
* Fix investment-transfer follow-ups from the transfer-kind changes

- Count matched contributions and withdrawals in investment flows when
  the cash side is outside investment/crypto accounts.
- Add data_migration:reconcile_investment_transfer_kinds to repair
  legacy transfer kinds on investment/crypto destinations.
- Keep a matched transfer's category on its outflow leg; the inflow leg
  shows it as a disabled field and both web write paths refuse it.
- Load both transfer legs in one query on repeat provider syncs.
- Stabilise the property subtype system test.

Closes #4037

* Base inflow category ownership on the transfer, parse DRY_RUN as boolean

A matched inflow leg stays read-only even when its kind is edited away
from a transfer kind, because ownership now comes from the Transfer
record instead of the leg's kind. DRY_RUN=0 or false no longer starts
a dry run.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-09 12:54:57 +02:00
Guillem Arias Fauste ab39cb205d Fix Disconnect and saves in Bank sync connection rows (#3844)
* Keep page-level provider panel saves on the Bank sync page

The drawer already submits provider panel forms from the page, and the
connection rows will too. Those requests carry no Turbo-Frame header, so
they skip the stream branches and take the fallback, which was broken or
left the page:

- Akahu, Coinbase, CoinStats, Enable Banking and Indexa Capital
  redirected errors with a 422. fetch doesn't follow a 422 Location and
  the body is empty, so Turbo showed nothing. They now redirect with a
  303, like the other panels, so the alert appears.
- Mercury, Lunch Flow and Sophtron rendered new/edit templates that
  don't exist, a 500. They now redirect back with the alert. Lunch
  Flow's update mirrors the fix its create got in #2724, and Sophtron's
  error helper drops the view_name it only used to pick the template.
- Saving an existing Mercury, Brex, IBKR, Trading 212, Lunch Flow or
  Wise connection sent the user to Accounts, and Wise's new SCA key was
  left behind on Bank sync. When Turbo asks for a stream, these updates
  and their errors now re-render the panel in place, through
  turbo_panel_request?, moved up from Trade Republic. Wise and Brex
  share their error helper with create, so a failed connect in the
  drawer shows its error there too, while a successful Brex create
  still moves on to Accounts. Lunch Flow's panel root gets the id its
  stream replaces.

The provider generator's controller template gets the same 303.

* Render connection row panels without a frame of their own

Each row under "Your connections" wrapped its panel in
turbo-frame#<key>-providers-panel with no target, so every form and link
in it was a frame request:

- Disconnect redirected to Accounts, or to Bank sync after the last
  connection went, and neither page has that frame, so the row showed
  "Content missing" and no flash. Links to Accounts, SnapTrade's OAuth
  and Wise's profile step broke the same way.
- 15 panel roots share that id. A save's turbo_stream.replace found the
  frame first and swapped it for the bare panel, so the next save was no
  longer a frame request, and for Wise and five others it went to
  Accounts.

Nothing else on the page is a frame, so the panel now renders straight
into the row and posts from the page, as the drawer's do. With the
previous commit, saves stay on Bank sync. Rows get a <key>-connection
id for tests, and Enable Banking's panel root gets the id its
SyncCompleteEvent broadcast replaces, which only the frame carried.

* Keep the remaining provider panel saves in place on Bank sync

Connection rows post from the page, so a panel's Turbo submission never
carries a Turbo-Frame header. Twelve panels (Akahu, CoinSpot, CoinStats,
Enable Banking, Fio, Indexa Capital, Kraken, Monobank, On-chain,
Questrade, Redbark, Up) still gated their in-place streams on
turbo_frame_request?, so a save redirected back to Bank sync and the
morph refresh collapsed the open row. Sophtron's row update left for
Accounts, as Mercury's did before the previous commit.

Updates and create or update errors now answer turbo_panel_request? and
replace the panel root, so the row or the drawer stays open with the
result. A successful create still redirects, which lists the new
connection under Your connections, and the frame-only stream branches
that could never run are gone. The CoinStats, Indexa Capital, Questrade,
Sophtron and Binance panels get the root id their streams target, and
CoinSpot, Kraken and On-chain replace the panel instead of nesting a copy
inside it. Binance and Coinbase have no edit form, so their update just
redirects.

The provider:family generator adds a FAMILY_PANELS entry instead of
injecting a turbo-frame section into show.html.erb, and drops the reject
condition that FAMILY_PANEL_KEYS already covers. Its controller and
panel templates follow the same rules, and the guide says what a
generated provider still needs to appear under Your connections.
Questrade's Disconnect and the Wallet account link drop a
data-turbo-frame="_top" that no enclosing frame needs.

The branch's panel tests now use as: :turbo_stream and
assert_turbo_stream. SimpleFIN's page-level create error is unchanged:
streaming it would break the edit modal, which shares render_error.

* Render provider panel saves through one shared helper

Twenty panel controllers wrote the same response by hand: for a Turbo
request, replace "<turbo_id>-providers-panel" with the panel partial,
adding the flash on success; otherwise redirect with the flash.
Changing that rule for the connection rows meant editing every one of
them and the generator's controller template.

ApplicationController#render_provider_panel now does it, keyed by the
panel's FAMILY_PANELS entry, which supplies the turbo_id (Trade
Republic's is "trade-republic") and the partial. An alert renders in
the panel with a 422, and a notice goes to the flash. Callers pass
their fallback path and any locals the panel needs.

The per-controller helpers are gone, including the private
render_provider_panel(flash_type, message) in Akahu, Up, Monobank and
Fio, which would have shadowed the shared one. Wise keeps its two
wrappers, since seven call sites share them. Locals the panel never
reads (CoinStats, Indexa Capital, Lunch Flow, On-chain, Sophtron), or
that repeat its own default query (Akahu, Up, Monobank, Fio, Kraken),
are dropped. CoinSpot's panel gets the default query Kraken's has.

Two fallbacks change. Lunch Flow's non-Turbo errors redirected back,
which is Bank sync whenever the browser sends a Referer; they now go
there directly, as every other panel's do. Questrade's error redirects
are 303s like the rest.

* List a generated family provider under Your connections

Since the connection rows moved to FAMILY_PANELS, rails g provider:family
adds the panel entry, so Bank sync lists the provider and opens its
drawer. Three more edits were left to the developer as a "Next steps"
item, and until they were made:

- SettingsHelper#provider_summary returned status off for the unknown
  key, so a connected provider stayed under Available.
- Without PANEL_SYNCABLE_TYPES and family_panel_items entries, its row
  had no sync status.
- Its row's Sync button posted a key that
  Settings::ProvidersController#sync ignores.

The generator now makes all three, as class methods tested against the
real helper and controller, the way append_family_panel_entry is. The
hash entries line their arrows up with the last entry's. Each insertion
skips itself when its entry is already there, so a re-run is a no-op,
and all four skip with --skip-view, since the row renders the panel.
The "Next steps" item is gone, and the guide describes the edits.

* Show SimpleFIN's connection errors where the form was

The Bank sync panel and the new-connection modal both post to
SimplefinItemsController#create with the same Turbo request, and
render_error chose between them on the Turbo-Frame header, which
neither sends. A panel error from a row or the drawer therefore
rendered the whole "new" modal page in place of Bank sync.

The panel's form now carries source=panel, and those errors replace
simplefin-providers-panel through render_provider_panel, which the
panel root now carries. Without Turbo they redirect to Bank sync with
the alert. The new modal still renders "new" with its error.

render_error's frame branch also answered the edit modal, which sits in
turbo-frame#modal: it streamed a panel that the Accounts page doesn't
have, so an invalid token showed no error at all. The modal now gets
the "edit" template, whose frame Turbo swaps in. Create's frame-only
success branch could not run and is gone.

* Keep the open connection row open after its panel's Sync

Fifteen panels have a Sync button inside the open connection row
(Akahu, Binance, Brex, Coinbase, CoinSpot, Enable Banking, Fio, IBKR,
Kraken, Mercury, Monobank, Trade Republic, Trading 212, Up and Wise).
Each sync action redirected back to Bank sync, and the morph refresh
collapsed the row the button was in, unless it was the family's only
connection.

The same actions answer the Accounts page's Sync buttons, and Fio's
account modals, with the same Turbo request, and those must keep going
back. So the panel buttons now send source=panel, and a panel Sync
re-renders the panel in place through render_provider_panel with a
"Sync started." toast, reusing the key the rows' own Sync button
already has in every locale. Trade Republic replaces only the card, as
its login steps do, so its other cards keep their state.
provider_panel_form? names the check, which SimpleFIN's panel errors
use too. Without Turbo, a panel Sync goes back to Bank sync.

Enable Banking's Sync had Turbo turned off, copied from Reconnect,
which does need a full-page redirect to the bank. Sync never leaves
Sure, so it now submits with Turbo like the others.
2026-10-01 06:13:49 +02:00
Juan José MataandClaude Opus 5 65ddc81d10 Stop FinanceKit data disagreements from ending ingestion (#3678)
* Stop FinanceKit data disagreements from ending ingestion

Follow-up to #3633, from the review of its last two commits.

A balance observation re-sent with the same identity but a different
amount fenced the whole publisher: repair_required, credential cleared,
uploads rejected until a foreground OAuth repair. That contradicts the
reasoning that made import validation retryable — a cleared credential
is recoverable only through a repair no background wake can perform —
and it is reachable without a client bug, since a balance revised in
place keeps its identifier. Detecting the disagreement is right; ending
ingestion over it is not. The stored observation stays immutable and the
canonical balance untouched, but it now raises a conflict for the family
and the capture continues.

`Payload::UUID` pinned the version and variant nibbles, rejecting
UUIDv7, v6, v8 and the nil UUID. Source identifiers come from FinanceKit,
so a value Sure does not mint could wedge the stream with no way through.
Relaxed to lib/uuid_format.rb, which every other caller already uses, and
the published schemas with it.

Downstream work now runs once per drain instead of once per capture.
Account syncs, family-wide transfer matching and rule application cost
the same whether one capture or fifty just landed, and a backlog drain
ran all three up to MAX_QUEUED times. apply_next! returns the applied
batch and the job fans out once, with the sweep recovering a lost job one
publisher at a time.

Also: `keep_sure` now derives review_required from whether an open
conflict remains, as retry_after_repair already did, so both resolutions
share one rule; `protected_entry?` reads columns before loading
associations, since transfer and split membership cost a query each; and
the FinanceKit log filters are anchored — unanchored `:credential` also
hid credential_id and has_*_credentials, and `:events` any key containing
"events".

Reverses one assertion added by the previous commit: a conflicting
balance observation now applies the batch instead of failing it.

Not included, and why: the AccountProvider account-row lock, which I had
flagged for cost, turns out to run only in user-initiated linking flows
rather than sync loops, so one indexed row lock per link is not worth
churn; preloading transfer and split state across a capture needs a
measurement first; and a family-admin disconnect path for another
member's connection is a product decision, not a cleanup.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BP2oKbsBexNUUx2M7oiqH6

* Recover FinanceKit downstream work from ids, not loaded rows

A pending batch still carries its payload — up to Financekit::MAX_BYTES,
retained for seven days — and an applied batch no longer counts against
the inbox cap, so a backlog awaiting downstream work has no ceiling of
its own. Loading one publisher's backlog with `to_a` therefore put an
unbounded amount of payload bytes in memory, on a job that runs on every
upload as well as every five minutes. The drain had the same shape,
holding up to MAX_QUEUED applied batches for the fan-out at the end.

Downstream now takes a scope and keeps only the ids, and the drain
collects ids as it goes. Snapshotting ids before the fan-out also stops a
capture applied concurrently from being marked done without downstream
work of its own. The recovery sweep is bounded per pass and per
publisher; the fan-out costs the same for one batch or many, so a larger
backlog clears over the following sweeps.

Covered by a test that counts FinancekitBatch instantiations during the
sweep: it reports 2 against the previous `to_a` and 0 now.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BP2oKbsBexNUUx2M7oiqH6

* Complete every chunk of a capture, not just the last

apply_next! returned only the final part of the capture it applied, so
the drain completed downstream work for that chunk alone. The recovery
sweep then found the earlier chunks still pending and ran the whole
family fan-out a second time, inside the same job run — measured at two
fan-outs for one two-chunk capture, which defeats the batching this
branch is for.

It now returns every part it applied and the job concatenates their ids,
so a capture is completed as a unit. The sweep keeps its own job.

The new test reports "expected exactly once, invoked twice" against the
previous return value.

Reported by CodeRabbit on #3678.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BP2oKbsBexNUUx2M7oiqH6

* Make conflict decisions durable and serialize downstream work

Four findings from the alpha review of 3b3ece1, each reproduced before
changing anything and each covered by a test that fails without its fix.

**Balance decisions did not survive a replay.** The observation conflict
was looked up by open status on the lineage, so `keep_sure` dismissed one
capture rather than settling the disagreement, and a distinct observation
on the same lineage could not raise its own conflict. The lookup now
matches the observation identity carried in `details`, the same way a
source transaction's decision is matched. `retry_after_repair` now
releases the declined observation: it is immutable, so the replayed money
would disagree again after the repair and the conflict would just reopen.
Every other observation on the lineage is untouched, and the canonical
balance still only moves when a newer booked value lands.

**Overlapping downstream workers both fanned out.** Two instances can
snapshot the same incomplete ids before either runs — a per-upload job
and the periodic sweep overlap exactly this way — and nothing rechecked
before repeating account syncs, transfer matching and rule application.
Work is now claimed per publisher with `pg_try_advisory_lock`, matching
the keying the other advisory-locked jobs use, and the pending ids are
re-read inside the claim. A worker that cannot claim leaves the batches
for the holder and the sweep.

**Tombstones ignored the remaining-open-conflicts rule.** The settled
branch reset `review_required` unconditionally, so a tombstone cleared
review while a `protected_tombstone` conflict was still open. It now
derives review state the same way resolution and upserts do.

**Completion metadata committed in two steps.** Batch completion landed
before publisher health, so a failure between them left completed batches
with stale health that the recovery sweep then skipped, because it only
looks for incomplete batches. Both writes now commit together, after the
scheduling, so nothing is enqueued from inside the transaction.

Reported by jjmata on #3678.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BP2oKbsBexNUUx2M7oiqH6

* Scope balance decisions to the family and canonical timestamps

Two gaps in the durability fix from 735cf3d, both reproduced first.

The lookup searched `@item.financekit_conflicts`, so a replacement device
opened a fresh conflict for a disagreement the family had already
answered. Observations live on the lineage and outlive the publisher
that sent them, so the decision has to as well. It now searches the
family, the same way a source transaction's decision already did; the
new row still belongs to the connection that raised it.

The lookup also matched the raw wire timestamp, while the observation
itself is keyed on the parsed instant. Two payloads spelling the same
moment differently hit one observation but missed one another's
conflict, so the decision lapsed on a reformat. Details now carry
canonical UTC, taken from the timestamp import_balance! already parsed.

Reported by CodeRabbit on #3678.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BP2oKbsBexNUUx2M7oiqH6

* Schedule downstream work inside the completion transaction

Making the two completion writes atomic left the fan-out outside them,
which traded one failure mode for another: a failed health write rolled
the batch back after the account syncs and rule jobs were already
queued, so recovery ran them a second time and RuleJob records a RuleRun
per execution. Measured at one job still queued against a rolled-back
batch; zero now.

Scheduling from inside the transaction is safe in this app: ApplicationJob
sets enqueue_after_transaction_commit, added for exactly this hazard —
its comment cites the stuck-sync regression from SyncJob enqueued in
Syncable#sync_later. SyncJob and RuleJob both inherit it, so they are
deferred to the commit and dropped outright on rollback. The nested sync
and transfer transactions join the same connection.

The earlier "nothing is enqueued from inside the transaction" comment
described a hazard this codebase has already engineered away, and is
replaced.

Reported by CodeRabbit on #3678.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BP2oKbsBexNUUx2M7oiqH6

* Recover lost downstream work in the publisher's own order

The recovery sweep limits each publisher to MAX_QUEUED batches per pass
but did not order them, so Postgres was free to return any subset of the
backlog. The added test shows it does: with one batch per pass it picked
the newer capture and left the older one waiting.

Order by the stream identity the publisher itself uses, which matches the
financekit_stream_sequence index, so the oldest lost work is recovered
first and a backlog clears front to back.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BP2oKbsBexNUUx2M7oiqH6

* Keep one open balance question per account lineage

create_observation_conflict! looked for an open conflict and then
inserted one, with nothing in the database enforcing the gap between the
two. A replacement device keeps the lineage of the device it replaces, so
two connections can reference the same financekit_account_lineage_id,
both find no open row and both insert — two open conflicts asking the
family about one disagreement.

Add a partial unique index on (financekit_account_lineage_id, details)
for open balance_observation_conflict rows, dropping any existing copies
first and keeping the oldest question. jsonb equality normalizes key
order, so the observation a conflict is about keys it exactly.

The insert then runs in a savepoint and treats a unique violation as the
other publisher having asked first: the question is open either way, and
a lost race must not abort the surrounding transaction with the rest of
the capture still to apply, or fail the batch and spend an attempt.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BP2oKbsBexNUUx2M7oiqH6

* Give the review-state rule one definition

X.update!(review_required: X.financekit_conflicts.open.exists?) had grown
four copies across Financekit::Processor and FinancekitConflict#resolve!,
where the rule matters most: a record is under review while any conflict
about it is still open, whatever raised or closed the last one. Four
copies is four places for the rule to drift.

Move it to FinancekitTransaction as review_required_from_conflicts, for
callers mid-write that save it with the rest of the record, and
refresh_review_required! for callers that are done. Both resolutions in
resolve! now land on the same call instead of repeating it per branch.

Left unmemoized on purpose: an import creates conflicts for the same
identity while it works, so a cached answer could clear a review that had
just been raised. Each check is an existence probe on the
financekit_transaction_id index.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BP2oKbsBexNUUx2M7oiqH6

* Let a client discard what a FinanceKit connection imported

Disconnecting has only ever meant one thing: revoke the credential, drop the
AccountProvider links, keep every account and transaction. That is the right
default -- the data describes the family's money, not the connection that
fetched it -- but it is not the only thing a family may want. Someone who
connects a wallet, watches a year of card spending appear and decides against
it is asking for the import to be undone, not parked. DELETE on a connection
took no parameters, and the published spec said as much in its own summary:
"Revoke a publisher and retain imported financial history".

It now takes a disposition. "retain" is unchanged, including its 204, so a
client that sends nothing sees nothing new. "discard" answers 202 and does the
removal in the background, because a year of history is not request-sized
deleting; the client polls the connection for purge_completed_at.

The vocabulary lives in ProviderDisconnectable rather than in FinanceKit, so a
second provider does not change the wire format. Support is per provider and
declared, defaulting to false: an unconverted provider reports only "retain"
and refuses "discard" instead of accepting it and keeping the data. Capabilities
advertises connection_dispositions so the client feature-detects.

What a discard does, per Wallet account:

- An account FinanceKit created is destroyed. An account it was linked to is
  emptied of FinanceKit-sourced entries and handed back to sync, which
  recomputes the balance from the history the family had before FinanceKit
  arrived. Nothing recorded which of the two an account was, so the lineage now
  carries account_origin; NULL predates the column and reads as "linked",
  the choice that cannot delete an account the family made themselves.
- Source identities, observations and conflicts for the lineage go, and the
  lineage is marked discarded so a later enrollment starts clean.
- A lineage another live connection still publishes into is left alone, which
  is the state during a device replacement window.

Entries are destroyed one at a time, not deleted in bulk: nothing in the
database points from a transactions row back to its entry, so a bulk delete
would strand the Transaction and with it any Transfer the entry belonged to.
Destroying the entry takes that chain and leaves the counterpart entry in
place, unpaired. Imported entries the family reconciled, excluded, split or
edited are removed too -- a partial deletion is worse than none once they have
been told the data is gone.

The request outlives the job that carries it out. purge_requested_at is written
inside the revoke transaction and the inbox sweep finishes any purge whose job
was lost, deliberately without the Financekit.enabled? gate the rest of that
job uses: the flag governs whether Sure accepts new data, not whether a family
may have what it already took removed. The controller has exempted disconnect
from the flag for the same reason.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BP2oKbsBexNUUx2M7oiqH6

* Scaffold the disconnect disposition in the provider generator

The generator produces the Unlinking concern every family provider gets, so a
provider wired up today would keep the retain-only signature and quietly drift
from the contract. It now scaffolds unlink_all! with the disposition keyword and
declares self.supports_discard = false on the item model, with a comment saying
what to do to turn it on and pointing at Financekit::Purge as the worked example.

The scaffold refuses a disposition it has not implemented rather than ignoring
it, so a provider cannot advertise a deletion it does not perform.

Covered by a test that renders the template and asserts the result parses, which
is what this test file already exists to do for the source-enum insertion: a
generator that emits invalid Ruby reports success and surfaces the damage later
with nothing pointing back at it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BP2oKbsBexNUUx2M7oiqH6

* Open FinanceKit to every family, gated only by the client

The server refused to serve the publisher endpoints unless an operator had set
FINANCEKIT_ENABLED=true and listed the family's UUID in FINANCEKIT_FAMILY_IDS,
and unless the enrolling admin had also ticked the per-user preview-features
toggle. Three gates for a feature that is now meant to work for anybody, and
none of them is the one that decides: whether a build offers Wallet sync is the
iOS client's call, made through StoreKit, which the server cannot observe.

Financekit.enabled? is gone, with its five call sites: the 503 in the API base
controller, the capabilities `available` flag, both guards in
FinancekitInboxJob, and the require in require_publisher!. The preview-features
check goes with it. `available` stays in the capabilities response because the
client reads it, but it now says this build speaks the protocol rather than
"an operator switched your family on".

Admin stays, deliberately. A publisher writes into accounts the whole family
reads, which is why every provider connector is admin-only, and require_publisher!
re-checks it on every upload so a deactivated, demoted or reassigned enroller
stops publishing. The writable-accounts check below it is what confines a
publisher to accounts that user may actually touch.

Nothing can return 503 "unavailable" on a FinanceKit path any more, so that
response is out of the shared error examples and out of openapi.yaml -- 100
lines of documented behaviour that could no longer happen.

One behaviour genuinely changes, for the better. Another family's admin used to
be stopped by the preview gate with 403; they now clear the access check and are
stopped by tenancy instead, because the connection scope is the caller's own
family and own user. That is a 404, which does not confirm to an outsider that
the connection id exists.

The test helper no longer grants preview features or stubs the flag, so the
whole FinanceKit suite now runs as an ordinary admin in an unconfigured
deployment. One test asserts that directly, end to end from capabilities through
enrollment to an accepted upload.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BP2oKbsBexNUUx2M7oiqH6

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-25 02:49:43 +02:00
8dd0394a09 Add Jev (TypeSafe) as a transaction-categorization provider (#3660)
* Add Jev (TypeSafe) as a typed classification provider

Jev answers typed questions about a state and returns calibrated
probabilities rather than generating text. That makes it a poor fit for
the :llm concept: it can never satisfy #chat_response or #process_pdf,
and preferred_llm_provider picks the first provider holding credentials
while assuming full capability, so registering it there would route chat
traffic to something that physically cannot serve it.

It therefore gets its own :classification concept, whose primitive is
#decide — one state, many questions — because the provider bills almost
entirely for the state: measured, five questions cost 1.31x one question.

Reachable through OpenRouter's Decisions API (the default) or TypeSafe's
own endpoint; the payloads are identical, so one class serves both via
JEV_ENDPOINT. Requires an explicit JEV_API_KEY with no fallback to other
keys, so an operator holding an OpenRouter key for an unrelated purpose
cannot find Jev silently enabled.

* Let evals benchmark classification providers against the LLM path

Eval runs could only construct OpenAI, so Jev could not be measured
against the provider it would replace.

Provider construction was duplicated across Eval::Runners::Base and
Eval::Langfuse::ExperimentRunner, which also disagreed on whether
provider_config used string or symbol keys — the jsonb column yields
strings, so a string-keyed caller of ExperimentRunner would have fallen
through to ENV silently. Both now share Eval::ProviderFactory, which
normalizes the config and keeps adding a provider to one edit.

Jev spends one request per transaction, so usage is attributable per
sample: cost and tokens now land on each eval_result rather than being
dropped. The comparison reporter gains a provider column, since keying
on model alone cannot distinguish two providers.

Adds an error_rate metric. A dead model slug previously recorded every
sample as incorrect and reported as a credible 0% accuracy rather than a
broken run. Also widens metric formatting, which rounded per-sample costs
of ~3e-05 to 0.0 and so reported any cheap provider as free.

* Let each family choose which provider categorizes its transactions

Family-scoped rather than a global Setting because the choice decides
whose transaction descriptions are sent to a third party — the same
reason assistant_type lives on the family. It also means the setting
means the same thing on a hosted instance as on a self-hosted one, where
Settings -> Self-hosting is unreachable.

Resolution is one rule: the ENV override, else the family's column.
Credentials alone never switch Jev on, and a family that has opted into
preview features but chosen the AI provider gets the AI provider —
preview gates whether the choice is offered, never what is used.

Carries a check constraint alongside the model validation, matching
chk_families_default_account_sharing on the same table: a value written
by update_column or a data migration would otherwise silently redirect a
family's transactions.

* Add settings UI for the categorization provider and Jev credentials

Both panels sit outside the llm_provider selector's show/hide targets,
since that selector governs chat and PDF, which Jev can never serve.
Behind the preview gate, so the entry point is what preview controls.

Adds DS::Note for the data-sharing disclosure. The shape was already
hand-rolled in the llm_provider selector and this would have been the
second copy; DS::Card is a raised surface and DS::Alert carries a live
region that standing prose should not announce.

The panel states that a key alone does not switch categorization over,
because it does not: an operator could otherwise save a key, see it
persist, and find nothing had changed.

* Quote the rule confirmation against the provider that will run

The confirmation screen hardcoded Provider::Registry.get_provider(:openai)
under a comment claiming it matched Family::AutoCategorizer. It did not:
an Anthropic install was already quoted the OpenAI model, and a family on
Jev was quoted an LLM model that would never serve the request.

Resolution moves to Family#resolved_categorization_provider so the screen
and the run read the same thing. LlmUsage has no pricing for Jev, so the
estimate comes back nil and the view says cost is unavailable rather than
inventing a figure from the wrong model's rates.

* Default Jev to TypeSafe directly rather than a gateway

The endpoint defaulted to OpenRouter, so an operator who enabled Jev
silently routed their families' transaction descriptions through a
reseller they never chose. Routing financial data through an extra party
should be opted into, not inherited.

The data-sharing notice was wrong for that default too: it named TypeSafe
and pointed at TypeSafe's retention policy while the descriptions
actually transited OpenRouter first. It now names the host the current
configuration will really send to, and says when a gateway forwards on.

Gateways remain fully supported — set JEV_ENDPOINT and JEV_MODEL. Also
corrects the AI Provider blurb, which claimed batch operations "always
use OpenAI"; that was already untrue for Anthropic installs.

* Let Jev's confidence decide whether an answer is applied

Confidence was recorded and then ignored — every answer was applied
regardless, which made a calibrated probability decoration rather than a
signal.

Below the threshold the category is not applied and not locked, so the
row stays enrichable and a later run retries it. Nothing is discarded.
Providers that report no confidence are never gated: the LLM path returns
a bare category name, and withholding on a confidence it cannot produce
would silently stop categorization.

The 0.7 default is measured, not chosen. Over the 200-sample golden set
it leaves 91.5% of transactions categorized while taking the error rate
on what is applied from 4.5% to 1.6%; 35.3% of answers below 0.7 were
wrong against 0% from 0.70-0.89. Raising it withholds far more and buys
nothing.

Shadow mode runs the unselected provider alongside, applies only the
selected one's answers, and records the disagreement. Sampled per run
rather than per transaction, because the LLM providers categorize a whole
batch in one request. Off by default: it doubles spend.

* Surface calibration, disagreement and the tuning controls

The eval could report two accuracy figures and nothing that explained
them. A tie hides everything that matters: two providers can score
identically while failing on disjoint samples.

Calibration buckets predictions by stated confidence against observed
accuracy, and flags only overconfidence — claiming more certainty than
earned is what auto-applies a wrong category, while the reverse is safe.
The verdict uses McNemar's test rather than comparing proportions,
because the runs are paired and only discordant samples carry
information. On the current data that returns p = 0.75, so it reports
statistically indistinguishable and recommends shadow on latency grounds
rather than claiming a quality win.

Settings gain the threshold, the shadow rate and a shadow readout, with
each control stating its cost where it is set. Credentials move inside
the categorization panel, revealed when Jev is selected, so choosing a
provider and giving it a key is one task — which removes the line of copy
that previously had to explain that a key alone changed nothing.

* Measure the cascade, and report when it cannot be measured

Categorization is a cascade: Family::BayesCategorizer runs first and only
the transactions it declines reach a provider. Benchmarking providers
over a whole dataset therefore credits them for rows they would never
receive, so the accuracy figures we had describe work Bayes would
largely have absorbed.

Adds a deterministic stratified split, a Bayes eval runner driving the
real classifier against a materialized throwaway family, and a cascade
report that states coverage first and provider accuracy on the residual
second.

On categorization_golden_v2 Bayes covers 0 of 115. That is a property of
the dataset, not the model: a golden set holds roughly one transaction
per distinct merchant, and naive Bayes needs the repetition a real
family's history has. Its shared vocabulary is state codes and digits,
so the highest confidence it assigns is 0.217 against a 0.043 uniform
baseline — no signal, not a threshold set slightly too high.

The report detects zero coverage and says the run does not measure Bayes,
rather than letting a reader conclude it is useless. Note also that the
raw metrics show null_accuracy 100% in this state, earned purely by
declining everything.

So whether the earlier provider figures overstate the residual remains
open. The machinery answers it against a dataset with realistic merchant
repetition, or against production traffic.

* Withhold a classification answer that reports no confidence

Two paths let an unconfident answer past the threshold.

Deriving confidence used `answer["confidence"] || noul_confidence(value)`.
noul_confidence is (value - 0.5).abs * 2, which is only meaningful for a
noul. As a general fallback it gave a choice missing its confidence nil —
and a score missing its confidence a value outside 0..1, since a score of
1.92 computes 2.84. It is now derived per type, and a choice or score
arriving without one reports 0: malformed, so maximally unconfident.

The gate then returned false on a nil confidence. That guard exists so
the LLM providers, which return a bare category name, are never gated on
a confidence they cannot produce — but it conflated "this provider does
not do confidence" with "this answer did not carry one", and the second
is exactly when withholding matters most. It now keys on the decision
type: a CategoryDecision comes from a provider that does report
confidence, so a missing one is withheld rather than applied.

* Report an unpriced eval run as unmeasured rather than free

`results.sum(:cost)` returns 0 when every row is NULL, so a provider that
reports no cost scored `total_cost: 0.0` — indistinguishable from a run
that genuinely cost nothing.

This stayed hidden while every Jev run went through the OpenRouter
gateway, which prices each call. TypeSafe's native API — the endpoint
this branch defaults to — returns token counts without a settled price,
and the OpenAI path never populates `cost` at all, so the default path
reported itself as free.

The consequence is not only cosmetic: ComparisonReporter picks the
cheapest run with `total_cost || Float::INFINITY`, so a stored 0 beats
every instrumented run and recommends whichever provider measures cost
least.

Both the metric and the stored column are now nil when nothing reported
a price, and the rake summary renders nil as "not reported". A measured
zero still reports as zero.

* Mark Jev's key lookups for the secret scanner

Pipelock flags `api_key = ...` assignments as a possible credential in a
URL. Both sites read a configured key out of ENV or Setting into a local
before constructing the provider — the same shape every other provider
builder in the registry uses, each of which already carries this comment.

Without it the scan fails the PR rather than reporting a finding.

* Harden the confidence gate, the split seed and the endpoint rule

Addresses automated review findings on the branch.

Eval::Runners::SampleSplit seeded its per-difficulty shuffle with
String#hash, which Ruby randomizes per process. The Bayes leg and the
provider leg of a cascade run are separate `rake evals:run` processes, so
the same seed produced a different split in each and the two legs were
scored over different test sets. CascadeReport compares only the recorded
seed and ratio, which matched either way, so nothing warned. A SHA256
digest is stable across processes.

Provider::Jev accepted an http:// endpoint: URI::HTTPS subclasses
URI::HTTP, so the obvious is_a? check passes both, and every request
carries a Bearer token and the family's transaction descriptions. The
rule now lives on the provider so the settings form, JEV_ENDPOINT and
eval-time construction share it, with loopback exempt so a local gateway
does not push operators into disabling verification.

A reported confidence outside 0..1 cleared every threshold and was
applied and locked. Bounds now sit next to the arithmetic that can breach
them, leaving intact the nil that means "not a number at all" — which the
gate already reads as zero and refuses.

CATEGORIZATION_CONFIDENCE_THRESHOLD and CATEGORIZATION_SHADOW_RATE
bypassed both the column validation and the check constraint. An
unbounded shadow rate makes `rand < rate` always true, doubling spend
silently.

A shadow comparison counted a missing decision as agreement: the rows
come from the union of both providers' decisions, so one side can be
absent, and nil == nil scored that as agreement. A shared abstention
still counts, and is tested separately.

The settings screen rendered stored values into fields disabled by an
environment override, so an operator saw a stale number — or, for the
endpoint, an empty box — while something else was in force.

evals:cascade documented a `+` separator because a comma inside a rake
bracket list is an argument separator. Rake exposes the surplus values as
`extras`, so the comma form works and needs no second syntax; evals:report
had the same bug and silently reported on the first id only.

* Fail an eval report naming a run that does not exist

`where(id: ids)` returns whatever matched, so one mistyped id quietly
narrowed the report instead of failing, and the output gave no hint a run
was missing — indistinguishable from a run that simply scored badly.

Newly reachable: until the previous commit taught these tasks to read
rake's surplus positional arguments, a second id in the bracket form was
dropped before it could be looked up, so a partial match could not arise
there.

The bayes lookup had the same gap from the other direction, raising a raw
RecordNotFound trace rather than naming the id.

* Fall back to the LLM provider when Jev's endpoint is rejected

Provider::Jev's constructor rejects an endpoint that would send the Bearer
token and a family's transaction descriptions in cleartext. The registry
builds a fresh provider on every lookup and get_provider rescues only
NoMethodError, so that raise escaped resolved_categorization_provider --
a method whose documented contract is to fall back to the LLM path when
Jev is unselected or unconfigured.

JEV_ENDPOINT is how an operator reaches it: unlike the settings form, ENV
never passes through the identical endpoint_allowed? check. One http://
typo against a non-loopback host therefore stopped auto-categorization
entirely and 500'd the rule confirmation screen, which is a worse outcome
than the misconfiguration it was guarding against.

Route both resolution paths through configured_jev_provider, which treats
a construction failure as "not configured" for the same reason a missing
key is -- the endpoint is unusable either way. Only Provider::Error is
rescued; anything wider would hide real registry bugs. It captures a
DebugLogEntry naming the endpoint, because the only symptom otherwise is
categorization quietly running on the provider the family did not choose,
with nothing in the UI explaining why.

This is the same exposure the confidence threshold and shadow rate
overrides are clamped for: an ENV override bypasses the column
validations, so each one needs its own guard at the point of use.

* Cut the configured_jev_provider comment down

Eighteen lines of comment over a three-line method, and the two middle
paragraphs restated the commit message that introduced them: why the
raise was reachable, what it took down, why the rescue is narrow. A
reader has `rescue Provider::Error` on screen for the last of those.

What survives is the part not derivable from this file -- that the
registry rebuilds the provider per lookup, that the constructor
validates, and that JEV_ENDPOINT reaches it without the settings form's
check.

* Bring the Jev diff's comments down to the repository norm

Six files sat well above the comment density this codebase actually
carries -- account.rb, transaction.rb and budget.rb all run 15-18% of
lines. Here 125 comment lines become 71.

Most of what went was rationale a reader could already derive, or
argument for the chosen design over an alternative nobody proposed: why
a classification provider is not an LLM stated three ways, the rollout
plan behind shadow comparisons, DS::Note's extraction history, the
worked example of a test set at 23% versus 13% null-expected. That
material is in the commits that introduced it.

What stayed is what the surrounding code does not show -- that
URI::HTTPS subclasses URI::HTTP so the obvious check accepts http://,
that Bayes cannot train on null-expected samples, that String#hash is
seeded per process and CascadeReport cannot catch the resulting drift,
that ActiveRecord already defines `transaction`.

DS::Note's comment also moved off `initialize` and onto the class it
actually describes.

Two files stay high by design. family.rb sits at 22% against a 21%
baseline on main, so it is at its own norm, and classification_concept.rb
is a 45-line contract whose type documentation is the content.

* Redact credentials from the Jev endpoint in diagnostics

A gateway URL can carry a key in userinfo or the query string, and
endpoint_allowed? accepts both. The rejected case is the one that gets
logged: Family#configured_jev_provider captured the raw endpoint into a
DebugLogEntry, and those rows are exported when an operator asks for
support.

Redacting only that metadata field would not have been enough. The
constructor built its message with the raw endpoint, and the same
capture records error_message alongside, so the credential survived in
the next field along -- and in Rails logs and any error reporter, which
the metadata fix never touches. Redact at the raise instead, so every
consumer gets the sanitized form.

URI#userinfo= cannot do this: Ruby returns early when passed nil and
leaves the credential in place, which reads as working. Clear password
before user, or the assignment raises on a URL carrying both.

Tests cover the redactor directly, the constructor's message, and the
captured metadata serialized whole, so a leak into error_message fails
the assertion rather than passing a check aimed only at the endpoint
field.

* Mark the redaction test fixtures for the secret scanner

Pipelock failed the branch on three "Credential in URL" findings, all of
them in the tests added for endpoint redaction. A test that proves
credentials are stripped from a URL has to hold a URL with credentials
in it, so the finding is correct and the code is too.

Use the repository's existing `# pipelock:ignore Credential in URL`
marker rather than assembling the literals at runtime, which would hide
the shape from the scanner instead of declaring it. Each file now has
one marked constant per URL shape rather than repeated inline literals,
so the suppressed surface is small and visible.

Also drops the AKIA prefix from the query-string secret. It is the real
AWS access-key shape, so it invites findings from every other scanner
the repository passes through, including GitHub push protection, for a
value that only needs to be recognisable in an assertion.

* Fix categorization provider rule entrypoints

* Keep categorization provider resolution read-only

* Resolve the categorization provider in one place again

683ad3522 rightly moved the misconfiguration DebugLogEntry out of
Family#resolved_categorization_provider, which views now call while
rendering rule labels. To keep the log on the run path, it copied the
resolution into AutoCategorizer, so the rule screen and the run each
had their own definition of which provider categorizes -- the drift
that method exists to prevent.

The resolvers now take an optional block that receives the construction
error. Views pass none and stay read-only; AutoCategorizer passes one
that logs. The same block now reaches shadow_categorization_provider,
which had gone silent when a rejected Jev endpoint skipped a sampled
comparison.

---------

Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: sure-admin <sure-admin@splashblot.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
2026-09-24 01:08:13 +02:00
Juan José Mata 5c3c079961 Add Apple Wallet settings, diagnostics, and realistic demo data (#3684)
* Preserve script nonces while making templates ERB-lint compatible

* Allow booked FinanceKit transactions without a posted date

* Expose Apple Wallet connections with diagnostics and demo activity

* Wait for asynchronous dialog updates in browser assertions

* Document Wallet settings with verified browser screenshots

* Wait for chart close and icon picker reset before continuing

* Address Wallet lifecycle and demo generation review findings

* Use the standard Apple domain logo for Wallet

* Allow backend unlinking of FinanceKit connections

* Model external provider setup with reusable links

* Keep provider card presentation in its ERB template

* Integrate Wallet data into standard demo generation

* Trim docs of transient info
2026-09-24 00:40:40 +02:00
William Wei MingandCursor 42836ccacc Fix EODHD Warsaw (XWAR) prices labelled as USD (#3141)
* Fix EODHD Warsaw prices stored as USD instead of PLN

Map XWAR/WAR so search persists the ISO MIC and price fetches resolve
PLN from the exchange currency table without depending on the 24h
search cache. Legacy securities with mic "WAR" keep working.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Prefer cached EODHD instrument currency over exchange default

USD-denominated listings on venues like LSE must keep the search-cached
currency; the Warsaw exchange map is only the fallback when cache is cold.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Canonicalize legacy WAR MIC to XWAR on security resolve

Treat WAR as an alias of XWAR so Resolver lookups and persistence cannot
create duplicate securities under the unique ticker+MIC index.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Backfill mis-tagged Warsaw security_prices from USD to PLN

Relabel historical XWAR/WAR prices, drop USD duplicates when PLN exists,
upgrade legacy WAR MICs when safe, and queue account syncs so holdings
revalue with corrected FX.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Bump schema version for Warsaw price backfill migration

CI uses db:schema:load; the data migration timestamp must be included in
schema.rb or db:seed aborts on pending migrations.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Batch Warsaw price backfill without per-price PLN lookups

Load PLN dates once per security and relabel/delete USD rows with
set-based update_all/delete_all instead of exists? per iteration.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Make Warsaw backfill sync recoverable on migration retry

Requeue account syncs for corrected Warsaw holdings even when USD
prices were already relabeled in a prior partial run, and raise
IrreversibleMigration explicitly on rollback.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix Warsaw backfill sync query and flaky fixture ticker

Security has no holdings association; resolve sync candidates via
Holding subqueries instead. Use a unique non-Warsaw ticker in tests.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Avoid NULL poisoning Warsaw retry sync with NOT EXISTS

Orphaned USD security_prices with a null security_id made NOT IN exclude every holding. Correlate with NOT EXISTS and cover the case in a regression test.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 22:45:32 +02:00
jaysbeekay bbccde10aa fix(providers): restore deletion flag when DestroyJob enqueue fails (#3562)
* Restore provider deletion flag when DestroyJob enqueue fails

Every provider item's destroy_later committed scheduled_for_deletion
before calling DestroyJob.perform_later. With Redis unreachable the
Sidekiq adapter raises out of perform_later, and an enqueue that is
rejected returns false; either way the flag stayed set with no job
queued. The connection then dropped out of active/syncable for good,
showing "Deletion in progress" indefinitely.

Move destroy_later into a DestroyableLater concern shared by all 24
item models and both provider generator templates. It restores the
flag with update_column when the enqueue raises (re-raising) or
returns false. update_column avoids QuestradeItem's refresh_token
validation, which only applies while the flag is clear and would
otherwise mask the enqueue error with RecordInvalid.

Refs we-promise/sure#3535

* Only clear the deletion flag the failing call set

A retry of destroy_later on an already-flagged item (the Delete menu
stays visible) cleared the flag when its own enqueue failed, even
though an earlier request's DestroyJob was still queued. Claim the flag
under a row lock and restore it only when this call set it. An
already-flagged item is still re-enqueued, since that is how a
connection stuck by a lost enqueue gets deleted.

The lock can't span the enqueue (ApplicationJob defers enqueues to
commit), so two first-time requests overlapping with one failing can
still clear the flag; the queued job destroys the item regardless.
Documented on the concern.

Also drop four comments left behind above the removed methods in the
CoinStats, Monobank, Redbark and Up models.

Refs we-promise/sure#3535

* Set the deletion flag without running validations

The claim used update!, so an item failing a validation unrelated to
deletion could not be deleted at all. BrexItem checks base_url against
an allowlist on every save; with a base_url outside it, destroy_later
raised RecordInvalid before enqueueing. Use update_column, matching the
restore. No item model declares save callbacks, so only the updated_at
touch is lost.

Update the WiseItem comment that described destroy_later's update!.

Refs we-promise/sure#3535
2026-09-16 06:47:48 +02:00
Justin McBrideandClaude Opus 5 e112c9aa7c fix(providers): use ProviderLogo for CoinSpot, Fio and the generator (#3581)
* fix(coinspot): render the connection logo with ProviderLogo

CoinSpot shipped with a hand-built badge on its Accounts card and its Bank
Sync connection row. Use ProviderLogo so it shows the Brandfetch icon for
coinspot.com.au, falling back to initials like every other provider.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(fio): render the connection logo with ProviderLogo

Fio shipped with a badge showing the first letter of the connection name on
its Accounts card and its Bank Sync connection row. Use ProviderLogo so it
shows the Brandfetch icon for fio.cz, falling back to initials.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(providers): render generated provider logos with ProviderLogo

The generated item partial built its own badge from the connection name, so
every provider created by the generator started out ignoring the ProviderLogo
pattern. Emit ProviderLogo instead, and document the pattern so provider views
and registry entries follow it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(providers): scope the logo rule and link the metadata fields

Setup forms and instruction panels carry no provider logo, so say cards and
connection rows rather than every surface. Point the generator guide at the
provider-logo guidance instead of naming only the domain field.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 06:05:56 +02:00
Juan José Mataandsure-admin 5c66a55201 feat: add "What's new" release highlight popup (#3505)
* feat: add "What's new" release highlight popup

Show a one-time release-notes popup the first time a user interacts with
the app after a version refresh, keyed to the exact deployed release tag
(.sure-version) instead of GitHub's latest release.

- Provider::Github#fetch_release_notes(tag) fetches notes for an exact
  tag, sharing serialization/caching with fetch_latest_release_notes
- ReleaseHighlights.pending_tag_for decides visibility: unseen deployed
  tag, per account (users.preferences), with a single eligibility
  predicate that includes alphas during testing and can flip to
  stable-only later
- The application layout mounts an inert Stimulus controller only when a
  tag is pending (no GitHub call on page render); on the first
  pointer/keyboard interaction it fetches the notes lazily from
  GET /release_highlight and opens one centered driver.js popover that
  shares its rendering with /changelog
- Dismissal (Done, close, overlay, Escape) PATCHes
  /release_highlight/dismiss to mark the tag seen account-wide; plain
  navigation tears the popover down without marking seen, and a
  window-level tag flag prevents double-shows across Turbo reconnects,
  cached page restores, and duplicate mounts
- driver.js 1.8.0 (MIT) is vendored for importmap, with theme-aware
  popover styling (light/dark, responsive, scrollable notes)
- /changelog keeps its current latest-release behavior and now renders
  through the shared pages/_release_notes partial

* Address review: cache release-note failures, never regress seen tag, vendor license

- Cache missing/failed GitHub release lookups briefly (5min) so an outage
  or missing tag cannot retry on every user's first interaction
- mark_release_seen! now runs under with_lock and refuses to move the
  marker to an older tag, so a stale tab during a rolling deploy cannot
  make an acknowledged release look unseen again
- Vendor driver.js MIT license text alongside driver.js.mjs

* Fix system test mock to allow the release highlight notes lookup

The settings system test stubs the GitHub provider with only
fetch_latest_release_notes; the release highlight popup's lazy fetch
calls fetch_release_notes on first interaction, so allow it too.

* Move release highlight styles to separate file

* Fix release highlight review issues

---------

Co-authored-by: sure-admin <sure-admin@splashblot.com>
2026-09-11 23:23:18 +02:00
Yaroslav Shparuk f96c6bb764 fix: stop a missing exchange rate from failing a whole account, and make the error legible (#3493)
* fix(money): always emit the ConversionError message

`ConversionError#initialize` guarded its message with `message ||`, but
`message` runs before `super` and so resolves to `Exception#message`'s
default, which returns the class name rather than nil. The `||` therefore
never reached the descriptive branch and that string was unreachable code.

Every raise anywhere in the app surfaced the bare `"Money::ConversionError"`,
losing the currency pair and date the exception already carried. `Sync#error`
records `e.message`, so a failed account sync showed a red "Error" whose only
detail was the class name, and Sentry reports lost the same context.

Fixes #3491

* fix(balance): keep one unconvertible entry from failing the account

`Balance::SyncCache#converted_entries` called `Money#exchange_to` with no
handling for a missing rate, so a single foreign-currency entry aborted
balance calculation for the whole account: the exception escaped through
`BaseCalculator#flows_for_date` and `ReverseCalculator#calculate`, no
balances were produced, and the account was marked as errored even though
its transactions had imported fine. `#holdings_value_by_date`, in the same
class, already handled the same failure.

Drop the entry instead. A 1:1 fallback like the holdings path uses would
silently misstate the balance by the size of the FX gap, which is the bug
reported in #1143, and `IbkrAccount::HistoricalBalancesSync` already sets
the precedent of excluding a row it cannot convert. Missing pairs are
recorded via DebugLogEntry so support can see which rate was absent, and
`unconvertible_entry_count` exposes the count for a future UI warning of
the kind bills and budgets already show.

Fixes #3492

* fix(balance): record the FX provider on the unconvertible-entry log

The diagnostic left `provider_key` nil, so the entry showed no provider in
the debug UI and was filtered out when support narrows logs by backend.

Read the configured provider from the setting rather than calling
`ExchangeRate.provider`, which raises `Provider::Registry::Error` on an
unrecognized configuration; `DebugLogEntry.capture` swallows failures in the
write, not in the arguments handed to it, so diagnostics must not risk
raising here.

* fix(balance): report holdings valued at a 1:1 fallback rate

The holdings path swallowed `Money::ConversionError` and counted the holding
at a 1:1 rate with nothing recorded, so an EUR holding in a USD account was
booked as USD with no trace. That silence is what made the same failure in
the entries path undiagnosable.

Keep the 1:1 result rather than excluding the holding. Dropping it would be
worse here than for entries: `BaseCalculator#derive_cash_balance_on_date_from_total`
derives cash as `total_balance - holdings_value`, so an excluded holding
reappears as phantom cash instead of merely lowering the total. Whether 1:1
is the right policy at all is a separate question — this only stops it from
being invisible.

No number changes; `report_missing_rates` now serves both paths, and
`unconvertible_holding_count` exposes the count alongside the entry one.
2026-09-10 20:19:05 +02:00
Pedro Coutinho f82a43d3e2 feat(i18n): Support Portuguese European language and locale (pt-PT) (#3265)
* Register new language - Portuguese European

* Adding pt-PT locales and translations files

* Adding pt-PT locales and translations files

* Changing translations to pt-PT

* Changing translations to pt-PT

* Refining pt-PT translations

* Adding pt-PT translations files

* Refining pt-PT translations

* Refining pt-PT translations

* Refining pt-PT translations

* Fixing locale issues

* Fixed missing keys

* Fixed missing keys and fine-grained some translations

* Fixed missing keys and fine-grained some translations
2026-09-03 05:52:34 +02:00
Brandon 686205c0ff feat(bills): schema and domain core for the bills subsystem (#3201)
* feat(bills): schema and domain core for the bills subsystem

First of three chunks carved out of #3083. This one carries the schema and the
domain layer: no bills pages, no calendar feed, no assistant tools. Nothing here
is reachable from the UI yet, so it changes no user-visible behavior on its own.

Schema, in a single migration with a full down:

- recurrence_rules, recurring_occurrences, recurring_allocations,
  recurring_price_changes and recurring_match_rejections
- bill columns on recurring_transactions (bill_type, payment_url, autopay,
  notes, anchor and end conditions, weekend adjustment, dedup scope)
- the four data backfills, in their original order

Domain layer:

- Schedule, the pure date PORO every cadence resolves through, and
  FrequencyPreset for the labels
- OccurrenceGenerator, Matcher, Allocator, PriceChangeDetector, Classifier,
  DeclaredBill, HistoryBackfiller and PaycheckPlanner
- Pipeline, tying detection to generation, plus the nightly job and rake task

Existing detection code changed in three places, each a bug this schema exposes:

- Cleaner used a flat two-month staleness threshold, which silently retired
  every quarterly and annual series
- SubscriptionAuditGenerator used a flat 45-day overdue threshold, meaningless
  at both ends of the frequency range
- CashFlowWarningGenerator read one projected entry per series, which only
  equalled the monthly amount because every series was monthly; weekly bills
  were under-counted fourfold in its 30-day projection

The JSON API travels with the model rather than the UI, because the status enum
widens here. The API accepts only active and inactive on write; suggested,
paused and ended are lifecycle states owned by detection, so the documented
enum stays truthful.

Uniqueness keys gain dedup_scope alongside amount, never instead of it: a
series that is not price-forked carries a blank scope, so amount is what keeps
two different prices apart.

Suite 7,550 runs, 0 failures. Rubocop and brakeman clean. Eager loading
verified, and the migration reverses and re-applies. Includes the first review round: orphan repair matches income and refuses coincidental twins, session imports persist occurrence mappings across chunks, semimonthly anchors canonicalize, classifier keywords match whole words, and the down refuses rather than failing when price-forked rows exist.

* Address second review round

Bound the cross-currency default allocation by the entry leftover and the
occurrence remainder, matching the same-currency path. Let keyword stems
carry a suffix again after the word-boundary fix silenced them. Skip an
incoherent recurrence rule row instead of rolling back the whole import.
Check rollback collisions per restored index so a refusal cannot land
after the bills tables are dropped. Replay the closed_at test through a
real second import. Preload the orphan repair associations and move the
allocator errors to locale keys.

* Match index NULL semantics in the rollback collision checks

GROUP BY treats NULLs as equal but the restored unique indexes do not:
account_id is nullable and indexed, so two accountless rows can never
collide under any of them. Excluding NULL accounts keeps the guard from
refusing a rollback PostgreSQL can perform. Verified live both ways:
accountless duplicates roll back, a real collision still refuses.

* Address maintainer review

Scope the payable debt-destination subquery to the row and its family
instead of scanning every account in the installation. Batch the cash
flow generator remaining-amount sums into one grouped query, matching
the two sibling sites. Enforce both window bounds in the after_count
branch so a future-anchored plan cannot leak past the requested end
date. Skip the explicit regeneration when the day column change will
fire the model callback anyway. Add the missing locale entry for the
allocation currency validation.
2026-08-31 23:41:38 +02:00
f0a0013da9 fix(charts): round series values to the currency's display precision (#3091)
* fix(charts): round chart values to the currency's display precision

Charts are drawn from the serialized amounts, not from the formatted strings,
so a sub-unit residue plotted as a visible move between two points that both
read $0.00, and the trend between them reported a change. Round in
`Series#as_json` so the series values stay exact for insights, goals and the
assistant.

Also hide the percentage when the previous value is zero, since that makes it
infinite.

* fix(charts): round the two payloads that bypass Series#as_json

`NetWorthBreakdownSeriesBuilder` builds its payload by hand, so the reports
chart never went through the rounding added in `Series#as_json` and still
plotted raw amounts: adjacent points printing the same value rendered a
visible move, and the tooltip it inherits reported a change between them.

`Series#trend` had the same gap on the server side. It is rendered right above
the chart by `UI::Account::Chart` and by the reports summary, so an account
going from 0 to a sub-cent residue showed a coloured $0.00 change next to a
flat line.

Rounding the trend can make a previously finite percentage infinite, so guard
the three views that render `percent_formatted` without checking, as
`shared/_trend_change` already does.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(charts): address net worth review comments

* fix(charts): tighten rounded trend handling

* fix(reports): restore positive sign in print trend

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: sure-admin <sure-admin@splashblot.com>
2026-08-22 04:30:23 +02:00