Re-admit loan insurance, down payment and repayment progress (#184 phase 2)
Summary
Part of #184 (phase 2 of the 2026-09-30 reconciliation plan: re-admit upstream we-promise/sure#3327).
The fork's weekly syncs dropped #3327's loan-overview features (604fdb69, 25fc8633, 55b243eb) to keep the fork's loan engine. This brings them back onto that engine, ported from upstream's current files:
- Database:
20260916210000_add_down_payment_to_loansand20260916210100_add_insurance_to_loans, at upstream's versions, withif_not_existsguards (the upstream sync branch carried them before forkmaindropped them).db/schema.rbis edited by hand to what the migrations produce; the version stamp stays at2026_10_08_100000. - Model:
Loan::Insurance(level-term and decreasing premiums). OnLoan:- the validations and
LEVERAGE_BANDS; #insurance,#total_insuranceand#total_cost;#months_elapsed,#remaining_months,#finished?,#remaining_balance_at,#payment_breakdownand#balance_paid_ratio;- the donut segments,
#initial_leverage_ratio,#leverage_bandand#origination_date.
- the validations and
- Engine:
Loan::AmortizationSchedule's fourstart_date || account_opening_anchor_datereads go throughloan.origination_date;scheduled_payment_datesis public. - UI: a new
LoansHelperwith #3327's two helpers, the form's down-payment and insurance fields and permitted params, the overview's Total Cost / Insurance / Leverage cards, the_repayment_progresspartial, and en + fr strings (other locales fall back to English). - Upstream's
Loan#original_balance: a positiveinitial_balance(the recorded contractual principal) wins over the first valuation.
Scope and dependencies
- Issue: #184 (phase 2).
- Parent PR/branch, if stacked: none. Base
main. - Intentionally out of scope: the demo generator part of #3327. It sets down payment and insurance on upstream's schedule-driven demo loans; the fork's demo loans carry no terms, and
generator_testskips that area. Decided below: it stays out of this PR.
Blast radius of original_balance.
- Readers:
- the schedule: whether it can amortise, the monthly payment, total cost, the simulator's opening balance;
- through the schedule: the payoff projection,
current_minimum_paymentfor fixed loans, the payoff chart, the extra-repayments tab, the retirement planner's loan seed and theamortization_scheduleAPI; - the schedule signature, the overview card, and the new insurance, repaid and leverage readers.
- Writers of
initial_balance:- the account form on create, with the same figure as the opening anchor;
- the loan form on edit, which never touches the anchor, so editing "Original loan balance" now changes the figures;
- Plaid student loans and Redbark imports.
Siblings fixed.
original_balanceis memoised, and assigninginitial_balanceor callingreloaddrops the memo.amortization_inputs_changed?includesinitial_balance, so a new principal queues a schedule rebuild.- The Redbark test comment that said
original_balanceignoresinitial_balanceis corrected. - The signature hashes the amount by value, so a loan whose principal equals its opening valuation keeps its signature (tested both ways);
ALGORITHM_VERSIONis unchanged.
Departures from upstream, with reasons.
origination_dateis the start date, else the opening anchor (the fork schedule's anchor). Upstream falls back to the first valuation's date.months_elapsedcounts the schedule's own payment dates on or beforeas_of. Upstream's schedule pays onstart >> n; the fork chainsnext_month, which drifts for loans drawn on the 29th–31st, and upstream's count would put such a borrower on an instalment already paid. New test; it returned 1 against an expected 2 before the change.- Insurance and the progress readers read the fork's hash rows (BigDecimals), not upstream's structs, and check
amortizable?where upstream checks for a nil schedule. - The insurance memo is keyed on the schedule instance plus the rate inputs, not cleared by attribute writers.
Loan#total_costuses the schedule'stotal_cost; upstream calls ittotal_paid.- The overview tab takes
as_ofas a local (defaultDate.current) and passes it to the repayment card, rather than setting it inside the template. - The student-loan processor test that 25fc8633 dropped is restored.
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.
Red first. The first run gave 162 runs, 12 failures and 31 errors.
- Assertion failures with the right values:
- "the principal is the recorded one": expected 20000, got 10000;
- "the schedule amortises what was borrowed";
- the signature-differs test;
- "saving a new principal queues a rebuild";
- the restored Plaid test: expected 20000, got 10000.
- Errors from methods not yet written: the insurance, progress, leverage and controller tests.
- Passed before the change: the anchor-origin progress test, because
origination_datewas written first. It is proved by M10 instead.
Mutations, each applied, run, then restored from a backup and checked with cmp:
| # | Mutation | Caught by |
|---|---|---|
| M1 | original_balance ignores initial_balance | 10 tests, incl. the principal tests, Plaid and the golden master |
| M2 | drop the positive guard | the zero/negative fallback test |
| M3 | setter no longer clears the memo | the assigning-principal test |
| M4 | reload no longer clears the memo | the reloading test |
| M5 | initial_balance removed from the rebuild callback | the rebuild-queue test |
| M6 | overview passes Date.current to the repayment card | the view test |
| M7 | insurance memo key without the schedule | the memo test |
| M8 | decreasing premium charged on the original principal | 3 insurance tests |
| M9 | upstream month arithmetic | the month-end test |
| M10 | upstream origin (first valuation) | the anchor test |
| M11 | card always titled "Total Cost" | the controller Total Cost test |
| M12 | insurance params not permitted | 2 controller tests |
| M13 | drop the short-schedule guard | the schedule-ended test |
| M14 | drop normalizes on insurance type | the blank-type test |
Golden master. Only initial_balance_differs_from_first_valuation.json moves. It was byte-identical to fixed.json, because its 320,000 principal was ignored; it now amortises 320,000:
| Figure | Before | After |
|---|---|---|
| Monthly repayment | 1,798.65 | 1,918.56 (= ×320/300) |
| Total interest | 348,220.55 | 371,435.23 |
| Payoff date | 2054-01-15 | 2054-01-15 (term-driven) |
| Projected payoff | 2053-05-15 | 2049-10-15 |
| Projected interest | 282,141.82 | 237,559.96 |
current_minimum_payment / planner seed | 1,798.65 | 1,918.56 |
The projection still starts from the 285,000 balance; it clears sooner because it holds the larger contracted repayment. A rerun without LOAN_GOLDEN_MASTER_WRITE: 9 runs, 0 failures.
Migrations on a scratch database built from main's schema: running them gives exactly the hand-edited loans table; running them again raises nothing and changes nothing; rolling back restores the original.
Validation
- Loan suites (loan models, loans and accounts controllers, views, Plaid, demo, Redbark, helpers,
UI::Loancomponents, retirement plan, account): 1,090 runs, 0 failures, 2 skips (the same 2 as the 697-run baseline). - Full
bin/rails test: 12,412 runs, 1 failure, the knownProvider::OpenaiTest#test_extra_headers_stringifies_nested_values_Ruby-style(Ruby 3.3 vs 3.4 string, unrelated). bin/rubocopon 15 files: no offenses.bin/brakeman: 0 warnings.erb_lint: 2 errors in_form.html.erb, both on the existing rate-change inputs (missingautocomplete); they are onmaintoo and are not touched here.test/system/loan_overview_test.rbwas not run here (no chromedriver in this container); CI runs it.- Checked against upstream
AGENTS.md. The repayment partial has two hand-built cards of the same shape, as upstream ships it; a reviewer could raise AGENTS.md's rule on repeated shapes.
Review findings
-
Gatekeeper light review (comment 6092621005): DRAFT_ON_TRACK, no material findings. Its recommendation, "resolve the deferred demo-generator decision before exiting draft", is answered under Risks below: decided, out of this PR.
-
"code master" review (comment 6105940287), BLOCK, on
b85b28f: nothing to change. Two findings were disproved by experiment, seven describe upstream's code as written, and the rest are declined. Each was compared withorigin/mirror/upstream-main:- Migrations dated before the schema stamp stay "pending forever": declined, disproved.
- Rails'
Schema.definerecords every migration version indb/migratebelow the stamp (assume_migrated_upto_version, activerecord 8.1.3.1schema_statements.rb:1397-1416). - Fresh
db:schema:load:db:migrate:statusshows both migrationsup, with 0 pending. - Columns present, versions missing:
db:migrateruns both as no-ops and records them. - A database at fork
main:db:migrateadds the columns and constraints and records both. - Empty database with the schema load disabled: all 468 migrations run in order.
- Rails'
- The insurance memo goes stale when
initial_balancechanges: declined, disproved.Loan#insurancecompares its key on every call.initial_balance=clears@original_balance(loan.rb:1272-1277), and the schedule signature includes it (loan.rb:951), so the key changes.- Temporary tests: assigning 24,000 moved
total_insurancefrom 144 to 288, andupdate!to 36,000 moved it from 144 to 432. - The only stale path is
update_columnson the same instance. There, schedule and insurance stay stale together, which is the documentedoriginal_balancememo (loan_test.rb:143-150).
balance_paid_ratioclamps silently: upstream's design (loan.rb:379-386upstream, tested by upstream's "owing more than was borrowed is not negative progress").months_elapsedcounts scheduled dates, not payments: upstream's design. Upstream counts calendar time from origination too; the fork changed only the date arithmetic for loans drawn on the 29th–31st. The quoted "on payment 7 of 12" text doesn't exist.- No upper bound on
insurance_rate: upstream's design. Upstream's validation and database check are the same>= 0.- Decided (owner, 2026-10-11): no fork-only cap. This PR copies upstream as written. The fork caps
interest_rateat 100% in the model andchk_loans_interest_rate_bounds, which upstream doesn't; aninsurance_ratecap would go upstream, where the fork'sinterest_ratecap could be proposed with it.
- Decided (owner, 2026-10-11): no fork-only cap. This PR copies upstream as written. The fork caps
- 4.0 matches two leverage bands: upstream's design.
findreturns the first, and upstream tests that "4x sits on the conservative boundary". scheduled_payment_datesmade public: declined. Making a method public breaks no caller, and this description records it under Engine.- New columns have no indexes: declined. No query filters on them, and upstream's migrations add none.
payment_ratiosconverts to float: upstream's design. It is shown only throughnumber_to_percentage(..., precision: 0).- "of $X" has no context: upstream's design. The partial and the string are upstream's, byte for byte.
- Migrations dated before the schema stamp stay "pending forever": declined, disproved.
-
Nightly review (comment 6120557988), READY WITH CONDITIONS, on
b85b28f: no blocking findings.- MEDIUM, upgrade reconciliation: agreed, and it can't be closed from code or fixtures.
- Already recorded under Risks ("Release effect"):
- Loans whose positive
initial_balancediffers from their first valuation get a new signature and restage, and every figure they show moves. - These are mainly Plaid student loans, Redbark loans, and loans whose balance was edited in the form.
- Loans whose positive
- Before release:
- Prebuild. Use the documented prebuild in
docs/loans/release-evidence.md. #405's version 5 restages every schedule anyway, so the same prebuild covers these loans. - Compare. Pick representative affected loans, meaning those where
initial_balanceis positive and differs from the first valuation. Compare their principal and repayment against a lender statement before and after.
- Prebuild. Use the documented prebuild in
- Not done here: that comparison needs real loan data and statements. No such statement exists in this session.
Review responses are recorded here rather than as comments, because comments posted from this session get an assistant footer appended, which this repository's attribution rule forbids.
Risks, blockers, and follow-up
- Release effect: loans whose positive
initial_balancediffers from their first valuation get a new signature and restage on first view. These are mainly Plaid student loans, Redbark loans, and loans whose balance was edited in the form. Every displayed figure for those loans moves. Compare a statement-backed sample before release (nightly review, above). - Queries: every
amortization_schedulecall reloads the account, and the overview now makes a few more such calls (insurance, total cost, payment breakdown). The pattern predates this; the cost is not measured. - Demo-generator half of #3327: decided, out of this PR.
- The fork's demo loans.
Demo::Generator, taken fork-side in #232/#272, creates them withLoan.new: no rate, term or start date.generate_loan_payments!pays each the same principal and interest split every month: mortgage 600 + 1,100, student loan 350 + 100, car loan 300 + 130. - Upstream's half sets down payment and insurance on schedule-driven demo loans, whose transactions follow their amortisation.
- Why it's separate. Porting it means replacing the fork's demo loan transactions. That is a demo-data change with its own blast radius: the demo tests, every screen built from demo data, and the next weekly sync of a fork-side file. It is not part of re-admitting the loan features, so it belongs in its own issue.
- The two
generator_testskips stay, with their reasons. The owner can overrule this.
- The fork's demo loans.
- Next: #184's remaining phases (the core engine swap stays deferred, per the plan).