Commit Graph
3278 Commits
Author SHA1 Message Date
Brandon bf5ceff269 Fix flaky sign_out teardown in six test suites (#3208)
Six suites (passkey, MFA, SnapTrade, categorize, onboarding and the Active
Storage authorization integration tests) share a sign_out helper that deletes
the user's sessions through the controller, one HTTP request per session,
iterating in unspecified order. The moment the loop deletes the session the
test itself is signed in with, every later request in the loop is
unauthenticated and silently deletes nothing, so whichever sessions happen to
sort after it survive. The sessions fixture belongs to the same user these
suites use, so a surviving fixture row then fails every assertion that expects
the user to have no sessions.

Row order usually favors the fixture, which is why the suites usually pass.
Under parallel CI they fail a few times a week, always in this file family,
always with the fixture session as the leftover. Forcing newest-first order
reproduces it deterministically on current main: ten of the fifteen passkey
tests fail.

Teardown hygiene is not the behavior under test, so the helpers now destroy
the sessions directly, which no order can break. All six suites run green
three times in a row.
2026-08-27 07:30:35 +02:00
Tim Katz 2fdb9ee175 Plaid: add accounts to an existing connection (#3199)
* feat: add accounts to existing Plaid items

* fix: harden Plaid account addition

* fix: guard Plaid follow-up sync retries

* fix: use debug log for Plaid retry exhaustion
2026-08-27 06:55:37 +02:00
Juan José Mata 547ad7e69a Update CHANGELOG with recent changes and fixes
Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
2026-08-27 01:59:21 +02:00
github-actions[bot]github-actions[bot] <github-actions[bot]@users.noreply.github.com>Juan José Mata
5becbb50f9 Bump version to next iteration after v0.7.4-alpha.11 release (#3196)
* Bump version to next iteration after v0.7.4-alpha.11 release

* Kick off the new release

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Juan José Mata <jjmata@jjmata.com>
2026-08-27 01:29:54 +02:00
Juan José Mata 0275fc74be Regenerate schema for Rails 8.1 (#3194) 2026-08-27 00:47:00 +02:00
Juan José Mata 2abce5f5b7 Verify PDF support with a synthetic health probe (#3191)
* Add synthetic PDF health checks

* Require exact marker in PDF health probes

* Report PDF health paths separately

* Refactor application code

* Remove unrelated schema dump changes

* Simplify synthetic PDF validation

---------

Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
2026-08-27 00:14:50 +02:00
0xmarty_andMarty 79a175806e Fix SimpleFIN balances-only liability signs (#3187)
* Fix SimpleFIN balances-only liability signs

* Fix SimpleFIN balances-only liability edge cases

* Fix importer test helper indentation

---------

Co-authored-by: Marty <marty0x@github.com>
2026-08-27 00:02:44 +02:00
4930aacdb8 feat: create merchant inline from transaction detail (#3106)
* feat: create merchant inline from transaction detail

Add a searchable "create or select" merchant combobox (DS::MerchantSelect,
mirroring the existing DS::TagSelect pattern) so a new FamilyMerchant can be
created directly from the transaction detail and new-transaction forms,
instead of requiring a trip to Settings > Merchants first.

FamilyMerchantsController#create now also responds to JSON so the combobox
can create-and-select a merchant without a full page reload.

* fix: address PR review feedback on merchant inline creation

- Handle Turbo validation failures in FamilyMerchantsController#create
  (missing format.turbo_stream branch raised ActionController::UnknownFormat)
- Guard connect() so disabled merchant selectors (no menu target) don't throw
- Select the exact match (or block form submission) on Enter when the
  create row is hidden
- Catch network/parse failures in createMerchant and show an error
- Localize the fallback "could not create merchant" error message
- Move the create button/error text outside the listbox and add
  aria-controls for accessibility
- Align create-option avatar size with the selected-value display

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

* fix: keep created merchant option inside the listbox, move logo URL logic to component

- Add a dedicated listbox target and insert newly created merchant
  options inside it (previously landed outside role="listbox" after
  the create button was moved out in the prior review-fix commit)
- Move selected-merchant logo URL transformation out of the template
  into DS::MerchantSelect#selected_merchant_logo_url

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

* fix: address maintainer review feedback on merchant inline creation

- Drop the explicit format.turbo_stream branch in the merchant creation
  failure path: respond_to's turbo_stream matching forces the response
  Content-Type to text/vnd.turbo-stream.html before the block runs, so
  render :new, formats: [:html] only changed template lookup, not the
  Content-Type. Turbo's client then received a turbo-stream response
  with no <turbo-stream> tags and silently did nothing. Leaving
  turbo_stream undeclared lets Rails negotiate down to format.html,
  which renders :new with the correct text/html type.
- Add truncate/shrink-0 classes to the merchant option partial's name
  and avatar spans so they match the selected-value display once
  updateSelectionDisplay clones them into the trigger button.
- Add a regression test simulating a Turbo form submission (Accept:
  turbo-stream, text/html) against a duplicate merchant name.

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

---------

Co-authored-by: Gerald <248542187+gfr-free@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-26 22:40:46 +02:00
Pavel Voronov f05559cdc1 docs: add Hostim.dev as a one-click hosting option (#2567)
* Add Hostim.dev as a hosting option

* docs: note storage volume and db:prepare in manual setup
2026-08-26 22:09:41 +02:00
buzzromainandClaude Opus 5 74bb980271 feat(goals): a reserve measured in months of spending, not a fixed sum (#3180)
* feat(goals): a reserve measured in months of spending, not a fixed sum

"Six months of expenses" is the way people actually describe an emergency
fund, and it is a moving number: what covered six months last January
does not cover six months today. A reserve pinned to a figure typed once
drifts quietly out of date, and the drift always runs the wrong way — the
bar reads full while the cover shrinks.

`target_amount` stays the single source of truth, rewritten monthly by
RefreshMaintainedGoalTargetsJob. That is the whole architectural decision
here. An `effective_target_amount` would have been the obvious shape and
the wrong one: `remaining_amount`, `progress_percent`, `Goal.summary_for`,
the ring, the card and every future caller would each have had to learn
which target to read. None of them change.

The job refuses to write more often than it writes, on purpose:

- a family with no spending history yet computes a floor of zero, which
  would both violate the `target_amount > 0` constraint and read to the
  user as "your reserve is complete". The previous target stands.
- a figure identical to the current one is not rewritten, so a reserve
  does not collect a fresh updated_at every month for nothing.
- a write that fails validation leaves the target alone and is recorded
  through DebugLogEntry, not just the application log: a reserve frozen
  at a stale floor is invisible to the user, who has no reason to suspect
  the number stopped moving.

The job reads the family's spending, not a member's view. IncomeStatement
falls back to Current.user when nobody says otherwise, which in a
background job is nobody — so the scope is the whole family, and the
number is the same whoever is looking. That is deliberate, and matches
how the rollover chain had to be pinned.

`target_months` is refused outside a months-mode reserve rather than
tolerated: a number nothing reads would sit there looking meaningful,
and the job would skip it for reasons no one could see.

schema.rb is hand-edited again — verified against a real migration on a
throwaway database, structures identical. The dumper on this Rails
version also rewrites every check-constraint cast, so the new constraint
is written in the file's existing style rather than the dumper's.

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

* fix(goals): pin the reserve calculation to the family, and get it right on day one

Review of the previous commit raised two things, and they are the same
thing seen from either end.

`IncomeStatement.new(family)` looked family-wide but was only so by
accident. Its constructor falls back to `Current.user`, and eligible_accounts
narrows to that user's accounts when one is present. The single caller was
a background job, where nobody is current — so the figure was correct for
the reason that it happened to be computed nowhere else. `target_amount`
belongs to the whole family: derived from a viewer's slice of the accounts,
it would have started moving with whoever last triggered it. This is the
same fallback that made the budget rollover carry depend on its reader.
The account scope is now passed explicitly, so the calculation is safe
whatever calls it.

That mattered immediately, because the second point required a new caller.
A reserve created as "6 months of expenses" had no floor computed until
the 1st of the following month: the user chose the mode, guessed an
amount, and lived with a wrong target for up to a month. The feature's
first impression was its least convincing moment. The floor is now
computed on creation, and whenever the mode or the number of months
changes — but never on an unrelated save, so the monthly job keeps owning
the cadence and renaming a goal cannot silently move a financial figure.

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

* fix(goals): keep a months-based floor derived, and in the right currency

Review on #3180.

The median comes back in FAMILY currency and `target_amount` is stored in
the GOAL's, so a EUR reserve in a USD family read a 3,000 dollar floor as
3,000 euros — and rewrote it that way every month, silently. Converted
now, and when there is no rate for the day the previous target stands:
the same safe failure the method already took for a family with no
spending history, because a stale floor beats a wrong one.

The callback also skipped a target_amount edit, so the form could persist
an arbitrary figure under a "six months of expenses" label until the next
monthly refresh. It runs on that edit now and overwrites it — and when
there is nothing to derive from, restores what the reserve already had
rather than accepting the typed figure.

The form marks the field read-only in that mode. The model does not depend
on it, but a field that silently discards what you type is worse than one
you cannot type into.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 22:02:57 +02:00
buzzromainandClaude Opus 5 03b783b139 feat(budgets): show what is actually free, beside the plan (#3179)
* feat(budgets): show what is actually free, beside the plan

The budget has never consulted an account balance. `budgeted_spending` and
`expected_income` are numbers the user typed, and every figure on the page
derives from them — a forecast, checked against reality after the fact. It
answers "what did I plan to spend" and cannot answer "what do I actually have".

Three methods answer the second question: `available_cash`,
`earmarked_for_goals`, and `free_cash`. They appear in their own panel, below
the plan and outside it.

That separation is the whole design, not a layout choice. Folding cash into the
allocation arithmetic turns the budget into a different product — YNAB's, where
you distribute money you hold rather than money you expect — and a page showing
"expected income 3,000" beside "really free 1,600" leaves the reader unsure
which number drives the split. `allocated_spending` and `available_to_allocate`
keep their exact meaning; a test asserts none of them moves.

**The subtraction has to be over the same accounts as the sum.**
`Goal::FUNDABLE_ACCOUNT_TYPES` includes Investment, so a goal can be backed by
a brokerage account that `available_cash` never counted. Subtracting that
earmark would show a "really free" figure too low, or negative, with nothing on
the page to explain it. `earmarked_for_goals` is therefore restricted to
`cash_accounts`, and `Goal#backing_within` exists to ask that question.

It reads through the shared pool rather than summing `allocated_amount`,
because a whole-account link reserves no fixed slice: summed naively it counts
as zero while actually claiming the remainder.

Scoped like `#transactions` — a personal budget sees its owner's accounts, the
household one what the viewer can see. A figure labelled "available" has to
mean available to the person reading it.

Behind the preview flag, because goals are: a panel that subtracts what they
claim, and links to them, would otherwise point at a page the reader cannot
open and explain a subtraction they cannot inspect.

bin/rails test: 7083 runs, 28500 assertions, 0 failures. RuboCop, erb_lint and
Brakeman clean.

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

* fix(budgets): make the cash panel work in more than one currency

Review on #3179. Three defects, all of them mine, all in the same seam.

`ExchangeRate.find_rate` does not exist. Every multi-currency family
opening the budget page hit a NoMethodError before the panel rendered.
`find_or_fetch_rate` is the lookup the rest of the app uses.

`earmarked_for_goals` summed each goal's backing in the goal's own
currency and subtracted it from an `available_cash` that had been
converted. A fully earmarked EUR 1,000 account in a USD budget read as
1,200 available, 1,000 earmarked and 200 free — when none of it is free.

The French keys landed under `budget_categories` instead of `budgets`, so
the partial's `t(".heading")` found nothing and French readers got the
English fallback.

A missing rate leaves the amount as it stands rather than raising: a panel
wrong by the spread beats the whole budget page failing to render.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 21:17:51 +02:00
buzzromainandClaude Opus 5 f0333c026e feat(goals): surface money that left a goal's accounts unexplained (#3177)
* feat(goals): surface money that left a goal's accounts unexplained

Goals never read transactions. `current_balance` is a stock summed from account
balances, so an outflow reaches a goal only as a smaller number, with nothing
saying which goal it belonged to. `consume!` closes that gap, but only for a
user who thinks to declare it — and the whole difficulty is that they have no
reason to think of it.

`Goal::WithdrawalDetector` surfaces the outflows nothing has claimed, and the
goal page offers them: *if any of this was spent on Trip, say so*. One click
records it with the transaction as evidence.

This is the pull half of what `GoalPledge` does for money coming in. A pledge
asks first and matches later; here there is nothing to promise, so the outflow
is surfaced after the fact and attributed — or not.

**Anchored on the transaction, not declared.** `consume!` now takes one and
stamps `extra["goal"]["consumed_goal_id"]`, the same namespace the pledges
write into. That is what makes attribution idempotent: replaying it cannot
credit a goal twice for one spend, and the stamp happens inside the
consumption's own transaction so a refusal rolls the whole thing back.

**Sign matters more than it reads.** In Sure an inflow carries a NEGATIVE
amount, so the detector selects the positive side. Reading it the other way
round would have offered to attribute the user's deposits as spending, and the
mistake would look right in a diff. A test pins it.

**A reserve is excluded.** It is drawn down and refilled, not spent, and asking
someone to attribute a withdrawal from one invites them to erase the very
shortfall it exists to report.

Known limitation, unchanged by this: `GoalPledge::Reconciler` only runs on
provider imports, never on a hand-entered transaction. This detector reads
entries directly and so has no such gap, but the two halves are not symmetric
and that is worth knowing.

bin/rails test: 7100 runs, 28540 assertions, 0 failures. RuboCop, erb_lint and
Brakeman clean.

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

* fix(goals): only offer an outflow the goal could still have spent

Review on #3177.

The panel offered outflows for completed and archived goals. Those have
handed their accounts back, so a later transaction on one is not evidence
about this goal — attributing it writes spending into a history that is
already closed. The detector now returns nothing for a released goal;
`consume!` refuses these too, but the panel should not ask in the first
place.

Provisional transactions were offered as well. A pending charge can be
reversed or replaced by its posted form, leaving the goal consumed for a
transaction that no longer exists while the posted twin arrives unstamped
and gets offered again. Filtered through the pending-provider SQL the rest
of the app already uses.

`thaw_completed_amount!` wiped `consumed_amount` unconditionally, so a goal
that recorded a spend and was then archived straight from active lost that
history on unarchive — and dropped its progress with it. Restarting is what
clears the figure, and a direct archive never closed a lifecycle to restart
from. Cleared now only when a frozen figure exists.

The attribution button was a hand-rolled `button_to` with raw `btn`
classes; it is `DS::Button` now, the same primitive the consumption dialog
uses, so the two ways of recording a spend do not read as two features.

Carried down from #3176 by rebase: the goal-level lock, the `:not_active`
guard, and the success notice, which was blank on this path because the
form posts only `transaction_id`. The resolved amount is formatted through
`Money` and the account behind an attributed outflow now resolves through
`accessible_accounts` like the named one.

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

* fix(goals): keep a private backing account out of the outflow panel

The same leak #3176 closed on the dialog, through a third door. A goal can
be backed by an account private to another family member, and the panel
listed its outflows — naming the account, what was spent on it and roughly
its size to someone with no access to it.

`WithdrawalDetector` takes `accounts:` now, and the controller passes the
links narrowed to what the viewer may see. It defaults to every linked
account for callers with no viewer to speak for.

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

* fix(goals): use the shared separator key in the outflow panel

DS Drift Patrol on #3177. The `·` between an outflow's date and its
account was a bare literal. `shared.dot_separator` already exists and is
already used three times in the goals views, so this was drift rather than
a missing mechanism.

Wrapped in `aria-hidden` like the existing uses: the separator is
decorative, and a screen reader was reading it out between the two values.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 21:15:31 +02:00
b6029c1e28 feat(goals): show what each account still has room to earmark (#3166)
* feat(goals): show what each account still has room to earmark

`Account#free_to_earmark` has existed, unused, since earmarks shipped —
its own comment said the UI was a follow-up. This is that follow-up, and
the wording is the substance of it.

It does not say "over-allocated". `free_to_earmark` is negative for as
long as the saving is unfinished, which is the normal condition of anyone
with goals in progress: a 6,000 account backing two goals of 5,000 gives
−4,000 and is a perfectly correct setup. A warning phrased as a fault
would fire permanently and teach people to ignore it. The message states
the consequence instead — the goals come to X for a balance of Y, so they
progress pro rata — and is never styled as an error.

The trap is the goal being edited. `goal_earmarked_total` counts every
goal including that one, so reopening a goal that earmarks 5,000 on a
6,000 account shows 1,000 of headroom, and re-entering the same 5,000
trips a message about a setup the user has not touched.
`earmarked_by_other_goals` excludes it, and only when it is persisted —
a goal being created has nothing to exclude.

The pool is read once per render and passed down, never per account: the
form lists every fundable account the user can see. A test counts the
query and fails at two.

The Stimulus controller is its own, with 3 targets. goal_form_controller
is at 10 against the 7 the project guidelines suggest, needs none of this
state, and is untouched.

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

* fix(goals): read the typed amount strictly, and format it in the app's locale

Addresses review feedback on #3166.

`Number.parseFloat` accepts prefixes, so "500abc" became 500, and the bare
comma-to-dot swap turned a thousands-separated "1,500" into 1.5. Either way the
preview described an amount the user had not typed — and the second case is a
habit from another locale, not a typo, so it would have gone unnoticed. The
value now has to match a complete number before anything is computed.

`Intl.NumberFormat(undefined, ...)` let the BROWSER pick the locale, so a
French user on an English-locale browser read separators and symbol placement
matching nothing else on the page. The amounts cannot be formatted server-side
— they change with every keystroke — so the server passes `I18n.locale` and the
client applies it. That puts the decision where the rest of the app's
formatting already lives.

bin/rails test: 6954 runs, 0 failures. RuboCop, erb_lint and biome clean.

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

* fix(goals): let the assistant create a second goal on a claimed account

Review on #3166. The function always built whole-account links and had no
way to express an earmark, so once exclusivity landed, asking for a second
goal on an account another goal already claimed came back as a bare
`validation_failed` — while the account list still advertised the account
as available. A common request became an unexplained refusal.

Three changes, and the list is the important one: it now says what is left
on each account and which are claimed in full, because the assistant
reasons from that list and had no way to know otherwise.

`earmarks` is an optional map of account name to amount, so the assistant
can reserve a slice rather than the whole balance. Accounts left out keep
the previous behaviour and take whatever is spare.

The refusal is named before the save — `account_claimed_in_full`, with the
account names — so the assistant gets a reason it can act on and ask about,
rather than a validation message it can only relay. Checked after the
currency check, which is the more fundamental of the two.

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

* test(goals): move the spend tests back out of the private section

The merge of `main` into this branch landed #3176's tests between
`count_pool_queries` and the helpers below it, inside the `private`
section and at the wrong indentation. `ci / lint` has been failing on
`Layout/IndentationConsistency` since.

They still ran — `test` is a class method, so `private` does not hide them
— which is why the unit job stayed green while lint went red.

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

---------

Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
2026-08-26 21:12:06 +02:00
buzzromainandClaude Opus 5 d7bf401cc7 fix(onchain-wallets): call transfers transfers, and drop the address swap (#3153)
* fix(onchain-wallets): call transfers transfers, and drop the address swap

Three things reported from real use.

**A transfer was announced as a purchase.** A movement was imported with
`activity_label: "Buy"/"Sell"` and named "Buy 1.5 FAKE" — but coins arriving at
an address were not bought there, and nothing here knows whether they were ever
bought at all. The trade shape stays, because it is what carries quantity and
cost basis in this ledger, but the label is now "Transfer" and the name is the
one the movement already had while it was unpriced. The old wording also made
the same event rename itself the day a price turned up for it.

Worth pairing with the change to trades/_header.html.erb, which until now read
the amount's sign and would still say "Buy" whatever the label.

**Changing a tracked address is gone.** It repointed the rows at a new address
while keeping their accounts, holdings and history — so trades reconstructed
from address A stayed under an account presented as address B. Its own help
text said so out loud: "The accounts, holdings and history stay as they are."
Removing the address and adding the new one is not just simpler, it is the only
one of the two that is honest, because it takes the old history with the old
address.

**The buttons follow the app's conventions now.** Actions that repeat per row
belong in a menu here — accounts/_account.html.erb renders its own that way —
not in a row of labelled buttons, which is what a provider panel does when it
has a single connection to act on. So the per-address actions are a menu, the
per-asset disconnect is icon-only, and the accounts-page card gains the actions
menu every other provider card already had.

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

* fix(onchain-wallets): give a tracked asset its icon on the accounts page

Account#logo_url asks its provider adapter for one, and ours answered nothing:
there is no institution behind a self-custody wallet, and nothing attaches a
file, so every tracked asset showed a blank where every other account shows an
icon. Fixing Security#crypto_base_asset covered the holdings list, which reads
the security directly — this is the other path, and it went through the adapter.

Built from the symbol rather than looked up. The accounts page renders one of
these per account, so resolving a Security each would be a query per row, and
the symbol is all Brandfetch's crypto endpoint needs. It answers nil without a
client id, which is the same nothing the page shows today.

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

* test(onchain-wallets): follow the moved banner and the menu in the browser

The system suite still expected the settings panel to carry the read-only
reassurance, and to find "Review tokens" as a visible button. Both moved in the
previous commit: the banner into the linking modal, where the question it
answers is actually asked, and the per-address actions into a menu, as repeated
row actions are rendered everywhere else in this app.

Caught by CI rather than by me — the per-branch checks I ran covered
`bin/rails test` and not `test:system`.

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

* test(onchain-wallets): pin the reassurance to the frame it moved into

The assertion proved the banner was somewhere on the page, which is exactly
what the change does not claim: the point is where it lives. Now it asserts the
text is absent from the settings panel and present inside the modal, so the
test fails if the banner drifts back or never arrives.

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

* fix(onchain-wallets): rename movements imported before transfers had a name

Review on #3153.

Wallets synced before this change keep their `Buy`/`Sell` labels and their
"Buy 1.5 shares of CRYPTO:BTC" wording, and nothing was rewriting them:
`perform_sync` returns early when no address changed on chain, and the
repair pass only ever looked at display-only `Transaction` rows. A cold
address would have shown the old wording indefinitely — which for a wallet
nobody touches is most of them.

The repair now relabels this processor's own trades too, scoped to its
`external_id` prefix and to `source: SOURCE` so a trade the user entered by
hand is never renamed. It runs from `perform_post_sync`, which is the pass
that already runs for every linked asset rather than only the changed ones.
Idempotent, so a nightly sync does not rewrite the same rows forever.

Separately: `Security.brandfetch_crypto_url` interpolated the symbol
straight into a URL path, and `Onchain::AssetSymbol.canonical` only upcases
and trims. An on-chain token can be called whatever its deployer chose, so
a slash pointed the path elsewhere on the CDN and a hash pushed the client
id into a fragment Brandfetch never sees. Guarded in the helper rather than
at the call site — six callers reach it from four providers.

Also from review: the icon test saves and restores
`Setting.brand_fetch_client_id` instead of hard-coding nil in its `ensure`,
which was erasing whatever the suite had configured.

The "one query" claim in a repair test's name was never asserted, and this
change adds a second query. Renamed to what it actually checks.

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

* test(onchain): drop the last change_address test with its feature

#3182 added a `change_address` test while this branch was removing the
feature it exercises. The rebase kept both, leaving a test calling a route
this branch deletes.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 21:07:58 +02:00
buzzromainandClaude Opus 5 613964529a feat(goals): let a goal be spent without looking like it fell behind (#3176)
* feat(goals): let a goal be spent without looking like it fell behind

Coming home from the holiday a goal paid for dropped it from 100% to 20%. The
money went where it was meant to go, and the app read that as failure. The only
way back was to edit the target — falsifying what the user had actually set out
to save.

`consumed_amount` records what was spent ON the thing the goal was for, and
progress reads `(backing + consumed) / target`. Spending the money is no longer
indistinguishable from losing it.

**The part that is easy to miss.** `consume!` also shrinks the earmark on the
account by the same amount. Without that, money the user has already spent
stays reserved and keeps its share away from every sibling goal — the exact
double-counting the exclusivity rules exist to prevent, arriving through the
back door. A test pins it through the pro-rata haircut, where the effect is
visible: a sibling's backing grows as the spent share is released.

**Kept separate from `completed_amount`.** That one freezes the BACKING at
closure; folding consumption into it would count the same money twice on a goal
partly spent and then closed. A test asserts each side is counted once.

**A reserve refuses consumption outright.** It is drawn down and refilled, not
spent, and recording a withdrawal as consumption would erase the shortfall the
reserve exists to report.

`account:` may be omitted only when the goal has one link — with several,
guessing would silently pick a side. The controller refuses an account id that
resolves to nothing rather than falling back to nil, which on a single-link
goal would have recorded the spend against an account the user never named.

The write is its own action rather than a verb branch inside `consume`: HEAD
routes like GET but `request.get?` is false for it, so a branch would send a
HEAD request down the write path. Brakeman caught that.

bin/rails test: 7088 runs, 28510 assertions, 0 failures. RuboCop, erb_lint and
Brakeman clean.

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

* fix(goals): make a spend either happen entirely or not at all

Review on #3176 found the recorded spend and the released earmark could
drift apart, and that nothing stopped the two figures being edited out of
agreement afterwards.

The lock was on the link, not the goal. `consumed_amount` lives on the
goal, so two concurrent requests locking only their own links both read
the same old value, both passed the target check, and both added to it.
The whole check-and-write now runs under `with_lock` on the goal.

Consuming more than the chosen link held was silently clamped: the link
released what it had while `consumed_amount` took the full figure, so
money counted as spent stayed reserved against every sibling goal. It is
refused now — `:exceeds_earmark` — rather than half-applied.

A dialog left open in another tab could still post to a goal that had
since been completed or archived; `:not_active` closes that.

Two validations stop the pair being separated after the fact: a goal that
has recorded a spend cannot become a reserve (reserves refuse consumption,
so the figure would count toward progress on an object whose model treats
spending as a shortfall), and the target cannot be lowered below what was
already spent.

Consuming cleared the columns and left the memos standing, so an instance
that had already read its backing kept reporting the pre-spend figure.
Progress holding steady is the feature — the earmark shrinks by what
consumption grows by — which is exactly what hid the stale backing.

Also from review: `accessible_accounts` rather than the whole family for
the account picker, `DS::Select` rather than a bare `select_tag`, the
flash amount through `Money#format`, and the French label for the menu
entry, which I had left untranslated.

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

* refactor(goals): reuse the cache reset the class already owns

Review pointed out `reset_state_dependent_caches!` exists for exactly this,
and that hand-rolling a second ivar list was the wrong shape. It was also
wrong in substance: mine omitted `@pooled_allocations`, and consuming
shrinks a link's allocation, which is precisely what the pool is computed
from. One list, kept in one place, stays right when a memo is added.

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

* docs(goals): put four comments back on the methods they describe

Rebases had stranded them: a paragraph about clearing memos on an AASM
transition, two about what reopening does to a frozen figure, and one
about `reload` leaving memos standing had all piled up in front of
`consumption_link_for`, which does none of those things.

The last is dropped rather than moved — its explanation now sits at the
call site in `consume!`, where the reset actually happens.

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

* fix(goals): keep a private backing account out of the consume dialog

A goal can be backed by an account the viewer is not allowed to see, and
the first pass only guarded the named-account path. Two ways round it
remained.

The dialog listed every link, so it named private accounts outright. And
with `account_id` left blank the model picked the sole link on its own,
without anyone having checked the viewer could reach it — so a direct POST
reduced a private account's earmark, the figures moving afterwards saying
roughly how much was in it.

The controller now derives the eligible links from
`Current.user.accessible_accounts`, the dialog renders those, and a blank
id resolves only to a sole *eligible* account. With none the request is
refused; with several it stays nil and the model asks, as before.

Naming the account explicitly matters even when the goal has several
links: the one the viewer can reach is not necessarily the one the model
would have picked.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 18:52:25 +02:00
github-actions[bot]andgithub-actions[bot] <github-actions[bot]@users.noreply.github.com> ec75b054e4 Bump version to next iteration after v0.7.4-alpha.10 release (#3185)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-08-26 18:48:44 +02:00
buzzromainandClaude Opus 5 90203139bf feat(goals): tell the user when a reserve has dropped below its level (#3175)
* feat(goals): reserves you maintain, not goals you finish

An emergency fund is not a goal you reach and close — it is a level you
hold, and every withdrawal is a shortfall to make good. Sure treated it
like anything else: at 100% it offered to close it, which would release
the very money being set aside; a withdrawal dropped the bar with no
sign that anything was owed.

`kind` (added by the lifecycle lot without behavior) now means something.
A maintained goal is `funded` or `depleted`, never `reached` — sitting at
its floor is a steady state, not an achievement to file away. `complete`
is refused by an AASM guard rather than merely hidden, so no path can
release a reserve's earmark.

Two ordering traps, both of which would have made a drained reserve
invisible:

`ACTIVE_DISPLAY_STATUS_RANK` falls back to 4 for any status it does not
know, so an unranked `:depleted` would sort a drained emergency fund
below everything else — the exact opposite of what it means. It ranks
alongside `:behind` now, and `:funded` sorts near the end with the goals
that need nothing.

`behind_pace?` excludes reserves. `monthly_target_amount` and `pace` both
derive from `target_date`, which a reserve does not have, so "save X/month
to catch up" would be advice about a deadline that does not exist.

The form leads with the choice, since it changes what the rest of it
means, and hides the target date for a reserve rather than disabling it —
a hidden field cannot submit a stale value that would then drive a pace.
The card states the shortfall, which is exactly `remaining_amount`. The
panel that offers a one-off its closing action tells a reserve it is
intact and offers nothing, because there is nothing to do.

Scope: fixed targets only. Targets expressed in months of expenses, the
monthly refresh job, and the depletion insight are the next two PRs.

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

* fix(goals): let a reserve behave like one everywhere it is shown

Addresses review feedback on #3167.

The kind selector never hid the target date. `data-controller="goal-kind"`
sat on the selector div while its `dateField` target is a sibling, so
`dateFieldTargets` came back empty and picking "Reserve to maintain" left the
deadline on screen and submittable. The controller moves to the form wrapper,
which encloses both.

Hiding a field is not enforcement, so the model now clears `target_date` for a
maintained goal. Normalising rather than rejecting: the field is hidden, and an
error about something the user cannot see is not actionable. A date could only
arrive through a conversion or a crafted request, and either way a stored
deadline would drive a pace the reserve does not have.

A completed goal could be switched to `maintained` from the edit form. It then
sat in a released state — one that has handed its earmark back — while the show
page promised its money stays reserved, and `complete` for reserves is refused
precisely to prevent that state. `kind` is now locked while released: reopen
first.

Reserves counted against the "goals on track" tile. Their statuses are
`funded`/`depleted`, which match none of the exclusions in `tracked_total`, so
they could never reach the numerator and a family with one reserve read
"0 of 1 on track" for a goal working exactly as intended.

Two more places still spoke of pace to something that has none. `pace_line` is
suppressed for reserves on the card, and a depleted reserve gets its own panel
before the projection card — the projection's summary, catch-up line and colour
are all built from a deadline. What a drained reserve needs is the number the
projection cannot show: how much is missing from the floor.

The French celebration copy read "Votre réserve est à son niveau", which never
says which level.

Each guard was confirmed load-bearing by removing it and watching its test
fail. bin/rails test: 6962 runs, 28003 assertions, 0 failures. RuboCop,
erb_lint and Brakeman clean.

Left open deliberately: extracting the show page's lifecycle panel into a
ViewComponent. The guideline behind it is right, but the refactor is wider than
this round of fixes and belongs on its own.

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

* fix(goals): finish teaching the status consumers about reserves

Second round of review feedback on #3167: two consumers still had no branch
for the reserve statuses.

`ProgressRingComponent#percent_text_class` styled only `:reached` as success,
so a funded reserve — a floor the user is holding exactly as intended — fell
back to the neutral colour and read as unfinished.

`status_callout_context` had no `:depleted` branch, so a drained reserve showed
no callout at all: the one status that most deserves a line of explanation was
the only one saying nothing. It now names the shortfall.

`:funded` deliberately keeps no callout — a reserve at its level has nothing to
report, and the celebration panel already says so. A test pins that, so the
silence reads as a decision rather than another missing branch.

bin/rails test: 6964 runs, 28008 assertions, 0 failures. RuboCop and Brakeman
clean.

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

* fix(goals): lock the kind on the state the goal is actually in

Addresses review feedback on #3167, on the guard that landed in c1c7f4f7.

`kind_locked_while_released` read the in-memory `state`, so a single write
setting `state: "active"` alongside the new kind saw the goal as already
reopened and waved it through.

The end state looks legitimate — active and maintained — which is why the hole
is easy to miss. It is not: the direct write skipped the `reopen` transition,
and with it `thaw_completed_amount!`. `completed_amount` survived, so
`current_balance` returned that frozen snapshot forever on a live reserve.
Reopening has to be its own gesture, because it is the gesture that thaws.

Now reads `state_in_database`, with a regression test on the combined write
asserting both that it is refused and that the frozen amount is untouched.

Confirmed load-bearing by reading the attribute again and watching it fail.
bin/rails test: 6969 runs, 28019 assertions, 0 failures. RuboCop and Brakeman
clean.

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

* fix(goals): send an empty reserve to the shortfall panel, not the empty state

Addresses the last review thread on #3167.

The `maintained?` branch sat after the zero-balance/zero-pace one, so a
brand-new reserve matched the generic "make your first transfer" card. I had
put it there on purpose, thinking a reserve with nothing in it wanted the
first-transfer nudge. The review is right that it does not: it is still a
reserve short of its floor, and the shortfall panel says so with the saved,
target and missing amounts, where the generic card says none of them.

Ordering it after also meant evaluating `pace` on a goal that has no pace to
evaluate.

bin/rails test: 6965 runs, 0 failures. RuboCop and erb_lint clean.

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

* fix(goals): stop a paused goal outranking a reserve that is whole

Review on #3175.

`:funded` and paused both ranked 3 in `active_display_sort`, so the tie
broke on name and a paused goal called "Alpha" sat above a reserve called
"Zeta" that was fully funded — the list saying the paused one wanted
attention more. Paused now ranks behind every status, which is what the
comment above the table already claimed.

The seven panels on the goal page were hand-rolled repetitions of
`DS::Card`'s exact shell, two of them adjacent and identical. They render
through the primitive now, so their surface styling cannot drift apart.

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

* refactor(goals): move the lifecycle panel decision out of the template

Review on #3167 and #3180.

Which panel a goal gets is a lifecycle question with five answers, and the
template worked it out inline from `completed?`, `maintained?`, `one_off?`,
`status` and `may_complete?` — five predicates deep in ERB where the
ordering between them was load-bearing and nothing said so.

`Goals::LifecyclePanelComponent` answers it in Ruby and the template
renders the answer. The markup moves across unchanged, keys made absolute
because a relative `t(".x")` in a component resolves against the
component's own path rather than the page these strings belong to.

The order is now stated once, where it can be read and tested:
`:reserve_shortfall` before `:empty`, because a brand-new reserve sits at
zero balance and zero pace and the generic "make your first transfer" card
would otherwise swallow it.

Closing from the panel now confirms, as the header menu already did.
Completing releases the goal's earmarked money, and the panel offered that
in one click. Both go through `goal_complete_confirm` rather than building
the wording twice — two copies drifting apart is how one ends up
describing the wrong consequence.

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

* fix(goals): refresh the pace suggestion when the deadline is cleared

Assigning `input.value = ""` fires no event, so `goal-form#suggestedChanged`
never ran: selecting "Reserve to maintain" cleared the date but left the
monthly pace suggestion on screen, derived from a deadline the goal no
longer has.

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

* fix(goals): let a depleted reserve look as urgent as it is

Review on #3179 and #3180.

`Goal#needs_attention?` names the pair of statuses that mean "this one wants
looking at" — a goal off its pace and a reserve below its floor. Three
places were spelling that out and the Plan hub's progress bar had fallen
behind, so a depleted reserve got a neutral bar an inch from its own amber
status pill: the same goal reported as needing attention and not.

`projection_summary` told a funded reserve it had "hit the target, no
projection needed". A reserve holds a level; there is no finish line to
project toward and no target to have hit. It does not reach that panel
today — the shortfall and celebration panels catch it first — but the
method reads as the single source of truth for that subtitle and should not
hand a caller a one-off's wording.

The legend swatches are bordered spans now rather than inline SVG, and the
label takes `text-xs` instead of an arbitrary 11px. The projection swatch
keeps the chart's own colour variables in an inline style rather than
`border-success` / `border-warning`: the chart hard-codes green-600 and
yellow-600, and a legend whose colour does not match the line it describes
is worse than the markup it would save.

The Plan-card test counts warning bars rather than matching one. A fixture
goal is already off its pace, so the markup is on the page either way and a
presence check passed without the fix.

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

* feat(goals): tell the user when a reserve has dropped below its level

A maintained reserve exists to hold a floor. Nothing said when it stopped
holding it: the goal page shows the shortfall, but only to someone who thought
to look, and a reserve is precisely the thing you stop looking at once it is
full. That silence is the gap this closes.

High priority, unlike most of this feed. `IdleCashGenerator` is a nudge about
money doing nothing; this is the opposite — a floor the user deliberately set
is no longer there. It is also the one signal a reserve can produce that a
one-off goal cannot, which is what makes it worth a generator of its own.

Three deliberate limits:

- **Active reserves only.** A paused one is shelved on purpose, and
  `behind_pace?` already excludes paused goals for the same reason. Nagging
  about a goal someone put down is noise.
- **The dedup key rotates monthly.** A reserve can sit short for weeks while it
  is rebuilt, and re-raising the same shortfall every night trains people to
  dismiss the feed.
- **Two at a time, worst shortfall first.** A family running four drained
  reserves has one problem, not four.

Loaded through `Goal.prepared_for` so the family-wide pooled allocations are
read once: asking each reserve for its status reaches `current_balance`, and
without that injection every one of them would re-read the whole pool.

bin/rails test: 7079 runs, 28491 assertions, 0 failures. RuboCop and Brakeman
clean.

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

* fix(insights): stop an insight naming something that has been renamed

Review on #3175: renaming a depleted reserve leaves the stored title
naming the old one for the rest of the month, because the name is not part
of the metadata that drives a refresh.

Rather than making the name material, the same-signal branch now refreshes
the title alongside the facts. The title is built from I18n and the
generator's own data — the model writes the body, not this — so keeping it
current costs nothing, and a rename is not a reason to resurface an
insight the user has already read.

The body still says the old name until the numbers move. Forcing an LLM
rewrite on every rename is the wrong trade, and making the name material
would do that *and* re-nag the user.

This is generic to every generator whose title embeds a name, not only the
reserve one.

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

* fix(insights): refresh the title on reactivation too

A gap in the previous commit: the expired-and-returned branch resurfaces an
insight without touching its title, so a subject renamed while the insight
was expired came back naming the old one.

Same reasoning as the same-signal branch — the title is I18n plus the
generator's own data, not the model's prose, so keeping it current costs
nothing.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 08:26:43 +02:00
buzzromainandClaude Opus 5 2c0d262cf6 fix(onchain): a deleted account leaves no wallet row behind (#3182)
* fix(onchain): a deleted account leaves no wallet row behind

Deleting a Sure account left its on-chain tracking row in place. The row
had a callback to follow its account link into the grave, but the guard
that stopped it destroying itself could not tell apart the two ways that
link dies — by the row, or by the account — and so caught both.

What survived was worse than untidy. The row synced nothing and showed
nowhere, yet it still answered "yes" to "is this address already
tracked?" and still held the asset's slot in the partial unique index.
The address became unusable: adding it again was refused as a duplicate
of something the user could not see, and moving another address onto it
raised a database error.

So three places learn the difference between a row that tracks an
account and one that merely exists: the guard now skips only its own
row's destruction, the family's linked check asks for a live link, and
the linker and address change let a dead row make way instead of
colliding with it.

No migration: a row already orphaned on a running instance is absorbed
the next time that address is tracked.

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

* fix(onchain): stop an orphan row passing itself off as a tracked asset

Review on #3182. Both findings are the same root: a row left behind by a
deleted account has no Account and no AccountProvider, but nothing
downstream was asking.

`revise` counted any matching row as tracked, orphans included, so ticking
an asset whose account had been deleted did nothing at all — no Account
created, the row still orphaned, and the screen still reporting the asset
as tracked. It now looks only at rows that are actually linked, and at the
ones that survived the removal pass.

`link` cleared only the rows matching the assets picked in that submit, so
relinking a subset left the rest as orphans. They still show up in
`grouped_accounts` and token review as tracked, and — before the fix above
— they also stopped `revise` from ever rebuilding them. Reclaiming an
address now clears every row it left behind. A live row is untouched, with
a test that fails if the sweep widens.

One existing test had to change its premise rather than its assertion. It
built two unlinked rows and asserted the surviving row object was the same
one; unlinked rows are orphans, so revising now rebuilds them and the
survivor is a new row. Linking them first is what a tracked asset actually
is, and the assertion then measures the removal it was written for.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 08:22:17 +02:00
buzzromainandClaude Opus 5 6d7ca3584c feat(goals): reserves you maintain, not goals you finish (#3167)
* feat(goals): reserves you maintain, not goals you finish

An emergency fund is not a goal you reach and close — it is a level you
hold, and every withdrawal is a shortfall to make good. Sure treated it
like anything else: at 100% it offered to close it, which would release
the very money being set aside; a withdrawal dropped the bar with no
sign that anything was owed.

`kind` (added by the lifecycle lot without behavior) now means something.
A maintained goal is `funded` or `depleted`, never `reached` — sitting at
its floor is a steady state, not an achievement to file away. `complete`
is refused by an AASM guard rather than merely hidden, so no path can
release a reserve's earmark.

Two ordering traps, both of which would have made a drained reserve
invisible:

`ACTIVE_DISPLAY_STATUS_RANK` falls back to 4 for any status it does not
know, so an unranked `:depleted` would sort a drained emergency fund
below everything else — the exact opposite of what it means. It ranks
alongside `:behind` now, and `:funded` sorts near the end with the goals
that need nothing.

`behind_pace?` excludes reserves. `monthly_target_amount` and `pace` both
derive from `target_date`, which a reserve does not have, so "save X/month
to catch up" would be advice about a deadline that does not exist.

The form leads with the choice, since it changes what the rest of it
means, and hides the target date for a reserve rather than disabling it —
a hidden field cannot submit a stale value that would then drive a pace.
The card states the shortfall, which is exactly `remaining_amount`. The
panel that offers a one-off its closing action tells a reserve it is
intact and offers nothing, because there is nothing to do.

Scope: fixed targets only. Targets expressed in months of expenses, the
monthly refresh job, and the depletion insight are the next two PRs.

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

* fix(goals): let a reserve behave like one everywhere it is shown

Addresses review feedback on #3167.

The kind selector never hid the target date. `data-controller="goal-kind"`
sat on the selector div while its `dateField` target is a sibling, so
`dateFieldTargets` came back empty and picking "Reserve to maintain" left the
deadline on screen and submittable. The controller moves to the form wrapper,
which encloses both.

Hiding a field is not enforcement, so the model now clears `target_date` for a
maintained goal. Normalising rather than rejecting: the field is hidden, and an
error about something the user cannot see is not actionable. A date could only
arrive through a conversion or a crafted request, and either way a stored
deadline would drive a pace the reserve does not have.

A completed goal could be switched to `maintained` from the edit form. It then
sat in a released state — one that has handed its earmark back — while the show
page promised its money stays reserved, and `complete` for reserves is refused
precisely to prevent that state. `kind` is now locked while released: reopen
first.

Reserves counted against the "goals on track" tile. Their statuses are
`funded`/`depleted`, which match none of the exclusions in `tracked_total`, so
they could never reach the numerator and a family with one reserve read
"0 of 1 on track" for a goal working exactly as intended.

Two more places still spoke of pace to something that has none. `pace_line` is
suppressed for reserves on the card, and a depleted reserve gets its own panel
before the projection card — the projection's summary, catch-up line and colour
are all built from a deadline. What a drained reserve needs is the number the
projection cannot show: how much is missing from the floor.

The French celebration copy read "Votre réserve est à son niveau", which never
says which level.

Each guard was confirmed load-bearing by removing it and watching its test
fail. bin/rails test: 6962 runs, 28003 assertions, 0 failures. RuboCop,
erb_lint and Brakeman clean.

Left open deliberately: extracting the show page's lifecycle panel into a
ViewComponent. The guideline behind it is right, but the refactor is wider than
this round of fixes and belongs on its own.

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

* fix(goals): finish teaching the status consumers about reserves

Second round of review feedback on #3167: two consumers still had no branch
for the reserve statuses.

`ProgressRingComponent#percent_text_class` styled only `:reached` as success,
so a funded reserve — a floor the user is holding exactly as intended — fell
back to the neutral colour and read as unfinished.

`status_callout_context` had no `:depleted` branch, so a drained reserve showed
no callout at all: the one status that most deserves a line of explanation was
the only one saying nothing. It now names the shortfall.

`:funded` deliberately keeps no callout — a reserve at its level has nothing to
report, and the celebration panel already says so. A test pins that, so the
silence reads as a decision rather than another missing branch.

bin/rails test: 6964 runs, 28008 assertions, 0 failures. RuboCop and Brakeman
clean.

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

* fix(goals): lock the kind on the state the goal is actually in

Addresses review feedback on #3167, on the guard that landed in c1c7f4f7.

`kind_locked_while_released` read the in-memory `state`, so a single write
setting `state: "active"` alongside the new kind saw the goal as already
reopened and waved it through.

The end state looks legitimate — active and maintained — which is why the hole
is easy to miss. It is not: the direct write skipped the `reopen` transition,
and with it `thaw_completed_amount!`. `completed_amount` survived, so
`current_balance` returned that frozen snapshot forever on a live reserve.
Reopening has to be its own gesture, because it is the gesture that thaws.

Now reads `state_in_database`, with a regression test on the combined write
asserting both that it is refused and that the frozen amount is untouched.

Confirmed load-bearing by reading the attribute again and watching it fail.
bin/rails test: 6969 runs, 28019 assertions, 0 failures. RuboCop and Brakeman
clean.

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

* fix(goals): send an empty reserve to the shortfall panel, not the empty state

Addresses the last review thread on #3167.

The `maintained?` branch sat after the zero-balance/zero-pace one, so a
brand-new reserve matched the generic "make your first transfer" card. I had
put it there on purpose, thinking a reserve with nothing in it wanted the
first-transfer nudge. The review is right that it does not: it is still a
reserve short of its floor, and the shortfall panel says so with the saved,
target and missing amounts, where the generic card says none of them.

Ordering it after also meant evaluating `pace` on a goal that has no pace to
evaluate.

bin/rails test: 6965 runs, 0 failures. RuboCop and erb_lint clean.

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

* fix(goals): stop a paused goal outranking a reserve that is whole

Review on #3175.

`:funded` and paused both ranked 3 in `active_display_sort`, so the tie
broke on name and a paused goal called "Alpha" sat above a reserve called
"Zeta" that was fully funded — the list saying the paused one wanted
attention more. Paused now ranks behind every status, which is what the
comment above the table already claimed.

The seven panels on the goal page were hand-rolled repetitions of
`DS::Card`'s exact shell, two of them adjacent and identical. They render
through the primitive now, so their surface styling cannot drift apart.

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

* refactor(goals): move the lifecycle panel decision out of the template

Review on #3167 and #3180.

Which panel a goal gets is a lifecycle question with five answers, and the
template worked it out inline from `completed?`, `maintained?`, `one_off?`,
`status` and `may_complete?` — five predicates deep in ERB where the
ordering between them was load-bearing and nothing said so.

`Goals::LifecyclePanelComponent` answers it in Ruby and the template
renders the answer. The markup moves across unchanged, keys made absolute
because a relative `t(".x")` in a component resolves against the
component's own path rather than the page these strings belong to.

The order is now stated once, where it can be read and tested:
`:reserve_shortfall` before `:empty`, because a brand-new reserve sits at
zero balance and zero pace and the generic "make your first transfer" card
would otherwise swallow it.

Closing from the panel now confirms, as the header menu already did.
Completing releases the goal's earmarked money, and the panel offered that
in one click. Both go through `goal_complete_confirm` rather than building
the wording twice — two copies drifting apart is how one ends up
describing the wrong consequence.

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

* fix(goals): refresh the pace suggestion when the deadline is cleared

Assigning `input.value = ""` fires no event, so `goal-form#suggestedChanged`
never ran: selecting "Reserve to maintain" cleared the date but left the
monthly pace suggestion on screen, derived from a deadline the goal no
longer has.

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

* fix(goals): let a depleted reserve look as urgent as it is

Review on #3179 and #3180.

`Goal#needs_attention?` names the pair of statuses that mean "this one wants
looking at" — a goal off its pace and a reserve below its floor. Three
places were spelling that out and the Plan hub's progress bar had fallen
behind, so a depleted reserve got a neutral bar an inch from its own amber
status pill: the same goal reported as needing attention and not.

`projection_summary` told a funded reserve it had "hit the target, no
projection needed". A reserve holds a level; there is no finish line to
project toward and no target to have hit. It does not reach that panel
today — the shortfall and celebration panels catch it first — but the
method reads as the single source of truth for that subtitle and should not
hand a caller a one-off's wording.

The legend swatches are bordered spans now rather than inline SVG, and the
label takes `text-xs` instead of an arbitrary 11px. The projection swatch
keeps the chart's own colour variables in an inline style rather than
`border-success` / `border-warning`: the chart hard-codes green-600 and
yellow-600, and a legend whose colour does not match the line it describes
is worse than the markup it would save.

The Plan-card test counts warning bars rather than matching one. A fixture
goal is already off its pace, so the markup is on the page either way and a
presence check passed without the fix.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 08:20:43 +02:00
ServaTilis 77a55fff5b fix(desktop): support a server hosted under a sub-path (#3127)
* fix(desktop): support a server hosted under a sub-path

`normalize_server_url` rebuilt whatever you typed as `scheme://host[:port]`
and dropped the path, so a self-hosted Sure behind a reverse proxy that
mounts it under a prefix — `https://home.example.com/sure` — could never
be added: the health check hit `{origin}/up`, where something else (or
nothing) answers, and the app reported "Couldn't reach a Sure server at
that address." The same bare origin was then used for the navigation, the
SSO hand-off and the IPC capability grant, so even a passing check would
have loaded the wrong site.

The path was being dropped for a reason — people paste the URL they have
in the clipboard, which is usually a deep link like `/sessions/new`. So
rather than guess, let the server say where it is: keep the path in the
canonical form, and have `check_server` probe `/up` from the address as
typed back up to the origin, returning the first base that answers 200.
A root-hosted server still resolves to its origin (one extra candidate,
tried only after the specific one 404s), and a transport-level failure
returns immediately instead of retrying a host that is not there.

`check_server` now answers with that resolved base instead of a bool, and
both callers save it rather than the raw input.

Tests: the sub-path base, trailing slash / query / fragment trimming, the
walk-up candidate list, ports preserved on every candidate, and the cap
that still keeps the origin.

* fix(desktop): carry the mounted base through SSO and deep links

Follow-up to the sub-path support in the previous commit: saving a base
with a path fixed adding and loading such a server, but left two flows
resolving against the bare origin.

The injected bridge only intercepted a form action shaped exactly
`/auth/{provider}`, so a mounted server's `/sure/auth/{provider}` was
never intercepted, and it emitted `location.origin`, which `begin_sso`
would then reject as an unknown server. Match the prefix that precedes
`/auth/` and emit the base it implies — empty at a domain root, so
root-hosted deployments are unaffected.

Deep links were gated on `target.server`, which `deep_link::parse` builds
from host and port alone. Gate on the destination instead, and let
`is_known_server` accept a URL that a saved base covers. `base_covers`
matches only at a path boundary, so a saved `https://sure.example.com`
does not cover `https://sure.example.com.evil.test`.

Reported by automated review on the PR.

* fix(desktop): cap candidates from the deep middle, not the shallow end

The cap kept the deepest MAX_BASE_CANDIDATES - 1 candidates plus the
origin, which discards the shallow ones in between — and a mount point is
shallow. A server mounted at /sure, reached by a link pasted three
segments into the app (`/sure/transactions/123/edit`), produced
`.../edit`, `.../123`, `/sure/transactions`, origin: `/sure`, the only
base that answers, was never probed, so the connection failed with
"Couldn't reach a Sure server at that address" against a live server.

Keep the address as typed plus the shallowest bases instead. Both
readings survive the cap: the base typed exactly, and the mount a deep
link sits under.

Reported by @jjmata in review.

* fix(desktop): bound discovery by mount depth, not candidate count

Capping the candidate list drops whole mount depths silently: with a
budget of four, `https://host/a/b/c/d/e` never probed `https://host/a/b/c`,
so a server mounted there was undiscoverable.

Bound the supported mount depth instead. The address as typed is always
probed first, so a base entered exactly still works at any depth; the
rest are every depth up to MAX_MOUNT_DEPTH, which keeps a pasted deep
link finite (typed + 4 probes) without skipping a depth in between.

Reported by coderabbitai in review.
2026-08-26 08:15:50 +02:00
eb498cfa0c Feature/category hierarchy and account search (#2845)
* Add parent/child category hierarchy to all category selects; add search to account select

Category selection consistency:
- DS::Select (shared component powering the main transaction form,
  transaction edit, bulk-update, and transfer category pickers) now
  indents subcategories with a corner-down-right icon, matching the
  existing transaction-row category dropdown.
- Feed DS::Select-based category pickers with Category.alphabetically_by_hierarchy
  (parent name, then parent-before-children, then own name) so children
  render directly under their parent.
- Added Category::Group.select_options, a shared helper producing
  parent-then-child ordered options (with an indent marker) for plain
  HTML <select> elements. Used by:
  - Rule builder category condition/action selects
  - Bulk 'categorize transactions' select
  - CSV/QIF import category mapping select
- Grouped the splits category combobox and the transaction search
  category filter checklist the same way, both with the
  corner-down-right indent icon used elsewhere.

Account selection:
- Added searchable: true to the account select in the new/edit
  transaction form, matching the category and merchant selects next
  to it.

* Fix SyntaxError: 'for' is a Ruby reserved keyword

Category::Group.select_options called for(categories) as a bare method
call, but Ruby parses a bare 'for' as the start of a for..in loop
statement, not a method invocation. Qualify it as self.for(categories)
to call the class method explicitly.

Verified with 'ruby -c' on all touched .rb files and ERB.new(...).src
on all touched .erb files.

* Add test coverage for category hierarchy and account search

Model-level:
- Category::GroupTest (new): for() grouping and the new select_options
  helper (order + indent labels).
- CategoryTest: alphabetically_by_hierarchy scope ordering.
- Rule::ConditionFilter::TransactionCategoryTest (new)
- Rule::ActionExecutor::SetTransactionCategoryTest (new)
- Import::CategoryMappingTest (new): grouping + 'Add as new category'
  still prepends correctly.

Controller/integration-level (asserting actual rendered HTML order):
- SplitsControllerTest: category combobox data-value ordering.
- Transactions::CategorizesControllerTest: bulk-categorize <select>
  option ordering.
- TransactionsControllerTest:
  - search filter checkbox ordering (q[categories][])
  - new-transaction DS::Select category ordering (via trigger id +
    ancestor traversal)
  - new-transaction account select renders a search box

All new/modified test files verified with 'ruby -c' (syntax) and
cross-checked fixture names, family scoping, route helpers, and field
names against the actual fixtures/routes/views. Ruby/Bundler network
access to rubygems.org is unavailable in this sandbox, so the suite
itself has not been executed — run 'bin/rails test' before merging.

* Align with design-sure conventions: keep domain logic in component, not template

Per .cursor/rules/view_conventions.mdc ('keep domain logic out of the
views'), the parent/child hierarchy check for DS::Select items belongs
in the component class, not inline in the ERB template. DS::Select
already has this exact pattern for other per-item derived properties
(color_for, icon_for, logo_for) — added child? alongside them and
updated the template to call it instead of computing it inline.

Added test/components/DS/select_test.rb (ViewComponent::TestCase,
no rendering needed) covering child? directly: subcategory objects,
root-category objects, non-hierarchical objects (merchants), and the
include_blank placeholder item.

Also did a broader pass against the design-sure .cursor/rules to confirm
the rest of this branch's changes already comply:
- Uses Current.family (never current_family) throughout
- Uses the icon() helper exclusively, never lucide_icon directly
- No new/hardcoded colors; only existing semantic Tailwind tokens
  already used elsewhere in these same files
- No changes to sure-design-system.css / application.css
- Extended existing components/partials rather than creating new ones
  where one already existed (view_conventions.mdc component-vs-partial
  guidance)
- Test additions stay in Minitest + fixtures, avoid system tests,
  and test query-method output directly (testing.mdc)

* Address CodeRabbit review: sort category groups, tighten test assertion, move grouping out of view

* Address review: fix arrow leak in rule summaries, filter panel alignment, simplify splits ordering

* fix(pages): set breadcrumbs for changelog and feedback pages (#2889)

* fix(app): set breadcrumbs for changelog and feedback pages

* feat(test): add test to assert breadcrumbs

* fix(test): remove changes

* feat(app): update breadcrumbs to use semantic nav element

* feat(test): add breadcrumb assertions to changelog and feedback pages

* fix(app): replace breadcrumb nav element with div containing data-breadcrumbs attribute

* fix ci failures

* resolved failures

* Regenerate schema.rb from migrations

* Fix test

* Remove schema dump noise

---------

Signed-off-by: Shibu M <23173570+DataEnginr@users.noreply.github.com>
Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Claude <claude@anthropic.com>
Co-authored-by: Kenrick Tandrian <60643640+KenTandrian@users.noreply.github.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
2026-08-26 07:59:00 +02:00
Sure Admin (bot) 3a9c8baf81 Warn before provider setup without encryption keys (#3007)
* Warn before provider setup without encryption keys

* Cover provider encryption warning states

* Warn on inline provider credential forms

* Avoid duplicate provider encryption warnings

* Add German passkey translations

* Standardize provider encryption warnings
2026-08-26 07:56:55 +02:00
Alessandro Pogliaghi d18d853c8e fix(lunchflow): keep balances current during rate limits (#3129) 2026-08-26 07:55:25 +02:00
8f9529fbe9 feat(goals): a reached goal lets go of the money it was holding (#3165)
* fix(goals): stop two goals from each claiming the same account in full

A GoalAccount with a NULL `allocated_amount` means "dedicate the whole
balance". Two of them on one account each claimed all of it, so the money
was counted twice:

    Livret A, 6,000        precaution 6,000    vacances 6,000
                           progress: 100%      progress: 100%

`Goal#backing_share_for` cannot catch this. Its pro-rata haircut only
scales FIXED earmarks, and an unallocated link contributes `nil.to_d` —
zero — to `others_fixed`, so the two links never see each other. The
invariant "shares never sum past the balance" held for every earmark
except the one that claims everything.

Enforce it at the door: GoalAccount now refuses a second whole-balance
link on an account another non-archived goal already claims in full, and
asks for an amount instead. The scope matches
`Goal.pooled_allocations_for` — archived goals are excluded from the
backing math, so they do not block; completed goals still hold their
money, so they do.

Rows written before this guard stay readable and editable. Autosave
revalidates every loaded goal_account on `goal.save`, so validating
untouched links would make a goal that merely holds a legacy overlap
impossible to rename. Only a new link, or one whose amount is being
cleared onto a contested account, is checked.

The goal fixtures encoded exactly the forbidden state — three goals
claiming `depository` in full — so tests that built a fourth whole
claim now use accounts of their own. `build_goal` mirrors the old
balance, leaving every KPI figure unchanged.

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

* fix(goals): keep a restored goal from re-claiming an account in full

Addresses review feedback on #3160, raised independently on #3165, #3166 and
#3167 — one bug seen four times, because those branches stack.

Archiving a goal releases the accounts it claimed in full, so another goal can
legitimately claim one while it is away. Restoring it then put two
whole-account links back on the same account and reopened the double-counting
`whole_account_link_must_be_exclusive` closes: that check only fires when a
link is written, and a state change writes none.

A validation rather than an AASM guard. `may_fire_event?` stays true, the save
fails, and GoalsController#perform_transition! already surfaces
`errors.full_messages` — the user reads which goal holds the account instead of
a generic "can't do that in this state".

The conflict lookup now lives in one place, `Goal#whole_account_conflicts_on`,
read both by the door (writing a link) and by the restore, so the two cannot
drift into disagreeing about which goals still hold their money. The
`new_record? || will_save_change_to_allocated_amount?` bound stays on the
validation rather than moving into the shared lookup: it exists so a goal
merely holding a legacy overlap can still be renamed.

`Goal::RELEASED_STATES` replaces the repeated "archived" literal. The old
comment already said this scope had to move with the pool's; the constant makes
that true rather than hoped for, and the restore guard will follow the day the
set grows.

Restores from a released state are guarded; `resume` from `paused` is not. A
paused goal never let go of its accounts, so nothing can legitimately have
claimed one meanwhile, and blocking it would strand a user on a goal they
merely shelved.

Two things this surfaced in the test data:

- The fixtures had three goals each claiming `depository` in full — the exact
  state the rule forbids. `test "AASM transitions"` failed on it, a true
  positive. Two of them now take a fixed 1,000 slice.
- `current_balance sums linked account balances` asserted the gross balance,
  which only held because of that overlap. A whole-account link takes what is
  left after other goals' fixed earmarks; the test now says so, and computes it
  from the data rather than a constant.

Each guard was confirmed load-bearing by removing it and watching its test
fail. bin/rails test: 6936 runs, 27911 assertions, 0 failures. RuboCop,
erb_lint and Brakeman clean.

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

* fix(goals): treat moving a whole-account link as the fresh claim it is

Addresses review feedback on #3160.

The exclusivity check was bounded to `new_record? ||
will_save_change_to_allocated_amount?`. A persisted whole-account row whose
`account_id` or `goal_id` changes is neither, so moving one landed it on an
account nobody had checked — the same double-counting hole a restore opened,
through a different door.

The bound is widened rather than dropped. It exists because `Goal has_many
:goal_accounts, autosave: true` revalidates every loaded child on `goal.save`,
so an unguarded check makes a goal that merely holds a legacy overlap
impossible to rename. That reason still holds for every row along for the ride;
it does not hold for a row being moved. A test pins both faces.

bin/rails test: 6939 runs, 27916 assertions, 0 failures. RuboCop and Brakeman
clean. Confirmed load-bearing by narrowing the bound back and watching the move
test fail.

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

* fix(goals): stop a link that is changing goals from conflicting with itself

Addresses review feedback on #3160, on the widening that landed in 00894c16.

Guarding ownership changes was right, but the conflict query excluded the
current record by GOAL, not by row. A link changing `goal_id` still carries the
old one in the database, so the query handed the moving row straight back and
the link was refused as its own conflict — the guard blocked the exact case it
had just been widened to cover.

`whole_account_conflicts_on` now takes the row being written and excludes it by
id. The restore guard passes nothing, which is correct: exclusion by goal
already covers every link the goal being restored owns.

Confirmed load-bearing by dropping the id exclusion and watching the new test
fail. bin/rails test: 6940 runs, 27917 assertions, 0 failures. RuboCop and
Brakeman clean.

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

* fix(goals): keep the ticked accounts when a creation is rejected

Addresses review feedback on #3160.

`new.html.erb` rendered the form without `currently_linked_account_ids`, whose
default is `[]`, so a rejected create came back with every account unchecked.
The amounts survived — the form reads those off the same built links — which
made it worse rather than better: the user faced an error telling them to enter
an amount, on a form whose account selection had silently cleared, and a
multi-account selection was gone entirely.

The failed path now derives the ticks from the in-memory links rather than
`pluck`: nothing is persisted on a rejected create, so a query would come back
empty and change nothing.

Confirmed load-bearing by emptying the list again and watching the new
controller test fail. bin/rails test: 6941 runs, 27920 assertions, 0 failures.
RuboCop and erb_lint clean.

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

* fix(goals): hold the account while checking whether it is already claimed

The exclusivity validation is a read followed by a write, so two requests
could both find no conflict and both commit a whole-account claim — the
double-count the validation exists to prevent, recreated by timing alone.

`whole_account_conflicts_on` now takes a transaction-scoped advisory lock
per account before reading. An advisory lock rather than a row lock
because the conflicting write may be an INSERT, so there is no row to
lock; transaction-scoped so it is released whichever way the enclosing
transaction ends. Accounts are locked in id order, so two goals claiming
the same pair in opposite orders cannot deadlock against each other.

Both doors go through this method — the link validation and the restore
guard — so both are covered by the one change.

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

* fix(goals): bind the advisory lock key instead of interpolating it

Brakeman flagged the hand-built SQL, correctly. The key is a digest of an
id and could not carry a payload, but a raw interpolated string in a model
is the shape a reader has to stop and verify.

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

* fix(goals): stop the advisory lock warning on every acquisition

`pg_advisory_xact_lock` returns `void`, which the adapter cannot type, so
each call logged "unknown OID 2278". Projected through a subquery so the
result set is a plain integer.

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

* fix(goals): claim every account a goal touches in one deterministic order

Follow-up on the advisory lock: autosave validates each link separately, so
each was taking its own account lock in association order. Two goals saving
links on the same two accounts in opposite orders would then hold one lock
each and wait on the other.

The goal takes the whole set up front, sorted, before any child validates.
The per-account lock inside `whole_account_conflicts_on` stays for a link
saved on its own, and re-taking a lock the transaction already holds costs
nothing.

The ordering test fixes the account ids rather than generating them: the
assertion is entirely about order, and random UUIDs would have let it pass
half the time on association order alone.

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

* feat(goals): a reached goal lets go of the money it was holding

Marking a goal complete did nothing to the money. Verified on a 10,000
account with two goals earmarked 5,000 each:

    both funded          precaution 5000 (100%) | vacances 5000 (100%)
    vacances completed   precaution 5000 (100%) | vacances 5000 (100%)
    spend 5000           precaution 2500 ( 50%) | vacances 2500 (100%)
    vacances archived    precaution 5000 (100%) | vacances 2500 ( 50%)

Three faults in a row. A completed goal kept reserving, so the pool still
claimed 10,000 from an account holding 5,000 and the pro-rata haircut cut
the untouched precaution goal in half. The intuitive action fixed nothing
— only Archive released anything, and its confirmation talked about list
visibility. And the history ended up false: a goal that genuinely reached
5,000 was filed away showing 2,500.

A completed goal now releases its earmark, and the amount it reached is
frozen when `complete` fires. Releasing alone was not enough: the figure
would still be recomputed from the live balance, so spending the money
would walk the finished goal back down and rewrite its own record.

THREE places filter on state, and they must agree or an account will
advertise headroom the goals deny: the shared pool, Account#goal_earmarked_total,
and the whole-balance link guard. They now read one constant,
Goal::RELEASED_STATES. The guard's two tests are inverted with it — a
completed goal no longer blocks a new link, because refusing one on
account of a finished goal whose money has already been handed back would
be inexplicable.

`paused` is deliberately not released: pausing means "I have stopped
feeding this", not "I have let it go". Nothing is backfilled either — an
already-completed goal's past value cannot be recovered, and guessing it
would freeze an already-eroded number.

The reached panel is the same one that already existed, corrected rather
than doubled. It used to say "Goal closed at ..." for a goal merely at
100%, and offer Archive — the one gesture that does not release anything.
It now offers closing, says what closing does to the money, and shows the
frozen amount and date once closed. `kind` arrives without behavior for
Lots B3 and B4, and already earns its keep: a maintained reserve at 100%
is never asked to close.

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

* fix(goals): stop a closed goal's projection outrunning its own accounts

Addresses review feedback on #3165.

Freezing `current_balance` at completion made it independent of the linked
accounts, but `projection_payload` still divides it by their live total to
scale the historical series. Spend those accounts after closing and the ratio
runs past 1, scaling every point by the difference and drawing a chart that
never happened.

Capped at 1. The series is the whole linked-account history scaled to this
goal's share of it, and a share cannot exceed the whole — whatever the frozen
figure says.

The test stubs the series at its collaborator rather than building Balance
rows: `ChartSeriesBuilder` returns zeros for a fixture account in this
environment, and a series of zeros multiplies to zero whatever the ratio, so
the obvious version of this test passed without the fix and proved nothing.
It asserts the scaled point never exceeds the historical figure it came from —
unclamped, 5,000 rendered as 5,000 x 33.

Confirmed load-bearing by removing the cap and watching it fail.

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

* fix(goals): stamp a goal closed only when it is actually closed

AASM runs an event's `after` hook on the non-bang form too, and the non-bang
form does not save. `goal.complete` therefore left the row `active` in the
database while stamping it with a completion snapshot — a goal still being
funded, carrying a frozen amount and a completion date. Verified in a
console: `state = "active"` beside `completed_amount = 4000`.

Everything downstream that keys off `completed_amount.present?` then read
that goal as closed, so the two halves of the same fact disagreed about
whether the goal had finished.

The side effects hang off the persisted state change instead, still inside
the save transaction so a later failure takes both back. `reopen` and
`unarchive` move the same way, and for the same reason — a plain `reopen`
was thawing a goal that stayed completed.

The memos are cleared again there: they are cleared at transition time, but
anything reading the goal between then and the save refills them from the
old state, and the frozen figure has to be the closing one.

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

---------

Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
2026-08-26 07:20:48 +02:00
c3cfdf03b2 fix(rules): validate Rule::Condition type registry + normalize legacy values (#1908)
* fix(rules): validate Rule::Condition type registry + normalize legacy 'name' values

Closes #1229.

/rules crashes with `ActionView::Template::Error (Unsupported condition
type: name)` when a Rule::Condition row has a condition_type the
registry doesn't know about. Reporter found two cases in the wild:

  - "name" — invalid, crashes the rules index because the view path
    (`_rule.html.erb` → `displayed_condition.filter.label`) ends up
    in `Rule::Registry#get_filter!` which raises.
  - "transaction_details" — actually a valid filter that searches the
    `transactions.extra` JSONB metadata field (see existing tests in
    test/models/rule/condition_test.rb). Reporter assumed it was a
    transaction-name synonym; it isn't. This PR leaves it alone.

Changes:

- Rule::Condition gains a SUPPORTED_CONDITION_TYPES registry constant
  matching Rule::Registry::TransactionResource#condition_filters plus
  "compound", an inclusion validation against it, and a
  before_validation callback that maps the one known legacy alias
  ("name" -> "transaction_name") so saving an existing rule fixes
  itself.
- Rule::Condition#filter now rescues UnsupportedConditionError and
  returns a Rule::ConditionFilter::Unsupported placeholder. The
  placeholder labels itself "Unsupported (<key>)" (i18n) and its
  #apply returns `scope.none`, so any stale row that survives the
  migration stops matching rather than silently matching everything.
- A one-shot migration normalizes existing "name" rows. Single UPDATE
  statement — rule_conditions is a small per-family table.

Tests added in test/models/rule/condition_test.rb cover the inclusion
validation, the normalization callback, and the graceful-render path
(uses update_columns to simulate a row written before the validation
existed — that's the exact codepath that crashes /rules today).

* test(rules): add system test for unsupported condition_type render + raise on migration down

- test/system/rules_test.rb: visit /rules with a row whose condition_type
  has been update_columns'd to "name" — assert page renders and shows
  the "Unsupported (name)" label instead of raising.
- db/migrate/...normalize_rule_condition_types.rb: replace the empty
  #down with `raise ActiveRecord::IrreversibleMigration` to match the
  repo's data-migration convention (see e.g. 20260219190000_scope_*).

* chore(rules): log unsupported condition + cross-check supported types

Address maintainer review on #1908:
- Log a Rails.logger.warn (with rule_id and condition_type) from
  Rule::ConditionFilter::Unsupported#apply so silent zero-match rules
  are traceable when debugging.
- Add a comment above Rule::Condition::SUPPORTED_CONDITION_TYPES and a
  test that cross-checks it against the registry's filter keys, so
  drift between the two surfaces as a failing test rather than a
  confusing validation error.

* refactor(rules): derive supported condition types from registry

---------

Co-authored-by: John Baillie <johnbaillie2007@gmail.com>
Co-authored-by: Khaostica <256858950+Khaostica@users.noreply.github.com>
Co-authored-by: sure-admin <sure-admin@splashblot.com>
2026-08-26 07:09:55 +02:00
buzzromainandClaude Opus 5 7a86ee47c5 fix(goals): stop two goals from each claiming the same account in full (#3160)
* fix(goals): stop two goals from each claiming the same account in full

A GoalAccount with a NULL `allocated_amount` means "dedicate the whole
balance". Two of them on one account each claimed all of it, so the money
was counted twice:

    Livret A, 6,000        precaution 6,000    vacances 6,000
                           progress: 100%      progress: 100%

`Goal#backing_share_for` cannot catch this. Its pro-rata haircut only
scales FIXED earmarks, and an unallocated link contributes `nil.to_d` —
zero — to `others_fixed`, so the two links never see each other. The
invariant "shares never sum past the balance" held for every earmark
except the one that claims everything.

Enforce it at the door: GoalAccount now refuses a second whole-balance
link on an account another non-archived goal already claims in full, and
asks for an amount instead. The scope matches
`Goal.pooled_allocations_for` — archived goals are excluded from the
backing math, so they do not block; completed goals still hold their
money, so they do.

Rows written before this guard stay readable and editable. Autosave
revalidates every loaded goal_account on `goal.save`, so validating
untouched links would make a goal that merely holds a legacy overlap
impossible to rename. Only a new link, or one whose amount is being
cleared onto a contested account, is checked.

The goal fixtures encoded exactly the forbidden state — three goals
claiming `depository` in full — so tests that built a fourth whole
claim now use accounts of their own. `build_goal` mirrors the old
balance, leaving every KPI figure unchanged.

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

* fix(goals): keep a restored goal from re-claiming an account in full

Addresses review feedback on #3160, raised independently on #3165, #3166 and
#3167 — one bug seen four times, because those branches stack.

Archiving a goal releases the accounts it claimed in full, so another goal can
legitimately claim one while it is away. Restoring it then put two
whole-account links back on the same account and reopened the double-counting
`whole_account_link_must_be_exclusive` closes: that check only fires when a
link is written, and a state change writes none.

A validation rather than an AASM guard. `may_fire_event?` stays true, the save
fails, and GoalsController#perform_transition! already surfaces
`errors.full_messages` — the user reads which goal holds the account instead of
a generic "can't do that in this state".

The conflict lookup now lives in one place, `Goal#whole_account_conflicts_on`,
read both by the door (writing a link) and by the restore, so the two cannot
drift into disagreeing about which goals still hold their money. The
`new_record? || will_save_change_to_allocated_amount?` bound stays on the
validation rather than moving into the shared lookup: it exists so a goal
merely holding a legacy overlap can still be renamed.

`Goal::RELEASED_STATES` replaces the repeated "archived" literal. The old
comment already said this scope had to move with the pool's; the constant makes
that true rather than hoped for, and the restore guard will follow the day the
set grows.

Restores from a released state are guarded; `resume` from `paused` is not. A
paused goal never let go of its accounts, so nothing can legitimately have
claimed one meanwhile, and blocking it would strand a user on a goal they
merely shelved.

Two things this surfaced in the test data:

- The fixtures had three goals each claiming `depository` in full — the exact
  state the rule forbids. `test "AASM transitions"` failed on it, a true
  positive. Two of them now take a fixed 1,000 slice.
- `current_balance sums linked account balances` asserted the gross balance,
  which only held because of that overlap. A whole-account link takes what is
  left after other goals' fixed earmarks; the test now says so, and computes it
  from the data rather than a constant.

Each guard was confirmed load-bearing by removing it and watching its test
fail. bin/rails test: 6936 runs, 27911 assertions, 0 failures. RuboCop,
erb_lint and Brakeman clean.

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

* fix(goals): treat moving a whole-account link as the fresh claim it is

Addresses review feedback on #3160.

The exclusivity check was bounded to `new_record? ||
will_save_change_to_allocated_amount?`. A persisted whole-account row whose
`account_id` or `goal_id` changes is neither, so moving one landed it on an
account nobody had checked — the same double-counting hole a restore opened,
through a different door.

The bound is widened rather than dropped. It exists because `Goal has_many
:goal_accounts, autosave: true` revalidates every loaded child on `goal.save`,
so an unguarded check makes a goal that merely holds a legacy overlap
impossible to rename. That reason still holds for every row along for the ride;
it does not hold for a row being moved. A test pins both faces.

bin/rails test: 6939 runs, 27916 assertions, 0 failures. RuboCop and Brakeman
clean. Confirmed load-bearing by narrowing the bound back and watching the move
test fail.

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

* fix(goals): stop a link that is changing goals from conflicting with itself

Addresses review feedback on #3160, on the widening that landed in 00894c16.

Guarding ownership changes was right, but the conflict query excluded the
current record by GOAL, not by row. A link changing `goal_id` still carries the
old one in the database, so the query handed the moving row straight back and
the link was refused as its own conflict — the guard blocked the exact case it
had just been widened to cover.

`whole_account_conflicts_on` now takes the row being written and excludes it by
id. The restore guard passes nothing, which is correct: exclusion by goal
already covers every link the goal being restored owns.

Confirmed load-bearing by dropping the id exclusion and watching the new test
fail. bin/rails test: 6940 runs, 27917 assertions, 0 failures. RuboCop and
Brakeman clean.

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

* fix(goals): keep the ticked accounts when a creation is rejected

Addresses review feedback on #3160.

`new.html.erb` rendered the form without `currently_linked_account_ids`, whose
default is `[]`, so a rejected create came back with every account unchecked.
The amounts survived — the form reads those off the same built links — which
made it worse rather than better: the user faced an error telling them to enter
an amount, on a form whose account selection had silently cleared, and a
multi-account selection was gone entirely.

The failed path now derives the ticks from the in-memory links rather than
`pluck`: nothing is persisted on a rejected create, so a query would come back
empty and change nothing.

Confirmed load-bearing by emptying the list again and watching the new
controller test fail. bin/rails test: 6941 runs, 27920 assertions, 0 failures.
RuboCop and erb_lint clean.

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

* fix(goals): hold the account while checking whether it is already claimed

The exclusivity validation is a read followed by a write, so two requests
could both find no conflict and both commit a whole-account claim — the
double-count the validation exists to prevent, recreated by timing alone.

`whole_account_conflicts_on` now takes a transaction-scoped advisory lock
per account before reading. An advisory lock rather than a row lock
because the conflicting write may be an INSERT, so there is no row to
lock; transaction-scoped so it is released whichever way the enclosing
transaction ends. Accounts are locked in id order, so two goals claiming
the same pair in opposite orders cannot deadlock against each other.

Both doors go through this method — the link validation and the restore
guard — so both are covered by the one change.

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

* fix(goals): bind the advisory lock key instead of interpolating it

Brakeman flagged the hand-built SQL, correctly. The key is a digest of an
id and could not carry a payload, but a raw interpolated string in a model
is the shape a reader has to stop and verify.

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

* fix(goals): stop the advisory lock warning on every acquisition

`pg_advisory_xact_lock` returns `void`, which the adapter cannot type, so
each call logged "unknown OID 2278". Projected through a subquery so the
result set is a plain integer.

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

* fix(goals): claim every account a goal touches in one deterministic order

Follow-up on the advisory lock: autosave validates each link separately, so
each was taking its own account lock in association order. Two goals saving
links on the same two accounts in opposite orders would then hold one lock
each and wait on the other.

The goal takes the whole set up front, sorted, before any child validates.
The per-account lock inside `whole_account_conflicts_on` stays for a link
saved on its own, and re-taking a lock the transaction already holds costs
nothing.

The ordering test fixes the account ids rather than generating them: the
assertion is entirely about order, and random UUIDs would have let it pass
half the time on association order alone.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 07:07:39 +02:00
buzzromainandClaude Opus 5 ed28fab807 fix(trades): let the header call a trade what the importer recorded (#3150)
The header derived its wording from the amount's sign and ignored
investment_activity_label, except for Dividend and Interest. So every other
labelled trade was announced as a buy or a sell: a Questrade journal, which
records "Transfer", opened as a purchase it never was.

The label now wins when this view has wording for it, and the sign remains the
fallback for a trade with no label, or one carrying a label this view does not
name. `I18n.exists?` guards that second case, so an unknown label degrades to
buy/sell rather than rendering a missing-translation string.

Wording added for the rest of Trade::ACTIVITY_LABELS. English only: fallbacks
are enabled application-wide, so the other seventeen locales inherit it rather
than raising.

Not fixed by this, in case the title suggests otherwise: Kraken records its
Contribution and Withdrawal labels on Transactions, not Trades, so it never
reaches this view — its labels already display through the quick-edit badge.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 07:05:18 +02:00
3d6a8d8b6e feat(budgets): move money between envelopes in one gesture (#3164)
* feat(budgets): carry a category's unspent budget into the next month

A budget category resets to zero every month, so anything non-monthly
(annual insurance, a holiday fund, car servicing) has no place to
accumulate. Two columns on budget_categories turn a category into a real
envelope: `rollover_enabled`, opt-in per category and off by default, and
`rolled_over_amount`, the surplus carried in from the previous month.

  rolled_over(n) = rollover_enabled
                   ? max(0, budgeted(n-1) + rolled_over(n-1) - actual(n-1))
                   : 0

v1 floors at zero: only a surplus carries, never an overspend.

The amount is materialized, not derived. March depends on February which
depends on January, so computing it on read would walk the whole chain on
every budget render. Budget::RolloverCalculator recomputes it in a single
forward pass and writes once via upsert_all, from Budget.find_or_bootstrap
and from BudgetCategoriesController#update -- allocations and the toggle
being the only inputs. No Transaction hook: a past month's actuals can
change after the fact, and the page load is a fine moment to catch up.

Scope kept deliberately narrow. `Budget#budgeted_spending`,
`#allocated_spending` and `#available_to_allocate` are untouched -- the top
of the budget page still answers "I planned to spend X, I've allocated Y".
The carry is per-envelope information, surfaced as `Budget#total_rolled_over`
and never folded into those totals.

What the carry does change is consumption: `available_to_spend`,
`percent_of_budget_spent` and `budgeted?` all count it, or a category funded
entirely by rollover would read as unbudgeted and get an alert pill while it
still had money left. `display_budgeted_spending` stays the month's
allocation alone -- the card shows the two figures side by side.

Details worth knowing:

- A parent's carry is net of its ring-fenced subcategories'. A parent's
  allocation already contains theirs and its actuals already contain their
  spending; those subcategories carry their own surplus, so counting the
  parent's raw leftover would roll the same money over twice.
- Chains never mix: household with household, a member's personal budgets
  with their own. A missing month is a gap the carry crosses, not a month
  budgeted at zero.
- The carry stops at a currency change. sync_budget_categories stamps
  categories with family.currency at sync time while a budget freezes its
  own at creation, so the guard is on budget_category.currency -- the unit
  the amount is actually denominated in.
- upsert_all writes with `update_only`, so a concurrent request that moves
  an allocation between our read and our write doesn't get it clobbered by
  the stale value we loaded.
- copy_from! copies the toggle, never the amount.

Cost for families that never turn it on: one EXISTS query per budget page
load, measured, including on the reports page which also bootstraps a
budget. With rollover on, the walk starts at the first month that uses it
rather than at the two-year history bound.

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

* fix(budgets): pin the household rollover chain to a viewer-independent scope

Addresses review feedback on #3143.

The household budget (user_id NULL) has no owner to scope actuals by, and
`IncomeStatement` falls back to `Current.user` when nobody says otherwise.
The calculator therefore computed one shared `rolled_over_amount` through
whichever member happened to load the page, and each viewer overwrote the
other's number -- last one wins, and a member could infer spending in
accounts they cannot see. `Budget#income_statement_accounts` can now be
overridden, and the calculator pins the household chain to the whole
family so the shared row holds one number. Personal chains are untouched:
they already scope to their owner's accounts and were always deterministic.

`copy_from!` runs after `find_or_bootstrap` has already recomputed the
chain, so copying `rollover_enabled` left the target sitting on a zero carry
until the next page load. It now recomputes before its transaction commits.

The toggle tooltip described the wrong direction. `incoming_carry` checks
the flag of the month being computed, so the toggle governs what that month
*receives* from the previous one, not what it sends forward. Reworded in
English and French.

The concurrency regression test now drives its concurrent write through
`Budget#budget_category_actual_spending`, a public seam, instead of stubbing
a private method of the calculator from another class's test suite.

Each guard was confirmed load-bearing by reverting it and watching its test
fail. bin/rails test: 6939 runs, 0 failures.

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

* fix(budgets): let the rollover choice stand instead of resetting each month

`rollover_enabled` lives on budget_categories, one row per (budget,
category), so a month created by `find_or_bootstrap` was born with the flag
off. Switching rollover on for Vacations in January and simply opening
February dropped January's surplus on the floor -- the user had to re-arm
the toggle every month, or go through "copy from previous budget". The
feature's headline case, a category funded 50/month accumulating over a
year, did not work as shipped.

New rows now inherit the flag from the last initialized budget of the same
owner, the same chain the carry itself walks. Turning the toggle off on a
given month still overrides it from there on, so the per-month escape hatch
survives.

The flag stays on budget_categories rather than moving to Category, which is
where comparable products (Monarch, Copilot, Lunch Money) put it. Categories
here are family-wide while budgets are per owner, so a category-level flag
would force one member's rollover choice onto everyone's personal budget and
onto the household budget. budget_categories is the only table carrying both
the category and the owner. A regression test covers that isolation.

Naming follows the same products: the toggle reads "Rollover", the noun, not
"Roll over", the verb -- which also matches `rollover_enabled` and the
calculator. Both tooltips now describe the property rather than a direction
("keep this category's unspent money from one month to the next"). The
previous wording named the direction the flag actually gates, incoming,
which is accurate but the opposite of the mental model every comparable
product installs; describing the property is true under either reading. The
French card string switched to "+%{amount} de report" so it no longer has to
agree in number with a currency noun it cannot see.

bin/rails test: 6942 runs, 0 failures. The inheritance was confirmed
load-bearing by removing it and watching its tests fail.

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

* fix(budgets): make a rollover opt-out stop the money in both directions

`incoming_carry` gates what a month receives, but `leftover_for` computed
what it sends regardless of the toggle. So switching rollover off for one
month and back on the next handed the opted-out month's whole allocation to
the month after: the surplus the user meant to forfeit reappeared a month
later. Reproduced at 100, where 0 was expected.

The outgoing carry is now gated on the same flag, which also skips the
actuals lookup for opted-out rows. "Off" now means this envelope does not
roll over, in either direction -- the reading the standing toggle and the
tooltip both promise.

Found by CodeRabbit on #3143. It only became wrong with the standing-choice
inheritance in 2b1cff5a: while the flag was per-month, "off" plausibly meant
"do not accept", and the previous month's surplus reaching a re-armed month
was defensible. Once the flag reads as a property of the envelope, it isn't.

bin/rails test: 6943 runs, 0 failures. Confirmed load-bearing by removing
the guard and watching the new three-month test fail.

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

* fix(budgets): serialize rollover recomputes for a chain with an advisory lock

`recompute!` reads the whole chain into memory, walks it, then upserts.
Nothing made that atomic: two overlapping recomputes for the same
(family, owner) chain could both load it, and the one that started first
could land its now-stale `rolled_over_amount` on top of the other's.
`update_only` keeps an upsert off allocations, but the carry is the very
column this writes, so nothing protected it. The wrong value survived until
the next page load recomputed it.

The read-then-write now runs inside a transaction holding
`pg_advisory_xact_lock` keyed on the chain, and the walk was extracted so
the guard is legible. The cheap `first_relevant_budget_date` check still
runs first and unlocked, so families that never enabled rollover pay one
query and never contend; the date is re-read under the lock because the
chain may have moved while waiting. The key names the (family, owner) pair,
so a household recompute and a member's personal recompute don't queue
behind each other.

This reverses the spec's "no advisory lock" guidance, at the request of an
upstream maintainer reviewing #3143.

On the test: under transactional fixtures a second connection cannot see the
data, so a true two-connection interleaving test isn't practical here. The
regression test asserts what is observable in-process -- the lock is taken,
it is taken before the write, and two chains produce different keys.
Removing `lock_chain!` makes it fail.

bin/rails test: 6944 runs, 0 failures.

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

* feat(api): expose the rollover toggle and carried amount on budget categories

`available_to_spend` started counting the carry in this branch, so an API
client could receive a category budgeted at 500 with 700 available and
nothing in the payload to account for the difference. The two fields that
explain it are now serialized.

`rollover_enabled` ships with the stored fields, so the summary rendered by
the index action carries it. `rolled_over_amount` sits with the derived
amounts behind `include_derived_amounts`, next to the `available_to_spend`
it accounts for -- the index deliberately omits both, unchanged.

Schemas updated in spec/swagger_helper.rb (BudgetCategory and
BudgetCategorySummary), docs regenerated with rswag, and behavioural
coverage added to the Minitest controller test: the show action returns the
toggle and the carry, and the index returns the toggle without the derived
amount.

Note on docs/api/openapi.yaml: 64 of the 72 added lines are not from this
change. The committed file had drifted from what rswag generates -- specs
for the merchant CSV import and transfer source fees had been added without
regenerating -- and the mandated `rake rswag:specs:swaggerize` picks them up.
Verified by regenerating on a clean tree, where those 64 lines appear on
their own. Hand-trimming them back out would leave the generated file not
matching its generator, so they are included; happy to split them into their
own commit if a maintainer prefers.

bin/rails test: 6945 runs, 0 failures.
ruby test/support/verify_api_endpoint_consistency.rb: OK.

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

* feat(budgets): move money between envelopes in one gesture

Overspending one category and covering it from another meant editing two
allocations by hand, with no atomicity: the budget could sit
over-allocated between the two saves, and a failure left it there.

`BudgetCategory.move_allocation!` does both sides in one transaction.
Deliberately no new table — v1 stores the resulting allocations and keeps
no history of the move itself.

Refused, each with its own localized message: an amount at or below zero,
more than the source has, two categories from different budgets, a
category and itself, "Uncategorized" (synthesized on read, it has no row),
and — the one that is not obvious — a category and its own direct parent
or child. `sync_parent_budgeted_spending!` rebuilds a parent from the sum
of its children plus its reserve, so money moved across that boundary
would be re-derived away and the total would not be conserved.

Lock order is the delicate part. `update_budgeted_spending!` locks its own
row and, for a subcategory, its parent, so two simultaneous moves in
opposite directions could each hold what the other needs. Every row the
operation will touch — both ends and their parents — is locked up front by
ascending id.

The rollover chain is recomputed by the caller AFTER the move commits,
never inside it. `Budget::RolloverCalculator` takes a transaction-scoped
advisory lock, and taking it while these row locks are held would invert
the order `#update` already established: one request holding rows and
waiting for the advisory lock, another holding the advisory lock and
waiting for those rows. A model test pins that `move_allocation!` never
recomputes on its own.

The recompute is not optional. A move is neutral for
`Budget#allocated_spending`, but not for the carry: `leftover_for` is
budgeted + rolled_over − actual, so moving money changes what both
envelopes hand to the next month.

UI is one native `<dialog>` shared by the page rather than one per row,
opened from a discreet button on each envelope that has something to give.
The Stimulus controller has 6 targets and disables the options the server
would refuse anyway, so an impossible move is never offered.

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

* fix(budgets): use the design-system dialog, and stop a parent lending its children's money

Addresses review feedback on #3164.

**The move dialog was hand-rolled.** `DS::Dialog` already exists and already
carries focus trapping, Escape, click-outside, focus restore and the
design-system chrome; rewriting those by hand is how they end up subtly wrong,
and the guidelines say to reach for the primitive first. It keeps the
one-dialog-for-the-page shape — the list holds dozens of rows and a per-row
dialog would be dozens of copies of the same markup — via `auto_open: false`
and `disable_frame: true`.

**It also stayed open after a successful move,** still showing the previous
source and amount. It now closes on `turbo:submit-end`, and only when Turbo
reports success: closing on submit alone would hide the reason a move was
refused.

**Submit was enabled with nowhere to send.** A lone envelope, or one whose only
peers are its own parent and children, offered a button whose only outcome was
a server error. The form now says so and disables itself.

**A parent could send away its children's money.** `budgeted_spending` on a
parent already contains its individually funded subcategories' allocations, so
comparing against the gross figure let a move spend what a child had
ring-fenced. The parent dropped below the sum of its children, and the next
edit to any child rebuilt it — the money appeared to teleport back. The
movable amount for a parent is now its own reserve.

`test "moving the whole allocation is allowed, moving one cent more is not"`
moved a parent's gross amount and passed: it encoded that bug. It now uses a
leaf as its source, where "the whole allocation" is the whole of it, and the
parent boundary gets its own pair of tests.

**A negative carry could be written.** The calculator floors it at zero but
writes through `upsert_all`, and a negative `rolled_over_amount` would quietly
subtract from `available_to_spend`. Now a CHECK constraint, verified by
replaying the migration on a throwaway database.

bin/rails test: 6967 runs, 28020 assertions, 0 failures. RuboCop, erb_lint,
Brakeman and biome clean.

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

* fix(budgets): carry the rollover choice into months already open, and mend the API schema

Addresses the remaining review feedback on #3164.

**Enabling rollover skipped months that already existed.** Inheritance runs
when `sync_budget_categories` creates a missing row, so it only ever reaches
months that do not exist yet. A user who opened March, then went back to
January and switched rollover on, left March sitting at `false` — created
before the choice was made, so it had nothing to inherit — and the chain died
there.

The toggle is a standing choice about the envelope, which is what
`inherited_rollover_flags` already says: "turning it off on a given month still
overrides it from there on." Applying the choice forward closes the hole
without a tri-state column. Later months take the most recent decision, which
is the one the user just made; earlier months keep theirs.

**`rollover_enabled` was emitted but not required.** The shared partial always
sends it in both list and detail responses. Added to the `required` list of
`BudgetCategorySummary` and `BudgetCategory` in `spec/swagger_helper.rb`, then
regenerated.

**`type: file` is not valid OpenAPI 3.0.3.** A Swagger 2.0 leftover in the
merchants import spec, which generated clients that send nothing the controller
can read. It surfaced now because this branch is the first to regenerate
`openapi.yaml` since it was written — `origin/main` has no occurrence of it.
Spelled as a string with `format: binary` instead.

Regeneration produced a four-line diff, so the checked-in document was already
in sync otherwise.

bin/rails test: 6969 runs, 28023 assertions, 0 failures. RuboCop and Brakeman
clean; 324 rswag examples pass.

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

* fix(budgets): stop the API serving a carry the web pages would have refreshed

Addresses the remaining P1 on #3164, and its duplicate on #3143.

The objection was that nothing recomputes when a sync, an edit or a
recategorisation changes spending in an earlier month. On the web that is by
design and measured: every surface showing the carry goes through
`Budget.find_or_bootstrap`, so it recomputes on the way in, and the alternative
— recomputing on every transaction write — buys nothing a page load does not
already give.

The API is the case that argument does not cover, and the review was right
about it. `Api::V1::BudgetCategoriesController` reads `rolled_over_amount`
straight off the column, so it was the one surface that could serve a stale
carry indefinitely, until somebody happened to open the budget page.

It now recomputes the chains it is about to read. A read that writes is a
smell, but it is the same bargain the budget page already makes, applied to the
surface that was missed: the walk is per family, and the calculator's leading
EXISTS makes it a single query that writes nothing for a family that never
turned rollover on.

Also from review: the move dialog's amount field allowed `min: 0` while
`move_allocation!` rejects zero as non-positive. Browser validation now matches
the server contract, at the currency step.

bin/rails test: 6970 runs, 28025 assertions, 0 failures. Confirmed load-bearing
by removing the callback and watching the new API test fail. RuboCop, erb_lint
and Brakeman clean.

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

* Fix budget rollover schema delta

* Remove duplicate rollover test class

---------

Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: sure-admin <sure-admin@splashblot.com>
2026-08-26 07:01:12 +02:00
buzzromainandClaude Opus 5 1fddb4d97c feat(budgets): carry a category's unspent budget into the next month (#3143)
* feat(budgets): carry a category's unspent budget into the next month

A budget category resets to zero every month, so anything non-monthly
(annual insurance, a holiday fund, car servicing) has no place to
accumulate. Two columns on budget_categories turn a category into a real
envelope: `rollover_enabled`, opt-in per category and off by default, and
`rolled_over_amount`, the surplus carried in from the previous month.

  rolled_over(n) = rollover_enabled
                   ? max(0, budgeted(n-1) + rolled_over(n-1) - actual(n-1))
                   : 0

v1 floors at zero: only a surplus carries, never an overspend.

The amount is materialized, not derived. March depends on February which
depends on January, so computing it on read would walk the whole chain on
every budget render. Budget::RolloverCalculator recomputes it in a single
forward pass and writes once via upsert_all, from Budget.find_or_bootstrap
and from BudgetCategoriesController#update -- allocations and the toggle
being the only inputs. No Transaction hook: a past month's actuals can
change after the fact, and the page load is a fine moment to catch up.

Scope kept deliberately narrow. `Budget#budgeted_spending`,
`#allocated_spending` and `#available_to_allocate` are untouched -- the top
of the budget page still answers "I planned to spend X, I've allocated Y".
The carry is per-envelope information, surfaced as `Budget#total_rolled_over`
and never folded into those totals.

What the carry does change is consumption: `available_to_spend`,
`percent_of_budget_spent` and `budgeted?` all count it, or a category funded
entirely by rollover would read as unbudgeted and get an alert pill while it
still had money left. `display_budgeted_spending` stays the month's
allocation alone -- the card shows the two figures side by side.

Details worth knowing:

- A parent's carry is net of its ring-fenced subcategories'. A parent's
  allocation already contains theirs and its actuals already contain their
  spending; those subcategories carry their own surplus, so counting the
  parent's raw leftover would roll the same money over twice.
- Chains never mix: household with household, a member's personal budgets
  with their own. A missing month is a gap the carry crosses, not a month
  budgeted at zero.
- The carry stops at a currency change. sync_budget_categories stamps
  categories with family.currency at sync time while a budget freezes its
  own at creation, so the guard is on budget_category.currency -- the unit
  the amount is actually denominated in.
- upsert_all writes with `update_only`, so a concurrent request that moves
  an allocation between our read and our write doesn't get it clobbered by
  the stale value we loaded.
- copy_from! copies the toggle, never the amount.

Cost for families that never turn it on: one EXISTS query per budget page
load, measured, including on the reports page which also bootstraps a
budget. With rollover on, the walk starts at the first month that uses it
rather than at the two-year history bound.

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

* fix(budgets): pin the household rollover chain to a viewer-independent scope

Addresses review feedback on #3143.

The household budget (user_id NULL) has no owner to scope actuals by, and
`IncomeStatement` falls back to `Current.user` when nobody says otherwise.
The calculator therefore computed one shared `rolled_over_amount` through
whichever member happened to load the page, and each viewer overwrote the
other's number -- last one wins, and a member could infer spending in
accounts they cannot see. `Budget#income_statement_accounts` can now be
overridden, and the calculator pins the household chain to the whole
family so the shared row holds one number. Personal chains are untouched:
they already scope to their owner's accounts and were always deterministic.

`copy_from!` runs after `find_or_bootstrap` has already recomputed the
chain, so copying `rollover_enabled` left the target sitting on a zero carry
until the next page load. It now recomputes before its transaction commits.

The toggle tooltip described the wrong direction. `incoming_carry` checks
the flag of the month being computed, so the toggle governs what that month
*receives* from the previous one, not what it sends forward. Reworded in
English and French.

The concurrency regression test now drives its concurrent write through
`Budget#budget_category_actual_spending`, a public seam, instead of stubbing
a private method of the calculator from another class's test suite.

Each guard was confirmed load-bearing by reverting it and watching its test
fail. bin/rails test: 6939 runs, 0 failures.

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

* fix(budgets): let the rollover choice stand instead of resetting each month

`rollover_enabled` lives on budget_categories, one row per (budget,
category), so a month created by `find_or_bootstrap` was born with the flag
off. Switching rollover on for Vacations in January and simply opening
February dropped January's surplus on the floor -- the user had to re-arm
the toggle every month, or go through "copy from previous budget". The
feature's headline case, a category funded 50/month accumulating over a
year, did not work as shipped.

New rows now inherit the flag from the last initialized budget of the same
owner, the same chain the carry itself walks. Turning the toggle off on a
given month still overrides it from there on, so the per-month escape hatch
survives.

The flag stays on budget_categories rather than moving to Category, which is
where comparable products (Monarch, Copilot, Lunch Money) put it. Categories
here are family-wide while budgets are per owner, so a category-level flag
would force one member's rollover choice onto everyone's personal budget and
onto the household budget. budget_categories is the only table carrying both
the category and the owner. A regression test covers that isolation.

Naming follows the same products: the toggle reads "Rollover", the noun, not
"Roll over", the verb -- which also matches `rollover_enabled` and the
calculator. Both tooltips now describe the property rather than a direction
("keep this category's unspent money from one month to the next"). The
previous wording named the direction the flag actually gates, incoming,
which is accurate but the opposite of the mental model every comparable
product installs; describing the property is true under either reading. The
French card string switched to "+%{amount} de report" so it no longer has to
agree in number with a currency noun it cannot see.

bin/rails test: 6942 runs, 0 failures. The inheritance was confirmed
load-bearing by removing it and watching its tests fail.

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

* fix(budgets): make a rollover opt-out stop the money in both directions

`incoming_carry` gates what a month receives, but `leftover_for` computed
what it sends regardless of the toggle. So switching rollover off for one
month and back on the next handed the opted-out month's whole allocation to
the month after: the surplus the user meant to forfeit reappeared a month
later. Reproduced at 100, where 0 was expected.

The outgoing carry is now gated on the same flag, which also skips the
actuals lookup for opted-out rows. "Off" now means this envelope does not
roll over, in either direction -- the reading the standing toggle and the
tooltip both promise.

Found by CodeRabbit on #3143. It only became wrong with the standing-choice
inheritance in 2b1cff5a: while the flag was per-month, "off" plausibly meant
"do not accept", and the previous month's surplus reaching a re-armed month
was defensible. Once the flag reads as a property of the envelope, it isn't.

bin/rails test: 6943 runs, 0 failures. Confirmed load-bearing by removing
the guard and watching the new three-month test fail.

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

* fix(budgets): serialize rollover recomputes for a chain with an advisory lock

`recompute!` reads the whole chain into memory, walks it, then upserts.
Nothing made that atomic: two overlapping recomputes for the same
(family, owner) chain could both load it, and the one that started first
could land its now-stale `rolled_over_amount` on top of the other's.
`update_only` keeps an upsert off allocations, but the carry is the very
column this writes, so nothing protected it. The wrong value survived until
the next page load recomputed it.

The read-then-write now runs inside a transaction holding
`pg_advisory_xact_lock` keyed on the chain, and the walk was extracted so
the guard is legible. The cheap `first_relevant_budget_date` check still
runs first and unlocked, so families that never enabled rollover pay one
query and never contend; the date is re-read under the lock because the
chain may have moved while waiting. The key names the (family, owner) pair,
so a household recompute and a member's personal recompute don't queue
behind each other.

This reverses the spec's "no advisory lock" guidance, at the request of an
upstream maintainer reviewing #3143.

On the test: under transactional fixtures a second connection cannot see the
data, so a true two-connection interleaving test isn't practical here. The
regression test asserts what is observable in-process -- the lock is taken,
it is taken before the write, and two chains produce different keys.
Removing `lock_chain!` makes it fail.

bin/rails test: 6944 runs, 0 failures.

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

* feat(api): expose the rollover toggle and carried amount on budget categories

`available_to_spend` started counting the carry in this branch, so an API
client could receive a category budgeted at 500 with 700 available and
nothing in the payload to account for the difference. The two fields that
explain it are now serialized.

`rollover_enabled` ships with the stored fields, so the summary rendered by
the index action carries it. `rolled_over_amount` sits with the derived
amounts behind `include_derived_amounts`, next to the `available_to_spend`
it accounts for -- the index deliberately omits both, unchanged.

Schemas updated in spec/swagger_helper.rb (BudgetCategory and
BudgetCategorySummary), docs regenerated with rswag, and behavioural
coverage added to the Minitest controller test: the show action returns the
toggle and the carry, and the index returns the toggle without the derived
amount.

Note on docs/api/openapi.yaml: 64 of the 72 added lines are not from this
change. The committed file had drifted from what rswag generates -- specs
for the merchant CSV import and transfer source fees had been added without
regenerating -- and the mandated `rake rswag:specs:swaggerize` picks them up.
Verified by regenerating on a clean tree, where those 64 lines appear on
their own. Hand-trimming them back out would leave the generated file not
matching its generator, so they are included; happy to split them into their
own commit if a maintainer prefers.

bin/rails test: 6945 runs, 0 failures.
ruby test/support/verify_api_endpoint_consistency.rb: OK.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 06:29:15 +02:00
Sure Admin (bot) 3bdfe9521e Fix AI health check for OpenAI-compatible endpoints (#3184)
* Fix AI health probe for OpenAI-compatible endpoints

* Stabilize accounts sync system test

* Address AI health probe review feedback
2026-08-26 04:46:49 +02:00
Alessio Cappaandcoderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> 0a7c1107fd fix(i18n): add missing Italian translations (#3170)
* Add missing IT translations

* Update config/locales/views/insights/it.yml

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: Alessio Cappa <104093777+alessiocappa@users.noreply.github.com>

* Update config/locales/views/layout/it.yml

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: Alessio Cappa <104093777+alessiocappa@users.noreply.github.com>

* Add plural variants for count-bearing messages.

* Fix indentation for insights key in Italian locale

Signed-off-by: Alessio Cappa <104093777+alessiocappa@users.noreply.github.com>

---------

Signed-off-by: Alessio Cappa <104093777+alessiocappa@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-08-26 01:37:02 +02:00
github-actions[bot]andgithub-actions[bot] <github-actions[bot]@users.noreply.github.com> cb283c54c6 Bump version to next iteration after v0.7.4-alpha.9 release (#3173)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-08-25 22:40:21 +02:00
Juan José Mata b438a1c8dd Improve chat tracking and system test assertions 2026-08-24 23:22:54 -07:00
Juan José Mata 54b5589745 Document user_modified transaction field in OpenAPI specs 2026-08-24 22:35:35 -07:00
colinedwardwood b1df16b0a7 Allow API transaction create to opt into sync protection (user_modified) (#3162)
* Allow API transaction create to opt into sync protection (user_modified)

The transactions API has no way to mark a newly-created transaction
user_modified, which is the only thing that protects an entry from a
later provider sync (Plaid/SimpleFin/etc.) silently overwriting its
category or name - Account::ProviderImportAdapter#import_transaction
claims any entry matching on date/amount/currency with no external_id
yet, then enriches unlocked fields from the sync payload.

This matters for any API client that owns writes into an account also
linked to a bank-sync provider: without a way to protect its own
entries, the client's data can be silently overwritten the first time
the linked provider happens to sync a matching transaction.

Adds an optional `user_modified` param to POST /api/v1/transactions,
reusing the existing Entry#mark_user_modified! (added for #1977, so far
only wired into the merchant merge/convert/unlink flows) rather than
mass-assigning the column directly. Exposes user_modified in the
transaction JSON response, matching how external_id/source already are.

Scoped to create only, matching the concrete need; happy to extend to
update in a follow-up if that's wanted too.

* fix: mark entry user_modified before enqueueing account sync

sync_account_later enqueued the background sync job before
mark_user_modified! ran, leaving a window where a fast-running job
could read and overwrite the entry before the protection flag was
set. Move the mark_user_modified! call ahead of the sync enqueue so
the flag is always in place first.
2026-08-25 07:31:40 +02:00
+2 225f72ad81 Rename native Swift app to Sure Insights (#3172)
* Add Swift-native Sure app

* Fix push subscriptions schema for CI

* Rename native app to Sure Insights

* Add Sure Insights App Store listing

* Add supported interface orientations

* chore(goals): drop copy-pasted duplicates and an unused lock-key helper (#3159)

`Account#goal_earmarked_total` and `Account#free_to_earmark` were each
defined twice, byte for byte, with no `private` boundary or singleton
class between the blocks — a copy-paste artifact where the second
definition silently overwrote the first. Keep one copy of each.

`Goal.advisory_lock_key_for` had no caller anywhere in app/; the only
reference was a test asserting the dead helper was deterministic. Remove
both. No behavior change.


Claude-Session: https://claude.ai/code/session_01DJ1npaGEHr6t2HW1rYZdt4

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>

* Add live AI checks to system health (#3155)

* Add live AI checks to system health

Give super admins a dedicated AI status view with bounded liveness probes for LLMs, vector stores, pgvector, and embedding endpoints. Record sanitized failures in both the system debug log and Rails logger, and document the recommended local configuration.\n\nCloses #3145

* Fix AI health CI checks

* Address AI health review feedback

* Correct Ollama model preload guidance

* Distinguish OpenAI-compatible providers

* Make Ollama startup readiness explicit

* Recognize Cloudflare AI endpoints

* fix(lunchflow): mark sync unhealthy when importer reports fetch failures (#1796) (#1873)

* fix(lunchflow): mark sync unhealthy when importer reports fetch failures (#1796)

`LunchflowItem::Syncer#perform_sync` called
`lunchflow_item.import_latest_lunchflow_data` but threw the result away
and then ran `collect_health_stats(sync, errors: nil)`. The importer
already catches per-account 429/500 fetch errors, bumps a
`transactions_failed` counter, and returns `success: false` — but the
syncer never inspected the return value, so the parent sync was marked
completed/green even when zero transactions were imported because every
fetch had been rate-limited.

Capture the importer result and translate any
`accounts_failed` / `transactions_failed` / `error` fields into the
`{ message:, category: }` error shape `collect_health_stats` expects.
The exception-path `rescue` branch is unchanged.

Closes #1796

* test(lunchflow): i18n the new health messages + add syncer invariant tests (#1796)

Two pieces of follow-up feedback:

- @coderabbitai + @JSONbored: the three new operator-facing strings should
  go through I18n.t. Add keys under provider_warnings.lunchflow_*
  (matching the existing provider_warnings.limited_investment_data
  shape) and use Rails pluralization for the count-bearing entries.
  Other locales follow the repo's normal translation flow.

- @jjmata + @JSONbored: add tests for the invariants. New
  LunchflowItem::SyncerTest covers:
    * successful import → sync healthy
    * accounts_failed positive → sync unhealthy with localized message
    * transactions_failed positive → sync unhealthy with localized message
    * both counters positive → both error entries recorded in order
    * sync raises → sync_error category + reraise (existing rescue branch)

@jjmata also asked to confirm the importer contract: LunchflowItem::Importer#import
returns 'success: accounts_failed == 0 && transactions_failed == 0' (see
importer.rb), so the early 'return [] if import_result[:success]' guard
is safe — success is never true while either counter is positive.

---------

Co-authored-by: jeffrey701 <jeffrey701@users.noreply.github.com>

* Exclude pending transactions from balances (#2897)

* Exclude pending transactions from balances

* Fix balance regression assertions

* Add pending balance review regressions

* Fix merge conflict commit

---------

Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Juan José Mata <jjmata@jjmata.com>

* perf: memoize Family#balance_sheet/investment_statement, cache transactions-index side queries (#3058)

* perf: memoize Family#balance_sheet/investment_statement, cache transactions-index side queries

The account sidebar renders on every page (mobile + desktop, 3 tabs each)
and calls Family#balance_sheet multiple times per render; neither it nor
Family#investment_statement/InvestmentStatement#current_holdings were
memoized, so each call rebuilt the underlying query from scratch. Memoize
both per-user (family sharing means different users must not share a
cached BalanceSheet/InvestmentStatement).

Also cache TransactionsController#index's uncategorized_count and
projected_recurring lookups, which run unconditionally on every request
regardless of whether the underlying data changed, using the same
entries_cache_version-keyed pattern already used elsewhere in the codebase
(e.g. Transaction::Search#totals).

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

* fix: address PR #3058 review feedback on cache invalidation and query reuse

- Invalidate transactions-index caches when the current user's AccountShare
  access changes, not just on entries/recurring updates (CodeRabbit/Codex
  flagged revoked users could see stale data for up to a day).
- Use full-precision timestamps instead of to_i in the cache keys so
  same-second updates aren't missed.
- Reuse the already-memoized investment_account_ids in
  InvestmentStatement#current_holdings instead of an extra any? query.
- Assert the rendered response instead of a controller instance variable in
  the uncategorized_count test, per CodeRabbit nitpick.

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

* fix: assert rendered response, not implementation details, in PR #3058 tests

Two CodeRabbit nitpicks from the second review round: the uncategorized-count
cache-reuse assertion matched a scope name that never appears in generated SQL
(making it vacuous), and the recurring-cache revocation test read the
controller's private @projected_recurring ivar instead of the rendered page.

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

* fix: bust transactions-index caches on entry/recurring deletion and account status change

jjmata's PR review flagged two invalidation gaps: hard-deleting an
uncategorized entry or recurring transaction left the previous max
updated_at unchanged (cache never busted), and toggling an account's
active status doesn't touch entries/AccountShare at all. Fold in
counts (like account_share_version already did) and a new
Family#accounts_status_version, and move the version helpers onto
Family/Current per the "fat models, skinny controllers" nit.

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

* fix: include merchant version in projected_recurring cache key

Editing or deleting a FamilyMerchant doesn't touch recurring_transactions,
so the cached projected-recurring list (rendered with merchant name/logo,
expires_in: 1.day) could show stale merchant data for up to a day.

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

* fix(transactions): version projected-recurring cache by referenced merchants, not just FamilyMerchant

recurring_transactions.merchant_id can point at a shared ProviderMerchant
(recurring detection copies transaction.merchant_id), not just a
family-owned FamilyMerchant. merchants_version only tracked
Family#merchants (FamilyMerchant), so a ProviderMerchant update (e.g.
ProviderMerchant::Enhancer setting name/logo) left the cached projected
recurring list stale for up to a day.

Replace Family#merchants_version with #recurring_transaction_merchants_version,
scoped to the merchant records actually referenced by the family's recurring
transactions (both FamilyMerchant and ProviderMerchant), and bump the cache
key version. Also fix a flaky test assertion that matched all
recurring_transactions-table queries instead of the actual projection query,
since computing the cache key itself still runs small COUNT/MAX queries
against that table on a cache hit.

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Gerald <248542187+gfr-free@users.noreply.github.com>

* Fix budget cache invalidation after transaction deletion (#2808)

Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>

* Add experimental Swift-native Sure Insights app (#3134)

* Add Swift-native Sure app

* Fix push subscriptions schema for CI

* Address native app review feedback

* Address remaining native app review feedback

* Use Flutter app logo for native icon

* Honor insight notification preferences and locale

---------

Co-authored-by: Juan Jose Mata <2v8shcb6pz@privaterelay.appleid.com>
Co-authored-by: sure-admin <sure-admin@splashblot.com>

* Refresh welcome screen branding

* Align welcome screen with brand green

* Remove welcome navigation title

* Center welcome screen logo

* Enlarge welcome screen logo

* Label fallback insights as samples

* Rename conversations menu label

* Add experimental Swift-native Sure Insights app (#3134)

* Add Swift-native Sure app

* Fix push subscriptions schema for CI

* Address native app review feedback

* Address remaining native app review feedback

* Use Flutter app logo for native icon

* Honor insight notification preferences and locale

---------

Co-authored-by: Juan Jose Mata <2v8shcb6pz@privaterelay.appleid.com>
Co-authored-by: sure-admin <sure-admin@splashblot.com>

* feat(snaptrade): add device-flow OAuth alongside the browser redirect (#3126)

* feat(snaptrade): add device-flow OAuth alongside the browser redirect

SnapTrade could only be connected through the authorization-code + PKCE
flow, which needs a confidential OAuth client: SNAPTRADE_OAUTH_CLIENT_SECRET
and a redirect URI registered on the OAuth app. A deployment that cannot
register one had no path at all.

Add the device grant (RFC 8628) as a second way to obtain the same token,
so people can pick the flow that suits their deployment. Both grants end at
SnaptradeItem#apply_oauth_tokens!, so a device-authorized item is
indistinguishable from a redirect-authorized one from there on -- same
Bearer data calls, refresh, revocation and sync. Nothing about existing
authorized items changes: no schema change, no migration, and the PKCE path
is untouched.

- Provider::Snaptrade gains start_device_authorization and poll_device_token,
  with endpoints read from SnapTrade's OAuth metadata document (cached).
- oauth_configured? now means "some flow is available" (public client id),
  which is what gates syncing and the provider panel; the new
  authorization_code_configured? gates the redirect flow specifically.
- Token and revocation requests authenticate as a public client when no
  secret is configured -- client_id in the body instead of HTTP Basic.
  Without this a device-authorized item would authorize fine and then fail
  at its first token rotation.
- The settings panel offers both when both are available; every other entry
  point picks one through SnaptradeItemsHelper#snaptrade_authorize_path.
- The device page carries a failed attempt's code back into the form, so
  "not confirmed yet" is a retry rather than a restart.

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

* fix(snaptrade): keep the provider panel's setup-step keys and cover both flows

Two test_unit failures from the panel change.

The setup steps were reordered and their keys renamed, which orphaned the
translations twelve locales already had for them and broke the test asserting
`oauth_setup_step_3`. The rename bought nothing: reword the steps in place
instead, leaving the callback URL on step 2 where the interpolation lives.

The panel tests stubbed `oauth_configured?`, which no longer decides which
buttons render -- that is now `authorization_code_configured?`. Stub both, so
the "configured" cases test the deployment they name, and add the device-only
case that was previously unreachable.

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

* fix(snaptrade): address device-flow review findings

Two real bugs from the bot reviews, plus consistency work.

The completion form posts into the `drawer` frame so errors re-render in place,
but a successful redirect was then followed as a frame navigation. Both
destinations carry the layout's empty `drawer` frame, so Turbo swapped that in
and merely closed the dialog: the notice was lost and `return_to=setup_accounts`
never advanced. Success now breaks out with a redirect stream action, the same
mechanism holdings and categorizes already use, while errors keep rendering in
the drawer.

RFC 8628 §3.1 requires a confidential client to authenticate its device
authorization request, and the panel offers the device code on deployments that
configured a secret. That request now carries the same client authentication as
the token request.

Token endpoint resolution is now shared by all three grants, since whatever
issued a token has to be what refreshes it. It reads the discovery document only
when already cached and never fetches it, so the browser flow keeps working off
the constant it has always used -- no new network call on refresh and no new way
for an existing authorized item to fail.

Also: the drawer no longer asks the provider whether it is configured, the
controller tells it; and the test helpers restore the previous OAuth config
rather than clearing it.

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

* fix(snaptrade): reject a device authorization response that cannot drive the flow

A 2xx missing device_code, user_code or a verification URI was passed straight
to the drawer, which then rendered a blank code and a link to nowhere -- a dead
end the user could only abandon. Every one of those fields is load-bearing, and
a response without them is partial or schema-changed, so fail with a message
instead. Same reasoning as the results-array check in get_positions.

verification_uri_complete substitutes for verification_uri when present, since
the drawer prefers it for the link anyway.

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

* fix(snaptrade): filter device-flow codes from request logs

complete_oauth_device_flow receives the device code as a request parameter,
and none of the existing filter_parameters patterns is a substring of
"device_code" -- ParameterFilter matches on substrings, and "token", "_key",
"secret", "code_verifier" and "code_challenge" all miss it. So Rails' default
"Processing by ... Parameters: {...}" line was writing it in plaintext.

That matters more here than ordinary log hygiene: the device code is the only
capability check on redemption. Unlike the redirect flow's state, nothing binds
a device code to the family that requested it, so anyone who can read the logs
could redeem another family's in-flight authorization into their own item and
pick up a token for that family's brokerage data.

Adds :device_code, :user_code and :verification_uri_complete (which embeds the
user code) to the filter list, with a regression test in the style of the
existing Sophtron credential-filtering test.

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

* fix(snaptrade): bind a pending device authorization to its session

The device code was posted back from the drawer as a form field, so the
request body was the only thing deciding which item a pending authorization
redeemed into. Nothing tied a code to the family that asked for it -- the
guarantee `state` gives the redirect flow -- so a code recovered from
anywhere could be redeemed into an item belonging to someone else, handing
them a token for the victim's brokerage data.

Hold the pending authorization in the session instead, where oauth_callback
already keeps its code_verifier and state:

- start_oauth_device_flow records the code, what the page displays, the
  family, the item and the return_to context under :snaptrade_device_flow.
- complete_oauth_device_flow reads the code from there and refuses unless
  the flow was started by this session for this family and this item. A
  device_code parameter is no longer read at all, so there is no longer a
  way to inject one.
- return_to and accountable_type come from the session too, so completion
  needs nothing from the form to find its way back.

The code now never reaches the browser, which also makes the previous
commit's log filtering a second line of defence rather than the only one.

A failed attempt keeps the code only while it is still redeemable: expired_token
and access_denied clear it so the page offers a fresh start, while a transient
failure leaves it in place to retry. expires_in and interval are no longer
carried anywhere, since nothing ever read them.

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

* fix(snaptrade): use one token endpoint for every grant

poll_device_token resolved the token endpoint from the cached discovery
document while exchange_code and refresh_tokens used TOKEN_URL, so which
URL a device-issued token was refreshed at depended on whether the 12h
metadata cache was still warm. If the discovered endpoint ever differed
from the constant, a device-authorized item would work until the cache
lapsed and then fail its first rotation -- and fail invisibly, since a
refresh failure marks the connection requires_update.

Resolve it by removing the choice rather than by making refresh depend on
discovery. RFC 8628 §3.4 redeems a device code at the authorization
server's token endpoint, the same one the authorization code grant uses:
there is one token endpoint, not one per grant, and nothing to keep in
sync between issuing a token and refreshing it. TOKEN_URL is also the
endpoint the browser flow has been using in production, so it is the one
with evidence behind it. Discovery is still consulted, but only for
device_authorization_endpoint, which has no hardcoded equivalent.

This also keeps refresh free of any network dependency it did not already
have: reintroducing discovery there would have put a fetch, with retries
and backoff, in front of every token rotation on items that never needed
one.

Also restore the previous OAuth configuration in the missing-client-id
test instead of leaving the client id nil, which made it order-dependent.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>

* feat(mcp): support Streamable HTTP transport (protocol 2025-06-18) (#2631)

* feat(mcp): support Streamable HTTP transport (protocol 2025-06-18)

Bumps the MCP protocol version from 2025-03-26 to 2025-06-18 to support
clients using the Streamable HTTP transport, notably Bifrost v1.6.3+.

Changes:
- Add after_action hook to set Mcp-Protocol-Version header on all responses
- Generate and return a sessionId in the initialize response
- Set Mcp-Session-Id header on subsequent responses

Without these headers, Bifrost's MCP client retries the initialize
handshake 5 times and ultimately fails with a context deadline exceeded
error, even though every JSON-RPC message is processed correctly.

* test: update mcp protocol expectations

* fix(mcp): negotiate protocol versions

* fix(mcp): align transport error responses

---------

Co-authored-by: secretsound <secretsound@users.noreply.github.com>
Co-authored-by: sure-admin <sure-admin@splashblot.com>

---------

Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Juan Jose Mata <2v8shcb6pz@privaterelay.appleid.com>
Co-authored-by: sure-admin <sure-admin@splashblot.com>
Co-authored-by: buzzromain <18685603+buzzromain@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Jeff <158072326+jeffrey701@users.noreply.github.com>
Co-authored-by: jeffrey701 <jeffrey701@users.noreply.github.com>
Co-authored-by: Atlas <atlas@maximusjb.com>
Co-authored-by: GFR <gerald-fritz@outlook.com>
Co-authored-by: Gerald <248542187+gfr-free@users.noreply.github.com>
Co-authored-by: Luke Blankenship <theLASTone413@gmail.com>
Co-authored-by: secretsound <secretsound@users.noreply.github.com>
2026-08-25 07:18:08 +02:00
3a50846cc7 feat(mcp): support Streamable HTTP transport (protocol 2025-06-18) (#2631)
* feat(mcp): support Streamable HTTP transport (protocol 2025-06-18)

Bumps the MCP protocol version from 2025-03-26 to 2025-06-18 to support
clients using the Streamable HTTP transport, notably Bifrost v1.6.3+.

Changes:
- Add after_action hook to set Mcp-Protocol-Version header on all responses
- Generate and return a sessionId in the initialize response
- Set Mcp-Session-Id header on subsequent responses

Without these headers, Bifrost's MCP client retries the initialize
handshake 5 times and ultimately fails with a context deadline exceeded
error, even though every JSON-RPC message is processed correctly.

* test: update mcp protocol expectations

* fix(mcp): negotiate protocol versions

* fix(mcp): align transport error responses

---------

Co-authored-by: secretsound <secretsound@users.noreply.github.com>
Co-authored-by: sure-admin <sure-admin@splashblot.com>
2026-08-25 04:51:38 +02:00
Juan José MataandClaude Opus 5 d6462f5fc9 feat(snaptrade): add device-flow OAuth alongside the browser redirect (#3126)
* feat(snaptrade): add device-flow OAuth alongside the browser redirect

SnapTrade could only be connected through the authorization-code + PKCE
flow, which needs a confidential OAuth client: SNAPTRADE_OAUTH_CLIENT_SECRET
and a redirect URI registered on the OAuth app. A deployment that cannot
register one had no path at all.

Add the device grant (RFC 8628) as a second way to obtain the same token,
so people can pick the flow that suits their deployment. Both grants end at
SnaptradeItem#apply_oauth_tokens!, so a device-authorized item is
indistinguishable from a redirect-authorized one from there on -- same
Bearer data calls, refresh, revocation and sync. Nothing about existing
authorized items changes: no schema change, no migration, and the PKCE path
is untouched.

- Provider::Snaptrade gains start_device_authorization and poll_device_token,
  with endpoints read from SnapTrade's OAuth metadata document (cached).
- oauth_configured? now means "some flow is available" (public client id),
  which is what gates syncing and the provider panel; the new
  authorization_code_configured? gates the redirect flow specifically.
- Token and revocation requests authenticate as a public client when no
  secret is configured -- client_id in the body instead of HTTP Basic.
  Without this a device-authorized item would authorize fine and then fail
  at its first token rotation.
- The settings panel offers both when both are available; every other entry
  point picks one through SnaptradeItemsHelper#snaptrade_authorize_path.
- The device page carries a failed attempt's code back into the form, so
  "not confirmed yet" is a retry rather than a restart.

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

* fix(snaptrade): keep the provider panel's setup-step keys and cover both flows

Two test_unit failures from the panel change.

The setup steps were reordered and their keys renamed, which orphaned the
translations twelve locales already had for them and broke the test asserting
`oauth_setup_step_3`. The rename bought nothing: reword the steps in place
instead, leaving the callback URL on step 2 where the interpolation lives.

The panel tests stubbed `oauth_configured?`, which no longer decides which
buttons render -- that is now `authorization_code_configured?`. Stub both, so
the "configured" cases test the deployment they name, and add the device-only
case that was previously unreachable.

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

* fix(snaptrade): address device-flow review findings

Two real bugs from the bot reviews, plus consistency work.

The completion form posts into the `drawer` frame so errors re-render in place,
but a successful redirect was then followed as a frame navigation. Both
destinations carry the layout's empty `drawer` frame, so Turbo swapped that in
and merely closed the dialog: the notice was lost and `return_to=setup_accounts`
never advanced. Success now breaks out with a redirect stream action, the same
mechanism holdings and categorizes already use, while errors keep rendering in
the drawer.

RFC 8628 §3.1 requires a confidential client to authenticate its device
authorization request, and the panel offers the device code on deployments that
configured a secret. That request now carries the same client authentication as
the token request.

Token endpoint resolution is now shared by all three grants, since whatever
issued a token has to be what refreshes it. It reads the discovery document only
when already cached and never fetches it, so the browser flow keeps working off
the constant it has always used -- no new network call on refresh and no new way
for an existing authorized item to fail.

Also: the drawer no longer asks the provider whether it is configured, the
controller tells it; and the test helpers restore the previous OAuth config
rather than clearing it.

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

* fix(snaptrade): reject a device authorization response that cannot drive the flow

A 2xx missing device_code, user_code or a verification URI was passed straight
to the drawer, which then rendered a blank code and a link to nowhere -- a dead
end the user could only abandon. Every one of those fields is load-bearing, and
a response without them is partial or schema-changed, so fail with a message
instead. Same reasoning as the results-array check in get_positions.

verification_uri_complete substitutes for verification_uri when present, since
the drawer prefers it for the link anyway.

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

* fix(snaptrade): filter device-flow codes from request logs

complete_oauth_device_flow receives the device code as a request parameter,
and none of the existing filter_parameters patterns is a substring of
"device_code" -- ParameterFilter matches on substrings, and "token", "_key",
"secret", "code_verifier" and "code_challenge" all miss it. So Rails' default
"Processing by ... Parameters: {...}" line was writing it in plaintext.

That matters more here than ordinary log hygiene: the device code is the only
capability check on redemption. Unlike the redirect flow's state, nothing binds
a device code to the family that requested it, so anyone who can read the logs
could redeem another family's in-flight authorization into their own item and
pick up a token for that family's brokerage data.

Adds :device_code, :user_code and :verification_uri_complete (which embeds the
user code) to the filter list, with a regression test in the style of the
existing Sophtron credential-filtering test.

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

* fix(snaptrade): bind a pending device authorization to its session

The device code was posted back from the drawer as a form field, so the
request body was the only thing deciding which item a pending authorization
redeemed into. Nothing tied a code to the family that asked for it -- the
guarantee `state` gives the redirect flow -- so a code recovered from
anywhere could be redeemed into an item belonging to someone else, handing
them a token for the victim's brokerage data.

Hold the pending authorization in the session instead, where oauth_callback
already keeps its code_verifier and state:

- start_oauth_device_flow records the code, what the page displays, the
  family, the item and the return_to context under :snaptrade_device_flow.
- complete_oauth_device_flow reads the code from there and refuses unless
  the flow was started by this session for this family and this item. A
  device_code parameter is no longer read at all, so there is no longer a
  way to inject one.
- return_to and accountable_type come from the session too, so completion
  needs nothing from the form to find its way back.

The code now never reaches the browser, which also makes the previous
commit's log filtering a second line of defence rather than the only one.

A failed attempt keeps the code only while it is still redeemable: expired_token
and access_denied clear it so the page offers a fresh start, while a transient
failure leaves it in place to retry. expires_in and interval are no longer
carried anywhere, since nothing ever read them.

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

* fix(snaptrade): use one token endpoint for every grant

poll_device_token resolved the token endpoint from the cached discovery
document while exchange_code and refresh_tokens used TOKEN_URL, so which
URL a device-issued token was refreshed at depended on whether the 12h
metadata cache was still warm. If the discovered endpoint ever differed
from the constant, a device-authorized item would work until the cache
lapsed and then fail its first rotation -- and fail invisibly, since a
refresh failure marks the connection requires_update.

Resolve it by removing the choice rather than by making refresh depend on
discovery. RFC 8628 §3.4 redeems a device code at the authorization
server's token endpoint, the same one the authorization code grant uses:
there is one token endpoint, not one per grant, and nothing to keep in
sync between issuing a token and refreshing it. TOKEN_URL is also the
endpoint the browser flow has been using in production, so it is the one
with evidence behind it. Discovery is still consulted, but only for
device_authorization_endpoint, which has no hardcoded equivalent.

This also keeps refresh free of any network dependency it did not already
have: reintroducing discovery there would have put a fetch, with retries
and backoff, in front of every token rotation on items that never needed
one.

Also restore the previous OAuth configuration in the missing-client-id
test instead of leaving the client id nil, which made it order-dependent.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-25 04:28:25 +02:00
0aa43de10a Add experimental Swift-native Sure Insights app (#3134)
* Add Swift-native Sure app

* Fix push subscriptions schema for CI

* Address native app review feedback

* Address remaining native app review feedback

* Use Flutter app logo for native icon

* Honor insight notification preferences and locale

---------

Co-authored-by: Juan Jose Mata <2v8shcb6pz@privaterelay.appleid.com>
Co-authored-by: sure-admin <sure-admin@splashblot.com>
2026-08-25 04:16:24 +02:00
Sure Admin (bot)andJuan José Mata 311f06e404 Fix budget cache invalidation after transaction deletion (#2808)
Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
2026-08-25 04:02:01 +02:00
3e79de5b64 perf: memoize Family#balance_sheet/investment_statement, cache transactions-index side queries (#3058)
* perf: memoize Family#balance_sheet/investment_statement, cache transactions-index side queries

The account sidebar renders on every page (mobile + desktop, 3 tabs each)
and calls Family#balance_sheet multiple times per render; neither it nor
Family#investment_statement/InvestmentStatement#current_holdings were
memoized, so each call rebuilt the underlying query from scratch. Memoize
both per-user (family sharing means different users must not share a
cached BalanceSheet/InvestmentStatement).

Also cache TransactionsController#index's uncategorized_count and
projected_recurring lookups, which run unconditionally on every request
regardless of whether the underlying data changed, using the same
entries_cache_version-keyed pattern already used elsewhere in the codebase
(e.g. Transaction::Search#totals).

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

* fix: address PR #3058 review feedback on cache invalidation and query reuse

- Invalidate transactions-index caches when the current user's AccountShare
  access changes, not just on entries/recurring updates (CodeRabbit/Codex
  flagged revoked users could see stale data for up to a day).
- Use full-precision timestamps instead of to_i in the cache keys so
  same-second updates aren't missed.
- Reuse the already-memoized investment_account_ids in
  InvestmentStatement#current_holdings instead of an extra any? query.
- Assert the rendered response instead of a controller instance variable in
  the uncategorized_count test, per CodeRabbit nitpick.

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

* fix: assert rendered response, not implementation details, in PR #3058 tests

Two CodeRabbit nitpicks from the second review round: the uncategorized-count
cache-reuse assertion matched a scope name that never appears in generated SQL
(making it vacuous), and the recurring-cache revocation test read the
controller's private @projected_recurring ivar instead of the rendered page.

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

* fix: bust transactions-index caches on entry/recurring deletion and account status change

jjmata's PR review flagged two invalidation gaps: hard-deleting an
uncategorized entry or recurring transaction left the previous max
updated_at unchanged (cache never busted), and toggling an account's
active status doesn't touch entries/AccountShare at all. Fold in
counts (like account_share_version already did) and a new
Family#accounts_status_version, and move the version helpers onto
Family/Current per the "fat models, skinny controllers" nit.

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

* fix: include merchant version in projected_recurring cache key

Editing or deleting a FamilyMerchant doesn't touch recurring_transactions,
so the cached projected-recurring list (rendered with merchant name/logo,
expires_in: 1.day) could show stale merchant data for up to a day.

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

* fix(transactions): version projected-recurring cache by referenced merchants, not just FamilyMerchant

recurring_transactions.merchant_id can point at a shared ProviderMerchant
(recurring detection copies transaction.merchant_id), not just a
family-owned FamilyMerchant. merchants_version only tracked
Family#merchants (FamilyMerchant), so a ProviderMerchant update (e.g.
ProviderMerchant::Enhancer setting name/logo) left the cached projected
recurring list stale for up to a day.

Replace Family#merchants_version with #recurring_transaction_merchants_version,
scoped to the merchant records actually referenced by the family's recurring
transactions (both FamilyMerchant and ProviderMerchant), and bump the cache
key version. Also fix a flaky test assertion that matched all
recurring_transactions-table queries instead of the actual projection query,
since computing the cache key itself still runs small COUNT/MAX queries
against that table on a cache hit.

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Gerald <248542187+gfr-free@users.noreply.github.com>
2026-08-25 03:40:57 +02:00
00d35993eb Exclude pending transactions from balances (#2897)
* Exclude pending transactions from balances

* Fix balance regression assertions

* Add pending balance review regressions

* Fix merge conflict commit

---------

Signed-off-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
Co-authored-by: Juan José Mata <jjmata@jjmata.com>
2026-08-24 23:32:45 +02:00
Jeffandjeffrey701 12eb9e15fb fix(lunchflow): mark sync unhealthy when importer reports fetch failures (#1796) (#1873)
* fix(lunchflow): mark sync unhealthy when importer reports fetch failures (#1796)

`LunchflowItem::Syncer#perform_sync` called
`lunchflow_item.import_latest_lunchflow_data` but threw the result away
and then ran `collect_health_stats(sync, errors: nil)`. The importer
already catches per-account 429/500 fetch errors, bumps a
`transactions_failed` counter, and returns `success: false` — but the
syncer never inspected the return value, so the parent sync was marked
completed/green even when zero transactions were imported because every
fetch had been rate-limited.

Capture the importer result and translate any
`accounts_failed` / `transactions_failed` / `error` fields into the
`{ message:, category: }` error shape `collect_health_stats` expects.
The exception-path `rescue` branch is unchanged.

Closes #1796

* test(lunchflow): i18n the new health messages + add syncer invariant tests (#1796)

Two pieces of follow-up feedback:

- @coderabbitai + @JSONbored: the three new operator-facing strings should
  go through I18n.t. Add keys under provider_warnings.lunchflow_*
  (matching the existing provider_warnings.limited_investment_data
  shape) and use Rails pluralization for the count-bearing entries.
  Other locales follow the repo's normal translation flow.

- @jjmata + @JSONbored: add tests for the invariants. New
  LunchflowItem::SyncerTest covers:
    * successful import → sync healthy
    * accounts_failed positive → sync unhealthy with localized message
    * transactions_failed positive → sync unhealthy with localized message
    * both counters positive → both error entries recorded in order
    * sync raises → sync_error category + reraise (existing rescue branch)

@jjmata also asked to confirm the importer contract: LunchflowItem::Importer#import
returns 'success: accounts_failed == 0 && transactions_failed == 0' (see
importer.rb), so the early 'return [] if import_result[:success]' guard
is safe — success is never true while either counter is positive.

---------

Co-authored-by: jeffrey701 <jeffrey701@users.noreply.github.com>
2026-08-24 23:26:06 +02:00
Juan José Mata fd6f4ff078 Add live AI checks to system health (#3155)
* Add live AI checks to system health

Give super admins a dedicated AI status view with bounded liveness probes for LLMs, vector stores, pgvector, and embedding endpoints. Record sanitized failures in both the system debug log and Rails logger, and document the recommended local configuration.\n\nCloses #3145

* Fix AI health CI checks

* Address AI health review feedback

* Correct Ollama model preload guidance

* Distinguish OpenAI-compatible providers

* Make Ollama startup readiness explicit

* Recognize Cloudflare AI endpoints
2026-08-24 22:41:08 +02:00
buzzromainandClaude Opus 5 c26b16d36f chore(goals): drop copy-pasted duplicates and an unused lock-key helper (#3159)
`Account#goal_earmarked_total` and `Account#free_to_earmark` were each
defined twice, byte for byte, with no `private` boundary or singleton
class between the blocks — a copy-paste artifact where the second
definition silently overwrote the first. Keep one copy of each.

`Goal.advisory_lock_key_for` had no caller anywhere in app/; the only
reference was a test asserting the dead helper was deterministic. Remove
both. No behavior change.


Claude-Session: https://claude.ai/code/session_01DJ1npaGEHr6t2HW1rYZdt4

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 21:17:54 +02:00
Brandon WolfandClaude Fable 5 41d4db38dc docs(api): sync openapi.yaml with merchants import and transfer fee fields (#2961)
* docs(api): sync openapi.yaml with merchants import and transfer fee fields

Regenerate the OpenAPI document from the request specs already on main
(bundle exec rake rswag:specs:swaggerize). Purely additive: documents
the POST /api/v1/merchants CSV import endpoint, the
MerchantImportResult schema, and the transfer source/destination fee
fields that were intentionally left out of #2823.

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

* fix(docs): describe merchants CSV multipart body as an object schema

type: file is a Swagger 2 idiom that is invalid under OpenAPI 3.0.3;
declare the multipart part as an object with a required binary file
property (matching params[:file]) and regenerate the document.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 17:02:47 +02:00
Juan José Mata 37a65be4b8 Fix Mintlify docs workflow (#3156) 2026-08-24 07:00:21 +02:00
buzzromainandClaude Opus 5 721fc394ec fix(securities): give prefixed crypto tickers their logo back (#3151)
Security#crypto_base_asset only stripped a fiat suffix — "BTCUSD" gave "BTC" —
so it answered nil for the "CRYPTO:BTC" form, which is the form every crypto
integration writes: the on-chain wallets, Kraken, CoinStats and Binance all
store the prefix. display_logo_url feeds that nil to the crypto branch, so none
of those securities carried a logo at all.

Provider::BinancePublic already parses every shape it accepts — the pair form,
the prefixed pair, the bare base asset and the USD stablecoins — so this
delegates instead of growing a second parser next to it. The parsing moves to a
class method for that; the private instance method stays as a delegator, so its
own callers and their tests are untouched.

Verified across the four documented forms: CRYPTO:BTC and BTCUSD both give BTC,
CRYPTO:ETH gives ETH, CRYPTO:USDT gives USDT.

A logo still needs BRAND_FETCH_CLIENT_ID configured — this fixes the parsing,
not the hosting requirement.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 06:12:24 +02:00
github-actions[bot]andgithub-actions[bot] <github-actions[bot]@users.noreply.github.com> 6a9c30a172 Bump version to next iteration after v0.7.4-alpha.8 release (#3144)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-08-24 06:10:54 +02:00
Sure Admin (bot) 79c826c0e3 Add Sure client overview docs (#2832)
* Add Sure client overview docs

* docs: address client API comments
2026-08-23 02:12:31 +02:00