# csv2journal Milestone 1 Technical Design ## 1. Scope And Inputs This document defines the technical design for milestone one. It is subordinate to [VISION.md](VISION.md) and [REQUIREMENTS.md](REQUIREMENTS.md). **This document changes no requirement.** Where a requirement appears contradictory or its implementation forces an interpretation, the concern is raised in §11 and left for explicit resolution rather than settled here. Requirement IDs are cited throughout; §10 lists the traceability matrix covering all 181 IDs (160 normative requirements plus 21 acceptance scenarios). Development process, TDD discipline, and commit policy are defined in [PROCESS.md](PROCESS.md). Build order and task breakdown are in [PLAN_M1.md](PLAN_M1.md). ## 2. Settled Decisions | # | Decision | Requirements | | --- | --- | --- | | **D1** | Interactive UI is a Zig-served JSON API plus hand-written ES modules, stylesheets, and one `index.html`, all embedded via `@embedFile`. The browser resolves the modules' `import`s itself. No npm, no bundler, no vendored JS library: everything the browser runs is written here. Development tools are allowed where each is one program from nixpkgs — `deno` lints and tests the JavaScript, `biome` lints the CSS — configured in `src/ui/`, with no package manager and no lockfile (§7). | `M1-UI-005`–`M1-UI-015`, `M1-PKG-006` | | **D2** | hledger 1.52.3 is obtained by `fetchurl` of the official static Linux binary, pinned by SHA-256. The compatibility suite is a **separate** flake check, not part of the default build. | `M1-JRN-008`, `M1-PKG-007`, `M1-PKG-002` | | **D3** | Amounts are an `i64` coefficient plus a `u8` scale. Rendering comes from the **normalized source string**, not from the number; the integer exists solely for exact comparison. | `M1-CSV-018`, `M1-CSV-019`, `M1-RULE-016`, `M1-HIST-008` | | **D4** | Conservative lossless-emission reject set (§4.5). | `M1-JRN-006`, `M1-JRN-011`, `M1-TPL-011` | | **D5** | Duplicate YAML mapping keys are **rejected**. `M1-YAML-007` leaves this free; rejecting is deterministic and requires no precedence rule. | `M1-YAML-007`, `M1-SAFE-001` | | **D6** | Diagnostics accumulate into a list; evaluation never early-returns on the first error. | `M1-DIAG-004` | | **D7** | Finalization writes a sibling temp file, `fsync`s it, then `link()`s it to the target. `link` fails with `EEXIST`, giving atomic creation and no-overwrite in a single syscall. | `M1-JRN-013`, `M1-JRN-014`, `M1-PROJ-014` | | **D8** | The interface colours each aliased column's cells and lists the aliases in a legend (§6.2). The state payload carries the resolved `fields`; which column gets which colour is tested in `legend_test.js`, and how the page shows it is checked by hand. | — (post-M1 issue "Colour-code the profile's fields in the interactive rows") | | **D9** | Tab completes a field alias in a rule's condition (§6.4). Where a field may go is decided in Zig, by `expr/Completion.zig` behind `POST /api/complete`, so it is tested there and the grammar is not restated in JavaScript. The client keeps no completion state beyond the last answer; when Tab takes it is tested in `completion_test.js`. | — (post-M1 issue "Tab-complete field aliases in the rule condition") | | **D10** | Each rule's fields fold under one line, and one rule is open at a time (§6.5). The line is drawn by `` from the rule it holds, so how a rule is shown stays in one element; folding itself is a native `
`, and `app.js` folds the others when one opens. What the line reads is tested in `rule_test.js`; folding is checked by hand. | — (post-M1 issue "Interactive: fold every rule but the one being edited") | | **D11** | Problems are a count in the bottom-right corner that opens into a floating panel listing every diagnostic (§6.6). The page reserves room below its content, so the panel never permanently hides anything. What the corner says is tested in `problems_test.js`; the panel is checked by hand. | `M1-UI-011`,`012`,`013` | | **D12** | Clicks select aliased cells of a row no rule matches, and two buttons at the row's end add their clauses, `alias ~= /text/i` joined with `and`, to a new rule, asked for its name and target account first, or to one picked by name (§6.7). The keys `a` and `x` press them. Added to a condition that says something, they become `or (…)` on a line of their own. The clauses are built in JavaScript with as little rewriting as keeps the literal well-formed, and the author edits anything subtler. The clauses, the selection, the buttons' states and keys, the picker's choices and the prompt's checks are tested in Deno; the clicks are checked by hand. | — (post-M1 issues #11 "Add a cell to a rule from its context menu" and #12, which replaced the menu with row buttons) | | **D13** | `interactive` logs to stdout through `std.log`, one stamped line per event, at info unless `CSV2JOURNAL_LOG=debug` (§6.8). Debug adds connections, requests and the steps of an evaluation, each timed, and every line logged while a request is served names it. The environment variable, not a flag, because `M1-CLI-001` fixes the invocation forms. How a line reads and which values the variable takes are tested; which lines appear is checked by hand. What the timings first showed, regex matching rebuilding its automaton on every call, is fixed, and `zig build bench` reproduces the timed steps on a generated project. | — (performance of `PUT /api/rules`) | | **D14** | The page is light, dark, or as the system says, chosen by three buttons in the top-right corner (§6.9). The choice is kept in the browser's `localStorage`, and "system" is kept as nothing at all. Every colour that must differ between the two is a system colour or a `light-dark()` pair, so switching sets only `color-scheme`. A line in `index.html` applies the kept choice before the stylesheet paints, and everything else is in `theme.js`. Reading and keeping the choice is tested in `theme_test.js`; the page in each scheme is checked by hand. | — (choosing light or dark by hand) | ### D3 detail Storage is `i64`. Scale alignment during comparison is performed in `i128` intermediates, so comparing a scale-0 value against a scale-18 value cannot overflow. A cell whose digits exceed `i64` range at its scale produces a **row diagnostic**, never a silently wrong value. ```zig const Decimal = struct { text: []const u8, // normalized: "100.00" -> emitted verbatim coef: i64, // 10000 -> comparison only scale: u8, // 2 }; fn order(a: Decimal, b: Decimal) !std.math.Order { var av: i128 = a.coef; var bv: i128 = b.coef; if (a.scale < b.scale) av *= pow10(b.scale - a.scale) else bv *= pow10(a.scale - b.scale); return std.math.order(av, bv); } ``` `100.0` and `100.00` compare equal (`M1-HIST-008`) while each still renders at its source scale (`M1-CSV-019`). `-0.00` yields `coef = 0`, so the sign vanishes without a special case. ### D7 detail `M1-PROJ-014` requires that a target created *after* discovery but *before* finalization must never be treated as writable. `link()` returning `EEXIST` enforces this at the kernel level, so no pre-flight existence check is performed and no TOCTOU window exists. This addresses the concern raised in the project `README.md` about race-condition requirements: the invariant is obtained from the choice of syscall, not from checking. ## 3. Architecture ### 3.1 Human-scale constraints The author must be able to maintain this project **without LLM assistance** (`PROCESS.md`). That is the constraint these rules serve: not simplicity for its own sake, but that one person returning after a month away can re-derive any part of the system unaided. Zig is a deliberate preference, not a neutral default. Idiomatic Zig — `comptime` included — is welcome wherever it is the natural expression. What is excluded is code whose behavior cannot be reconstructed by reading it. These are design constraints, not aspirations: - No source file exceeds ~400 lines of implementation; test blocks below the `// -- tests` divider do not count (PROCESS.md §1). A module approaching the limit is split along a seam already present in the requirements. - No function exceeds ~60 lines. - Each module is independently testable with no filesystem or network access, except `discover.zig`, `Snapshot.zig`, `Target.zig`, and `ui/server.zig`. - Abstraction is justified by a second caller, not by anticipation of one. ### 3.2 Module map ``` src/main.zig CLI entry, exit codes M1-CLI-006 src/log.zig stamped log lines on stdout -- (D13) src/util/time.zig stopwatch and lap timer -- (D13) src/bench/main.zig timings of one evaluation -- (D13) src/cli.zig command execution, reporting M1-CLI-002..005,007,008 src/cli/Invocation.zig argument parsing M1-CLI-001 src/diag.zig diagnostic accumulator M1-DIAG-001..004 src/Diagnostic.zig one diagnostic, and its rendering M1-DIAG-001..003 src/Decimal.zig i64+scale parse/compare/render M1-CSV-018,019, M1-RULE-016 src/Date.zig the accepted date formats M1-CSV-016 src/currency.zig the supported currency set M1-CSV-020 src/yaml/events.zig libyaml wrapper + subset gate M1-YAML-001..004,009,010,011 src/yaml/tree.zig the configuration tree M1-YAML-005,006,007 src/yaml/schema.zig typed decode, key-path errors M1-YAML-008,012 src/yaml/emit.zig canonical rules writer M1-UI-017,018 src/config/Manifest.zig Manifest/Profile model M1-PROJ-001..005 src/config/rules.zig Rule/Ruleset model + actions M1-RULE-001,002,011,012,013 src/expr/lexer.zig tokens, keywords, literals M1-RULE-014,015,021, M1-CSV-015 src/expr/parser.zig precedence, parens M1-RULE-003,004,005 src/expr/regex.zig regex literal -> zig-regex M1-RULE-017,018 src/expr/eval.zig short-circuit, tri-state M1-RULE-019,020 src/expr/Completion.zig aliases that fit at the cursor -- (D9) src/csv/reader.zig zarko wrapper (see §3.3) M1-CSV-001..007,010 src/csv/fields.zig preamble, header, alias resolve M1-CSV-008,009,011..014,023 src/row.zig row -> date/amount/currency M1-CSV-016,017,020,021 src/template.zig placeholders, escapes M1-TPL-001..012 src/Journal.zig the journal, emit and compare M1-JRN-001..012, M1-HIST-006..010,014 src/journal/Transaction.zig one transaction M1-JRN-002,003 src/journal/Posting.zig one posting M1-JRN-004,005,006,009 src/journal/Amount.zig quantity and currency M1-CSV-021 src/journal/Comparison.zig one approved-vs-candidate walk M1-HIST-009,010 src/journal/parse.zig approved-journal subset parser M1-HIST-004,005,013 src/discover.zig recursive pairing M1-PROJ-006..014 src/Snapshot.zig read-once immutable contents M1-PROJ-015,016,017 src/engine.zig orchestration, candidate eval M1-RULE-006..010, M1-HIST-001..003 src/engine/Candidate.zig resolved configuration M1-PROJ-018, M1-RULE-013 src/engine/Profile.zig the manifest's profile, resolved M1-PROJ-018 src/Target.zig atomic exclusive create M1-JRN-013,014, M1-SAFE-002,003 src/ui/server.zig std.http.Server loop, routing M1-UI-001..004 src/ui/Session.zig the interactive session M1-UI-007,009..021, M1-PROJ-018 src/ui/state.zig the read-only state view M1-UI-005,006,007,011,012,013 src/ui/Editor.zig in-memory rule draft M1-UI-008,015,016,019, M1-PROJ-016 src/ui/Project.zig opening a project once M1-PROJ-018 src/ui/Output.zig journal text, and writing it M1-UI-014,021 src/util/io.zig reading a whole file -- src/util/path.zig lexical paths under a root M1-PROJ-005 src/util/order.zig byte order of strings M1-SAFE-001 src/acceptance.zig end-to-end acceptance suite M1-AC-001..021 src/compat/ hledger compatibility corpus M1-JRN-008, M1-PKG-007 src/ui/{index.html,app.js,app.css} @embedFile M1-UI-005..015 (D1) src/ui/rule-editor.{js,css} one rule's fields M1-UI-008 (§6.3) src/ui/legend.js the field legend D8 (§6.2) src/ui/problems.js problems corner M1-UI-011..013, D11 (§6.6) src/ui/draft.js the page's draft M1-UI-008,010,015 src/ui/api.js requests to server M1-UI-005,006,010 src/ui/completion.js when Tab completes D9 (§6.4) src/ui/clause.js a cell's clause D12 (§6.7) src/ui/selection.js the selected cells D12 (§6.7) src/ui/row-actions.js a row's buttons D12 (§6.7) src/ui/rule-picker.js the rule picker D12 (§6.7) src/ui/rule-prompt.js a new rule's prompt D12 (§6.7) src/ui/popover.js popovers below a row D12 (§6.7) src/ui/fuzzy.js fuzzy name matching D12 (§6.7) src/ui/rule.js a rule's boxes, line M1-UI-008, D10 (§6.3, §6.5) src/ui/journal.js journal outcomes M1-UI-014,021 src/ui/summary.js the summary line M1-UI-005 src/ui/theme.js light or dark D14 (§6.9) src/ui/*_test.js their tests (Deno) §8 ``` Dependency direction is strictly downward: `diag` and `decimal` depend on nothing; `engine` depends on everything below it; `ui` and `cli` depend on `engine`. No cycles. ### 3.3 CSV reader This module carries the most requirement weight because **zarko provides none of the strictness milestone one requires**. Verified against the pinned commit: `Parser.init(allocator, input, dialect)`, `next() !?Record`, error set `{InvalidCsv, UnterminatedQuote}` — no record ordinal, no error positions, tolerates line endings disagreeing with the configured dialect, and yields a record for a blank line. `csv/reader.zig` therefore owns: 1. **Leading byte-order mark removed, UTF-8 validated** before parsing (`M1-CSV-001`). The mark is dropped rather than refused, because exporters add one to files the user cannot regenerate; a configuration file's mark is still rejected, since those files are the user's own. 2. **Byte-level line-ending pre-scan** (`M1-CSV-003`). A lone CR is illegal *everywhere*, including inside quoted fields, so this scan needs no quote tracking: in `lf` mode reject any `\r`; in `crlf` mode reject any `\r` not followed by `\n` and any `\n` not preceded by `\r`. 3. **Dialect construction** from the profile; quote is always `"` (`M1-CSV-002`, `M1-CSV-005`). 4. **Physical row counter** — zarko has none (`M1-TPL-004`, `M1-DIAG-001`). 5. **Blank-record rejection**, distinguishing a physically blank record from a record of empty fields (`M1-CSV-010`). zarko's own test at `Parser.zig:425` shows `"a\n\nb"` yielding records `a`, `""`, `b`, so an interior blank line does reach us and must be rejected here. 7. `skipRecords` and `header` handling, header uniqueness and width, headerless minimum width (`M1-CSV-008`, `009`, `012`, `013`, `014`). Because zarko errors carry no position, a mid-record failure is reported at the record's starting physical row. This satisfies `M1-DIAG-001` but is coarser than ideal (§10, risks). Two things need **no** work here, contrary to an earlier draft of this section. zarko already suppresses a spurious record from a single trailing line ending (`Parser.zig:279`) and already accepts a final record ending at EOF (`Parser.zig:272`). `M1-CSV-005` makes that pinned behaviour ours, so `M1-CSV-004` and the trailing-newline case are covered by regression tests that pin the dependency's behaviour, not by code of our own. ## 4. Data Model ### 4.1 Tri-state matching `M1-RULE-020` requires that a rule whose numeric predicate cannot parse its field yields an *unavailable* result while every other rule is still evaluated. ```zig const MatchResult = ?bool; // null = unavailable const RowStatus = enum { zero, one, multiple, unavailable }; ``` Classification: if **any** rule result is `null`, the row is `unavailable` regardless of how many rules matched; otherwise count the `true` results. Known matches and all evaluation errors are still reported (`M1-RULE-020`, `M1-AC-012`). ### 4.2 Diagnostics ```zig const Diagnostic = struct { file: []const u8, // relative to inputPath, '/' separators physical_row: ?usize, // M1-DIAG-001 key_path: ?[]const u8, // e.g. "profile.csv.fields.date" M1-DIAG-002 rule: ?[]const u8, line_col: ?struct { line: usize, col: usize }, // libyaml, M1-YAML-010 message: []const u8, }; ``` Accumulated into a list, never early-returned (D6), so one bad row does not mask independent errors in other rows or other historical pairs (`M1-DIAG-004`). ### 4.3 Journal model ```zig const Posting = struct { account: []const u8, amount: ?struct { qty: Decimal, currency: Currency }, // null = inferred comment: ?[]const u8, }; const Transaction = struct { date: Date, narration: []const u8, postings: [2]Posting }; ``` Amount **presence** is part of structural equality: an omitted destination amount is not equal to an explicit one (`M1-HIST-007`, `M1-JRN-005`, `M1-HIST-005`). ### 4.4 Memory One arena for the operation snapshot, living for the whole invocation or interactive session (`M1-PROJ-015`). One evaluation arena, reset on every re-evaluation. Snapshot contents are never reread. A save establishes the session's saved rules in the editor, not by going back to the file (`M1-PROJ-016`). ### 4.5 Lossless emission set (D4) | Context | Rejected | | --- | --- | | Narration | `\n`, `\r`, `;`, `\|`, C0 controls; a leading `*`, `!` or `(`; leading or trailing whitespace | | Account | `;`, two consecutive spaces, leading/trailing whitespace, `(` or `[` prefix | | Posting comment | `\n`, `\r` | `;` starts a comment; `\|` splits hledger's description into payee and note, which would change parsed data (§11). A leading `*` or `!` is read as a transaction status and a leading `(` as a transaction code, so a narration starting with one would not survive the round trip; the same characters elsewhere in the text are ordinary. That leading-character rule was found while writing the approved-journal parser in T17, and is an addition to D4 as originally stated. Leading and trailing whitespace in a narration is a second addition, found in T26 by running hledger 1.52.3 rather than by reasoning about it: hledger strips whitespace from both ends of a description, so such a narration has no lossless representation and `M1-TPL-011` requires generation to fail. Interior whitespace is preserved by hledger and is kept. Tabs were already excluded everywhere in a narration as C0 controls, which is stricter than hledger requires. `(` and `[` prefixes denote virtual postings, barred by `M1-JRN-006`. Tabs are retained in comments because `M1-TPL-010` forbids trimming. ## 5. Pipeline ``` load manifest -> discover -> snapshot -> parse rules -> evaluate -> generate -> compare history -> finalize ``` `check`, `convert`, and `interactive` share every stage up to finalization (`M1-CLI-003`, `M1-CLI-005`). `check` stops before it; `convert` proceeds; `interactive` re-runs evaluate through compare on each edit. Finalization (D7): write `.tmpXXXX` in the target's directory, `fsync`, `link()` to the target, `unlink` the temp. A failure at any point leaves no target (`M1-JRN-013`). ## 6. Interactive Interface Zig 0.17 `std.http.Server`: `init(&reader.interface, &writer.interface)`, `receiveHead()`, `respond()`. Blocking, one connection at a time — sufficient for a single-user loopback tool. Every response says `connection: close`, so a connection carries one request. A browser holds an idle keep-alive connection open for minutes, and while the server waits on it, requests the browser sent on its other connections wait in the backlog; the page then never finishes loading. | Endpoint | Purpose | Requirements | | --- | --- | --- | | `GET /api/state` | rows, cells, match status, diagnostics, resolved fields (D8) | `M1-UI-005`,`006`,`007`,`011`,`012`,`013` | | `PUT /api/rules` | candidate edit; returns re-evaluated state | `M1-UI-008`,`010`,`015` | | `POST /api/save` | validate and atomically rewrite rules file | `M1-UI-016`,`017`,`018`,`019` | | `GET /api/preview` | full journal preview or reason unavailable | `M1-UI-014` | | `POST /api/finalize` | interactive finalization | `M1-UI-020`,`021` | Re-evaluation is synchronous within the request. The client marks results pending between send and response, satisfying `M1-UI-010`'s requirement that pending be distinguishable from current results. Manifest and profile are served read-only (`M1-UI-009`). **Filtering and search run server-side**, as `?status=` and `?q=` on `GET /api/state`. This is a change from the original design, made in T23. `M1-UI-006` fixes the semantics precisely — a case-sensitive UTF-8 byte substring over every cell, with an empty query showing everything the status filter allows — and a rule stated that exactly deserves tests. In the client it would sit where this project had, at the time, no way to test it. On loopback the extra round trip costs nothing, and the client is smaller for it. `?status=` names a set of statuses, comma-separated, and a row is shown when its status is one of them, so the interface can show unmatched and multiply matched rows together. Leaving the parameter out shows every row, so a bare URL is useful; `status=` with nothing after it shows none, which is how the interface says that no box is checked. A word naming no status is skipped. The interface's "all" checkbox is a shorthand for the four and never reaches the server. Every request answered with the state payload carries the view, and `api.js` notes whether the controls still show that view when the answer arrives. A state refresh for a view since left is dropped, because whatever changed the view has asked again; an edit's answer is still shown, since it says what became of the edit, and is followed by a refresh. `api_test.js` tests both against a stand-in for `fetch`. Every endpoint that answers with the state payload honours both parameters, not only `GET /api/state`. The interface replaces its rows with whatever an edit, a save or a finalize returns, so it sends the view it is showing with each of them; an answer for a view that has since changed is followed by one more `GET`. A guided expression builder is not built (`M1-UI-022` makes it optional); expressions are edited as text within structured per-rule controls, and the rules file is never exposed as raw YAML (`M1-UI-008`). ### 6.1 Shutdown and the listen endpoint `M1-UI-004` makes SIGINT and SIGTERM the way the server stops, and the default disposition already did that. What it did badly was give the endpoint back. The server holds one connection at a time, and the connection still open when the signal arrives is closed by the kernel on the process's behalf — our FIN first, so the socket keeps the listen endpoint through `FIN_WAIT_2` and `TIME_WAIT` for another minute and the next `bind` fails. Measured: with a connection held, a restart is refused; with none held, it succeeds. Connections the browser already closed cost nothing, because our close of those is passive, and backlog connections the kernel resets. So `ui/server.zig` installs a handler for both signals that resets that one connection — `SO_LINGER` with a zero timeout, then `close` — before exiting. It cannot instead set a flag and let the loop notice: `std.Io.Threaded` retries `EINTR` internally, so the blocking read would simply resume. The handler owns the descriptor through an atomic swap, so it and the accept loop can never close the same one twice. The obvious alternative, `reuse_address` on the listener, is rejected. Zig 0.17 sets SO_REUSEADDR and SO_REUSEPORT together (`std.Io.net.IpAddress.ListenOptions`), and SO_REUSEPORT would let a second `interactive` bind the same endpoint alongside the first, with the kernel dividing requests between two servers holding different sessions. That is worse than what `M1-UI-001` forbids. Zig offers no way to ask for SO_REUSEADDR alone. **Exit status.** A signalled shutdown exits `0`. `M1-CLI-006` enumerates what must exit non-zero — configuration, discovery, parsing, matching, historical validation, server startup, finalization — and a shutdown the user asked for is none of them; `M1-UI-004` calls it "Normal server shutdown". Reading recorded here because the requirement does not name the case either way. **Untested.** This behaviour has no automated test, by explicit decision. Asserting it needs a real process to signal, `serve` is called from no test, and the repo has no precedent for either. It is verified by hand: hold a connection, signal, confirm `ss` shows no socket on the endpoint and that a restart binds. Recorded so the gap is visible rather than silent. ### 6.2 Field legend (D8) When writing a condition it helps to see which cell an alias names. `GET /api/state` carries `fields`: every alias with its zero-based column and its selector, shaped as the profile writes it. The list comes from the layout `engine.classify` resolved, so it is empty whenever no rows are shown. The two go together, and a legend with no rows to explain would say little. The client gives the aliased columns colours left to right, from twelve hues ordered so that each neighbouring pair stays distinguishable for colour-blind readers. Adjacent cells therefore wear adjacent hues, which is the only pairing the palette is checked for. Past twelve, the hues repeat with diagonal stripes, then with a dashed outline. Aliases that share a column share its colour, and the cell's tooltip names every one of them. Unaliased cells are dimmed but kept, since the search covers them. Which column gets which colour is tested in `legend_test.js`; how the page shows it is not. To check that by hand, run `interactive` on a project whose profile has more than twelve aliases, one column that two aliases select, and one column none does: 1. The Fields legend sits just above Rules, in column order, each entry naming its selector (`header "…"` or `index N`). 2. Every aliased cell wears its legend swatch's colour, and hovering it names its alias or aliases. 3. The thirteenth column onward is striped. Unaliased cells are dimmed. 4. A draft that does not prepare, such as `text ==`, removes the legend along with the rows. ### 6.3 Rule editor Each rule's fields are one `` element (`rule-editor.js`), with its own shadow root and its own stylesheet (`rule-editor.css`), so page styles and the card's layout cannot disturb each other. It is given a rule as its `rule` property and keeps a copy, so it never changes the draft it came from. It reports back with three events, each carrying the rule as the fields now say it: `rule-edit` on every keystroke, `rule-commit` when a changed field is left, and `rule-delete`. `app.js` decides what each event means for the draft, which `draft.js` keeps along with what the server last accepted, so it can say whether the results are for the fields (`M1-UI-010`, `M1-UI-015`); `draft_test.js` tests that. Which boxes a card has, and what an empty one means, are tested in `rule_test.js`; the element is not. To check it by hand, run `interactive` on a project with three rules: 1. Open the second rule and type in its name. The state reads "results are for your last finished edit" until the field is left, then the results update. 2. Empty the second rule's source account, leave the field and save. The rules file has no source account for that rule. 3. Add a rule. It opens empty with the cursor in its name, and the text typed into the others is still there. 4. Open the second rule and delete it. That rule goes, and the others keep their text. 5. Each open card has the name and both accounts on one row, the condition in a monospace textarea across the full width below them, and delete in the bottom-right corner. Tab visits them in that order, except where the condition completes an alias instead (§6.4). Below 50rem everything stacks in one column, with delete still at the right. ### 6.4 Completing a field in a condition (D9) The condition's textarea completes field aliases on Tab wherever `M1-RULE-003` admits a field: at the start, or after `(`, `and`, `or` or `not`. The partial is the identifier characters directly before the cursor, so `not` followed by Tab can become `notes`. Text before the cursor that does not lex, such as an unterminated string, offers nothing. `Completion.init` takes the text up to the cursor rather than an offset, so the browser's UTF-16 offsets never have to agree with Zig's bytes. The candidates are the aliases starting with the partial, case-sensitively and in byte order; `insert` is their longest common prefix less the partial. There is no cycling: with several candidates, typing more letters narrows them. The aliases are the view's `fields`, so they are there whenever the rows are (§6.2). Tab must decide in `keydown` whether to complete, before any request could return. So the element asks on every `input`, `keyup` and `mouseup`, keeps the last answer with the text it was for, and takes Tab only when that text is still what precedes the cursor and there is a candidate. Otherwise Tab moves focus as it always did. `app.js` hands the element the function that asks, so the element itself never fetches. When Tab takes an answer is tested in `completion_test.js`; the element around it is not. To check that by hand, run `interactive` on a project whose profile has the aliases `payee` and `payee_iban`, and no other alias starting with `pa`: 1. Focus an empty condition. The line under it lists every alias, in byte order. 2. Type `pa` and press Tab. The condition reads `payee`, the cursor after it, and the line lists `payee` and `payee_iban`. Tab again changes nothing and keeps focus. 3. Type `_` and press Tab. The condition reads `payee_iban`. 4. Type ` == "x and ` and press Tab. Nothing is inserted, and focus moves to the delete button. 5. Clear it, type `payee == "x" and ` and press Tab. It completes again. 6. Leave the field after a completion. The results update for the completed condition. 7. Shift-Tab and a Tab with text selected move focus, never complete. ### 6.5 Folding rules (D10) Most of the time one rule is being edited and the others are there to be read, so each `` folds its fields under a native `
`. Folded, its line shows the name, the target account and the condition cut to one line; open, only the name, since the fields below say the rest. A rule with an empty name reads "(unnamed rule)". The element draws the line from the rule it holds and redraws it on every keystroke, so a folded line is never behind its fields. Delete is inside the fields, so a folded rule cannot be deleted by a stray click. One rule is open at a time. The element reports `rule-open` when it is opened, and `app.js` calls `fold()` on every other card. Which rule is open is not kept anywhere else: `app.js` rebuilds the cards only on first load, where every rule starts folded; on add, where `edit()` opens the new rule with the cursor in its name; and on delete, which removes the rule that was open. An exclusive `
` group would need no script, but it does not reach across the cards' shadow roots. What the line reads is tested in `rule_test.js`; the folding is not. To check it by hand, run `interactive` on a project with three rules, one of them with a condition spanning two lines: 1. Every rule shows one line: its name in bold, its target account, its condition in monospace. The two-line condition reads as one line, and a condition too long for the width ends in "…". 2. Open a rule. Its line shows only the name, with the fields below it. 3. Type in its name, target account and condition, then fold it. The line shows what was typed. 4. Empty its name. The line reads "(unnamed rule)". 5. With the keyboard alone, Tab to a folded line and press Enter or Space. It opens; again, it folds. Folding a rule whose field has an edit not yet left commits that edit. 6. Open the first rule, then the third. The first folds. 7. Add a rule. It opens, the third folds, and typing goes into the new rule's name. 8. Delete the new rule. Every rule is folded. ### 6.6 Problems in the corner (D11) A fresh project matches no rules, so every row is a problem, and a list at the top of the page pushed the rules and rows out of sight. Problems are therefore a button in the bottom-right corner reading "3 problems", or nothing when there are none. Clicking it opens a floating panel in the same corner listing every diagnostic, with the list scrolling inside it. The panel's header minimizes it back to the count. The first-five preview that the old list had is gone, because a panel whose height is bounded has no reason to hold anything back. `M1-UI-011` to `M1-UI-013` require every diagnostic to be displayed. The payload is complete and every entry is one click away, which is the same reading the preview relied on, so there is no concern for §11. The panel starts minimized, and only a click opens it. The count changing is the signal. The panel stays as last chosen while the count drops to zero and comes back, for as long as the page is loaded. While it is open, the page gets as much padding at the bottom as the panel can be tall, so anything under it can be scrolled into view. Like the rows, it dims while the results are stale (`M1-UI-015`), by fading its text rather than its opacity, since opacity would let the page show through. Where each problem is, the count and what the corner holds are tested in `problems_test.js`; the panel on screen is not. To check that by hand, run `interactive` on a project whose rules leave more rows unmatched than fit in the panel: 1. The corner reads "N problems" and nothing else shows the diagnostics. With one problem, it reads "1 problem". 2. Click it. A panel opens in the corner, headed "N problems", with the list scrolling inside it. Focus is on the header. 3. Scroll to the bottom of the page. The end of the journal section can be brought above the panel. 4. Edit a rule. While the edit is in flight, the corner's text is faded, and the panel stays open. 5. Press Escape, or click the header. The count comes back, and focus is on it. 6. Make every row match. The corner is empty. Break a rule again. The count comes back, not the panel. 7. At phone width, the panel spans the page with a margin on each side, and the page does not scroll sideways. ### 6.7 Adding a row's cells to a rule (D12) Writing a rule for an unmatched row mostly means copying cells' text into a condition and typing the alias and a regex around each. Selecting the cells and pressing a button does that instead. On a row with status zero, a click on a cell an alias names selects it, and a second click unselects it. Unaliased cells and cells of only whitespace cannot be selected. One row holds the selection at a time: a click in another row starts it over there. The table is drawn anew on every answer from the server, so `selection.js` keeps the selection by physical row number and column, and drops it once its row is no longer shown unmatched, whether a rule now matches it or the filter or search hides it. Each selected cell gives `alias ~= /text/i` under the first alias naming its column: unanchored, case-insensitive, and with the text trimmed. The text is rewritten only where it would break the literal (`M1-RULE-017`): `/` becomes `.`, and line breaks and tabs become `\r`, `\n` and `\t`. Other regex characters keep their meaning, so a cell such as `AMAZON.DE*MKTP (EU)` gives a clause the author has to edit. Until then its invalid regex makes every row unavailable (`M1-RULE-013`), as any invalid regex does. The pinned zig-regex folds case one character at a time, ASCII or not (`M1-RULE-018`), so `/müller/i` finds `MÜLLER`, but `/straße/i` does not find `STRASSE`. The clauses go left to right, joined with `and`. Into an empty condition they go as they are. After a condition that says something they are an alternative to it: a line break, `or`, and the clauses in brackets when there is more than one. They always go at the end. The cursor and which rule is open play no part. Two square buttons end each unmatched row; every other row has an empty cell there. Both stay disabled until a cell of their row is selected, and "add to an existing rule" also until some rule has a name. A disabled button's title says why; an enabled one's names its key. With a cell selected, `a` presses the row's "add to a new rule" and `x` its "add to an existing rule", and Escape unselects the cells, as long as focus is not in a field or popover and no modifier is held. The keys press the buttons, so a disabled button's key does nothing. "Add to a new rule" opens a popover below the button asking for the rule's name, with the cursor in it, and its target account, which suggests the target accounts other rules use. Tab moves between them, and Enter or "create" adds the rule. It is refused, with a note saying why, while the name is empty or another rule's, or the account is empty: what would make the server refuse the draft (`M1-UI-016`) or the rule useless. Whether the account can be written to a journal is the server's to say (`M1-JRN-006`), as for any rule. Escape or a click elsewhere cancels, keeping the selection; after Escape the keyboard is back on the button. The rule is complete when it is added, so it is pushed at once, and the condition, which the prompt does not show, is the clauses. "Add to an existing rule" opens a popover below the button: an input and the named rules in file order, narrowed by `fuzzy.js` as letters are typed. A name matches when it holds the letters in order, ignoring case. Names whose letters sit together rank first, then names whose letters start words. The arrow keys move through the choices, and Enter or a click takes one. The popover closes itself on Escape and on a click elsewhere, which keeps the selection. The chosen rule opens, folding the others. `popover.js` places both popovers, and `app.js` closes them on scroll, since they hang from the button. Either way the added text is left selected in the focused condition, so it shows what was added, one Delete takes it back, the leading line break included, and the left arrow goes to its start. It is committed when the field is left, as a Tab completion is (§6.4). The editor's method is `extend(clauses)`. The `M1-UI-022` test rules out `addClause` as the name of a guided builder. The condition is still a text field, and the buttons only type into it. The clauses are tested in `clause_test.js`, the selection in `selection_test.js`, the buttons' states and keys in `row-actions_test.js`, the matching in `fuzzy_test.js`, the picker's choices in `rule-picker_test.js`, and the prompt's checks and suggestions in `rule-prompt_test.js`. The clicks, the keys and the popovers on screen are not. To check those by hand, run `interactive` on a project with two named rules, three unmatched rows, one of them with a cell of only spaces, and two aliases on one column: 1. Every unmatched row ends in two disabled buttons whose titles say to select cells first. Other rows have none. 2. Click two aliased cells of an unmatched row. Both are outlined and the row's buttons are enabled. Click one again: it is no longer outlined. Click the cell of only spaces, or an unaliased cell: nothing happens. Click a cell in another row: the first row's cells are no longer outlined, and its buttons are disabled again. 3. With two cells of one row selected, press "add to a new rule". A popover below it asks for a name, with the cursor in it, and a target account, which suggests the accounts of the two rules. Press Escape: the popover closes, the cells are still outlined, and focus is on the button. 4. Press Enter to open it again, and Enter again: it says the rule needs a name. Type a name another rule has, Tab, an account, and Enter: it says so. Change the name and press Enter. A rule opens with focus in its condition, which reads `a ~= /…/i and b ~= /…/i`, all of it selected, and the row now matches. The cells are no longer outlined. A cell containing `/` gives a dot. The column with two aliases gives the first. 5. Select a cell of another row, edit any rule, and leave the field. The cell is still outlined after the results come back. 6. Press "add to an existing rule". A popover below the button lists the named rules in file order, with the cursor in its input and the first one marked. Type a few letters of one name, not adjacent ones: only matching names are left. Press Escape: the popover closes and the cell is still outlined. 7. Open the picker again, press the down arrow, then Enter. That rule opens, the others fold, and its condition ends in a new line `or a ~= /…/i`, selected from the line break on. Press Delete: the condition is as it was. 8. Select two cells, add them to an existing rule by clicking its name. The new line reads `or (a ~= /…/i and b ~= /…/i)`. 9. Delete the names of all rules. With a cell selected, "add to an existing rule" stays disabled, and its title says no rule has a name. 10. Select a cell and press `a`: the prompt opens. Escape, then `x`: the picker opens. Escape, then Escape again: the cell is no longer outlined. With a cell selected, type `a` into the search field, and press Ctrl+A: neither opens anything. ### 6.8 The server's log (D13) A line reads `2026-10-03T14:05:11.041Z DEBUG (session) c3#42 PUT /api/rules: classified 512 rows in 36.8 ms`: the time in UTC to the millisecond, the level, the `std.log` scope, which connection and request the line is about, and the message. UTC because Zig's standard library has no time zone database. Connections and requests are numbered from one as they arrive, requests across connections, so `#42` tells two edits of the same path apart. The query string appears only on the request's first line. At info, the default, the log holds the URL, the shutdown, what saving and finalizing did, and failures the server would otherwise drop: a failed accept, a request head it cannot parse, a body it cannot read. `CSV2JOURNAL_LOG=debug` adds, for each connection, when it was accepted and closed; for each API request, its start with the body size and its end with status, size and elapsed time; in between, decoding the draft, loading the profile, preparing the rules, classifying the rows, validating history and rendering the response, each with how long it took. A static file gets only its end line, since a page load fetches twenty. Any other value of the variable fails startup, so a typo never silently yields no debug output. The server serves one connection at a time, and a browser opens several. A request sent on a second connection waits in the kernel's backlog until the first is answered and closed, and no timer the server starts can see that wait. It shows instead as the gap between one connection's `closed` and the next one's `accepted`. `std.log` filters at compile time, so `main` sets that level to debug and `log.zig` applies the one chosen at startup. The level and the current connection and request are globals, because `std.log`'s callers pass nothing but the message; the server is single-threaded, so lines never interleave. The shutdown line is written from the signal handler, which may not call `std.log`. It formats the same stamp into a stack buffer and writes it with one syscall. The first thing the timings showed was a `PUT /api/rules` taking nine seconds in a Debug build, almost all of it classifying about a thousand rows against some thirty rules: 6 ms a row. `Regex.isMatch` builds a fresh lazy DFA on every call, which is about 40 µs per match in Debug, and the DFA is allocated in the rules' arena, which grew by over a gigabyte. Each compiled regex now matches through a `Regex.Matcher`, which builds the DFA once and keeps it. Evaluation therefore updates the program it runs, so a program is for one thread, as the server is. `zig build bench` times the same steps the debug log does, on a generated project rather than anyone's bank data: a thousand rows with long booking texts, thirty rules of five or'd predicates, where only the last predicate matches. It reports each step's mean, spread and arena size, and `-Doptimize` compares builds. With the matcher, classification takes 0.27 s in Debug instead of 5.3 s, and 26 ms in ReleaseSafe. Nothing checks the numbers, since a timing assertion would only be flaky. The allocation they exposed is tested instead: a regex that has matched once allocates nothing to match again. ### 6.9 Light and dark (D14) `app.css` sets `color-scheme: light dark`, and almost every colour on the page is a system colour, so the page has always followed the system's setting. D14 adds a way to override it. Three buttons in the top-right corner pick system, light or dark, and the one in force is shown pressed. They are a group of `aria-pressed` buttons rather than a radio group, so Tab reaches each one and no arrow-key handling is needed. A choice sets `data-theme` on the root element, and two rules in `app.css` turn `light` and `dark` into a `color-scheme`. Any other value, `system` included, matches neither, and the browser follows the system, changing with it while the page is open. Everything the browser draws follows `color-scheme`: the page, the form controls, the scrollbars and the rule editor's shadow root, which inherits it. The few colours written out, the field hues and the refusal's red, are given as `light-dark()` pairs, which resolve against the same `color-scheme`. Over a dark page, a 25% tint of the darkest hues barely lifts off the page, although neighbouring tints stay as far apart as they are in light. The dark tints are therefore stronger, while the hues and their order stay as they are. The contrast each pair was chosen for is written beside it in `app.css`. The choice is kept in `localStorage`, so it lasts across reloads and server restarts in that browser. Only `light` or `dark` is ever stored, and choosing system removes the key, so a stale value cannot linger. Storage can refuse to be read or written, for example when the browser blocks the site's data. Then the page follows the system, and a choice lasts until the page is reloaded. Nothing goes to the server: a display preference is not part of the project, and `M1-UI-009` keeps its files read-only anyway. The modules run after the page first paints, so a kept choice applied by `app.js` would show the other scheme for a moment on every load. A one-line inline script in `index.html`, before the stylesheet, copies the stored value onto `data-theme` and decides nothing. What counts as a choice and what gets stored is in `theme.js`, and the two places that name the storage key point at each other. A value the line copies that is not a choice matches no rule, and the page follows the system until `app.js` replaces it. Like the problems corner (§6.6), the buttons float over the page, and nothing stays hidden under them. At the top of the page they sit beside the header, which keeps room for them on its right. Anything further down can be scrolled out from under them. Reading and storing the choice is tested in `theme_test.js`; the page is not. To check it by hand, run `interactive` on a project with more than twelve aliases and some rows no rule matches, with the system set to light: 1. The corner shows three buttons, and "follow the system" is pressed. The page is light. 2. Press dark. The page, the rows' tints, the inputs, the scrollbars and an open rule's fields all turn dark, and dark is pressed. 3. Reload. The page is dark from the first frame, with no light flash. 4. Switch the system to dark and back while the page is open with dark pressed. Nothing changes. Press "follow the system", and switch again. The page follows. 5. In both schemes, neighbouring field colours are told apart, and the text on them reads easily. Open a new rule's prompt and give it a name already taken. The refusal reads easily. 6. At the top of the page, nothing is under the buttons. Scroll down: the rows pass under them and can be scrolled clear. 7. With the browser blocking the site's data, press dark: the page turns dark. Reload: the page follows the system again, and nothing fails. 8. At phone width, the summary wraps beside the buttons rather than under them. ## 7. Build And Packaging `build.zig.zon` pins the three dependencies exactly as required by `M1-PKG-003`, `M1-PKG-004`, and `M1-PKG-005`. The Nix flake (`M1-PKG-002`) provides: - `packages.default` — the application, Zig 0.17.0 (`M1-PKG-001`). - `checks.unit` — `zig build test`. - `checks.lint` — `zig build lint`, zlinter over the Zig sources. - `checks.ui-lint` — `zig build lint-ui`: `deno lint` over the interface's JavaScript and `biome lint` over its CSS, each configured in `src/ui/` (D1). HTML is not linted. - `checks.ui-test` — `zig build test-ui`, `deno test` over the interface's JavaScript (D1). - `checks.hledger` — the compatibility suite, hledger 1.52.3 via pinned `fetchurl` (D2, `M1-JRN-008`, `M1-PKG-007`). hledger is never a runtime dependency (`M1-JRN-007`, `M1-PKG-007`). `zig build bench` is not a check. It times the steps of one evaluation (§6.8) and is never installed. `zig build test` compiles it and runs its test, so it cannot rot unnoticed. ## 8. Test Strategy Tests are written **before** implementation (`PROCESS.md`). Every test name begins with the requirement ID it discharges: ```zig test "M1-CSV-003: crlf mode rejects a lone LF inside a quoted field" { ... } test "M1-HIST-008: 100.0 and 100.00 compare structurally equal" { ... } ``` This makes coverage mechanically checkable: extracting IDs from test names and diffing against REQUIREMENTS.md reports any uncovered requirement. Three layers: 1. **Unit** — per module, no I/O. 2. **Golden fixtures** — `tests/fixtures/`, CSV and journal pairs exercising emission and comparison. 3. **Acceptance** — `M1-AC-001` … `M1-AC-021` end-to-end against temporary project trees. The interface's JavaScript is tested with `deno test`, one `name_test.js` beside each module, named the same way (`Deno.test("D8: …")`, with the design decision's number where no requirement applies). Only what can run without a page is tested: the modules export the decisions the interface makes, and build elements only when called, so a test imports them without a DOM. `app.js` and `rule-editor.js` touch the page when loaded and have no tests; they are kept to wiring, and what they do on screen is checked by hand (§6). Assertions come from `node:assert`, built into Deno, so the tests need no network and nothing to fetch. `M1-JRN-008` requires compatibility tests covering the complete range of emittable text. The generator enumerates the §4.5 accepted set and asserts hledger 1.52.3 parses each result. ## 9. Deferred Work The REQUIREMENTS "Deferred And Out-Of-Scope Features" list applies unchanged. Design-level deferrals additionally: - No concurrency in the server; one request at a time. - No incremental re-evaluation; every edit triggers a full re-evaluation of current and historical rows. Acceptable because snapshots are in memory and the workload is one user's bank statements. - No regex compilation cache across edits. - Cells are selected with the mouse only (§6.7). Reaching them from the keyboard would need focusable cells or arrow keys within the table. The row buttons and the rule picker work from the keyboard. ## 10. Traceability, Assumptions, Risks ### 10.1 Traceability matrix | Group | IDs | Owning modules | | --- | --- | --- | | M1-YAML | 001–004, 009–011 | `yaml/events.zig` | | | 005–007 | `yaml/tree.zig` | | | 008, 012 | `yaml/schema.zig` | | M1-PROJ | 001–005 | `config/Manifest.zig` | | | 006–014 | `discover.zig`, `Target.zig` (014) | | | 015–017 | `Snapshot.zig` | | | 018 | `engine/Candidate.zig`, `engine/Profile.zig`, `ui/Project.zig`, `ui/Session.zig` | | M1-CSV | 001–007, 010 | `csv/reader.zig` | | | 008, 009, 011–014, 023 | `csv/fields.zig` | | | 015 | `expr/lexer.zig`, `template.zig` | | | 016, 017, 020, 021 | `row.zig` | | | 018, 019 | `Decimal.zig` | | | 022, 024 | `engine.zig`, `diag.zig` | | M1-RULE | 001, 002, 011–013 | `config/rules.zig` | | | 003–005 | `expr/parser.zig` | | | 006–010 | `engine.zig` | | | 014, 015, 021 | `expr/lexer.zig` | | | 016 | `Decimal.zig` | | | 017, 018 | `expr/regex.zig` | | | 019, 020 | `expr/eval.zig` | | M1-TPL | 001–012 | `template.zig` | | M1-JRN | 001–012 | `Journal.zig`, `journal/Transaction.zig`, `journal/Posting.zig`, `journal/Amount.zig` | | | 013, 014 | `Target.zig` | | M1-HIST | 001–003 | `engine.zig` | | | 004, 005, 013 | `journal/parse.zig` | | | 006–010, 014 | `Journal.zig`, `journal/Comparison.zig` | | | 011, 012 | design invariant: no accept/suppress path exists | | M1-CLI | 001 | `cli/Invocation.zig` | | | 002–005, 007, 008 | `cli.zig` | | | 006 | `main.zig` | | M1-UI | 001–004 | `ui/server.zig` | | | 005–021 | `ui/Session.zig`, `ui/state.zig`, `ui/Editor.zig`, `ui/Output.zig`, `ui/app.js` and the modules it imports (§3.2) | | | 022 | design note: builder not implemented (optional) | | M1-DIAG | 001–004 | `diag.zig` | | M1-SAFE | 001 | cross-cutting; asserted by determinism tests | | | 002, 003 | `Target.zig` | | | 004 | cross-cutting; arena limits and checked arithmetic | | M1-PKG | 001–007 | `build.zig`, `build.zig.zon`, `flake.nix` | | M1-AC | 001–021 | `acceptance.zig` | ### 10.2 Assumptions Each is a deliberate position, not an oversight. - **A1** — `i64` amount range. `M1-CSV-019` requires exact decimals without stating a bound; a cell exceeding `i64` at its scale produces a diagnostic rather than a representation. User-approved (D3). - **A2** — Duplicate YAML keys are rejected (D5). `M1-YAML-007` permits either behavior. - **A3** — *Discharged in T01.* Dependency APIs were originally read over the network; they have since been verified against the vendored sources. Confirmed: `Parser.init(allocator, input, dialect)`, `next() !?Record`, error set exactly `{InvalidCsv, UnterminatedQuote}`, no position in errors, and Parser fields `allocator, input, pos, dialect` with **no record ordinal**; `CompileFlags{case_insensitive, multiline, dot_all, extended, unicode}` giving `M1-RULE-017` its `i`/`m`/`s` directly. Corrected: §3.3 previously claimed we must suppress a trailing-newline record, which zarko already does. - **A4** — `M1-UI-022` makes the guided expression builder optional; it is not built. ### 10.3 Risks - **R1 — Regex blowup.** *Narrowed in T09, not closed.* zig-regex advertises linear-time Thompson NFA *and* backreferences and lookaround, which no single engine provides. Measured against the pinned revision: `(a)\1`, `(?=a)b` and `(?<=a)b` all compile, so a backtracking path exists; but `(a+)+b` is **refused at compile time**, so the textbook catastrophic shape is unreachable from a rule. Whether other exponential shapes survive that guard is unknown. `M1-RULE-018` defers semantics to the pinned revision; `M1-SAFE-004`'s fail-safe requirement is checked in T26. The library also ships `pattern_analyzer.analyzeAndValidate` if a further guard proves necessary. - **R2 — Dependency maturity.** zig-regex's `root.zig` still reports version `0.1.0` at the v0.2.1 tag, and the surface is very large for a 0.2 release (C API, WASM, macros, linting). - **R3 — libyaml encoding.** libyaml auto-detects UTF-16 and may silently consume a BOM, so `M1-YAML-001` must be enforced by inspecting the first bytes *before* the buffer reaches libyaml. - **R4 — zarko error positions.** Errors carry no position; a mid-record failure reports the record's starting row. - **R5 — hledger binary availability.** *Resolved.* Release 1.52.3 (2026-08-27) publishes `hledger-linux-x64.tar.gz`; the extracted binary reports `hledger 1.52.3, linux-x86_64`. Fetch it with: ```nix url = "https://github.com/simonmichael/hledger/releases/download/1.52.3/hledger-linux-x64.tar.gz"; hash = "sha256-0UpPwqyAS1VvSBtk6MVO+jgNsayFs3I8nfex7q3nSzo="; ``` Only an x86_64 Linux build is published, so `checks.hledger` exists on that system alone. The tarball also carries `hledger-ui` and `hledger-web`, which milestone one does not use. ## 11. Requirement Concerns Raised, not resolved. No requirement text is modified. ### 11.1 Whitespace-only posting comments `M1-TPL-010` requires emitting an untrimmed whitespace-only posting comment, and `M1-JRN-009` defines the decoded payload as exact text minus syntax delimiters. hledger trims comment whitespace when parsing, so such a comment is **not** round-trip-lossless through hledger, which is in tension with `M1-TPL-011` and `M1-JRN-011`. **Resolved.** Our own parser is the model of record. A posting comment is emitted as `; ` followed by the payload, and parsed by consuming exactly one space after `;`, so a whitespace-only payload round-trips through **our** parser. `M1-HIST-004` makes that parser authoritative for historical comparison, and `M1-JRN-007` requires only that hledger *accept* the syntax, not that hledger's decoded payload equal ours. Two consequences are accepted rather than avoided. hledger's own reading of such a comment differs from ours, so `M1-JRN-008`'s compatibility suite asserts only that hledger parses the output, not that it agrees about the payload. And a trailing-whitespace comment is fragile under external editors and version-control hooks that strip it, which would show up as a historical difference. ### 11.2 `|` in narration hledger splits a transaction description into `payee|note`. Our model treats narration as one opaque string, so a `|` would mean hledger and csv2journal disagree about parsed data. D4 rejects `|` in narration, which resolves the divergence at the cost of failing rows whose bank text contains a pipe. Recorded so the trade is visible rather than implicit. ### 11.3 Narration whitespace in an approved journal **Raised, not resolved.** `M1-AC-005` requires that an approved journal differing from the candidate only in *whitespace* still validate. `M1-HIST-009` requires narrations to be compared with exact string equality, without trimming. For whitespace **surrounding a narration** these pull in opposite directions, and only running hledger 1.52.3 makes the disagreement visible: hledger strips such whitespace, so it reads two journals that differ only there as identical, while our parser does not. The surface is now small. D4 was extended in §4.5 so a narration with surrounding whitespace can never be *emitted*, which means no journal this program generated can exhibit the difference. What remains is an approved journal written or reformatted by hand — for instance by an editor that strips trailing whitespace — whose narration then stops matching the candidate. Two ways to close it, neither taken here: 1. Trim the narration when parsing an approved journal, on the grounds that hledger's description genuinely does not include surrounding whitespace, so this determines what the narration *is* rather than how it is compared. This satisfies `M1-AC-005` fully and leaves `M1-HIST-009`'s "exact equality" applying to the parsed value. It is a reinterpretation of `M1-HIST-009` and so is not ours to make. 2. Amend `M1-AC-005` to say which whitespace it means — indentation, field gaps, line endings and blank lines — which is what the acceptance test now covers. The acceptance test for `M1-AC-005` deliberately exercises only the whitespace that is uncontroversially non-structural, and names this section. **Mitigated, pending that decision.** `journal/Comparison.zig` now detects when two values differ only in whitespace and renders them with the whitespace visible — a space as `·`, a tab as `→` — rather than printing two strings that look identical. This changes nothing about what counts as equal; it only stops the refusal reading like a fault in the comparison. The likeliest instance is not a narration but a posting comment: `M1-TPL-010` requires emitting one untrimmed, and editors strip trailing whitespace on save. ### 11.4 Two-digit years **Raised, not resolved.** Issue #9: German banks export dates such as `30.12.25`. `M1-CSV-016` admits a format of exactly `YYYY-MM-DD` or `DD.MM.YYYY`, so every row of such a file fails with `'30.12.25' is not a DD.MM.YYYY date`, and no profile can describe it. Proposed wording, for the author to adopt or reject: > **M1-CSV-016**: `profile.transaction.date` MUST contain a field alias and a format of exactly > `YYYY-MM-DD`, `DD.MM.YYYY`, or `DD.MM.YY`. The selected cell MUST represent a valid Gregorian > calendar date in that exact format. A two-digit year `YY` denotes the year `20YY`. Generated dates > MUST use `YYYY-MM-DD`. What the wording settles: - A third format rather than a looser `DD.MM.YYYY`. Each profile still names one exact format, so a `DD.MM.YY` profile rejects `30.12.2025` and a `DD.MM.YYYY` profile still rejects `30.12.25`. - `YY` is always `20YY`. The POSIX pivot (69–99 as 19xx) would silently move `70` to 1970, and a bound relative to today would make output depend on when the program runs (`M1-SAFE-001`). - The cell is exactly eight characters, zero-padded, like the other two formats. One profile holds one format, so an input root whose files mix two-digit and four-digit years remains unsupported. That matches the author's data and is not addressed here. **Resolved.** The author amended `M1-CSV-016` to admit `DD.MM.YY`, meaning "a year in the 21th century". The author confirmed the reading taken here: `00` to `99` map to 2000 to 2099, as proposed above, rather than the strict 2001 to 2100. ### 11.5 Grouped amounts **Raised, not resolved.** Real bank exports write amounts such as `3.907,07`, meaning `3907.07`. `M1-CSV-018` rejects grouping outright, and `M1-YAML-012` limits `profile.transaction.amount` to exactly `field` and `decimalSeparator`, so no profile can describe such a file. Proposed wording, for the author to adopt or reject: > - `profile.transaction.amount`: exactly `field` and `decimalSeparator`, with optional > `groupSeparator`. > **M1-CSV-017**: `profile.transaction.amount` MUST contain a field alias and a `decimalSeparator` of > exactly `dot` or `comma`. It MAY contain a `groupSeparator` of exactly `none`, `dot`, or `comma`; > when absent it is `none`. A `groupSeparator` equal to the `decimalSeparator` MUST be rejected. > **M1-CSV-018**: An amount cell MUST consist of an optional ASCII `+` or `-`, an integer part, and an > optional separator followed by one or more ASCII fractional digits. The separator MUST be the > configured `.` or `,`. The integer part MUST be one or more ASCII digits or, when a group separator > is configured, one to three ASCII digits followed by one or more groups, each the configured group > separator and exactly three ASCII digits. Grouping with any other separator or group width, exponent > notation, `.5`, `1.`, and surrounding whitespace MUST be rejected. > **M1-RULE-016**: … A CSV field reached by a numeric predicate MUST use the profile's amount-cell > grammar and separators. … What the wording settles: - A separate optional key rather than a combined format pattern, so every existing profile keeps its meaning and needs no edit. - Grouping is permitted, not required. A `groupSeparator: dot` profile accepts both `3.907,07` and `3907,07`: the tool accepts what banks export rather than validating their formatting. - Within one cell grouping is all or nothing. `1.234567,00` and `1234.567,00` are rejected, as are empty groups (`.907,07`, `3..907`, `3.,07`) and a trailing group separator. A leading `0` group such as `0.907,00` is accepted, consistent with `007` today. - One grammar for every numeric cell. Because grouping is optional, applying it to every field a predicate reaches costs nothing for ungrouped columns and needs no second grammar. - Output is unchanged: `M1-CSV-019` already renders `3.907,07` as `3907.07`. Rule literals stay ungrouped under `M1-RULE-016`, so `amount >= 1.000` still means one. Deliberately left out until a real file needs them: space, apostrophe, and no-break-space grouping; a trailing sign such as `3.907,07-`; two-digit (Indian) grouping; grouped amounts in approved journals. The `none | dot | comma` enumeration can grow without breaking existing profiles. **Resolved.** The author amended `M1-CSV-017`, `M1-CSV-018`, `M1-RULE-016` and the amount line of `M1-YAML-012` with the wording proposed above.