Re-admit loan insurance, down payment and repayment progress (#184 phase 2)

Draft
JA
2mo ago
+4688-3636

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_loans and 20260916210100_add_insurance_to_loans, at upstream's versions, with if_not_exists guards (the upstream sync branch carried them before fork main dropped them). db/schema.rb is edited by hand to what the migrations produce; the version stamp stays at 2026_10_08_100000.
  • Model: Loan::Insurance (level-term and decreasing premiums). On Loan:
    • the validations and LEVERAGE_BANDS;
    • #insurance, #total_insurance and #total_cost;
    • #months_elapsed, #remaining_months, #finished?, #remaining_balance_at, #payment_breakdown and #balance_paid_ratio;
    • the donut segments, #initial_leverage_ratio, #leverage_band and #origination_date.
  • Engine: Loan::AmortizationSchedule's four start_date || account_opening_anchor_date reads go through loan.origination_date; scheduled_payment_dates is public.
  • UI: a new LoansHelper with #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_progress partial, and en + fr strings (other locales fall back to English).
  • Upstream's Loan#original_balance: a positive initial_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_test skips 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_payment for fixed loans, the payoff chart, the extra-repayments tab, the retirement planner's loan seed and the amortization_schedule API;
    • 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_balance is memoised, and assigning initial_balance or calling reload drops the memo.
  • amortization_inputs_changed? includes initial_balance, so a new principal queues a schedule rebuild.
  • The Redbark test comment that said original_balance ignores initial_balance is corrected.
  • The signature hashes the amount by value, so a loan whose principal equals its opening valuation keeps its signature (tested both ways); ALGORITHM_VERSION is unchanged.

Departures from upstream, with reasons.

  • origination_date is the start date, else the opening anchor (the fork schedule's anchor). Upstream falls back to the first valuation's date.
  • months_elapsed counts the schedule's own payment dates on or before as_of. Upstream's schedule pays on start >> n; the fork chains next_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_cost uses the schedule's total_cost; upstream calls it total_paid.
  • The overview tab takes as_of as a local (default Date.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 BigDecimal and 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_date was written first. It is proved by M10 instead.

Mutations, each applied, run, then restored from a backup and checked with cmp:

#MutationCaught by
M1original_balance ignores initial_balance10 tests, incl. the principal tests, Plaid and the golden master
M2drop the positive guardthe zero/negative fallback test
M3setter no longer clears the memothe assigning-principal test
M4reload no longer clears the memothe reloading test
M5initial_balance removed from the rebuild callbackthe rebuild-queue test
M6overview passes Date.current to the repayment cardthe view test
M7insurance memo key without the schedulethe memo test
M8decreasing premium charged on the original principal3 insurance tests
M9upstream month arithmeticthe month-end test
M10upstream origin (first valuation)the anchor test
M11card always titled "Total Cost"the controller Total Cost test
M12insurance params not permitted2 controller tests
M13drop the short-schedule guardthe schedule-ended test
M14drop normalizes on insurance typethe 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:

FigureBeforeAfter
Monthly repayment1,798.651,918.56 (= ×320/300)
Total interest348,220.55371,435.23
Payoff date2054-01-152054-01-15 (term-driven)
Projected payoff2053-05-152049-10-15
Projected interest282,141.82237,559.96
current_minimum_payment / planner seed1,798.651,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::Loan components, 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 known Provider::OpenaiTest#test_extra_headers_stringifies_nested_values_Ruby-style (Ruby 3.3 vs 3.4 string, unrelated).
  • bin/rubocop on 15 files: no offenses. bin/brakeman: 0 warnings. erb_lint: 2 errors in _form.html.erb, both on the existing rate-change inputs (missing autocomplete); they are on main too and are not touched here.
  • test/system/loan_overview_test.rb was 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 with origin/mirror/upstream-main:

    1. Migrations dated before the schema stamp stay "pending forever": declined, disproved.
      • Rails' Schema.define records every migration version in db/migrate below the stamp (assume_migrated_upto_version, activerecord 8.1.3.1 schema_statements.rb:1397-1416).
      • Fresh db:schema:load: db:migrate:status shows both migrations up, with 0 pending.
      • Columns present, versions missing: db:migrate runs both as no-ops and records them.
      • A database at fork main: db:migrate adds the columns and constraints and records both.
      • Empty database with the schema load disabled: all 468 migrations run in order.
    2. The insurance memo goes stale when initial_balance changes: declined, disproved.
      • Loan#insurance compares 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_insurance from 144 to 288, and update! to 36,000 moved it from 144 to 432.
      • The only stale path is update_columns on the same instance. There, schedule and insurance stay stale together, which is the documented original_balance memo (loan_test.rb:143-150).
    3. balance_paid_ratio clamps silently: upstream's design (loan.rb:379-386 upstream, tested by upstream's "owing more than was borrowed is not negative progress").
    4. months_elapsed counts 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.
    5. 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_rate at 100% in the model and chk_loans_interest_rate_bounds, which upstream doesn't; an insurance_rate cap would go upstream, where the fork's interest_rate cap could be proposed with it.
    6. 4.0 matches two leverage bands: upstream's design. find returns the first, and upstream tests that "4x sits on the conservative boundary".
    7. scheduled_payment_dates made public: declined. Making a method public breaks no caller, and this description records it under Engine.
    8. New columns have no indexes: declined. No query filters on them, and upstream's migrations add none.
    9. payment_ratios converts to float: upstream's design. It is shown only through number_to_percentage(..., precision: 0).
    10. "of $X" has no context: upstream's design. The partial and the string are upstream's, byte for byte.
  • 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_balance differs 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.
    • 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_balance is positive and differs from the first valuation. Compare their principal and repayment against a lender statement before and after.
    • 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_balance differs 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_schedule call 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 with Loan.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_test skips stay, with their reasons. The owner can overrule this.
  • Next: #184's remaining phases (the core engine swap stays deferred, per the plan).