Add a rule action that records a loan rate change
Summary
Part of #142 (phase 2, the fork's remaining work; phase 1 merged as #213).
A bank's "rate change" notice arrives as an ordinary transaction on the loan account, and nothing in Sure read it. This adds a transaction-rule action, "Record loan rate change from description" (record_loan_rate_change). It reads the new rate from the transaction's name, then its notes, and records it as a dated row in the loan's variable_rate_schedule through the same guarded write as phase 1.
636f3fa3b, 965f4267e and 2e186c335, 2026-10-12/13: movement words, "your rate is", and a direct test of the shared writer.
636f3fa3b: movement words are change wording too (nightly review 6120552186 follow-up; comment 6124535122).- Before:
CHANGE_WORDINGcovered only change/adjust forms, so "Rate increase 0.25%", "Rate rise 0.25%", "Rate decrease 0.25%", "Rate hike 0.25%" and similar each read as a new rate of 0.25%. On a 6.49% variable loan that is a wrong rate written to the schedule. - Now: increase, decrease, rise/rose, raise, reduce/reduction, lowered, cut, hike, fall/fell and drop are change wording too. Without a new-rate marker they are refused as
change_wording. With one ("Rate increased to 6.5%") the marked rate is read. - "up"/"down" and bare "lower"/"higher" are deliberately not in the list. The cost: "RATE INCREASE 6.74% P.A." is now refused and logged rather than read.
- Tests: "movement wording without a new-rate marker is refused" (failed first: "Rate increase 0.25%" gave 0.25), "movement wording with a new-rate marker gives the marked rate", and, through the rule action, "a rate-increase notice that names only a percentage records nothing and is logged".
- Before:
965f4267e: "rate is" is a new-rate marker (owner decision, 2026-10-12; comment 6125984385).- "Following the RBA cut your rate is 6.24%" reads 6.24, and "RATE INCREASE - YOUR RATE IS 6.74% P.A." reads 6.74. Both were refused as
change_wordingbefore. - Exception 1, a movement noun governs the rate (
RATE_IS_MOVEMENT): in "The change in your rate is 0.25%" the percentage is the movement, so the text stays refused aschange_wording. - Exception 2, a qualifier names another rate (
RATE_IS_OTHER_RATE): "comparison / previous / old / former / prior rate is X%" staysambiguous. Without it, "Rate 6.25% comparison rate is 6.40%" would write 6.40. - Decided (owner, 2026-10-13): keep exception 2. It was added beyond the "rate is" instruction and held for the owner. A refusal is logged; a wrong rate re-prices every later period.
- Only "rate is" was added. "rate will be" and "rate of" are not markers.
- Tests: "a rate-is marker gives the rate after it" (failed first), "rate-is after a movement noun is not a new-rate marker", "a rate-is marker does not lift the refusal of a bare movement", "rate-is after a qualifier naming another rate is not a new-rate marker", and through the rule action "a your-rate-is notice records the rate". Dropping the marker, the movement exclusion or the other-rate exclusion each turns at least one red.
- "Following the RBA cut your rate is 6.24%" reads 6.24, and "RATE INCREASE - YOUR RATE IS 6.74% P.A." reads 6.74. Both were refused as
2e186c335:Loan#enrich_reporting_refusaltested directly (code master review F6). Test-only; see Review findings.- Validation at
2e186c335: fullbin/rails test12,437 runs, 0 failures, 0 errors, 35 skips.bin/rubocopno offenses,bin/brakeman0 warnings.
f21a14a7f, 2026-10-12: "Rate change 0.25%" is refused unless a marker names the rate (nightly review BLOCKER; owner's instruction: "go with your recommendations").
- Before: "Rate change 0.25%" held one percentage, with no movement marker in front of it, so it was read as a new rate of 0.25%. A bank can mean a 0.25-point movement by it, and the text can't say which; read as a rate, it would put a 6% loan at 0.25%.
- Now:
Loan::RateChangeTextrefuses such text as a new problem,:change_wording, logged like the others.- It applies when the text speaks of a change ("change", "changed", "changes", "changing", "adjust", "adjusted", "adjustment", ...).
- It does not apply when a percentage follows a new-rate marker ("to", "now", "new rate"). Then the marked rate is read as before, for example "Rate change: now 6.24%", "Rate adjusted to 6.24% p.a." and "INTEREST RATE CHANGE - NEW RATE 6.24% P.A.".
- A signed or "by" percentage is still
change_amount_only.
- Tests, failing first where they assert the fix:
- "change wording without a new-rate marker is refused", across seven wordings. "Rate change 0.25%" gave 0.25 before.
- "change wording with a new-rate marker gives the marked rate".
parsereturns nil for "Rate change 0.25%".- Through the rule action: "a rate-change notice that names only a percentage records nothing and is logged", with problem
change_wording.
- Tests rewritten to keep their meaning:
- The spelling, range and parse tests used "Rate change N%" only as a carrier. They now use "New rate N%", so they still test what they name.
- "The name is read before the notes" now has readable notes ("New rate 6.10%"), so it still proves the order.
- Mutations caught: the refusal removed (3 failures), applied even with a marker (8), and the wording narrowed to "change"/"changes" (1).
- Siblings: the rule action is the parser's only caller. Its header comment now names the new refusal.
- Validation: full
bin/rails testonf21a14a7fgave 12,425 runs and 1 failure, the known Ruby 3.3Provider::OpenaiTeststring.bin/rubocopreports no offenses, andbin/brakeman0 warnings. - Propagation:
f21a14a7fmerged intoclaude/loans-integration-base, then #405 and #404 (see #404).636f3fa3b,965f4267eand2e186c335followed on 2026-10-13 through the same chain.
The issue is needs:design: the plan asked for real bank wordings first, and none were collected. The owner asked for grounded decisions rather than waiting, so these were made deliberately narrow. Each is stated in record_loan_rate_change.rb's header:
| Decision | What it does |
|---|---|
| Which transactions | Only those on a Loan account (filtered in SQL; others are skipped silently). Only variable/adjustable loans record. A fixed loan, or a blank rate_type, records nothing and logs a disagreeing rate. Blank is not read as variable: phase 1 adopts variable only on the bank's structured rateType, and free text isn't that. |
Parsing (Loan::RateChangeText) | A number followed by %, per cent or percent. A marker before it (to, now, new rate, new interest rate, optionally is/of/:) makes it the new rate. So does "rate is", unless a movement noun governs the rate ("the change in your rate is") or a qualifier names another rate ("comparison rate is", "previous rate is"). Without a marker, the text must hold exactly one distinct value and no change or movement wording (change, adjust, increase, decrease, rise, raise, reduction, cut, hike, fall, drop); otherwise nothing is recorded. A number after by, after "increase/decrease/cut of", straight after a bare change verb ("decreased", "rose", "cut", "down"), before a comparative ("0.25% higher"), or with a sign (-0.25%) is a change amount, not a rate, and records nothing. Rounded to 3 places, which is what the loan stores; it must be > 0 and < 100. |
| Date | The transaction's entry.date. Nothing reads the clock; the test runs under travel_to another day to prove it. |
| Write path | Loan#variable_rate_update_for decides the row and the new Loan#enrich_reporting_refusal writes it, with source rule and rule_id/entry_id metadata. Never add_variable_rate_change, which writes past locks. |
| Locks | Always honoured, even under "Apply rule" (ignore_attribute_locks: true). That flag covers the transaction attributes rules own, not the user's hand-edited loan schedule. |
| Same-date clash | Stricter than the provider path: an existing row on that date with a different rate is never overwritten; the clash is logged. The date is matched by parsed value, so a row stored as 20260914 counts. |
| Ordering | Oldest first, so a notice repeated months later records once. |
| Excluding the $0 line | Not folded in. Add the existing "Exclude from budgeting and reports" action to the same rule. |
| Logging | Every refusal is a DebugLogEntry, category loan_rate, with the family and account. Reasons: ambiguous, change_wording, change_amount_only, out_of_range, not_variable, date_clash, refused. Text with no percentage logs nothing. |
First commit: a shared write. Loan#enrich_reporting_refusal is extracted from the Redbark and Plaid loan writers, which each carried their own copy (enrich, then on refusal restore attributes, clear errors and return the messages). Their tests are unedited and green.
Scope and dependencies
- Issue: #142 (phase 2). Upstream: we-promise/sure#3891 asks about porting phase 1; this phase isn't proposed upstream.
- Parent PR/branch, if stacked: none. Base
main. - Intentionally out of scope: collecting real bank samples; the v2 Redbark API (#160); Plaid's processors (#158).
Blast radius.
- Every transaction rule's action list now offers the action: the form select, the index label, and the
action_executorsJSON the Stimulus controller reads. Its type is"function", so it takes no value and hides the value input the wayexclude_transactiondoes; a controller test checks the edit page. - Rule import, export and
Rule::Actionhandle action types generically. - The extraction changes only private methods in
RedbarkAccount::LoanDetailsProcessorandPlaidAccount::Liabilities::LoanTermWriter, which pass the same hashes as before. Loan#variable_rate_update_for(shared by Plaid, Redbark and this rule) now replaces a same-day row stored under another ISO spelling rather than adding a second row for that day. For canonical keys its behaviour is unchanged.
Siblings. grep -rn "restore_attributes\|errors.clear\|enrich_attributes" app/models: only the Redbark and Plaid loan writers had the duplicated pattern. PlaidAccount::Processor writes subtype for every account type and isn't the loan rate path. add_variable_rate_change has no app or lib callers. For the date-key fix, grep -rn "variable_rate_schedule" app: the rule's clash lookup and variable_rate_update_for were the two exact-key readers; current_variable_rate and variable_rates already parse keys.
Evidence checklist
- Each issue in this PR has its own acceptance criteria and no unrelated issue work is included.
- Contract rows touched by this change name existing tests.
- Any gate test has an observed failing mutation transcript attached.
- Fixtures used as evidence assert internal consistency.
- Financial calculations use
BigDecimaland documented rounding points. - De-identification uses token-shape allowlists; no personal data is included.
- Files changed, decisions, tests/runtime, risks, and next unblocked issue are documented below.
Tests:
test/models/loan/rate_change_text_test.rb: 30 tests, plus 2 inf21a14a7f, 2 in636f3fa3band 4 in965f4267e;test/models/rule/action_executor/record_loan_rate_change_test.rb: 25 tests, plus 1, 1 in636f3fa3band 1 in965f4267e;- 2 in
test/controllers/rules_controller_test.rb; - 1 added to
test/models/loan_test.rb, plus 4 in2e186c335.
Fail first
- Parser: all initial tests errored,
NameErrorbefore the class existed. - Executor: all failed with
UnsupportedActionErrorbefore registration. Against a registered no-op stub, 15 failed on their assertions (every positive, plus fixed, blank-type, ambiguous, out-of-range, date-clash, provenance, run-twice, date-order and count). 6 guard negatives passed against the stub, as negatives do; each was then shown to fail by mutation. - Written after the code and proved by mutation instead: the refusal test, the unmarked "same rate twice" parser test, the 2 controller tests, and the locked non-empty schedule test (987b98b).
- Review fixes, red first: "a percentage straight after a bare change verb is a change amount" (read 0.25 as the rate), "a row on the transaction's date under another ISO spelling is a clash too" (no clash logged), "variable_rate_update_for replaces a same-day row under another ISO spelling" (kept both rows), and "change wording without a new-rate marker is refused" (read 0.25 as the rate).
Mutations, each restored from a copy and confirmed by a clean git status:
| Mutation | Caught by |
|---|---|
| Remove the Loan filter | non-loan test |
| Remove or reverse the date ordering | date-order test |
entry.date → Date.current | 8 tests |
| Treat every loan as variable / blank as variable | fixed-loan and blank-type tests |
| Remove the date-clash guard | clash test |
Source → "plaid" | provenance test |
| Notes before name / never read notes | name-order / notes tests |
| Always return true | all three lock tests |
"Was anything written?" compared with nil instead of the pre-write value | all three lock tests |
| Remove refusal reporting / log with no problem / never log parse problems | refusal / no-percentage / ambiguous and out-of-range tests |
Shared writer: ignore_locks: true | 12 tests across the rule, Redbark and Plaid |
Shared writer: drop errors.clear / restore_attributes | existing Redbark and Plaid tests |
Parser: markers off, <= 100, >= 0, no rounding, change-marker, sign, ambiguity and range checks removed | 1 to 5 tests each |
| Parser: drop the bare-verb alternative | bare-verb test |
| Parser: drop the change-wording refusal / apply it even with a marker / narrow the wording | 3 / 8 / 1 tests |
| Clash lookup back to the exact key | alternate-spelling clash test |
variable_rate_update_for keeps the other spelling | alternate-spelling update test |
Action type → "text" | controller hidden-input test |
Two survivors were handled: the parser's .uniq survived until an unmarked duplicate test was added; and a per-account Loan memo survived even with its preload removed, so it did nothing and was deleted.
Validation
- CI on
987b98b: all checks green.- The first attempt of CodeQL
Analyze (java-kotlin)failed before analysing anything. The runner's Android NDK download came back corrupt (java.util.zip.ZipException: Archive is not a ZIP archivewhile installingndk;26.3.11579264), so Gradle'sassembleDebugformobile/androidcould not configure. - This PR doesn't touch
mobile/. - A single re-run of the failed job passed. No code changed.
- The first attempt of CodeQL
- Rule, rule-run, rule-import, Loan, Redbark, Plaid, rules controller, data exporter, rule job and i18n suites: 754 runs, 0 failures, 4 skips (pre-existing i18n skips). After the review fixes: loan, parser, rule, Redbark and Plaid tests, 280 runs, 0 failures. On 987b98b: the executor test file, 25 runs, 0 failures.
- Full
bin/rails testonf21a14a7f: 12,425 runs, 1 failure: the known environmentalProvider::OpenaiTest#test_extra_headers_stringifies_nested_values_Ruby-style(Ruby 3.3 here, 3.4 pinned). bin/rubocopon changed Ruby files: no offenses.bin/brakeman --no-pager -q: 0 warnings. No ERB changed.- System tests not run (no chromedriver here). The browser path that hides the value input on switching the action type is untested locally; the server-rendered edit page is tested.
- Checked against upstream
AGENTS.md.
Review findings
-
cubic, bare change verbs read as a rate (
rate_change_text.rb): valid. Fixed in 3ca45eb. -
cubic, same-day clash missed under an alternate ISO key (
record_loan_rate_change.rb): valid. Fixed in 3ca45eb, with the sibling inLoan#variable_rate_update_for. -
cubic,
enrich_reporting_refusalcould report a stale error or clear an unrelated one (loan.rb): declined. Traced every caller: the Redbark processor, the Plaid term writer and this rule each load the loan fresh, and the only path that populateserrorsinside this method clears them before returning. A save attempt re-validates, which resetserrorsanyway. No real caller reaches the case, and distinguishing "errors from this write" from earlier ones would mean re-implementing Enrichable's skip logic. -
Gatekeeper light review, comment 6100021879, MINOR: "
index_withkeys by position, so the was-anything-written check compares with nil": the defect is declined; the test it asks for is added in 987b98b.- The premise is wrong.
index_withis ActiveSupport'sEnumerable#index_with, which keys by element:%i[variable_rate_schedule rate_type].index_with { |a| a.to_s.upcase }gives{variable_rate_schedule: "VARIABLE_RATE_SCHEDULE", rate_type: "RATE_TYPE"}(run on this branch's Ruby and ActiveSupport). Sobefore[attr]is the attribute's pre-write value. - The existing lock tests already catch the hypothesised defect. I swapped the comparison for
!= niland both lock tests fail (Expected: 0), because the untouched schedule column reads{}, not nil. - The coverage gap was real, though. Both lock tests started from an empty schedule. The new test, "a locked schedule that already holds a row is not added to, and nothing counts as applied", fails under the
!= nilmutation and under "always report a write".
- The premise is wrong.
-
"code master" review (comment 6106247701), hold, on
987b98b: none of its findings holds as written. Checking F2 turned up a different parser defect, which writes a wrong rate. It is fixed inca5ce2874, pushed on the owner's instruction (2026-10-11: "Push the held commits; go with your recommendations"). The review's line numbers don't exist; the executor has 138 lines, and the real sites areloan.rb:666andrecord_loan_rate_change.rb:93.- F1, a malformed schedule key crashes every write path: declined.
- A bad key can't be stored: every writer goes through validation, and
variable_rate_schedule_entries_are_valid(loan.rb:1077-1101) rejects any keyDate.iso8601can't parse.- The form keeps a bad date as typed, so validation rejects it.
add_variable_rate_changeusessave!, andvariable_rate_update_forwritesday.iso8601.- The providers and this rule write through
enrich_attributes, which callssave. Family::DataImporternever writes the schedule.- Shown with a temporary test.
- A key forced in with
update_columnalready crashesmain'svariable_ratesandcurrent_variable_rate, before the new line is reached, so this is no new crash class. - The review's examples are wrong too: Ruby's
Date.iso8601parses"2026-015"and"2026-W03-1".
- A bad key can't be stored: every writer goes through validation, and
- F2, "NEW RATE +6.24%" is refused as
change_amount_only: confirmed as described. An owner decision, not a defect.- It, "New interest rate is +6.24%" and "Rate now +6.24%" are refused and logged. Nothing is misread.
- The review's fix, "a marker beats a sign", is unsafe:
nowandtoare markers, and the sign is what stops "Your rate is now +0.25% higher" being recorded as 0.25%. - A narrow version would pass every test: only
new rate/new interest rateoverride a+, and-stays a change amount. - Decided (owner, 2026-10-11): keep the refusal until a real bank sample shows a signed new rate, as this description's "widen from real samples" says.
- F3,
loan.variable_ratesisn't defined: declined. It is onmain(loan.rb:592) and returns sorted[key, rate]pairs, which is what thefindexpects. - F4, same-day rows are silently replaced for every caller: already decided (the executor header, and Blast radius above). The stated consequence is false: reporting the same rate returns nil before anything is rewritten, and a real change used to leave two rows for one day.
- F5, falling back from the name to the notes loses the notes' problem: not worth its code. Nothing is recorded either way, and the log carries
entry_id. - F6, no direct test of
enrich_reporting_refusal: test gap closed in2e186c335. It callssave, notsave!, so the review's "if it raises" can't happen. Four tests inloan_test.rbnow pin its contract: an accepted update is written, a blank one writes nothing, a refusal returns its messages with the loan restored and its errors cleared, and a locked attribute is skipped. Mutations: droppingrestore_attributes, droppingerrors.clear, returning nil,ignore_locks: trueand skippingenrich_attributesare each caught. Dropping theattrs.blank?guard survives as an equivalent mutant, sinceenrich_attributes({})writes nothing (comment 6140866744). - Not in the review: "now 0.25% higher" became the loan's rate. Confirmed; fixed in
ca5ce2874.- The parser looked only before a percentage for change wording.
- So on a 6.49% variable loan, "Your variable rate is now 0.25% higher" wrote
{"2026-09-14" => 0.25}. - A percentage followed by higher, lower, above, below, more or less (optionally after "p.a.") is now a change amount.
- New tests: "a percentage followed by a comparative is a change amount" (five wordings; it failed first with
Expected 0.25e0 to be nil), and "a comparative that does not follow the percentage leaves the rate alone" ("Rate now 6.24%, higher than last year" still gives 6.24). - Parser, executor, loan and rules controller tests: 146 runs, 0 failures.
- F1, a malformed schedule key crashes every write path: declined.
-
Nightly review (comment 6120552186), NOT READY TO MERGE, on
ca5ce2874.- BLOCKER, "Rate change 0.25%" is accepted as an absolute rate: confirmed, and fixed in
f21a14a7fas it required: ambiguous change wording is refused unless an explicit new-rate marker identifies the rate, with the regression test through the rule action it asked for (top of this description).
- BLOCKER, "Rate change 0.25%" is accepted as an absolute rate: confirmed, and fixed in
-
Nightly review (comment 6134304915), READY TO MERGE, on
965f4267e. No blocking or other material findings. It confirms the "Rate change 0.25%" case is refused and logged. Nothing to change. The other-rate guard it reviewed was confirmed by the owner on 2026-10-13 (top of this description).
Review responses are recorded here rather than as thread replies, because replies posted from this session get an assistant footer appended, which this repository's attribution rule forbids.
Risks, blockers, and follow-up
- Decisions made without bank samples.
- "Rate change 0.25%" was a known edge here, read as a rate of 0.25%. It is now refused (
f21a14a7f). - A real notice worded as "Rate change 6.24%" will also be refused and logged, rather than recorded. That is the cost of the fix; the notice's rate can be entered by hand, or the wording added once a real sample shows what the bank means.
- "CHANGE-6.24%" still reads as a signed change.
- Real samples should settle these.
- "Rate change 0.25%" was a known edge here, read as a rate of 0.25%. It is now refused (
- First reading on a loan with no base rate becomes the base rate from the loan's start. That's
variable_rate_update_for's existing shared behaviour, but a dated notice arguably deserves different handling. - Not behind the preview gate. Loan pages and phase 1 aren't gated either, but the rule editor is a general surface. Owner to confirm.
- New
DebugLogEntrycategoryloan_rate: checked 2026-10-10.DebugLogEntryvalidates only that a category is present, andSettings::DebugsControllerbuilds the filter fromDebugLogEntry.distinct.pluck(:category), soloan_rateappears in/settings/debugonce the first entry is logged. Nothing to register. - Label is English only; other locales fall back through
i18n.fallbacks.