Commit Graph
62 Commits
Author SHA1 Message Date
Lucas WintherandClaude Opus 5 e6da85e7f9 fix(sw): the service worker had never installed, and updates raced the reload
Two defects behind "the new version is ready" not going away.

1. THE WORKER NEVER INSTALLED — in any environment, ever.

   install did `cache.addAll([...PRECACHE, SHELL])`. PRECACHE is derived from
   the build's own outputs, which already contain index.html, and SHELL is
   index.html again. addAll() rejects the ENTIRE install on a duplicate
   request:

     InvalidStateError: Cache.addAll(): duplicate requests (.../index.html)

   So install failed on every load, the worker went redundant, and nothing
   ever activated. Registration itself succeeds and the failure is inside the
   install event, so nothing surfaced it — which is why offline behaviour was
   listed as "never verified" rather than "broken". All 11 precached URLs
   return 200; the list was the only fault. Deduping now lives in
   src/swPrecache.ts, at the point of use, so no future addition to either
   list can reintroduce it.

   Verified in a real browser for the first time: the worker installs,
   activates, claims the page, and caches 11 entries. A rebuild is then
   detected, the prompt appears, clicking Reload applies it, stale caches are
   dropped and the prompt does not return.

2. THE DEV WORKER IGNORED THE LIFECYCLE — my own regression, from 53707b1.

   That commit made the dev server serve an inert sw.js to silence a MIME
   error. Inert included the lifecycle: no skipWaiting, no clients.claim, no
   message handler. A worker like that can sit in `waiting` forever and can
   never be applied, so the prompt returns on every load and the Reload button
   cannot possibly clear it. This is the likeliest cause of the reported
   symptom, since with defect 1 a production build could never have shown that
   prompt at all. The dev worker still caches nothing — that would fight HMR —
   but now honours install, activate and SKIP_WAITING.

3. applyUpdate RACED ITS OWN RELOAD — real, measured, but not reproducible on
   demand, so it is hardening rather than a proven fix.

   It posted SKIP_WAITING and called window.location.reload() on the next
   line. Measured in Chrome: at that instant the new worker was still
   `installed` and the controller had NOT changed — it changed 2 ms later. The
   window is wider in practice because activate deletes every stale cache
   before claiming clients. When the reload wins, the reloaded page still finds
   registration.waiting and shows the prompt again. It now waits for
   controllerchange, with a timeout backstop so a worker that ignores
   SKIP_WAITING cannot leave the button dead. The sequencing is pure and
   tested (src/ui/swUpdate.ts): listener attached before the message, reload
   exactly once, unsubscribed after.

Tooling: scripts/screenshot.ts gains --profile (a fresh Chrome profile has no
registered worker, so nothing stateful across loads could be reproduced at all)
and --eval-after-file (observe a flow that ends in a navigation from the other
side of it).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 15:28:06 +02:00
Lucas WintherandClaude Opus 5 5a0fd26008 docs: TODO reflects sections 2 and 4 done, section 3 one of four in
Records the redesign decomposition and its diagnosis, so whoever picks up
sub-project 2 starts from why the old design was bypassed rather than
rediscovering it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 15:15:29 +02:00
Lucas WintherandClaude Opus 5 a159189b01 feat(ui): group a month's purchases under date headings
The density the owner chose. Newest day first, weekday named because that is
what a person recognises, and order within a day preserved so a row just
entered stays where it was put.

Two cases the obvious implementation gets wrong, both tested:

A finance plan's later slices belong in this month — money moves this month —
but the purchase's own date does not. Filing them by date would have put
"14 August" inside the September list, so they group separately, last, under
"Financed from earlier months".

A purchase date may legally be "YYYY-MM" with no day at all, which gets its
own trailing group rather than a heading reading "NaN".

The weekday is computed in UTC on both ends. `new Date("2026-09-01")` parses
as UTC midnight, so `getDay()` anywhere west of Greenwich reports the previous
day and every heading would be wrong by one for the user. A test pins three
timezones.

Trade-off worth stating: headings cost vertical space on a day with a single
purchase, and only pay for themselves when a day has several. PRODUCT.md says
the owner records in batches — "a grocery trip is twenty lines entered in one
sitting" — so real data should sit on the paying side of that.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 15:14:52 +02:00
Lucas WintherandClaude Opus 5 d8ee579fe7 docs: spec for the design foundation, with the alternatives rejected
Records why the brand teal is --primary rather than --accent, why @font-face
cannot live in the bundled stylesheet (measured: 70 KB -> 303 KB of
render-blocking bytes, and unicode-range subsetting defeated), why the theme
preference is not in the dataset, and the carry-meter regression that earned
the undefined-token guard.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 15:12:35 +02:00
Lucas WintherandClaude Opus 5 bb3c661ef6 feat(ui): design foundation — two themes, shipped type, one card
Sub-project 1 of the redesign. The diagnosis that shaped it: a design system
already existed and was never wired up. src/index.css defined --paper, --ink
and a muted teal with a contract document behind them, while the app painted
itself with shadcn's default white and near-black. Those tokens reached the
screen in exactly two places — the carry meter and the +/- number colours.

TOKENS. Two layers: --budget-* is the app's own vocabulary, defined once per
theme, and shadcn's whole variable set points at it, so every primitive
inherits both themes rather than being fought. Light is cool paper with ink
navy; dark is deep slate, never pure black, because a black ground makes the
hairlines and the carry meter float.

The brand teal is --primary, NOT --accent. That is precisely what the old bug
got wrong: shadcn's --accent is a subtle hover BACKGROUND paired with
--accent-foreground, so a saturated colour there turns every hover into a
coloured slab with unreadable text. src/cssPairs.test.ts now makes the rule
mechanical — redefining either half of a shadcn pair without the other fails
the build, in any block.

CONTRAST was computed, not eyeballed: the weakest text pair is 5.50:1 against
a 4.5:1 requirement, and field borders clear the 3:1 non-text requirement on
both of their backgrounds. Verified afterwards by reading the tokens back out
of the live browser in both themes rather than trusting the arithmetic.

TYPE. Inter and JetBrains Mono, self-hosted (SIL OFL, licences committed
alongside), latin + latin-ext only. Not in index.css: Bun's CSS bundler
resolves every url() from disk and inlines woff2 as base64 — relative or
absolute, and a "file" loader override does not stop it — which made the
stylesheet 303 KB of render-blocking bytes and defeated the unicode-range
subsetting entirely. They are injected at boot from one definition instead,
which is the only arrangement identical in dev and in a subpath build.

THEME TOGGLE cycles system / light / dark, remembers the choice in
localStorage (a per-device display preference does not belong in the exported
budget), keeps following the OS while set to "system", and is applied by a
tiny inline script before first paint so a dark-theme user never sees a white
flash. Every storage access is wrapped: localStorage throws outright in some
configurations, and a theme preference must never stop the app booting.

A REGRESSION I CAUSED AND CAUGHT: renaming --rule to --budget-rule silently
killed the carry meter. An undefined custom property inside linear-gradient()
does not warn, does not throw and does not fall back — the declaration is
invalid, so the element paints nothing. It looked like a missing feature. Only
pixel-sampling a screenshot found it. src/ui/cssTokens.test.ts now fails if any
TypeScript file references a token src/index.css does not define.

Also: one Section/Stat card treatment applied across month, year, summary and
settings; quiet uppercase table headers; row hover; the rule-editing and
purchase-row actions revealed on hover instead of six always-on links; a scroll
fade on the year matrix so it reads as "more to come" rather than clipped; and
"September 2026" instead of "2026-09" as the month heading.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 15:11:43 +02:00
Lucas WintherandClaude Opus 5 11e9405203 fix(ui): make the year matrix readable
Found by screenshotting it. 13 numeric columns of "28,000.00" in a mono face
cannot fit in min-w-[48rem], so the table shrank the cells instead of
scrolling and the figures ran together: the income row read
"28,000.0028,000.0028,000.00", the total read "0.000.00248,500.00", and
columns 11 and 12 were crushed to nothing. Every cell now has horizontal
padding and cannot wrap, and the table is wide enough that the container
scrolls rather than crushing.

Verified by screenshot at 1440px: every figure separated, columns aligned.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:48:57 +02:00
Lucas WintherandClaude Opus 5 53707b14ca feat(tooling): drive headless Chrome, and see the app for the first time
CLAUDE.md, AGENTS.md, ARCHITECTURE.md and TODO.md all said no browser exists
in this environment, so appearance had never been verified by anyone. Chrome
is on PATH. Its own --screenshot flag is what fails: it fires on the load
event, before this app's async IndexedDB read resolves, and captures a blank
page — which is presumably how the claim took hold.

scripts/screenshot.ts drives CDP instead: waits past the load event, seeds
IndexedDB via --eval-file and reboots the app with --reload, clicks with
--click, applies shadcn's class-based dark palette with --dark, and reports
console errors and uncaught exceptions. A page that renders blank from a
thrown error looks identical to an empty one, so the console output is half
the value.

Two defects found by simply looking:

- The month table's numeric columns had no horizontal padding, so figures ran
  into each other: "+7,175.00 DKK4,200.00 DKK". Now padded.
- Dev logged "The script has an unsupported MIME type ('text/html')" on every
  boot, because registerServiceWorker asks for sw.js and the "/*" catch-all
  answered with the HTML shell. Dev now serves an inert worker.

Confirmed working, first time seen: the carry meter (including red where a post
is overspent), the Task 5 rule-history editor, the Task 6 "change from here"
control, and baked FX rates showing as "manual - 2026-09-01" in Settings.

Recorded in the docs, with the limits stated: this container's fontconfig maps
every generic family to a monospace face, so screenshots need a FONTCONFIG_FILE
override or you will chase a font bug that does not exist; Chrome starts from
an empty profile each run; and no screenshot can judge how a design feels.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:46:59 +02:00
Lucas WintherandClaude Opus 5 b4e1933761 feat: bake FX rates in at build time so a fresh install can convert
TODO section 2, designed and approved, now built. A brand-new dataset arrives
with DKK/USD/EUR rates instead of erroring on the first EUR purchase.

build.ts fetches at build time and embeds the result via `define`. A network
failure does NOT fail the build — it bakes committed constants instead, and an
incomplete response is treated as a failure too, since one unconvertible
currency is the problem this solves. Fetched rates carry source "api" and the
BUILD date, which is why parseFxResponse now takes an explicit updatedAt; the
constants carry source "manual" and their own date, so Settings never claims a
hardcoded number came from a rate service. SKIP_FX_FETCH=1 and FX_API_URL are
there for offline, CI and reproducible builds.

They seed a NEW dataset and nothing else. They are NOT a fallback for a missing
rate: clearing a rate removes its row so MissingRateError surfaces, rather than
silently converting money at a number the user never chose. A test asserts a
cleared rate still throws, and loading an existing dataset never touches its
rates.

Domain purity forced the shape. createSeedDataset takes the rates as an
argument (and copies the rows, so shared constants cannot be edited out from
under the caller); the env read lives in the new src/store/bakedRates.ts behind
the try/catch accessor, because an unset BUN_PUBLIC_* leaves a bare process.env
in the browser bundle; and createSnapshotStore takes seed rates as a parameter
so it stays free of the ambient environment, with src/store/index.ts wiring it.

Verified all three build paths: live fetch bakes api-sourced rates with today's
date, an unreachable endpoint and SKIP_FX_FETCH both bake manual constants and
still build, and the payload is present in the bundle in each case. Verified at
runtime that a fresh install converts EUR 100 -> 747.50 DKK and USD 100 ->
644.95 DKK with the variable both set and unset.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:37:39 +02:00
Lucas WintherandClaude Opus 5 f50c65bd77 feat: ship the 192 and 512 PNG icons Chrome's install prompt wants
TODO recorded these as needing a human because binary assets cannot be
generated in the agent environment. That turned out to be wrong: Chrome is on
PATH here and rasterizes the SVG exactly, so scripts/make-icons.ts generates
them and the output is committed. Verified pixel-accurate against src/icon.svg
before trusting it (background #0f172a, bars #38bdf8, underline #e2e8f0,
transparent rounded corners).

The generator uses an explicit Bun.spawn with a timeout rather than a shell
template, because Chrome did not always exit on its own here.

Both sizes now appear in the manifest, get copied into dist, are served by the
dev server, and are listed in the service worker precache — along with
icon.svg and manifest.webmanifest, which were also absent from it because the
list is derived from bundler outputs and these are written separately. Without
that an installed app could not render its own icon offline.

src/icons.test.ts checks the committed files are genuine 8-bit RGBA images of
the right dimensions by inflating IDAT and asserting the exact pixel-data
length, so a truncated or stub file cannot pass. It cannot detect staleness
if src/icon.svg changes — re-run the generator.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:32:37 +02:00
Lucas WintherandClaude Opus 5 71e8fc948b perf(export): fold once per month when building the ODS
monthView folds from the start of the dataset, so it costs O(months) per
call. The summary sheet and every per-post sheet each called it once per
(post, month), making a full export O(posts x months^2). buildWorkbook now
takes one pass, indexes the figures by post, and hands that to the sheets.

TODO called this "fine at personal-budget scale". Measured against the old
code it is not, once history accumulates: 30 posts over 10 years went from
7983 ms to 135 ms (59x), and that work is synchronous on the main thread, so
it was a visible freeze on clicking Export. 10 posts x 2 years: 44 ms -> 2.5 ms.

content.xml is byte-for-byte identical on a fixture exercising every sheet
(versioned rules, an override, an archived post, a percent split, a fixed
split and a finance plan).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:27:23 +02:00
Lucas WintherandClaude Opus 5 b9be882c05 fix: four latent defects from TODO section 4
Each of these was recorded with its reasoning already settled; each is fixed
test-first, and two turned out to be worse than the note claimed.

EMPTY_FIGURES is frozen. figuresFor returns it by shared reference for every
(post, month) the fold has no entry for, so one consumer mutating its result
would have moved every other unknown row with it.

Split values now round by what they MEAN. A split's value is a percentage in
"percent" mode but MONEY in the purchase's currency in "fixed" mode; both were
rounded to a hardcoded 2 places. sliceTotal likewise rounded to DKK's minor
unit whatever currency the slices carried. Note this is narrower than TODO
claimed: round2 is still correct for Rule.percent, which is not money at all.
Neither bug is observable while every supported currency uses hundredths, so
the tests force CURRENCY_DIGITS for their duration.

confirmImport guards its write. A failed import was an unhandled rejection with
nothing shown; the dialog now reports it and keeps `pending` so the user can
retry. A source-level guard covers the whole UI, in the spirit of
eventCapture.test.ts.

The manifest has one definition. The dev placeholder did not merely hardcode
scope "/" — it was never served at all: the "/*" catch-all answered
/manifest.webmanifest with the HTML shell, as text/html, and /icon.svg too.
buildManifest moves to src/manifest.ts, the dev server generates both from the
base path, and the source file stays as a valueless resolution stub because
Bun.serve has no `external` option to skip the <link> href.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:25:35 +02:00
Lucas WintherandClaude Opus 5 ba790d104b docs: record the completed rule series in TODO and the SDD ledger
All six tasks are built. The ledger carries every deviation from the extracted
briefs with its reasoning, including four that fixed real defects in the brief
code, and states plainly what could not be verified without a browser.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:14:55 +02:00
Lucas WintherandClaude Opus 5 f94e45871d feat(ui): change a post's rule from the month you are looking at
The natural moment to decide "15% from July" is while looking at July. The
control writes the same setRuleFrom action the history editor uses, so the two
surfaces cannot drift apart. A month where a version begins gets its own badge,
distinct from a one-month override, so a step in the numbers has a visible
cause; a month can carry both.

The editor is keyed on post and month so switching posts remounts it — without
that, React reuses the instance and useState keeps the previous post's values.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:13:29 +02:00
Lucas WintherandClaude Opus 5 e3023d0322 feat(ui): add the rule history editor to Settings
Each post's allocation over time, as rows of "from this month, this rule".
Adding a rule for a month that already has one replaces it, and the form says
so rather than looking like an append. An unbudgeted post says so explicitly,
since that is a different state from a rule of zero.

The Add button stays disabled until the month parses, because setRuleFrom sorts
with compareMonths, which throws on a malformed MonthId. Also retires the
"Standing rule" wording, which Task 1's model change left stale.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:11:42 +02:00
Lucas WintherandClaude Opus 5 1cb91d37ea feat(export): validate rule versions on import
Rejects a missing rules array, a malformed or out-of-range start month, and two
versions sharing a month — which would make the effective rule ambiguous — at
the import boundary rather than letting the fold resolve something arbitrary.

Also rejects a rule of an unknown kind and a fixed rule in an unsupported
currency. The first falls through resolveRule's percentage branch and turns
every figure after it into NaN; the second throws MissingRateError deep inside
the balance fold. Both are the failure class this validation exists to stop.
The rule's VALUE stays unvalidated: over-budget is always allowed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:09:28 +02:00
Lucas WintherandClaude Opus 5 de128e3c87 feat(store): add setRuleFrom and removeRuleFrom
setRuleFrom replaces rather than appends for a month that already has a
version, keeping the effective rule unambiguous, and keeps the series sorted.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 14:07:33 +02:00
Lucas WintherandClaude Opus 5 fe9f6c6dec docs: add TODO, ARCHITECTURE and AGENTS guides for handover
TODO.md carries the remaining work with the reasoning already settled, so the
next agent does not re-derive decisions: tasks 3-6 of the versioned-rules plan,
the designed-but-unbuilt baked FX rates, the queued visual redesign, the small
residuals, and an explicit list of what only a human with a browser can check.

ARCHITECTURE.md explains the layer rules, the single-implementation fold, the
mutation pipeline's three deliberate properties, and the gotchas that each cost
a real bug — reading a deferred event.target.value, an unset BUN_PUBLIC_* var
reaching the browser, and overriding shadcn's --accent.

CLAUDE.md gains those gotchas, the dated-rule model that replaced standingRule,
the validation this project deliberately omits, and an explicit statement that
visual and offline behaviour cannot be verified in the agent environment.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 02:26:25 +02:00
Lucas Winther 1214d2b2ed test(store): cover a v1 post missing standingRule entirely (v1 -> v2)
Previously only an empty posts array was tested for the "no standingRule"
path; a post that IS present but lacks the field was exercised only by an
ad-hoc script, not a committed test. Asserts rules === [] (never a version
wrapping undefined, which would later crash resolveRule/ruleAt) and that a
sibling post's rule is unaffected.
2026-09-02 02:23:02 +02:00
Lucas Winther 15dcf935f4 feat(store): migrate allocation rules to a dated series (v1 -> v2)
A pure shape change: standingRule becomes one version effective from the fold
start, which is where it already applied from. Asserted behaviour-preserving —
every post in every month resolves to the same allocation before and after, so
no balance moves.
2026-09-02 02:20:12 +02:00
Lucas WintherandClaude Opus 5 aa781a2885 docs: capture durable product truth in PRODUCT.md
Written via the impeccable init flow. Records what future work must not
reinvent: a permanently single-user tool for one person managing their own
money, offline-only with no account, and five product principles including two
the owner added directly — changing an allocation must never destroy history,
and splitting a purchase across posts must stay easy.

Evidence on Hand deliberately records absences: no customers, testimonials,
usage data or integrations exist, and the only real content is the owner's own
budget data, which never leaves their browser. Future surfaces must not
manufacture them.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 02:18:26 +02:00
Lucas Winther 68712e72a3 feat(domain): allocation rules become a dated series
Post.standingRule becomes Post.rules: RuleVersion[], resolved by ruleAt() as
the last version effective at or before a month. Per-month overrides still win
outright; a post with no applicable version allocates zero rather than
applying its earliest rule backwards.

allocationFor keeps its signature, so the fold, the views and the ODS export
are untouched. Settings gets a read-only rule summary for now; the history
editor follows.
2026-09-02 02:15:34 +02:00
Lucas WintherandClaude Opus 5 c74a66aea9 docs: implementation plan for time-versioned allocation rules
Six tasks. Task 1 is deliberately large because the model change is atomic
under TypeScript: Post.standingRule -> Post.rules will not compile as a partial
change, so everything referencing it moves together, with the settings UI
getting only a read-only summary until Task 5.

Self-review closed two spec requirements that had no test: a version dated
before the fold start is legal but inert, and an archived post still resolves
its rules because it still folds.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 02:08:34 +02:00
Lucas WintherandClaude Opus 5 acf973f322 docs: spec time-versioned allocation rules
A post's allocation rule becomes a dated series: a version takes effect in its
month and continues until the next replaces it. Per-month overrides survive
alongside as one-month exceptions, because collapsing the two loses the
distinction between a permanent change and a temporary one.

A post with no version yet allocates zero rather than applying its earliest
rule backwards, which would invent budget for months never budgeted and let
the rollover fold carry that fiction forward.

Requires the project's first real migration (schemaVersion 1 -> 2). It is a
pure shape change and behaviour-preserving by construction, and the spec makes
that a tested property rather than an assumption: every month's allocation must
be identical before and after.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 02:02:53 +02:00
Lucas WintherandClaude Opus 5 ae34f9519d feat(ui): keyboard-first bulk rows, optional day, notes per purchase
Implements docs/superpowers/specs/2026-09-02-fast-entry-refinements-design.md.
Three changes shipped together because they share one tab order.

Bulk rows are description -> amount -> note, and nothing else is a tab stop.
The list always ends in exactly one blank row, appended as soon as the last
row is filled, so Tab flows into a new line with no special case and new rows
appear on touch too. The Add-line button is gone; the per-row remove button is
now a hover/focus x with tabIndex={-1}, and Backspace in an empty description
removes the row and lands on the previous row's note.

Purchases no longer demand a day. `date` accepts "2026-09" as well as
"2026-09-14"; entry defaults to the month, with an opt-in "set exact date"
link. No migration: monthOf() already parsed both shapes, verified before
choosing this over splitting the field into month + optional day, which would
have meant a schema migration in the browser against the user's only copy of
their data for an identical outcome.

Notes are an optional field on Purchase, in both entry forms and shown beside
the description in the month lists. Empty notes are omitted rather than stored
as "", so absent stays absent.

Also closes a pre-existing gap the spec surfaced: the JSON importer never
validated purchase.date, so a malformed date passed import and threw later
inside the balance fold. It is now rejected at the boundary, with out-of-range
months and days covered.

A row holding only a note is deliberately NOT blank: it asks for the missing
description and amount rather than being silently discarded.

Keyboard behaviour - tab traversal, Backspace-to-remove, focus after append -
cannot be verified in this environment and needs confirming in a browser.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 01:57:58 +02:00
Lucas WintherandClaude Opus 5 6924a593fb docs: spec fast-entry refinements (tab flow, optional day, notes)
Three entry-form changes specified together because they share the same tab
order: keyboard-driven bulk rows, purchases that no longer demand a day, and
an optional note per purchase.

Records why the date change widens IsoDate rather than splitting it into
month + optional day: the split is the better model but changes a type every
layer depends on and needs a migration run in the browser against the user's
only copy of their data, for an identical user-visible outcome. Verified that
monthOf() already parses both date shapes and still rejects out-of-range
months.

Time-versioned allocation rules are explicitly out of scope and get their own
cycle.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 01:53:43 +02:00
Lucas WintherandClaude Opus 5 da87bff9c3 feat(ui): add fast entry for many purchases at once
A grocery trip is twenty lines, and opening the full dialog twenty times
is the thing this exists to avoid.

PurchaseDialog gains a One / Many toggle, shown only when adding — editing
an existing purchase edits exactly one, so the toggle is hidden there. In
Many mode the date, post and currency are set once at the top and each line
is just a description and an amount; Enter on an amount starts the next
line, so a receipt can be typed without leaving the keyboard. Blank trailing
rows are ignored rather than flagged.

The whole batch commits in a single mutate: one write, one queue entry, and
no way to half-commit a shopping trip.

Lines are deliberately simple. A line needing a split or a payment plan is
saved plain and then edited from the month view — building per-line split
and plan editors would have been most of the work for a case the grocery
run never hits, and would have slowed the common path.

Line logic lives in a pure module (src/ui/bulkEntry.ts) following the
purchaseForm.ts pattern, so it is testable with no DOM: 20 tests covering
blank-row handling, per-row validation messages, the running total, and
that N lines become N purchases landing wholly in the shared post. Each
line is built through the same toPurchase the single form uses, so there
is one definition of what a purchase is.

Validation mirrors validatePurchase in what it deliberately does NOT
reject: a negative amount is a refund, not an error.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 01:44:55 +02:00
Lucas WintherandClaude Opus 5 417adb0d85 fix(ui): capture event values before deferring to mutate()
The "Income this month" field could not be changed from 0. Typing zeros
appeared to work; typing any non-zero snapped the field back to a single 0.

mutate() defers its callback behind the store's serialization queue and an
IndexedDB write. React re-renders and resets a controlled input's DOM value
back to the last committed value well before that callback runs, so a handler
reading event.target.value INSIDE the callback read the reset value and
committed 0 — forever. Committing 0 matches what is displayed, which is why
typing zeros looked fine.

Six handlers had this shape (income, post name, post currency, standing-rule
kind, base currency, rate service URL). Each now reads the DOM value
synchronously and passes it in. Sites that already captured into a const first
— the FX rate and the standing-rule amount — were never affected, which is why
those fields worked.

Purchase, split and plan editors were never affected either: they write to
local component state synchronously, never through the deferred queue.

Adds a source-level regression guard, because the trigger is real-browser
render timing that happy-dom does not reproduce.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 01:36:46 +02:00
Lucas WintherandClaude Opus 5 d1d6735596 fix(ui): survive an unset BUN_PUBLIC_BASE_PATH in the browser
Bun inlines a literal `process.env.FOO` reference only when FOO is set. With
it unset — a bare `bun --hot src/index.ts`, which is what the README tells you
to run — the reference survived into the client bundle and the app died on
load with `ReferenceError: process is not defined`, before rendering anything.
Production builds were unaffected, because build.ts passes an explicit define.

Reading the value now goes through readBasePathEnv(), which catches. Catching
rather than a `typeof process` guard is deliberate: after inlining the literal
becomes a string, but a typeof test would still run in the browser and discard
that inlined value, silently breaking every subpath deploy. Verified all four
paths: dev unset (reference survives, caught, base "/"), dev set (inlined),
and root + subpath production builds (inlined by define).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 01:19:51 +02:00
Lucas WintherandClaude Opus 5 ed1667f8a0 fix: serialize snapshot mutations, catch export/plan throws in event handlers
Fixes the three findings from the final whole-branch review:

- SnapshotStore.mutate/replace now serialize behind a promise queue, so
  concurrent mutate() calls (e.g. two independent onChange handlers firing
  before either write resolves) each clone from the previous commit instead
  of racing on a stale snapshot and silently losing an edit. Preserves
  write-before-move-snapshot, caller-visible rejections, structuredClone
  identity, and non-wedging on a failed write. Adds tests for concurrent
  mutations and a failing write mid-queue.
- DataSection's exportJson/exportOds are wrapped in try/catch and report
  failures through the existing import error state/rendering, since a throw
  (e.g. MissingRateError from buildOds) inside a plain onClick is invisible
  to the error boundary. The pre-import JSON backup now explicitly aborts
  the destructive replace if the backup export fails, rather than relying on
  an uncaught throw to prevent it.
- PlanEditor no longer calls monthOf()/withPlan() with an empty or partial
  date from a native <input type="date">, and requires an integer month
  count (with step={1}) before calling withPlan/equalSlices, preventing
  both domain throws from firing inside plain event handlers.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 01:10:12 +02:00
Lucas WintherandClaude Opus 5 da0d1ac35c fix(ui): catch render throws with an error boundary around routed content
A purchase in a currency with no configured exchange rate makes
src/domain/fx.ts throw MissingRateError (correct behavior — never silently
convert at a wrong rate). Nothing caught it: 5 of 6 routes call
monthView/yearView/summaryView and threw during render, and with no error
boundary anywhere in src/, the throw unmounted the entire React tree
including the nav bar. Since the catch-all route redirects to the current
month on first load, one un-rated foreign-currency purchase white-screened
the app immediately on landing, with the only way out (Settings, where the
rate is added) unreachable because the nav was gone too.

Adds RouteErrorBoundary (a class component, as required for
getDerivedStateFromError/componentDidCatch) that renders the thrown
message plus a link to Settings and a "Try again" reset, and
RouteErrorBoundaryReset, a wrapper that keys the boundary on the current
route so it clears on navigation. Wraps only <Routes> in App.tsx, not
<nav>, so navigation stays usable when a route throws.

Also guards the happy-dom per-file GlobalRegistrator.register() call in
registerSw.test.ts and the new ErrorBoundary.test.tsx with
isRegistered, since Bun can run both files in one process.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-02 00:57:05 +02:00
Lucas Winther 6eb77c8733 feat(deploy): add Docker image, static server, and CI workflows
One build artifact serves both a self-hosted subpath deploy and GitHub
Pages. CI runs the tests, typechecks, builds, and smoke-tests the image.

server.ts's traversal guard uses a separator-aware check
(resolved === root || resolved.startsWith(root + path.sep)) instead of
a bare startsWith(root), which would let a request resolving to
"/app/dist-evil/x" pass a check against root "/app/dist".
2026-09-01 21:33:45 +02:00
Lucas WintherandClaude Opus 5 4478c46a43 fix(pwa): make manifest/icon hrefs absolute for multi-segment SPA routes
Relative hrefs in the built index.html ("manifest.webmanifest", "icon.svg")
resolve against the *document* URL, not the site root. Since this is an
SPA where every route serves the same shell, a route with more path
segments than the base path (e.g. /budget2.0/month/2026-09, which is
where the app's own catch-all route redirects on first load) resolved
these to a wrong, 404ing path — breaking the manifest and favicon, and
with them installability, on the app's default landing URL.

build.ts now rewrites both hrefs to be absolute (prefixed with basePath)
as part of the existing dist/index.html -> dist/404.html step, keeping
the two files byte-identical. src/index.html itself keeps the plain
relative hrefs unchanged, since the substitution only happens in the
built dist/ output.

Also fixes a pre-existing, previously-uncaught bug surfaced while
verifying the dev server: bun --hot src/index.ts 500'd on every request
because Bun's dev-server HTML bundler (unlike Bun.build) has no
equivalent of the `external` build option and always tries to resolve
<link> hrefs as module imports — manifest.webmanifest never existed as a
real file under src/, only as build.ts's generated dist/ output. Added
src/manifest.webmanifest as a small static placeholder so the dev server
can resolve it; the production build still ignores this file entirely
(external: ["*.webmanifest"] in build.ts) and writes its own generated
manifest, unaffected by this addition.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-01 21:26:45 +02:00
Lucas WintherandClaude Opus 5 c069ed3a94 feat(pwa): add service worker, manifest, and subpath-aware build
The precache list is generated from Bun.build's outputs, so hashed asset
names cannot drift. A waiting worker prompts to reload rather than
pinning the user to a stale build.

Two fixes beyond the brief: naming.entry changed from "[dir]/[name].[ext]"
to "[name].[ext]" because [dir] resolved to "src", putting index.html at
dist/src/index.html instead of the dist root; and external:
["*.webmanifest", "*.svg"] was added because Bun's HTML bundler otherwise
tries to resolve <link> hrefs as module imports, which fails outright for
the not-yet-generated manifest.webmanifest and would hash icon.svg,
breaking the fixed paths the manifest and service worker depend on.

happy-dom is registered per-file in src/ui/registerSw.test.ts only, not
as a global test preload, so src/domain/smoke.test.ts still guards the
domain layer's DOM-free invariant.

PNG icons (192px/512px) are not included — binary image generation isn't
available here; a human needs to add them for full Chrome installability.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-01 21:22:58 +02:00
Lucas WintherandClaude Opus 5 31f030fdea feat(ui): add settings for currency, rates, posts, and data
Rate fetching is optional and fails soft: any network or parse error
leaves cached rates untouched and shows a message, never throwing into
render. A cleared or non-positive FX rate input now calls the new
removeFxRate action instead of storing 0, since toBase() silently
converts a stored 0 to a 0-value conversion while an absent row
correctly throws MissingRateError. Posts are archived, never deleted.
Import downloads a backup of the current data before replacing it and
requires confirmation showing before/after counts.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-01 21:14:35 +02:00
Lucas Winther 408a473dcd feat(ui): add summary view with post and month grouping 2026-09-01 21:07:04 +02:00
Lucas WintherandClaude Opus 5 59e8f4549d fix(ui): stop showing cancelled finance-plan slices as committed
PostMonthRoute's "Already committed" list filtered future schedule slices
only by month, never consulting cancelledFromMonth, so a cancelled plan's
remaining slices kept appearing as future obligations the fold would never
actually charge. Reuse sliceAmountForMonth's existing cancellation rule
instead of re-deriving it inline, to avoid a second copy of the >= boundary
drifting from the domain's.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-01 21:01:53 +02:00
Lucas WintherandClaude Opus 5 6c0fc67f1c feat(ui): add year matrix and per-post month and year views
Future finance-plan slices are surfaced as already-committed so a plan is
visible before it lands.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-01 20:59:59 +02:00
Lucas Winther 5b879809d2 feat(ui): add finance plan editor
Plans default to an equal split, each slice is individually editable, and
plans compose with splits. Cancelling keeps past slices.

planBalance delegates to domain slicesBalance rather than recomputing the
same total-minus-slices arithmetic, per the project's one-implementation
rule for shared math.
2026-09-01 20:53:05 +02:00
Lucas WintherandClaude Opus 5 5a11941d39 feat(ui): add purchase dialog with split editor
Validation lives in purchaseForm.ts as pure functions. Unbalanced splits
and over-budget purchases are deliberately not errors.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-01 20:48:51 +02:00
Lucas WintherandClaude Opus 5 b278dcaf12 fix(ui): namespace carry-meter accent token to avoid shadcn contrast regression
A bare --accent in src/index.css silently overrode shadcn's own
--accent/--accent-foreground pairing (near-white background paired with
near-black text) with the design contract's dark teal, without touching
the paired foreground. That dropped the computed contrast ratio on every
outline/ghost button, select item, badge link and dialog close button
that uses bg-accent/text-accent-foreground to 3.23:1 -- below WCAG AA's
4.5:1 minimum for text.

Renamed the token to --budget-accent everywhere it's declared and
consumed (src/index.css, src/ui/components/PostTable.tsx's carry meter),
leaving shadcn's own --accent/--accent-foreground pair untouched. The
other five contract tokens (--paper, --ink, --rule, --surplus,
--overspend) don't collide with any shadcn token name in
styles/globals.css, so they are unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-01 20:39:52 +02:00
Lucas WintherandClaude Opus 5 dd612565cb feat(ui): add month view with income entry and post table
Negative remaining balances are shown in a warning treatment; nothing
blocks going over budget.

Applies the Tasks 18-23 design contract: --paper/--ink/--rule/--accent/
--surplus/--overspend tokens and the three type-role font variables in
src/index.css, --font-money on every money figure, and the carry meter
(a 3px hard-stopped gradient beneath each PostTable row) encoding
carried-in surplus, allocation track, spend fill and overrun.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-01 20:35:35 +02:00
Lucas WintherandClaude Opus 5 ccb97818d7 feat(store): add plan slicing and dataset actions
Every mutation is a pure function over a draft dataset, so the write
surface is unit-tested without React. Money amounts (income, purchase
totals, split values, schedule slices, fixed/percent rule amounts) are
rounded to their currency's minor unit before they land in the draft,
per CLAUDE.md's round-before-persisting rule -- actions.ts is the
single boundary every UI mutation passes through. FxRate.baseUnitsPerOne
is deliberately exempt: it is stored at six decimal places, not money.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-01 20:25:14 +02:00
Lucas Winther 7edcc7f31e feat(ui): add app shell, router, and base path handling
Base path comes from BUN_PUBLIC_BASE_PATH so the same bundle serves both
a root Docker deploy and a GitHub Pages subpath.

Deviation from the task-16 brief: does not install @happy-dom/global-registrator,
does not create test/setup.ts, and does not add a [test] preload to bunfig.toml.
A global DOM preload would make src/domain/smoke.test.ts's "importable without a
DOM" assertion vacuously true, silently retiring the check that guards the
domain-layer-stays-pure invariant. Nothing in this task needs a DOM: basePath.test.ts
is pure string logic, and the shell render test was intentionally omitted by the
brief itself. A later task will register happy-dom per-file where a DOM is
genuinely required.
2026-09-01 20:17:57 +02:00
Lucas Winther 69bf4393fb feat(export): add ODS workbook export
Generated in-browser with fflate, so export works offline. mimetype is
stored first and uncompressed as the ODS spec requires.

Also adds datasetMonthSpan to the domain views layer, which determines
the month range an export should cover: from the fold start through
the latest month touched by any month record or purchase slice,
including future finance-plan slices.

Widened the mimetype-header test's byte slice from 64 to 96 bytes: the
zip local-file header for "mimetype" is 38 bytes and ODS_MIMETYPE is
46 characters, so 64 bytes could never contain the full string
regardless of implementation.
2026-09-01 20:11:08 +02:00
Lucas WintherandClaude Opus 5 c627051e66 feat(export): build ODS XML documents
Numeric cells carry office:value so the export can be summed and pivoted
in a spreadsheet rather than arriving as text.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-01 20:05:40 +02:00
Lucas WintherandClaude Opus 5 932b88b189 feat(export): add JSON export and validated import
Import validates far enough that the fold cannot throw on imported data:
exactly one remainder-absorbing split per purchase, at least one split,
every split.postId resolving to a real post, every currency supported,
and every MonthId well-formed and in range (01-12). Over-budget and
percentages not summing to 100 remain permitted.

Tightens MONTH_ID to /^\d{4}-(0[1-9]|1[0-2])$/ (shape-only regex would
let "2026-13" through import and silently misfile inside the balance
fold, mirroring the defect already fixed in src/domain/months.ts).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-01 20:02:02 +02:00
Lucas WintherandClaude Opus 5 0625a5ffa5 feat(store): add in-memory snapshot with write-through
Persistence is injected, so the store is testable with no browser. Writes
land before the snapshot moves, so the UI never shows unsaved data.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-01 19:58:47 +02:00
Lucas WintherandClaude Opus 5 15ae45a804 feat(store): add IndexedDB persistence and schema migrations
The dataset is one atomic record, so a write can never leave posts and
purchases inconsistent.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-01 19:55:08 +02:00
Lucas WintherandClaude Opus 5 438d53d016 feat(domain): add seed dataset and domain barrel
Add SCHEMA_VERSION and createSeedDataset to initialize first-run state
with three budget envelopes (Video Games, Food, Events and Social),
newId() for generating unique identifiers, and complete the domain
export barrel with all pure domain modules.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-01 19:51:57 +02:00
Lucas Winther 564a5f4079 feat(domain): add month, year, and summary view models
All three aggregate over foldBalances rather than recomputing rollover.
2026-09-01 19:48:48 +02:00