8000 EPIC-06: units, money and the fuel engine by zakariaf · Pull Request #11 · zakariaf/Odova · GitHub
[go: up one dir, main page]

Skip to content
8000

EPIC-06: units, money and the fuel engine - #11

Merged
zakariaf merged 30 commits into
mainfrom
epic/06-units-money-and-fuel
Sep 4, 2026
Merged

zakariaf merged 30 commits into
mainfrom
epic/06-units-money-and-fuel

Conversation

@zakariaf
@zakariaf zakariaf commented Sep 4, 2026
Copy link
Copy Markdown
Owner

What and why

Odova stores canonical integers and derives everything else. Until this branch the
units lived in the names — odometerM, quantityMl, totalCostMinor beside
currency — and a naming convention was the only thing stopping a metre being added
to a mile or a euro to a yen. This epic builds the value objects, the money
primitives and the whole fuel engine that reads them, then swaps the models onto
them.

Five things worth reading before the file list. Four of them are bugs that existed
and were found, which is the argument for the passes that found them.

lib/core/ is now provably Flutter-free. tools/check_core_purity.sh bans
package:flutter/, package:flutter_, dart:io, dart:ui and package:intl from
the domain layer, and dart test test/core runs the 328-test domain suite on the
plain Dart VM as the other half of the proof. The gate found three real offenders on
its first run: money_format.dart, number_format.dart and unit_format.dart were
in lib/core/l10n/ on the reasoning that they import no Flutter — true, and not the
whole rule. A function that formats has taken a locale as a hidden input, and the
same computation then answers differently in Tehran and Toronto. All three moved.

Two Money types compiled, and both were imported. EPIC-04 wrote
lib/core/money.dart before EPIC-06 existed; its own header said EPIC-06 would
"extend rather than replace" it. EPIC-06 wrote lib/core/money/money.dart instead.
For nine commits the tree held both, with two tables of ISO 4217 exponents four
directories apart, free to disagree — and they were not identical. Which one
shipped depended on which file a caller imported; on a yen amount that is a
hundredfold error with nothing going red. The gate that replaced it then found a
second instance: CalmConsumptionUnit, four values against ConsumptionUnit's six,
with l_per_100km and mpg_imp where SPEC.md §3 says l_100km and mpg_uk.

A mutation found a hole that reading did not. Replacing
moneyOf(row.totalCostMinor, row.currency) in the mapper with a hardcoded 'USD'
passed all 2,304 tests. Every fixture in the suite used EUR, so the stored
currency and a constant were the same value everywhere anybody had looked. The same
technique then found that storing miles in the odometer_m column passed the
structural "no conversion on write" gate too — a conversion written as arithmetic
names no getter, so a grep cannot see it.

consumptionTrend refused every EV and CNG history. The same three-arm
FuelQuantity switch was written four times, and one copy handled only litres. A car
with forty charges logged was told there was not enough data. A second copy,
fuelVolume, added grams into millilitres and returned the total in the first fill's
form — 45.2 L of diesel plus 4,000 g of CNG came back as 49.2 litres, presented as a
fact and indistinguishable from a correct one.

Six of seven refusal types could not be produced, and the seventh lied.
InsufficientData(have: 0, need: 1) stood in for five distinct causes. Its sentence
is "one more full fill", and for a CNG car asked for litres per 100 km no number of
fills will ever produce a litre figure for a vehicle with no tank.
The driver was
being told to keep logging, forever, in a screen that would never change.

And /code-review then found five more, four confirmed by running the code —
including two in the commits above, which is the honest measure of what the second
pass was worth. consumptionTrend proved the fuel forms matched within each window
and never across them, so six charge segments followed by three petrol ones returned
leaner, -40%, comparing watt-hours per metre against millilitres per metre.
ServiceRecord.total reduced with Money.+ and therefore threw on a job
part-billed abroad — a plain getter a list screen reads for every row.
roundHalfAwayFromZero used add-half-then-floor, so 0.49999999999999994 rounded to
1, and returned -0.0 for small negatives, which ICU renders as "-0".
fuelCostPerDistance kept a whole segment's distance while dropping the fills with no
cost row, reading ~40% cheap. The full table is in epics/progress/EPIC-06.md.

Closes

EPIC-06 tasks 1–10 (6.1 … 6.10), complete. 29 commits.

Spec

SPEC.md §2 (Storage is canonical; Derived values are never persisted; Never guess in
a way that looks like fact), §3 (Canonical units, Currency, Display conversion and
rounding, the fuel-segment pseudocode), §12 Ground rules (Money never mixes), §17
(the fuel fixture suite).

One deliberate spec change, and it is the one to read. SPEC.md §3 said
consumptionTrend "compares the mean of the last 3 segments against the 6 before
them" in line 504, "never the mean of per-segment figures" two lines above, and
"everything here is total-over-total" in §13 — about the same function. Two of the
three already agreed with the code. /code-review caught the third as silent drift.

Resolved in SPEC.md in favour of total-over-total, for the reason line 502 already
gives, which applies harder over three segments than over ninety: a 40 km town
top-up at 12 L/100 km beside two 900 km runs at 6.0 is a mean of 8.0 and a
total-over-total of 6.13. The mean reports a 33% rise and tells the driver their car
got thirsty; the truth is 2.2%, inside the ±8% band.
The spec paragraph says what it
used to say and why it changed. The implementation was mutated to the literal "mean"
to confirm the new test distinguishes the two rules rather than passing under either.

Six further decisions the spec does not cover, each written down at the call site as
well as in epics/progress/EPIC-06.md:

  • ServiceRecord.total is a MoneyTotal, grouped by currency — not a Money?,
    and not a sum. Money.+ refuses across currencies by design, which is right for an
    expression a caller wrote and wrong for a getter a list screen reads for every row.
    An empty record gives an empty total rather than a zero: summing nothing has no
    currency, and inventing one would put a euro sign on a Japanese service.
  • OdometerWouldGoBackwards carries Distance, not int. It reaches the UI — §3
    requires the refusal to name the conflicting reading — and a screen must render it
    in the vehicle's unit.
  • A consumptionTrend change of exactly 8% reads as steady, and change is rounded
    to six decimals before the comparison so a float artefact cannot decide a direction.
  • completedMonthsBefore excludes the current month: a month-to-date total beside
    eleven full months is a downward-sloping chart that is not a trend.
  • FuelQuantity.+ throws on a form mismatch and sumOf returns null. A single
    addition of litres to grams is a caller mistake; a mixed list is data — an importer
    landing a bi-fuel car's fills under one fuel_kind — and §3 says the engine discards
    such a segment rather than averaging across two physical things.
  • whyNoSegments orders its five cases by what the user can act on: a data error
    first, then an EV that never marks a charge full, then FirstFill — the only one of
    the five that is not a task. An empty history needs two full fills, not one.

Localisation

No user-visible string is added or changed by this PR, so no ARB file moves. The
three formatters relocated out of lib/core/l10n/ kept their behaviour exactly;
test/l10n/ still asserts SPEC §5's number and money tables by codepoint across
all seven tags, including U+202F for French grouping and U+066B/U+066C for Persian,
and those tests are unchanged apart from the import path and the Money constructor.

Two things here do reach a translator, and both reduce the work rather than adding to
it. formatMoney now reads its decimals from Currency.exponent rather than a second
table, and the refusal vocabulary lost mixed_currency (unproducible — the money
figures group rather than refuse) and gained mixed_fuel_forms,
unit_not_applicable and non_positive_quantity, which are three sentences that can
actually be shown in place of one that could not.

Visual parity

Not applicable — this epic builds no screen. The epic file says so and carries no
calm-visual-parity line. Nothing under lib/ui/ changed except calm_figure.dart,
whose only diff is an import path. When a number from this epic first appears on a
screen, the parity check belongs to the owning screen epic.

Tests

+2,376 green (flutter test), 347 of them also green on the plain Dart VM
(dart test test/core). flutter analyze --fatal-infos --fatal-warnings clean. All
81 gate self-test arms green. flutter build apk --debug succeeds.

Newly pinned:

  • Six policy gates. core_is_pure_test (no Flutter in the domain, and every core
    directory is a named subject — an allowlist, because a blocklist of five words let
    lib/core/util/ through), no_conversion_on_write_test (nothing outside the mapper
    unwraps a value object into a column), no_currency_conversion_test (no exchange
    rate anywhere, no IRT), one_money_type_test (one Money, one exponent table, and
    no wire value declared twice), refusals_are_reachable_test (a declared refusal is a
    promise that something can produce it), value_equality_completeness_test (extended).
  • tools/check_core_purity.sh, in CI's repo job, with six self-test arms —
    it shipped with three, and the two added here were each verified to bind by removing
    the pattern from the gate and watching the arm go red. The
    regen_fuel_vectors --check gate got its two arms the same way, after
    /code-review pointed out I had added a CI gate and no self-test for it in the same
    branch that added six for another one.
  • SPEC §17's fuel fixture suite — ten vectors, regenerable, --check gated in CI,
    ids asserted by name so the suite cannot quietly shrink to nine. It now records
    why each fill was discarded, not just that it was.
  • value_object_mapping_test — all nine row mappers, every field holding a value
    no other field of its type has, and a vehicle's purchase, sale and default prices in
    three different currencies. Ten mutations planted, ten red.
  • unit_preference_test — the behavioural half of "convert on read, never on
    write": every record entered in miles and US gallons, every column asserted equal to
    what went in, and a SHA-256 over every quantity-bearing table before and after every
    unit preference is flipped and flipped back.

Bugs the tests caught while being written rather than after: constants named
microlitresPerGallonUs holding nanolitres (a 1,000× error the name had wrong);
two MoneyTotals that compared equal reporting different dominant currencies; and
including the opening fill's own volume in its segment, an off-by-one that shifts
every consumption figure the app displays.

Three tests were wrong when first written and a mutation caught each: the ordering
test inserted two readings in id order so the third ORDER BY key was never
load-bearing; the wire-value gate accepted only a trailing comma, so it missed the
last value of every enum and reported a planted duplicate as clean; and the digest
test would have passed with a conversion applied uniformly at write time, which is why
it now makes two separate claims.

Deferred

  • Nothing from the epic's task list. All ten tasks are built and their tests pass.
  • /simplify: 21 applied, 2 answered. /code-review: 14 applied, 1 answered. All
    36 are in epics/progress/EPIC-06.md with what was done or why not. The two refusals are on the record there — collapsing
    the golden quantiser onto the display rounding rule looks obviously right and is
    wrong (they disagree at exact decimal ties and nowhere else, so the swap would have
    rewritten every committed vector at the values nobody inspects), and
    Vehicle.tankCapacityMl should become a Volume but in the epic that can pay for
    it, with the line to start from named.
  • SPEC.md §18 question 25 (the two failing Calm light-theme contrast values, plus
    the two dark-theme and one focus-ring failures calm_contrast_test.dart found) is
    untouched and still belongs to EPIC-17. This epic did not make it more expensive: no
    screen was built, so the reference set does not need re-shooting yet.
  • CivilDate is not built, and EPIC-07 thinks it inherits one. EPIC-07's Where
    we are now
    states that EPIC-06 delivered "the zoneless CivilDate with
    calendar-month addMonths". It did not, and its ten tasks never named it — while
    EPIC-07 puts it in the signature of almost every function it specifies. Left to
    EPIC-07 deliberately: it is due-engine infrastructure and the tests that would
    justify its shape all live there. epics/progress/EPIC-06.md carries what EPIC-07
    needs from it and why a DateTime is not it. The other half of that sentence is
    fine — the injected Clock does exist, and EPIC-05 built it.
  • Merge on import stays out of v1 (§2: import replaces). Nothing here approaches it.
  • lib/data/repositories/odometer_fan_out.dart keeps int? odometerM at its own
    boundary rather than taking a Distance. It builds raw SQL against columns, so
    speaking column units there is the honest shape, and the wrap happens where the rows
    come back.

🤖 Generated with Claude Code

https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5

zakariaf and others added 30 commits September 4, 2026 02:50
EPIC-06 task 6.1. `lib/core/` is pure Dart — no Flutter, no dart:io, no
dart:ui, no intl — and the gate found three violations immediately.

`lib/core/ids/id_provider.dart` was a Riverpod provider in the pure core. A
provider there means the core cannot be tested without a ProviderContainer,
which is the opposite of the point. It is DI wiring, so it belongs in
`lib/app/`; the factory it wires is pure and stays.

`number_format.dart`, `money_format.dart` and `unit_format.dart` imported
`package:intl`. EPIC-04 moved them into `lib/core/l10n/` on the reasoning
that they import no Flutter — true, and not the whole rule. A domain function
that formats has taken a locale a
8000
s a HIDDEN input: the same computation answers
differently in Tehran and Toronto. Formatting is a presentation act and they are
back at the edge, each carrying a note saying why.

The intl ban is the one worth having. The other three are obvious the moment
somebody writes them; this is the one added by accident, reaching for a
NumberFormat halfway through a unit conversion.

Four self-test arms, one per ban plus the grab-bag directory — `utils/` is
where a pure core stops being one, because nothing states what belongs there so
everything does. All four seen to fail.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
… thousand

EPIC-06 task 6.2. Distance, Volume, Energy and Mass, each an integer canonical
with double getters used only at the presentation edge.

The canonical units are chosen by what they keep EXACT, and each choice has a
number behind it. Distance is metres because a mile is exactly 1609.344 m:
whole miles are whole millimetres, and metres lose 344 um each — 41 m over
120,000 miles, which is invisible on a dashboard, where centimetres would make
it 41 km. Volume is millilitres because a US gallon is 3785.411784 mL, so whole
litres would round every American fill-up. Energy is watt-hours because a
charging session is quoted to a tenth of a kWh. Mass is grams because CNG is
sold by mass, and a kilogram of compressed gas is a fixed amount of fuel where
a litre of it is not.

The gallon constants were named `microlitresPerGallonUs` and held NANOlitres,
so every gallon reading came out a thousandfold wrong. The test caught it on its
first run: `Volume(3785412).gallonsUs` returned 1.0 where a thousand gallons was
expected. Renamed, with a note recording that the unit in a constant's NAME is
the only thing checking the arithmetic that uses it.

The two gallons are separate constants and the test asserts they DISAGREE: a
50 L tank is 13.209 US gallons and 10.999 imperial ones, and conflating them
puts a 20% error into a consumption figure that looks entirely reasonable.

`FuelQuantity` is sealed over LiquidVolume, GasMass and ElectricEnergy, so
SPEC.md §3's "exactly one of these three is non-null" lives in the type system
rather than in a comment. A switch over it needs no default and a fourth fuel
form is a compile error at every call site.

`test/policy/no_conversion_on_write_test.dart` is the gate for SPEC.md §3's
"convert on read, never on write". A fill-up stored in gallons because the form
was in gallons reads back as litres for the next user, and eight years of
consumption figures are wrong by a factor of 3.785 with nothing to say so.

It fired immediately on `DistanceUnit.km` — an enum value, not a conversion — so
the matcher excludes the unit enums by name, and there is a guard case for that
because firing on them would make the only route to green be deleting the gate.

Two bugs in my own gates, both found by their guard tests: three consecutive
lookbehinds do not compose the way one combined one does, and the
props-completeness parser absorbed an enum declared after a class into that
class's chunk — so DistanceUnit.wire was read as a field of Distance, which is
a false positive on every units file there will ever be.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
EPIC-06 task 6.3. Money is exact, never mixes currencies, and is never
converted.

`Currency` carries the ISO 4217 exponent rather than assuming 100 — which is a
100x error on the yen, with no subunit, and a 10x error on the Kuwaiti dinar,
with a thousand. The table is ISO minor units and deliberately not intl's
`currencyFractionDigits`, which carries CLDR's CASH rounding; the two disagree
on IQD, where CLDR says 0 because Iraqi cash does not circulate in fils and ISO
says 3 because the dinar is divided into a thousand of them. `tryParse` returns
null for anything that is not three letters, because "default to two decimals"
is how a yen amount ends up a hundred times too small.

Adding two currencies THROWS. A screen that adds euros to pounds is wrong in its
own logic, not handling a runtime condition —
`error-handling-typed-results` rule 8 — and mixed totals go through
`MoneyTotal`, which groups. Its dominant currency is the one with the most ROWS,
per SPEC.md §12: a household that logs 400 fill-ups in euros and one repair in
pounds is a euro household, and sorting by magnitude would call it a sterling
one. Ties break on the code, so the screen does not pick a different primary
currency between two launches.

`allocate` is the single largest-remainder primitive every division of money
routes through. 1,200.00 EUR over 365 days is 3.287671 per day; 365 x 3.29 is
1,200.85 and 365 x 3.28 is 1,197.20, and neither is what the user paid. The
parts sum to exactly the whole, asserted over 500 seeded weight shapes. Ties in
the residual break toward the EARLIEST part, stated rather than left to sort
stability — which is not a promise any language makes, and a golden vector would
otherwise be valid on one run and not the next. A negative total allocates too:
a refund spread over a coverage window is the same arithmetic, and refusing it
would push a special case into every caller.

The percentage test is the one worth reading. `allocate` coverage alone does not
catch the two-rounding-sites trap, so the test shows the naive per-part rounding
FAILING beside the correct single rounding — the trap made visible rather than
described.

Three gates: no exchange-rate concept anywhere in lib/, no `IRT` (not an ISO
code; the toman is a display divide-by-ten over a stored IRR amount, and a
non-ISO code in a backup would fail the file's own validation), and no `double`
in any money signature. All three seen to fail, and the rate matcher has a guard
case for the rates this app legitimately has — a daily distance rate, a
consumption rate.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
The props-completeness gate added in EPIC-05 caught this on the first class it
was pointed at. `MoneyTotal` holds two maps — the sums and the ROW COUNTS — and
only the sums were inside equality. `dominantCurrency` reads the counts, so two
totals with identical sums and different row counts compared EQUAL while
answering differently about which currency leads. Every watch stream in the data
layer de-duplicates on that equality, so the change would have been swallowed
and the screen would have kept the old primary currency.

Both maps are now encoded into props as sorted strings. They have to be encoded
rather than listed: a Map in props compares by IDENTITY, so two totals built
from the same amounts would never be equal at all — which is why the gate could
not see them and why the exemption is named per file with the reason rather than
waved through by type.

The test is the two totals side by side: same sums, different counts, different
dominant currency, therefore not equal.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
EPIC-06 task 6.4.

The canonical form is the PAIR — a distance and a fuel quantity — not a ratio,
because the six units are not all the same ratio: four are fuel-per-distance and
two are distance-per-fuel, and storing one and inverting loses precision in the
direction nobody notices.

Every conversion is TOTAL. A zero distance or a zero quantity returns null, not
Infinity: an Infinity that reaches a formatter becomes a very large number on a
screen, and SPEC.md §2 would rather show a dash than a plausible lie. A test
walks every consumption shape against every unit asserting nothing is NaN or
Infinite.

A MISMATCHED pairing is also null, and that is the interesting refusal. Asking
for kWh/100 km from a litre quantity is not a conversion with a small answer, it
is arithmetic on two different things — and CNG has no consumption unit at all,
because it is sold by mass and SPEC.md §3 offers no mass-based unit. Returning a
litre figure there would mean inventing a density.

The MPG conversions are cross-checked against 235.214583 and 282.481, the
standard constants derived from the gallon and mile definitions rather than from
this code — `testing-strategy` rule 3, because checking a function against
itself proves only that it is consistent. And the two gallons are asserted to
DISAGREE by a factor of 1.2, which is the 20% error that conflating them puts
into a figure the user compares between cars.

`ConsumptionUnit.isFuelPerDistance` exists because a chart axis and a best/worst
comparison both need to know which direction is good, and getting it backwards
makes the thirstiest tank the best one.

Rounding is HALF AWAY FROM ZERO, not half-even. Half-even is the better rule for
accumulating statistics and it looks broken to somebody checking a figure
against their phone calculator — 2.5 would round to 2, and the user concludes
the app cannot add up. The test shows both sequences side by side.

And it happens ONCE, from the canonical value. 6.449 to one decimal is 6.4;
rounding to two first gives 6.45 and rounding that gives 6.5. The test asserts
the double-rounded path DIFFERS, so the wrong implementation fails loudly.

Every row of SPEC.md §3's decimals table has a named case. The two that are not
2 are the ones worth having: a unit price is three, because fuel is priced to a
tenth of a cent and two decimals loses the difference between two stations; and
a cost per distance is three, because 0.089 EUR/km must not become 0.09 — a 1%
error in a figure people compare between cars. A segment distance rounds by its
own MAGNITUDE rather than by its field, so 96 km shows a tenth and 1,240 km does
not.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…figure

EPIC-06 tasks 6.5 and 6.6. SPEC.md §3's `buildFuelSegments`, line for line, plus
the sealed refusals that keep a wrong number off the screen.

The line that matters most is `pending = []` after opening a segment. The
OPENING fill's own fuel belongs to the segment BEFORE it, because that fuel
filled the tank for a distance the app knows nothing about. Three full fills at
0 / 600 / 1,200 km with 40, 45 and 50 L give a first segment of 600 km on 45 L,
not on 40. Getting it wrong shifts every consumption figure in the app by one
tank, and the result looks entirely plausible. It has its own named test, and
the mutation was watched go red.

The refusals are typed values, not zeros. `FuelValue` is sealed over `Computed`
and `Unavailable`, so "no number" is something the compiler makes the caller
handle rather than a 0.0 that renders as a figure — SPEC.md §3: a wrong
consumption number is worse than none, because the user will believe it. Seven
reasons, each with a stable code and its own parameters and never a
user-facing string, because the sentence is localised at the presentation edge
in six languages.

Two fills at the same odometer flag BOTH and emit nothing. Only the user knows
which of the two numbers is wrong, and a 0 L/100 km is a number they would
believe. A chain break DISCARDS the segment it would have closed — not averaged,
not pro-rated, because averaging across a gap produces a figure that looks like
a measurement.

Bi-fuel gives two independent series and neither sees the other's fills, so an
LPG fill between two petrol fills is not a petrol chain break.

A volume more than 15% over the tank WARNS and still builds. Some people carry a
jerrycan, and refusing the row would lose a real fill-up to protect a heuristic.
The boundary is strictly over, asserted, because a 57.5 L fill in a 50 L tank is
an ordinary brim-full.

The builder takes CUMULATIVE metres rather than the domain `FillUp`, because the
raw dash number is not comparable across a cluster swap and only the repository
can apply the corrections. It is total: seven mutations were each seen to turn
the suite red, and one of them — the ordering rule — only did so after the test
fixture was fixed. Its ids ran a, b, c, d alongside the dates, so sorting by id
alone gave the same answer; a real ULID is minted when the row is WRITTEN, and a
backdated fill is written last.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…ritten down

EPIC-06 tasks 6.7 and 6.8.

`averageConsumption` is TOTAL OVER TOTAL, and the test is the one that matters:
a 40 km segment at 12 L/100 km beside a 900 km segment at 6 L/100 km. The mean
of the two figures is 9.0 and the true average is 6.26. A mean of means
over-weights the short segment, and for anyone who tops up in town it drifts
several percent high — permanently, in the number they quote when they sell the
car. Five hundred seeded chains are checked against an inline oracle.

`best` and `worst` follow the UNIT's direction. Lower is better in L/100 km and
higher is better in MPG, and getting that backwards makes the thirstiest tank
the best one. They carry the SEGMENT rather than a number, because the UI shows
the closing fill's date beside the figure and a bare double could not say when.

Every refusal is `Unavailable`, never a zero. A zero here renders as
0.0 L/100 km, which is a number the user would believe.

**A spec decision, recorded.** SPEC.md §3 says the trend uses "a ±8% threshold"
without saying whether the boundary is inclusive. Exactly 8.0% is treated as
STEADY and only strictly more alarms, because the rule exists to suppress false
alarms and a rule written to suppress them should not fire at its own edge.

Making that decision testable needed a second one. A change of exactly 8%
computes as 7.999999999999999 in binary floating point, so the boundary was
being decided by where the float landed rather than by the rule — and the
mutation from `>` to `>=` could not be told apart. The comparison now rounds to
six decimal places first: far finer than anything the UI shows, far coarser than
the wobble. With it, the mutation fails as it should.

The direction is computed on the CANONICAL ratio and not on a display unit. In
MPG the sign inverts, and in whatever the user happened to select the verdict
would depend on a setting.

Nine segments is the floor, because the comparison is the last three against the
six before them, and only VALID segments count — a discarded pair is not in the
list, so nine means nine measured tanks and not nine attempts.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
EPIC-06 task 6.9.

Every money figure is a Map keyed by currency, never one scalar. The app has no
exchange rate, so a price per litre that added euros to pounds and divided by
litres is a number with no meaning that looks like a price — and somebody would
compare it between two cars.

`unitPrice` is derived and stored nowhere: SPEC.md §3 has the form take any two
of {total, quantity, price} and compute the third, because storing all three
guarantees a day when they disagree and nobody knows which is the receipt. It
returns minor units per CANONICAL fuel unit — per millilitre, per gram, per
watt-hour — because that is the only ratio that stays exact; the presentation
edge multiplies up and rounds to three decimals.

`avgPricePaid` is total over total, not the mean of the per-fill prices. A 5 L
motorway top-up at 2.00 beside a 60 L supermarket fill at 1.60 has a mean of
1.80 and an average of 1.631, and the second is what the driver paid.

`fuelCostPerDistance` uses exactly the fills whose fuel BUILT each segment.
Including an open, unmeasured tank at the end charges its fuel against a
distance that excludes it, which makes the figure high by exactly one tank and
looks entirely plausible.

A segment whose fills span two currencies is EXCLUDED and COUNTED. It still
contributed its volume and its distance to the consumption figure; only the
money is unanswerable. Counted rather than silently dropped, because SPEC.md §12
wants the data-quality row — "1 tank spanned two currencies, no cost per
kilometre for it" — and a silent drop makes the figure quietly cover less than
the user thinks.

`completedMonthsBefore` is SPEC.md §12's ground rule: on 2 September 2026, "Last
12 months" is 1 Sep 2025 to 31 Aug 2026, and the current month is out of the
numerator and the denominator alike. Including a part-month always reads the same
way — on the 2nd the figure looks great, and by the 28th it has "risen", because
two days of spending were being divided by a whole month. The test asserts the
1st and the 30th give the same answer, which is the whole point.

A zero-quantity fill is skipped in the average rather than contributing its cost
with no quantity, which would raise the price for every other fill in that
currency. An imported row with a missing quantity is exactly how one arrives,
and the mutation was seen to turn the suite red.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
EPIC-06 task 6.10. Ten cases — the nine §17 names plus the total-over-total one
it calls out separately — as a file a reviewer can READ: inputs beside expected
outputs, one entry per case, each carrying a sentence saying WHY it exists.

The ids are asserted BY NAME. Deleting a case from the generator fails that list
rather than quietly running one fewer test, which is how a definition-of-done
gate shrinks without anybody deciding to shrink it.

`tools/regen_fuel_vectors.dart --check` regenerates and diffs, and it runs in
CI. That is the gate that matters: a vector edited by hand to match a bug is
worse than no vector at all, because it carries the authority of a golden file
and the only way to tell is to regenerate. Changing one figure in the committed
file was seen to fail both the check and the suite.

Values are written to six decimals so the file is stable across architectures —
a raw double's last bits differ between them, and the check would then fail for
the machine rather than for the code.

A guard test refuses any vector that pairs a refusal reason with a numeric
value: two contradictory assertions in one entry, where whichever the test
happened to read first would decide the outcome.

The test uses `package:test` rather than `flutter_test`, because
`dart test test/core` runs that directory on the plain VM to prove the domain
needs no Flutter — and the structure gate caught the first version the moment it
was written.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
EPIC-06 task 6.3. SPEC.md §3 Canonical units (Money) and §3 Currency.

EPIC-04 needed an amount before EPIC-06 existed, so it wrote `lib/core/money.dart`:
an extension type over `(int minorUnits, String currency)` with a `double get major`
and its own table of ISO 4217 exponents. Its header said, in as many words, that
EPIC-06 would "extend rather than replace" it.

EPIC-06 wrote `lib/core/money/money.dart` instead — a class over
`(int amountMinor, Currency currency)` that refuses doubles and refuses to add two
currencies. For nine commits the tree held BOTH. Both compiled. Both were imported.
Two tables of currency exponents sat four directories apart, free to disagree, and
which one shipped depended on which file a caller happened to import. On a yen
amount that is a hundredfold error with nothing going red.

So this deletes the older one and moves its four callers onto the real type. The
`double` it offered as `major` moves into `lib/l10n/money_format.dart` as a private
`_major`, because ICU genuinely needs a decimal to place a separator — and because
the moment a value object offers a `double` getter, somebody sums with it. The
projection now lives one step from the pixel, is never stored, and is never read
back.

`test/policy/one_money_type_test.dart` is the gate, and it was seen to fail on both
arms before this: a second `class Money` anywhere under `lib/` fails the first, a
second `'JPY': 0` table fails the second. It was mutation-tested afterwards by
planting each violation again.

The exponent tables were not identical, which is the whole argument. EPIC-04's
carried IRR, AFN, KRW, VND, CLP and ISK; EPIC-06's carries those and the same
twelve dinars. Had a caller imported the wrong one for a currency present in only
one table, the amount would have been right and the decimal point would not.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
EPIC-06 tasks 6.2 and 6.3, final step. SPEC.md §2 Storage is canonical, §3
Canonical units, §12 Ground rules (*Money never mixes*).

EPIC-05 stored canonical integers and put the unit in the NAME: `odometerM`,
`quantityMl`, `totalCostMinor` beside `currency`, `previousM` and `newM`. The
suffix was the only thing stopping a metre being added to a mile, and a naming
convention is not a type. This swaps every one of them for `Distance`,
`FuelQuantity` and `Money`, through the domain models, the pure odometer
arithmetic and the data layer, in one pass.

**The columns did not change.** `lib/data/db/mappers/row_mappers.dart` is now the
only layer that knows both shapes: it joins a fill-up's three quantity columns
into one sealed `FuelQuantity` and splits it back, and it reunites every
`(amount_minor, currency)` pair into one `Money`. Nothing above it can hold half
a price. The schema, the migration steps and the drift snapshots are untouched,
which is why eight years of service history does not care that this happened.

Three things the compiler found on the way through:

`cumulativeByReading` returns `Map<String, Distance>` now, and `OdometerBlocked`
and `OdometerWouldGoBackwards` carry `Distance` rather than `int`. That last one
reaches the UI: SPEC.md §3 requires the refusal to name the conflicting reading,
and a screen that has to format it needs the vehicle's unit, not a bare number of
metres it might render as kilometres.

`ServiceRecord.total` returns `Money?` and is now null for a record with no lines,
where it used to be `0`. Summing nothing has no currency, and inventing one would
put a euro sign on a Japanese service. The schema forbids a line-less record; an
import could still produce one, and SPEC.md §2 says the app never guesses in a way
that looks like fact.

`Vehicle.currency` is a `Currency`, whose only constructor is `tryParse`, so the
two tests that saved a vehicle with the currency `'EU'` to prove the CHECK fires
could no longer be written — the invalid state became unrepresentable. They now
violate `tank_capacity_ml > 0` instead, which is the same shape of constraint and
still reachable, and both say why at the call site.

`test/data/db/mappers/value_object_mapping_test.dart` is new and exists because a
mutation found a hole rather than because anything looked wrong. Replacing
`moneyOf(row.totalCostMinor, row.currency)` with a hardcoded `'USD'` passed all
2,304 tests: every fixture in the suite used EUR, so the stored currency and a
constant were the same value everywhere anybody had looked. It now gives every
field a value no other field of its type has, and prices a vehicle's purchase, its
sale and its default in three different currencies — because SPEC.md §12 says
money never mixes and a mapper that crosses two columns of the same type is
otherwise silent. Ten mutations were planted against it and all ten went red.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…ing did not

The handover the next epic reads. It carries the two things EPIC-06 was asked
to record — the exact FuelValue/ConsumptionUnavailable signatures the due engine
will want to reuse, and the SPEC.md §17 phrase-to-case-id table — plus the four
decisions this epic took that the epic file did not anticipate.

The section worth reading twice is the one about the mapper hole: replacing the
stored currency with a hardcoded USD passed all 2,304 tests, because every
fixture in the suite used EUR. The general form of that lesson belongs to the
screen epics, not to this one, so it is written down where they will read it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
EPIC-06's definition of done asks that "no stored byte changes when a unit
preference changes". SPEC.md §3: convert on READ, never on write.

`test/policy/no_conversion_on_write_test.dart` was the whole answer until now, and
it is a grep: it proves no file under `lib/data/` CALLS a conversion getter. That
is a real guarantee and it is not this one. A conversion can arrive as arithmetic —
`metres * 1000 ~/ 1609344` names no getter — and the gate cannot see it. Planting
exactly that, storing miles in `odometer_m` on every miles vehicle, passed the
structural gate and all 2,308 tests.

So this is the behavioural half, and it makes two claims because one was not
enough:

1. The column holds the CANONICAL value. Every record in the fixture is entered in
   miles and US gallons, and every stored column is asserted equal to the metre and
   millilitre count that went in — with `odometer_unit` and `quantity_unit` asserted
   to still read `mi` and `gal_us` beside them, because the entry unit is provenance
   and is the half that IS allowed to say miles.
2. Flipping every unit preference the app has, and flipping them back, moves no
   byte. SHA-256 over every row of every quantity-bearing table, not a spot check on
   one column.

Claim 2 does not imply claim 1, which is why both are here: a conversion applied
uniformly at write time is present in both digests and cancels. That was verified,
not assumed — the miles mutation above passes the digest test and fails only the
round-trip assertions.

Two guard tests come with it, because a digest computed over the wrong thing equals
itself and reports everything above it as passing: one asserts a single millilitre
moves the digest, and one reads `sqlite_schema` and fails if any table with a
`_m`, `_ml`, `_g`, `_wh` or `_minor` column is outside the hand-written list.

Writing it found two things:

`mustSave` exists because the fixture was silently writing nothing. `Result` makes
that easy to do by accident — an `Err` is a value, not an exception, so an
unchecked `await save(...)` looks like a successful write, and every assertion
below it is then vacuous.

The repositories now share ONE `UlidFactory`, as `providers.dart` wires them. A
separate seeded `testIds()` per repository makes all four generate the same first
id, and the second derived odometer reading collides on the primary key — a failure
that only appears when two kinds of record are written in one test.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
/simplify and the reuse and altitude passes all landed on the same file:
`FuelQuantity` was the only value object in this epic with no arithmetic, so
every caller that needed to add two quantities destructured the sealed type by
hand. `_sum` in `build_fuel_segments`, `_sumQuantities` in `consumption_stats`,
`_ratio` + `_totalOverTotal` in `consumption_trend`, and `_amountOf` + `_rebuild`
in `fuel_money` — about 110 lines answering the same two questions.

Four copies of a rule is four chances to state it differently, and two of them
already had:

**`consumptionTrend` refused every EV and CNG history.** `_totalOverTotal`
handled only `LiquidVolume`, so a car with forty charges logged was told there
was not enough data — the app claiming not to know something it did know, which
SPEC.md §2 forbids more strongly than it forbids being wrong. kWh/100 km is a
shipped consumption unit (§3).

**`fuelVolume` added grams into millilitres.** It summed the canonical integers
across whatever forms it was given and rebuilt in the FIRST fill's form, so
45.2 L of diesel plus 4,000 g of CNG came back as 49.2 litres — a number with no
physical meaning, presented as a fact and indistinguishable from a correct one.
It can arise: an importer landing a bi-fuel car's fills under one `fuel_kind`
produces exactly that list.

So the rule moves onto the type, once. `FuelQuantity` gains `int get amount`,
`FuelQuantity withAmount(int)`, `operator +` and `static sumOf`, and `isZero`
becomes `amount == 0` on the base rather than three overrides.

The two refusals are deliberately different, and the tests say why. `+` THROWS on
a form mismatch, exactly as `Money.+` throws across currencies: a single addition
of litres to grams is a caller mistake and a screen cannot recover from it.
`sumOf` returns NULL, because a mixed LIST is data rather than a bug — the
bi-fuel import above — and SPEC.md §3 says the engine discards such a segment
rather than averaging across two physical things. An empty run is null too:
summing nothing has no form, and inventing one reports zero litres for a car that
runs on electricity.

`fuelSpend` returns a `MoneyTotal` now instead of re-implementing its grouping.
That was the fourth place money could have been summed across currencies by
mistake, and it hands the caller `isMixed` and `dominantCurrency` — the two
things SPEC.md §12's "one figure or a list" decision actually asks, and which a
bare map makes the screen re-derive.

Both new form checks were mutated and both went red.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
Found by the reuse pass over this epic, and it is the same failure as the two
`Money` types two commits ago — which is the point of the commit.

`lib/l10n/unit_format.dart` carried `CalmConsumptionUnit`: four values, against
`lib/core/units/consumption.dart`'s six. Two of the four wire strings disagreed
with SPEC.md §3, which spells the stored vocabulary
`l_100km|km_l|mpg_us|mpg_uk|kwh_100km|mi_kwh` — the Calm copy said `l_per_100km`
and `mpg_imp`. Its `higherIsBetter` had no kilowatt-hour case at all, so it would
have put an EV's best tank at the bottom of a chart axis.

It had no production caller, so nothing had gone wrong yet. What made it worth
finding anyway is that `test/l10n/money_and_units_test.dart` was its ONLY
reference: the wrong spelling was pinned by the suite while nothing exercised the
right one. The first `Settings` writer to import the nearer of the two names
would have written a `consumption_unit` the schema's own CHECK refuses, into a
backup file no other install could read.

Deleted, and its test now asserts SPEC.md §3's six wire values against the real
enum, plus `isFuelPerDistance` on all four interesting cases including the two
electric ones.

The gate generalises rather than naming this enum. `one_money_type_test.dart`
gains a check that no wire value is declared in two files — matched on the
VALUES rather than the type name, because a duplicate never shares the name; it
is the values that collide, and the values are what reach a column and a backup.

Its first version accepted only a trailing comma, so it missed the LAST value of
every enum — and reported a planted duplicate as clean. That is exactly what
CLAUDE.md §4 means by a gate that has not been seen to fail: it was green,
against a tree that contained the thing it was written to find. It now accepts
`,` or `;`, and the planted duplicate goes red.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…h lied

Found by /simplify's reuse, simplification and altitude passes independently —
all three landed on the same file, which is usually the sign that a thing is
actually wrong.

`ConsumptionUnavailable` declared seven cases. Six had no construction site
anywhere in `lib/`. The seventh, `InsufficientData(have: 0, need: 1)`, was
constructed nine times and stood in for five distinct causes — an empty segment
list, mixed fuel forms, a zero-quantity fill, a unit that does not apply, and a
null ratio.

Its sentence is "one more full fill". For a CNG car asked for litres per 100 km
that is not merely imprecise: **no number of fills will ever produce a litre
figure for a vehicle with no tank.** The driver was being told to keep logging,
forever, in a screen that would never change. That is CLAUDE.md rule 7 broken in
the way it is easiest to break — a refusal that is technically typed and
substantively a guess.

Meanwhile the information existed. `buildFuelSegments` knows precisely whether a
fill was discarded for a chain break, a missing odometer or a backwards reading,
and it threw that away into `FuelSegmentSet.flaggedFillUpIds`, a bare
`List<String>`.

So:

`FuelSegmentSet.discarded` is a `Map<String, ConsumptionUnavailable>` and
`flaggedFillUpIds` becomes a derived, sorted getter over its keys — no caller
loses anything and every caller gains the reason. `NonPositiveDistance` carries
BOTH ids on both entries, so a highlighted row can say which other row it
conflicts with; "this reading and the one on 3 September are the same number" is
actionable and "check this fill-up" is not.

`whyNoSegments(fills, set)` answers the screen's actual question, and the order
of its cases is the design: a data error outranks everything because it is what
the user can fix today, an EV that never marks a charge full comes next because
ticking a box is also a task, and `FirstFill` is last because it is the only one
of the five that is not. An empty history needs TWO full fills, not one — a
segment needs one to open it and one to close it, and "one more" would be wrong
on the day a new user logs it.

`MixedFuelForms`, `UnitNotApplicable` and `NonPositiveQuantity` replace the
placeholders. `MixedCurrency` is DELETED rather than wired: the design answer to
mixed currency turned out to be "group, don't refuse" — `fuelSpend` returns a
`MoneyTotal` and `avgPricePaid` a per-currency map — so nothing can produce it,
and carrying a reason the l10n epic must write six sentences for that no code
path emits is worse than not having it.

`test/policy/refusals_are_reachable_test.dart` is the gate: a declared reason is
a promise that something can produce it. It was seen to fail — it named
`FirstFill` and `NoFullCharge` before `whyNoSegments` existed.

Alongside, the second typed-outcome spine goes. `ConsumptionUnavailable`
declared `String get code` — the whole `Failure` contract — without implementing
it, beside a `FuelValue<T>`/`Computed`/`Unavailable` restating
`Result<T, F>`/`Ok`/`Err`. Two vocabularies for "no value, and here is why" means
a screen already switching on a `PersistFailure` writes a second unrelated switch
for a fuel figure, and `fold`/`map` live on only one of them. `valueOrNull` moves
onto `ResultX` beside them.

That also makes honest a promise this branch's progress file had already written:
EPIC-07 can reuse the wrapper with its own reason type. `Unavailable<T>` hardcoded
`ConsumptionUnavailable`, so it could not.

The golden vectors are regenerated and now record WHY each fill was discarded, not
just that it was. Two vectors changed answer, both correctly: `chain_broken` and
`missing_odometer_import` flagged nothing before and now name the fill.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…eir jobs

/simplify's four passes turned up the same class of problem in four places: a
gate that is green against a tree containing the thing it was written to find.

**`check_core_purity.sh` bans five prefixes; the self-test planted three.**
`dart:ui` and `package:flutter_` were never planted. CLAUDE.md §4: a gate that
has only ever been green is a comment. Both are now planted, and both were
verified to bind by removing the pattern from the gate and watching the arm go
red. `dart:ui` is the one that mattered most — it compiles fine under
`flutter test` and dies only under `dart test test/core`, which is the lane it
exists to protect.

**`no_currency_conversion_test`'s guard-the-guard checked a copy.** The banned
patterns were local to the first test and RETYPED as literals in the self-test.
Editing the real map left the guard green against the old copy — the exact
failure a guard-the-guard test exists to prevent. Hoisted to one top-level map
that both read; weakening one pattern now fails the self-test, verified.

**The core-purity rule was stated three times and the copies disagreed.**
`structure_test.dart` checked three of the five prefixes against UNSTRIPPED
source, so a doc comment naming `dart:ui` in order to explain why the core does
not use it false-positived there and not in the newer test. Deleted, with a
pointer to the two places that own it: the Dart test (all five, comments
stripped) and the shell gate (the same five, in the toolchain-free lane).

**The grab-bag check was a blocklist, and `lib/core/util/` walked through it.**
Singular. So did `support/`, and `lib/`. The failure the rule exists to prevent
is not the word "utils"; it is a directory nobody had to name the subject of,
and only an allowlist asks that question. `lib/core`'s nine subjects are now
listed with what each holds, and both directions are checked — an unnamed
directory fails, and so does a name left behind after its directory goes.

Also in `check_core_purity.sh`: `for f in $files` split on whitespace, so a path
containing a space became two paths that do not exist and the gate silently
checked fewer files than it reported. NUL-delimited now. The pattern loop moved
inside the file loop while fixing it, which strips each file once instead of five
times — 37 subshells instead of 370.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
/simplify's efficiency pass, applied. None of these change an answer; all four
are on paths that scale with a ten-year history, which is the size this app is
designed for.

**A RegExp compiled on every `Currency.tryParse`.** That is the hottest read
path there is: `row_mappers` calls it for every fill-up, expense, service line
and vehicle, and drift's stream invalidation is TABLE-level, so the whole query
re-maps on every write. A thousand fills meant a thousand regex compiles per
emission. Hoisted to a top-level `final`.

**`checkReading` sorted the same list twice.** `cumulativeByReading` sorts
internally and the neighbour lookup sorted again — four list copies and two
full sorts of the vehicle's entire reading history, on every fill-up, service,
expense and trip save. The path a user is standing at a pump waiting for.
`cumulativeBySorted` is split out and `checkReading` sorts once.

**And `OdometerRepository` sorted a third time, over rows SQL had already
ordered.** The query ordered by `(occurred_on, created_at_utc_ms)` and
`compareReadings` adds `id`, so the repository re-sorted to get the third key.
The query now has all three and nothing above it re-sorts.

That introduces an invariant — SQLite compares TEXT with memcmp on UTF-8 and
Dart's `compareTo` uses UTF-16 code units — so it is asserted rather than
commented. They agree because every key here is ASCII (a ULID is Crockford
base-32, a date is digits and hyphens), and the test writes four readings that
exercise all three keys.

**That test was wrong the first time and a mutation caught it.** It inserted the
two same-date, same-created-at readings in id order, so SQLite's rowid order and
`compareReadings` agreed by accident and removing `r.id` from the query left it
green. It now inserts them in the OPPOSITE order, where only the id can
separate them, and the mutation goes red.

**`bestSegment`/`worstSegment` sorted everything to read one element.** Called
twice per screen, so a ten-year history was two full sorts of ~900 segments for
two answers. A `reduce` with the identical comparator — same tiebreak, same
determinism, verified by reversing the tiebreak and watching the vectors go red.

**`MoneyTotal.props` sorted two maps on every access**, and `props` is read by
both `==` and `hashCode`, so one comparison between two totals was four sorts
and four lists of interpolated strings. Computed once in the factory now, which
matters because this type is headed for a `.distinct(valuesEqual)` on a watched
stream.

Also: `allocate` copied a list it was about to sort and never read again, and
`check_core_purity.sh` ran 370 subshells where 37 do — the pattern loop was
outside the file loop, so each file's comments were stripped five times.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
The last of /simplify's findings, all of them small and all of them the same
shape: a thing the epic built, sitting beside four copies of what it replaces.

`test/support/values.dart` exists so a fixture stops writing
`Currency.tryParse('EUR')!`. Four of the newest test files declared their own
`Currency get _eur` anyway — `money_test`, `money_total_test`, `allocate_test`
and `fuel_money_test`, nine getters between them. They import the helper now.

`Distance.fromKm` exists and is `const`. Four test files wrote
`const int _km = 1000` and multiplied. The remaining `_km` uses are genuine
metre-typed record fields (`FillUpPoint.cumulativeM`), which is a different
thing and stays.

`segmentConsumption(segment)` was a top-level function returning
`segment.consumption`, whose only caller was its own test. A second name for one
idea, in a public API somebody has to document and keep.

The rounding one is different and worth reading. The generator and the vector
test each declared a character-identical `_round`, and the reuse pass proposed
collapsing them onto `roundHalfAwayFromZero` — while noting the two might not be
equivalent at ties. They are not: `0.1234565` quantises to `0.123456` through
`toStringAsFixed` and rounds to `0.123457` through the display rule, and across
200,000 seeded values they disagree only there. So the swap would have silently
rewritten every committed vector, at exactly the values nobody checks.

One definition now, in `lib/core/rounding/` and named `quantiseForGolden` so it
cannot be mistaken for the display rule, with a doc that says which to use for
what — and `rounding_test.dart` PINS the difference at four ties, so the next
person who notices the resemblance finds a test explaining why they are separate
instead of a green suite after a refactor.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
/simplify's altitude pass, and it is the sharpest finding of the set: the claim
this epic makes in `row_mappers.dart`'s own header — that it is the only layer
which knows both shapes — was true on read and false on write.

`moneyOrNull` refuses to build half a price. An amount without its currency is
not a smaller amount, it is an unknown one. And then FORTY sites across five
repositories unwrapped `.amountMinor` and `.currency.code` straight into
companions, where writing one without the other compiles and produces a row
nothing above the mapper can read back.

So the write direction gets the same treatment the three fuel-quantity columns
already had: `amountMinorColumn`/`currencyColumn`, `metresColumn`, and their
`OrNull` pairs — nullable and non-nullable in pairs, because a `NOT NULL` column
and a nullable one are different columns and the type should say which.
`no_conversion_on_write_test.dart` gains the gate: outside
`lib/data/db/mappers/`, nothing unwraps a value object into a column. Zero raw
unwraps remain, and planting one goes red.

**The public/private mapper split was accidental, and it had a cost.** Nine
`Row -> Model` functions, none of which touched `this`. Four were public in
`row_mappers.dart`; five were private methods on whichever repository happened
to grow first — `_expenseFromRow` beside a public `fillUpFromRow` of exactly the
same shape, in a different file, for no reason anybody chose.

That mattered because `value_object_mapping_test.dart` exists precisely because
a hardcoded `'USD'` in a mapper passed 2,304 tests, and the five on the other
side of the split were unreachable from it — including `serviceLineFromRow`,
which carries the price of a service line. All nine are in the mapper now and all
nine are covered: an expense's own currency, a trip's three independent
distances, a service line's price, a service item's four metre columns and the
settings row. Five mutations planted across them, five red.

While wiring the gate it found a third thing. `test/support/source_tree.dart`
says it skips generated code by reading `analyzer: exclude:` — and it honoured
only the DIRECTORY globs. `**/*.g.dart`, `**/*.freezed.dart` and
`**/*.drift.dart` are suffix globs in that same list, so every grep gate that
walks `lib/` has been reading `app_database.g.dart` and reporting generated code
as source. `excludedSuffixes` closes it, and removing it again fails the new
gate.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
The last two findings from /simplify's altitude pass, both small and both the
same shape: a thing in the wrong place because of who called it first.

`ConsumptionUnit.isElectric` had zero production callers. The pairing it
described — a litre figure on an EV and a kWh figure on a diesel are both
nonsense — was already enforced one file away, in `asUnit`'s exhaustive switch
over the sealed `FuelQuantity`. That is strictly stronger than a predicate: a
seventh unit is a COMPILE error in the switch and a silent `false` in the
getter. Deleted, and its test replaced with the rule it described, asserted on
`asUnit` in both directions.

While there, `asUnit`'s `ElectricEnergy` arm caught its four inapplicable units
with a `_ => null` wildcard where the `LiquidVolume` arm lists them. Listed now,
so a seventh unit is a compile error in both arms rather than one.

`completedMonthsBefore` moves from `lib/core/money/` to `lib/core/time/`. There
is no money type anywhere in the file — it is `DateTime` in and `YYYY-MM-DD`
out. It landed under money because its first caller was a cost figure, and
EPIC-07's due engine needs the same month-boundary arithmetic for
`interval_months`. Two implementations of "when does a month end", in an app
that has an OPEN QUESTION about whether `ckb-IR` defaults to the Jalali calendar
(SPEC.md §18), is a bug waiting for a Persian user. One file move today; two
implementations after EPIC-07.

`time` is now the tenth name in `core_is_pure_test.dart`'s allowlist of core
subjects, which is exactly the moment that allowlist exists to create: somebody
has to say in one line what the directory holds.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…fused

CLAUDE.md: findings are applied or answered, and silently dropping one is not
an option. Twenty-one applied, two answered.

The two answers are the ones worth having on the record. Collapsing the golden
quantiser onto the display rounding rule looks obviously right and is wrong:
they disagree at exact decimal ties and nowhere else, so the swap would have
rewritten every committed vector at precisely the values nobody inspects. And
the tank-capacity value object is a real finding handed to the epic that can pay
for it, with the line to start from named, rather than done badly here.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
EPIC-07s "Where we are now" states that EPIC-06 delivered "the zoneless
CivilDate with calendar-month addMonths clamping to the last day of the target
month". It did not, and it was never asked to: CivilDate appears nowhere in
EPIC-06s ten tasks, its "What we will have", or its definition of done. EPIC-07
then puts it in the signature of almost every function it specifies.

The other half of that sentence is correct -- the injected Clock does exist, and
EPIC-05 built it.

Rather than build a type this epic has no test to justify the shape of, the gap
goes in the handover with what EPIC-07 actually needs from it and why a DateTime
is not it: this epic hit the local-time daylight-saving bug in monotonicity.dart
and routed around it through wholeDaysBetween, and the due engine divides by
days far more often.

lib/core/time/ is already the named subject for it, which is half the reason
completed_months.dart moved there.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
EPIC-06s definition of done reads "every division of money goes through
allocate()", and unitPrice divides money and does not. Checking that claim while
preparing the PR, the code was right and the reason was only in my head.

allocate SPLITS a total into parts that must sum back to it, where the residual
has to go somewhere and largest-remainder decides where. A unit price is a RATE:
nothing sums back, there is no residual to place, and routing it through a
splitter would be asking for something allocate does not compute.

A reviewer reading the definition of done and then this line deserves the
distinction at the line, not in a PR description they will not have.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
/code-review, confirmed by running it. `roundHalfAwayFromZero` computed
`(scaled.abs() + 0.5).floorToDouble()` — the classic add-half-then-floor defect,
sitting under a doc comment explaining that the explicit form was safer than
Dart's own `round()`.

`0.49999999999999994` is the largest double strictly below one half. Adding 0.5
to it TIES in binary and lands on exactly 1.0 before floor ever sees it, so the
function answered 1 for a number that is not half. `(0.49999999999999994).round()`
answers 0, which is correct, and Dart's `round()` is already half-away-from-zero:
`(-2.5).round()` is -3. The comment claimed not relying on that "survives
somebody swapping in a different rounding call"; what it actually did was
reintroduce the bug it was avoiding.

Reachable at every zero-decimal call — `Decimals.odometer` and
`Decimals.percentage` are both 0 — where a derived value just under a half
rounded up. `rounding_test.dart` pinned 2.5, -2.5, 0.05 and 6.449 and never a
value in that band, which is exactly why a test suite full of round numbers does
not find a floating-point bug.

Second defect in the same two lines: it returned NEGATIVE ZERO for any small
negative. `(-0.4)` gave `-0.0`, and ICU renders that with a leading minus, so a
refund-driven cost per kilometre of -0.0004 came out as "-0.000 EUR/km" and a
-0.04% change as "-0%". SPEC.md §3's rule is half away from zero on the absolute
value; zero has no sign to carry away from it. Going through `int` rather than
`roundToDouble()` has no negative zero, and the final divide is guarded because
`-0.0 / 100` is `-0.0` again.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…40% leaner

/code-review, applied. Five defects, two of them in code this epic's own commits
added to fix exactly this class of thing.

**`consumptionTrend` compared two windows it never proved comparable.**
`_totalOverTotal` runs per window and checks the forms match WITHIN each — and
nothing across the seam. Six charge segments followed by three petrol ones passed
both checks and produced `TrendDirection.leaner, -40%`, comparing watt-hours per
metre against millilitres per metre. A range-extender EV, or a bi-fuel car an
importer landed under one `fuel_kind`, is exactly that list. Confirmed by running
it. The whole nine-segment window is checked once now, before it is cut in two.

**`ServiceRecord.total` threw on a record billed in two currencies.** It
`reduce`d with `Money.+`, which refuses across currencies by design — right for
an expression a caller wrote, wrong for a plain getter a list screen reads for
every row: a job part-billed abroad crashed the screen instead of showing what is
known. It returns a `MoneyTotal` now, like `fuelSpend`, `avgPricePaid` and
`fuelCostPerDistance` already did. The suite missed it because every fixture used
euros — the same blind spot the mapper mutation found two commits earlier, in a
different file.

**The discard branch reported an odometer conflict for three unrelated causes.**
The guard was `distance > 0 && quantity != null && !quantity.isZero` and the else
built `NonPositiveDistance` for all of it. A fill saved with 0 mL between two
correct readings 600 km apart told the user "these two readings are the same
number", sending them to check two odometers that are right.
`NonPositiveQuantity` and `MixedFuelForms` were in the sealed set the whole time
and the builder constructed neither — `refusals_are_reachable_test` passed only
because `unitPrice` happens to construct one elsewhere, which is a hole in that
gate as much as in this code. Three branches now, and a zero-quantity fill names
ITSELF rather than its innocent neighbour.

**`_rank` had the same conflation.** `asUnit` returns null for a form/unit
mismatch AND for an unmeasurable segment, so a diesel car whose segments all had
zero distance was told litres per 100 km does not apply to it.

**`fuelCostPerDistance` understated a segment missing some of its costs.** The
numerator dropped the fills with no cost row and the denominator kept the whole
segment distance — a 600 km tank whose middle top-up was saved without a total
read about 40% cheaper per kilometre. A partial cost is not a smaller cost, it is
an unknown one, which is the argument `moneyOrNull` already makes about half a
price. Excluded and COUNTED now, beside the mixed-currency case; a segment with
no costs at all used to `continue` with no counter, so SPEC.md §12's data-quality
row said nothing had been left out while a tank had been.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
…other

/code-review found the code diverging from SPEC.md §3 line 504 — "compares the
mean of the last 3 segments against the 6 before them" — while
`consumptionTrend` computes each window total-over-total. CLAUDE.md §3: the spec
is right until a deliberate PR changes it, and drifting silently is not an
option. This is that deliberate change, and it also resolves a contradiction the
spec already had.

§3 line 502, two lines above: "The lifetime average is a total-over-total, never
the mean of per-segment figures. A mean of means over-weights a 40 km segment
against a 900 km one." §13 *The numbers, exactly*: "Segments, partial fills and
consumptionTrend come from the domain model... Everything here is
total-over-total." Line 504 said mean. Two of the three already agreed with the
code.

Total-over-total wins, for the reason line 502 itself gives — which applies
HARDER over three segments than over ninety. A 40 km town top-up at 12 L/100 km
beside two 900 km runs at 6.0 is a mean of 8.0 and a total-over-total of 6.13:
the mean reports a 33% rise and tells the driver their car got thirsty, and the
truth is a 2.2% rise, inside the ±8% band. One short tank must not be a third of
the answer, and SPEC.md §2 rates a wrong figure worse than none because the user
will believe it.

The paragraph in the spec says what it used to say and why it changed, so the
next reader finds the decision rather than a discrepancy.

The test pins the numbers above, and the implementation was mutated to SPEC's
literal "mean of the last 3" to confirm the test distinguishes the two rules
rather than passing under either.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
The rest of /code-review, applied.

**`dart run tools/regen_fuel_vectors.dart --check` shipped with no self-test
arm.** I added the CI step and six arms for `check_core_purity.sh` in the same
branch, and zero for this one — CLAUDE.md §4 in the plainest possible terms: "a
gate that has only ever been green is a comment". Two arms now, both seen to
fail: one digit changed by hand in a committed vector, and a whole case deleted
from the fixture. The second is the shape people actually reach for when a
golden file starts failing.

**The exponent table's comment claimed IQD was its only departure from ISO
4217.** AFN is a second one, in the opposite direction: ISO assigns the afghani
exponent 2 (100 pul), CLDR says 0, and this app says 0 because the pul has not
circulated for decades and SPEC.md §5 ships `fa-AF`. EPIC-04's table carried that
sentence; EPIC-06 deleted that file and dropped the sentence with it, leaving a
row that read as an oversight under a header saying the opposite.

That matters more than a comment usually does, because the exponent drives BOTH
`minorPerMajor` and the formatter's decimals — so anybody "correcting" the table
to match its own stated contract silently reinterprets every stored AFN amount by
a factor of a hundred. The header now names both departures and says so, and
`money_test.dart` pins both values with the reason.

**`FuelSegmentSet.props` was rebuilt and re-sorted on every read** — the exact
cost `MoneyTotal` was refactored away from four commits earlier, in a type headed
for the same watched stream with a segment per tank over ten years. Computed once
in a factory now, with `flaggedFillUpIds` cached beside it.

That makes five of its fields exempt in the props-completeness allowlist, and an
allowlist entry is a promise rather than a proof — so four tests prove the
encoding instead. Writing them, a mutation caught one of my own: the
"different reason" test compared two runs that flag DIFFERENT id sets, so the ids
alone separated them and dropping the reason objects left it green. It now
compares a chain-broken fill against one with no reading, which flag the same
single id and differ only in why.

**`MoneyTotal`'s factory re-parsed each code back into a `Currency`** to index
the two maps it had just built — twice per currency, and with a nullable key, so
a `tryParse` failure would have interpolated "null" into the equality encoding
rather than failing. It sorts the entries directly now.

**The vector generator's `_averageJson` took `List<dynamic>` and cast**, in the
one file whose output CI then blesses as authoritative.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
Fourteen applied, one answered. Four were verified by running the code rather
than reading it, and five were wrong answers a user would have believed -- a
trend comparing watt-hours against litres, a total that threw on a job billed
abroad, a cost per kilometre 40% low, and a rounding function that rounded a
value below one half up to one.

Two of them were in code this epic added two commits earlier to fix exactly that
class of thing, which is the honest summary of what the pass was worth.

The answered one is tankCapacityMl, named independently by both review passes.
Two reviews reaching the same finding is a stronger signal than one, so it moves
out of a findings table and into the deferred list with the line to start from.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
CI caught this on the first push, which is the right outcome and an
uncomfortable one: the arms I added for the regen_fuel_vectors --check gate went
into check_gates_selftest.sh, which runs in the toolchain-free repo job.

dart is not on that PATH. Both arms expecting a RED exit passed -- on 127,
"command not found" -- while the two expecting green failed. The gate had never
run and half the output said it had. That is precisely the failure the self-test
apparatus exists to prevent, reproduced inside the apparatus.

Two changes. The arms move to tools/check_vectors_selftest.sh, run in the app
job beside the gate itself, which is where check_numeric_input_selftest.sh
already lives -- the precedent was there and I did not follow it.

And assert() now treats 126 and 127 as a FAILURE whatever the expectation, with
the reason written at the line: "not runnable" is not "the gate said no". Any
future arm placed in a lane without its toolchain now fails loudly instead of
reporting a gate seen to fail that never executed. The guard was verified
against a missing command.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FJWFfVyw9Wxbn5FuFRBbY5
@zakariaf
zakariaf merged commit c1ce8e4 into main Sep 4, 2026
4 checks passed
@zakariaf
zakariaf deleted the epic/06-units-money-and-fuel branch September 4, 2026 04:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

0