GitHub
Imports internals

Imports internals

This page is for maintainers. It explains how the import pipeline works and why it is built the way it is. For how to use it, see the user pages:

The rules-file scope is to discover, present, edit and save rules files, and to draft a new one from a dropped CSV. Writing a chosen category back as a new if rule is still out of scope. The model below is shaped so that it can be added later without changing what exists.

The GUI does not offer raw text editing, because a terminal does that better. The GUI covers preferences, the row mapping, the two default accounts, and an ordered list of if rules.

Statement conversion handles CSV/TSV/SSV, OFX/QFX/QBO, and xls/xlsx/xlsm/xlsb/ods. PDF is refused by name. See PDF statement extraction for the survey and the route back in. A QuickBooks Online Journal .xlsx is detected and handed to its own pipeline, described in Importing a QuickBooks Online Journal export below.

Where the code is

PathWhat it holds
crates/ledgeline-core/src/rules.rsThe format-preserving document model: parse, classify, render, EditPlan/apply/verify
crates/ledgeline-core/src/rules/discovery.rsThe directory scan, RulesPath, Discovery::resolve, the CSV preview
crates/ledgeline-core/src/rules/matching.rsScoring a rules file against dropped data with the two-stage matcher
crates/ledgeline-core/src/rules/generate.rsDrafting a NEW rules file from a CSV: column guessing, date-format, decimal-mark
crates/ledgeline-core/src/convert/Statement preprocessors: ofx, spreadsheet, delimited, shared encoding
crates/ledgeline-core/src/reimport.rsMatching a re-downloaded statement against the journal by row id, and the four-way split that follows
crates/ledgeline-core/src/sort.rsFormat-preserving date sort of a journal file
crates/ledgeline-core/src/journals.rsRanking candidate target journals, by content only
crates/ledgeline-core/src/aliases.rsalias directives: forwarding them to --alias, and the one-line-wide span editor
crates/ledgeline-core/src/hledger_conf.rshledger.conf: reading its --alias options, and the escaping rule for writing one
crates/ledgeline-server/src/rules_api.rs/api/rules, /api/rules/{*id}, /api/rules-preview/{*id}, /api/rules-create
crates/ledgeline-server/src/alias_api.rs/api/aliases, /api/aliases/{*journalId}
crates/ledgeline-server/src/{hledger,prefs}.rsSubprocess invocation, the preferences store
web/src/lib/imports/Pure form model, reorder, date-format catalogue, store, UI
fixtures/rules/, fixtures/import/The corpora. Each README.md explains what every fixture is for

Subprocesses: one module, no shell

crates/ledgeline-server/src/hledger.rs is the only place in production code where Command::new may appear for an external tool. This rule is deliberate and can be enforced. The codebase already refuses to execute a rules file’s source ... | CMD directive (see Security), so it would make no sense to then spread process spawning across the server.

That module follows these rules:

No hledger we run reads a config file

Every invocation starts with --no-conf, added in Invocation::argv. Every argument vector passes through that one function on its way to Command::args.

hledger 1.40 introduced automatic config files, and the search is not opt-in. hledger looks for hledger.conf in the working directory or any directory above it, then $HOME/.hledger.conf, then the XDG config dir. Invocation deliberately sets no working directory, so without the flag we would inherit whatever config sat above the directory Ledgeline was launched from. Ledgeline never chose that file and cannot see it.

A config file can replace the command. This was verified against hledger 1.52, with a hledger.conf whose entire content is the bare word balance:

$ hledger import --dry-run -f rt.journal --rules ms.csv.rules ms.csv
hledger: Error: Unknown flag: --dry-run
* while parsing the following args, final command line:
*  balance import --dry-run -f rt.journal --rules ms.csv.rules ms.csv

Our command became an argument to a different command. hledger’s manual states the rule: a first word in the general section that does not begin with a dash is taken as the command, overriding the command line. That example errors, but other configs would not. A config could inject --auto, --forecast, -b/-e, --depth or --alias into invocations whose output we parse and whose results we append to the user’s journal. Explicit flags do beat config ones (verified: -O json on our command line beats -O csv in a config). So the danger is not only breakage. A config file would decide what our subprocesses do, instead of Ledgeline.

This has two consequences:

The test is an argument-level lint (import_api::tests::every_import_invocation_disables_config_files) plus a companion that counts .invoke( call sites, so a new invocation cannot be added without the flag. A behavioural test would need a hostile hledger.conf planted above the test runner’s working directory, which is this repository, and it would break every other test in the run. The flag is also observed arriving at a real process in tests/prefs.rs.

Two journals for writing and for reckoning

The file an import is written TO is not the file its balances are computed FROM.

An import appends to one file, for example 2026/2026.journal. A balance is a property of the whole tree, so it is computed from the root, the journal Ledgeline was opened with. In a single-file journal the two are the same file and nothing here matters. In every split layout they are different files, and treating them as one caused both of the bugs below.

import_api::Plan therefore has no field called journal. It has target (the write destination) and root_journal (what everything is reckoned against). A single field named for neither job is how the two got confused.

Why the import disables balance assertions

hledger import runs with --ignore-assertions. Removing it does not restore safety.

import is the only invocation that reads the target file alone, with one -f naming a fragment. A balance assertion inside an included fragment cannot be correct in that context, because the balance it asserts accumulates through files hledger was never asked to read. Turning it off loses nothing. This was verified against 1.52 on the layout in fixtures/import/layouts/split-year-assert/:

$ hledger -f main.journal check                 # the tree is fine
$ hledger -f 2026/2026.journal import --rules bank.csv.rules bank.csv
hledger: Error: …/2026/2026.journal:13:38:
  13 |     assets:bank:checking              $0 = $900.00
Balance assertion failed in assets:bank:checking

A start-of-year assertion carrying the prior year’s closing balance is what hledger close --assert writes, and it is a very common way to keep books. Without the flag, the import failed for every journal kept this way. The assertion is meaningful at the root, where hledger still evaluates it.

The flag does not lose either of these, both checked against the binary:

The flag goes on that one invocation and no other, the same rule --alias follows. Two unit tests check both directions. One asserts the import carries it ahead of the subcommand, and the other asserts no balance invocation does.

Why the balance verifications read the root

verify_balance and check_assertion send include <ROOT> plus the proposed entries down one pipe. They never use two -f flags (fact 3), and never read the target. include <root> plus the proposed entries is what the tree will look like once this import lands. The proposed entries are hledger’s own dry-run stdout, which is not in the target yet, and the target is reached through the root’s own include, so nothing is counted twice.

Reading the target instead caused two failures, and the second is worse:

what the user saw
target holds an assertioncomputed: "" and a refused commit, quoting hledger’s complaint about a start-of-year line the user never typed
target holds nonea plausible balance that is silently wrong by whatever the other files hold: $2043.55 where the truth is $2038.55, matches: false, and no error anywhere

import_endpoints.rs tests both against the committed fixtures/import/layouts/split-year-assert/ tree, and asserts the right number and the wrong number. Equality with the wrong one is the bug, so a test that only checked the right one would pass whenever the two coincided.

Two reads deliberately stay on the target:

Keeping a rules file’s skip count correct

skip N is counted against the file the BANK produced. Our conversion strips the preamble, so Ledgeline pads every copy hledger reads until skip N lands on the first data row again.

hledger has no header concept. skip N discards N records and every record after them is data, so a rules file written for a two-line preamble plus a header says skip 3. Ledgeline converts that download to a canonical CSV with the header on line 1, and then hands the converted statement to the same rules file. Verified against hledger 1.52:

the file hledger readsskiptransactions
the raw download (2 preamble lines, header, 3 rows)33
our converted CSV (header, 3 rows)31
our converted CSV (header, 2 rows)30

The exit code is 0 every time, with nothing on stderr. The user’s own correct rules file and their own statement produce a silently truncated import that reports success. On a short statement every transaction is lost. On a long one it is worse, because some transactions do arrive and the loss is harder to notice.

convert::align_to_skip fixes the count by prepending skip - 1 empty records. One accounts for the header, which hledger still skips, and the rest stand in for the preamble that is gone. skip 0 and skip 1 are already correct against a header-on-line-1 file and are returned byte for byte, so nothing about an import that works today changes.

Three details were measured, not chosen:

These are the places that read an aligned copy:

What reads itHow it is aligned
candidate scoring’s printStage::aligned(candidate's skip)
the dry-run, the dedup measurement, the alias diffs, the balance preflightStage::materialize(…, plan.skip)
the commit’s import and --catchupthe CSV written to the user’s destination

Note the last row: the CSV a commit saves carries the padding. It has to. Those two invocations must read the destination file, or hledger would key .latest.NAME to a name in a temp directory that is about to be deleted. An unpadded file there would make the commit import the wrong rows and report that count as the full count. It is also the file the user keeps and re-imports later, from this screen or from a terminal, with that same rules file. The padding makes both imports read the same rows. save-csv writes the canonical CSV unpadded, because that route has no rules file and so no skip to align to.

The canonical staged CSV (Stage::data()) is never padded. The preview is rendered from it and save-csv keeps it. matching::prefilter and sample_dates work on the in-memory Tabular rather than on any file. They already compensate for the stripped preamble there, so padding that copy would compensate twice.

fixtures/import/delimited/preamble.csv and preamble.csv.rules are the test pair, and both checks that use them assert the wrong number as well as the right one: converted_and_aligned_imports_what_the_raw_download_does (core, LEDGELINE_HLEDGER_CONVERT_CHECK) and a_rules_files_own_skip_still_counts_after_the_preamble_is_stripped (server, LEDGELINE_HLEDGER_IMPORT_CHECK, covering the candidate card, the dry-run and the commit).

hledger proposes; Ledgeline appends

hledger import never writes a user’s journal. It previews, and it remembers.

The commit runs three steps where the obvious design would run one:

  1. hledger import --dry-run → the deduped proposal, on stdout;
  2. Ledgeline appends that text, unaltered, with edit::atomic_write;
  3. hledger import --catchup → hledger records .latest.NAME itself.

Why

It makes the preview the bytes. The text the dry-run route returned is the text the commit appends. It is the same string, not a second rendering of the proposal that could differ from the one the user approved on screen. The rest of this section depends on that. The byte-compatibility test can compare whole files, and the entry count is taken from the text that was written.

Splitting the write also means Ledgeline performs the one atomic write it needs, and hledger still maintains .latest. The dedup state stays in hledger’s format, managed by hledger, and Ledgeline does not interpret it.

Commodity style: why imported amounts keep hledger’s own spelling

Read this before proposing to re-print imported entries in the journal’s declared style. It was built, it worked, and it was removed on purpose.

A journal declaring commodity $1,000.00 receives $165.2 and $-405 where its author writes $165.20 and $-405.00. That is a real but minor annoyance, and it is accepted.

The facts, all verified against hledger 1.52:

It was removed because prepending those directives changes how the entries parse, not merely how they print.

$ hledger -f 2026/2026.journal import --dry-run …    # the fragment declares nothing
    assets:bank:checking        EUR165.2
$ printf 'commodity 1.000,00 EUR\n\n…' | hledger -I -f- print --round=soft
    assets:bank:checking     1.652,00 EUR             # exit 0

That is ten times the money, with no error. It happens here because the import reads a fragment, the file that does not carry the declaration, so hledger writes the CSV’s own . while the tree declares ,.

A value-comparison guard did catch it. The guard parsed both texts bare, compared dates, status, code, tags, accounts, amounts and assertions, and discarded the restyle on any disagreement. The guard worked, and the feature was still removed. On a multi-commodity book the failure is not a tenfold error on a bank balance but a wrong share quantity. A cosmetic gain does not justify that risk, even behind a guard that currently works. (The motivating user’s own rules file has a commented-out #currency $ # messes up stock quantities, so they had already hit a version of this problem.)

So imported amounts keep hledger’s own spelling. imported_amounts_keep_hledgers_own_spelling_not_the_declared_style asserts it, so the behaviour cannot change back by accident.

If a future implementer wants the declared style, the safe approach is to make the CSV carry correctly scaled amounts. That belongs in the rules file or a preprocessor, where the number is still only a number. Do not re-print finished entries under directives they were not parsed with.

The catch-up, and what happens when it fails

--catchup records .latest.NAME without appending anything. This was verified: the journal is byte-identical afterwards, the state file is byte-identical to the one a writing import leaves (including the repeated same-date lines that encode how many records share the newest date), and a following dry-run reports no new transactions.

If it fails after the append, the journal would hold the entries while the marker still pointed at the previous import, and the next import of that statement would propose them again. So a failed catch-up rolls the journal back to the bytes read moments earlier under the write mutex and reports the whole commit as failed. That is the same all-or-nothing property preflight_assertion gives a mistyped balance. If the roll-back itself fails, the error says so explicitly and names the duplication risk, because the user has to know about that state.

Byte compatibility with hledger’s own append

Ledgeline copies hledger’s append exactly, because when we take over hledger’s write we should not change its output. A dry-run writes its proposal followed by a blank line. A real import appends a leading newline and the same text with that blank line removed:

stdout   "2026-02-01 A\n    …$-405\n\n2026-02-03 B\n    …$165.2\n\n"
appended "\n2026-02-01 A\n    …$-405\n\n2026-02-03 B\n    …$165.2\n"

hledger does not check whether the file already ends in a newline, so a journal saved without one gets the first imported transaction on the line straight after the last posting. Ledgeline reproduces this exactly. An empty proposal appends nothing at all.

the_appended_bytes_are_hledgers_own_append tests this end to end. A real hledger import imports the same statement into a copy of the same journal, and the test compares the two files byte for byte. Because nothing re-styles the proposal in between, this now holds for every journal, not only the ones declaring no commodity style.

Matching a re-download by row id

hledger de-duplicates by DATE, and dates cannot tell a re-downloaded row from a new one.

.latest.NAME holds the newest imported date, and every row at or before it is dropped. That is right for an append-only download and wrong for the YTD-redownload workflow, where the same row arrives twice: once as an authorization hold, and again once it settles. The second copy sits behind the marker, is never proposed, and the journal keeps the pending version forever. TODO.md records this, and the worse part of it: the dry-run’s “N rows skipped” count cannot distinguish “already imported identically” from “already imported differently”.

The id is the bank’s, and it needs no new grammar

OFX/QFX/QBO give every transaction a FITID, which convert::ofx already emits as the fitid column. A rules file names it as the dedup id with one ordinary line:

comment id:%fitid

comment is a top-level assignable field, so this needs nothing added to rules.rs. Verified end to end against hledger 1.52:

$ hledger print -f bank.csv --rules bank.csv.rules
2026-01-05 ! COFFEE SHOP  ; id:FIT0001
    assets:bank:checking           -4.50
    expenses:unknown                4.50
$ hledger print -f bank.csv --rules bank.csv.rules -O json | jq '.[0].ttags'
[["id","FIT0001"]]

A FITID reaches the fitid column with its commas removed. An hledger tag value ends at the first comma (verified against 1.52), and our own parse::parse_tags splits the same way. One credit union’s Web Connect file writes 20260227 212165 561,516 1,041,790, which hledger reads back as 20260227 212165 561. Every row sharing that prefix then shares an id, so the second row is classified against the first and silently left out. convert::ofx::tag_safe strips the commas and collapses whitespace runs, and a_fitid_with_commas_survives_as_a_whole_hledger_tag pins it. A draft from rules/generate.rs writes comment id:%fitid whenever the data has a fitid column, so a rules file made by Ledgeline is on this path from its first import.

The tag must also come through our own parser, and that is the part that matters. parse.rs’s tag extraction puts ("id", "FIT0001") in Transaction.tags, which is what reimport.rs reads. hledger’s JSON is never consulted at runtime. The tag key is plain id rather than a Ledgeline-private spelling, because the rules file has to stay readable to somebody running hledger from a terminal.

An id can remove rows from an import, never add them

The feature depends on this safety property, and it is asymmetric on purpose.

Journals hold transactions imported before the rules file grew its comment id: line, and those carry no id at all. If a missing id were ever read as “this row is new”, the first re-download after adding that line would duplicate every untagged transaction in the file. So:

Each row gets one of four outcomes, and only two of them change anything:

what happens
newno transaction carries this id. Imported as usual, still subject to .latest
unchangedthe journal already holds it, identically. Not imported, not edited, counted
statusChangedonly the clearing status differs, as with a hold that settled. Synced
conflictingsomething a status flip cannot express differs. Reported with the diff, never imported and never edited

“Status-only” means only status. A hold that settled for a different amount (the tip added at the till) is conflicting, not a sync. A rules file that assigns no status field at all produces no status-only rows. Every proposed row is then unmarked, so a * the user typed by hand would read as a status-only difference, and syncing it would erase their mark. Ledgeline tells whether the file assigns a status from hledger’s own output rather than by reading the rules file, because import never marks a transaction by itself.

The comment is deliberately not compared. People annotate transactions they have already imported there (; id:FIT0001, reimbursed by work), and treating a note as a conflict would report one for every annotated transaction.

The status flip is the ordinary transaction editor

This uses no new write path. JournalEditor::set_status already rewrites exactly one header line’s */! marker and re-parses to check it, and edit_api::set_statuses drives it through the same lock_editor → bound → save_and_publish sequence, with the same re-sync on a partial failure, that PATCH /api/transactions/{index} has always used.

The flip has three rules about when and where it writes:

Nothing is ever written on a dry-run, so applied is false throughout a preview.

Opt-in, byte for byte

A rules file that names no id gets "idMatches": null, not an empty object, because “there is no id to match on” and “there is, and nothing matched” are different answers. The proposal is passed on as the same String hledger produced, without going through the filter. Even when the filter does run and finds nothing to drop, it hands back the borrowed input, so the untouched path cannot differ by a byte. fixtures/import/reimport/pending-then-cleared/ has no-id.csv.rules beside bank.csv.rules. It is the same file minus that one line, so the two can be run against the same statement and compared.

One upload, several accounts

A “download all accounts” OFX holds one STMTRS/CCSTMTRS per account. QuickBooks Web Connect files from credit unions are the common case. They are never merged: a rules file names one account1, and .latest.NAME is keyed to the CSV’s name. If two accounts shared a CSV, the account whose statement ends earlier would lose rows to the other’s marker. So one stage reads one statement:

Ranking ties, and the names that break them

Every QBO converts to the same seven columns, so a rules file written for one bank’s Web Connect file scores the same against every bank’s. matching::rank therefore treats candidates whose scores show as the same percentage as tied. Among them, Ranking::affinity comes first, ahead of the raw score and the mtime. NameHints takes the words of the upload’s name, dropping extensions, generic words such as export and activity, and every number, because a year shared with the wrong file is no hint. It also takes the account’s last four. Affinity counts the words that appear in the rules file’s id or account1, and adds 2 when a run of digits there ends in the account’s last four. A word matches only a whole word, so el does not match elevations. A name never outranks a better shown score, and the family order of plan 32 D27 applies inside the same tie.

The one invariant everything rests on

Item spans partition the file exactly. items[0].span.start == 0, each item ends where the next begins, and the last ends at text.len(). There are no gaps and no overlaps.

Three properties follow directly from that:

CRLF, a BOM, tabs, column alignment, trailing whitespace and a missing final newline all survive with zero special cases, because nothing is re-rendered that was not edited.

This is why the model is spans over a String and not an AST with a pretty-printer. When an AST meets a construct it does not model, it silently loses data on save. The file still parses, but it no longer says what it said. When a span model meets one, it reports that the item cannot be edited, which is visible and safe.

Editable vs opaque

The editor has two separate obligations. Mixing them up is how a span editor corrupts files.

(A) Extent must agree with hledger exactly. If our idea of where an item stops differs from hledger’s, editing or moving it damages its neighbour. When extent is uncertain, widen it and put the ambiguous text into one opaque item.

(B) Classification may be as narrow as we like. Anything unclassified is opaque: its bytes are preserved, it is listed in order, and it can still be reordered. When in doubt, make it opaque.

An if block is editable only if every matcher is plain, a plain line-prefix & AND-continuation, or one piece of a same-line && join (no !, no leading &/&& on the first matcher line), has no match group, and does not begin with ;/#/*; every body line is a known field assignment or a bare skip/end. Everything else, including if tables, negated matchers, match groups and skip N, renders as a dimmed read-only card that says why it is locked. It can still be moved.

A block’s matchers are therefore an OR of AND-groups: a plain line opens a new OR branch, and each & line below it, plus each &&-joined piece on any of those lines, is AND-ed onto that branch. if\nA\n& B\nC\n& D selects (A and B) or (C and D), and so does if\nA && B\nC && D. The two spellings compose: if\nFIRST\n& SECOND && THIRD\nFOURTH is (FIRST and SECOND and THIRD) or FOURTH. Neither combinator is stored as text. The model represents the AND as nesting (groups[].matchers[] on the wire), so no matcher pattern can contain one, and the renderer only ever writes the line-prefix form.

A block may also carry hledger’s control flow, as control: "skip" | "end" beside the assignments rather than as an assignment: skip drops the matching row and end stops reading at it. A block whose whole body is one of those is legal and needs no assignment at all. Reordering such a block among other blocks does not change a single imported row (verified), so the rules list moves it like any other.

Order matters. Every matching block applies, and the last assignment to a field wins. The UI says “later matches win” for that reason.

Grammar facts that are easy to get wrong

These were verified against hledger 1.52’s RulesReader.hs and the binary, not only the manual:

An if table’s extent is terminated by a blank line, so when something is placed after a table that ran to EOF, the renderer supplies that blank line. Without it the new rule would be read back as another table row.

Account aliases

A statement’s account column often holds the bank’s own words. A real Morgan Stanley export says PW Roth IRA - 3077 where the journal says assets:morganstanley:pw-roth-ira, and a rules file that interpolates the column (account1 %acct) writes the bank’s words straight into the ledger. The usual workaround is a source ./x.csv | ./clean.py line adding a mapped column, which this codebase will never run (see Security). So Ledgeline does the mapping itself.

What reaches an import’s CSV

Verified against hledger 1.52, in both directions:

So Ledgeline reads the journal’s own alias directives and hands them to hledger as --alias. The user already wrote the mapping. Ledgeline only passes it along.

The two homes an alias can live in and what each affects

The command-line parity feature depends on this distinction. The two look like the same thing but are not:

applies when hledger READS the journalapplies to an import’s CSV
alias directive in the journalyesno
--alias in hledger.confyesyes

The result is a silent difference between the GUI and the terminal. The same statement, rules file and journal give two different sets of account names depending on which tool the user ran. Verified: a plain hledger import writes PW Roth IRA - 3077:cash where Ledgeline writes assets:morganstanley:pw-roth-ira:cash.

So Ledgeline reads hledger.conf itself and merges its --alias values into the ones it forwards. Ledgeline reads the file but never passes --conf. No hledger we run reads a config file exists so that no external file controls our subprocess, and a config may hold --depth or -b/-e, which would change output we parse. Taking only the --alias values we understand gets the parity without that risk.

Ledgeline looks for the config in these places:

The config’s aliases go first. --alias options compose left to right and the first to match an account wins. Putting the config first means that wherever the two disagree, the config’s answer wins, and the config’s answer is what the terminal produces. Putting the journal first would make Ledgeline disagree with the command line in the opposite direction.

Whitespace in config aliases, and the escaping rule

hledger’s config parser splits on whitespace and IGNORES QUOTES. There is no escape for a space.

As far as we could find, this is undocumented upstream, and it is easy to lose time on. All three of these fail with a parse error:

--alias="/^PW Roth IRA - 3077/=assets:morganstanley:pw-roth-ira"
--alias='/^PW Roth IRA - 3077/=assets:morganstanley:pw-roth-ira'
--alias=/^PW Roth IRA - 3077/=assets:morganstanley:pw-roth-ira

The workaround is that the pattern is a regex, and . matches a literal space:

--alias=/^PW.Roth.IRA.-.3077($|:)/=assets:morganstanley:pw-roth-ira\1

hledger_conf::conf_argument applies these rules, in order:

  1. If there is no whitespace anywhere, write it verbatim, in whichever form the user declared. It is identical to what we forward, because it is the same string.
  2. If the replacement has whitespace, refuse. An account name is matched literally, so there is no wildcard to stand in for its space. A mapping that looks installed but never matches is worse than a visibly missing one.
  3. If a regex pattern has whitespace, substitute one . per whitespace character (never one per run, because . matches exactly one character). Refuse when the pattern also holds [, where a . is an ordinary dot, or \, where substituting beside somebody else’s escape is a guess.
  4. If a plain pattern has whitespace, convert it to a regex. A plain alias matches the whole account name or a prefix ending at a : (verified: it rewrites a and a:sub and leaves abc alone). That is exactly /^PATTERN($|:)/ with \1 carrying the boundary into the replacement. Regex metacharacters are escaped first, then whitespace becomes .. The order matters, because otherwise a literal . in the bank’s name would silently become a wildcard.

The conversion widens the match in two ways, both deliberately. A . matches any character, not only a space, and hledger’s regex aliases are case-insensitive where plain ones are not (both verified). A converted alias therefore matches everything the original did and can match a little more. That is the cost of being able to write it at all, so the resulting line is shown on screen before it is written rather than after.

Writing a config file

Writing hledger.conf is a new write target, and it gets the same safeguards as every other one here:

Column interpolation composes with it, which is what keeps the rules file small: with account1 %acct:cash, a prefix alias rewrites the base and leaves :cash intact, so one alias covers every subaccount rather than needing one per account × type.

Where the flags go, and where they do not

--alias goes on every invocation that reads the CSV, and on no other.

That means import and the candidate-scoring print. The import calls are the dry-run, the dedup measurement and the real commit. They all use one argv builder, import_invocation, with --dry-run as a parameter, so the preview and the write cannot get different aliases. Adding the flag to print means a rules card’s sample accounts are the accounts the dry-run will propose.

It is deliberately not on the balance verifications. Those read a journal, and a journal’s accounts already have the names it was written with. hledger applies the journal’s own alias directives when reading, as it always has. Adding --alias there would apply the mapping twice, and a regex alias broad enough to match its own output would rewrite an account that was correct.

Scope

hledger’s aliases are positional and file-scoped. An alias is in force from its line to the end of its file, applies to anything included after it but never back out to the including file, and stops early at end aliases. All three were checked against the binary.

--alias is global and has no way to express any of that, so Ledgeline forwards every alias not closed by an end aliases in its own file. That is the set in force where an import appends. An alias the user explicitly bounded is listed, is editable, and is never forwarded, with the reason on screen. Which file an alias is in does not change whether it is forwarded. That is a simplification, and to make up for it the whole set is shown rather than applied invisibly.

Ledgeline reads aliases but does not apply them

Journal.aliases is populated and Journal account names are left exactly as written. This is a deliberate narrowing of parse.rs’s “reject rather than misparse” rule, and that module’s docs explain it at length. In short, an alias line used to fail the whole journal, so a user who had one could not open their books here at all, and an import cannot write into a journal that will not parse. Applying the /REGEX/ form would mean reproducing hledger’s regex dialect (Haskell regex-tdfa, POSIX ERE, case-insensitive, \1 in the replacement) over every account name in someone’s books, and Rust’s regex crate is a different dialect. A near-miss would be a silent wrong answer, while declining is visible. The Account Aliases tab in Settings says this explicitly, and a test checks the sentence.

The one narrow, deliberate exception is the QuickBooks Online Journal import (WP-17; plans/17-quickbooks-journal-import.md). That pipeline cannot go through hledger import at all (there is no rules-file construct for “keep reading rows until a total line closes the group”), so it has to compute an account’s hledger name itself before it can write a transaction. It does the narrowest possible version of what this section otherwise refuses: plain (non-regex) alias matching only. That means exact string equality, plus hledger’s own rule that a plain alias also matches a prefix ending at : (the same rule hledger_conf::conf_argument’s module docs verify: “it rewrites a and a:sub and leaves abc alone”; see ledgeline_core::qb_import’s module docs for the full argument). A /REGEX/ alias is never used there either, and the account it might have matched is reported as unmapped.

What the editor refuses to model

The alias editor follows the same approach as the rules editor, applied to single lines. AliasDoc splices only the pattern and replacement extents of the line being changed, so the alias keyword, the =, and every space between them are re-emitted verbatim and a column-aligned block stays aligned with no alignment code. verify then re-renders, re-parses, and requires every unedited alias line to come back byte-identical. The server adds a whole-journal re-parse with the edited text in memory, and only then writes.

A line it cannot promise to rewrite is presented read-only with the reason, exactly as an unclassified rules construct is:

LockWhy
commentLikeA ; or # on the line. alias a = b ; note declares the account literally named b ; note, because hledger does not treat it as a comment (verified). Rewriting would lock in a reading its author almost certainly did not intend.
emptyAn empty pattern or replacement. There is no separator to re-emit, and no mapping.
delimiter= inside a plain pattern (hledger splits at the first one, so the line does not say what it appears to) or \/ inside a regex one. Re-escaping is a guess.
control / tooLongA byte this module will not write, or too many of them.

Reordering is not offered at all. Aliases are positional, so a reorder changes meaning even though it looks cosmetic. An inserted alias goes immediately after the file’s last alias line. That is the furthest-forward position that is still in force where an import appends and cannot change what anything already in the file means. If there is no alias line, or an end aliases would otherwise close it, the alias goes at EOF.

What the user sees before committing

An account rewrite must never happen silently right before an irreversible write, so the dry run reports the renames. They are measured, not inferred. The engine repeats the same import with no --alias at all and diffs the two proposals, so the before/after pairs are hledger’s own answer rather than our reimplementation of its regexes. It is the technique skipped_by_dedup already uses, and it costs one extra subprocess only when the journal declares an alias. An empty rename list means the aliases matched nothing in this statement, and the section stays hidden.

The same panel shows the command-line divergence notice, measured the same way. The engine repeats the import with exactly the aliases a config file supplies, which is what a terminal would apply, and diffs that proposal against the one on screen. With no config file the two baselines are the same command line, so the second measurement is free. With one, it costs a third --dry-run.

Measuring matters more than comparing alias strings. A user who hand-wrote an equivalent mapping into their config in their own spelling sees no notice, which is correct for a config that already works. When they do diverge, the notice names the accounts that would differ, shows the exact --alias lines the fix would write, lists any alias that cannot be expressed in a config file with the reason, and offers the one-click fix. web/src/lib/imports/aliasModel.ts holds every sentence and every decision (parityNotice, parityWarning, parityFixLabel, canInstallParityFix); ui/DryRunPanel.svelte only renders them.

Importing a QuickBooks Online Journal export

This is a second, separate import pipeline (WP-17; plans/17-quickbooks-journal-import.md has the full design). QuickBooks Online’s “Journal” report uses several rows per transaction and is already double-entry. hledger’s CSV rules engine has no construct for “keep reading rows until a total line closes the group,” so this format cannot go through hledger import at all. Ledgeline parses it itself (ledgeline_core::qb_journal) and writes transactions directly (ledgeline_core::edit::JournalEditor::add_transaction), matching each QuickBooks account against the journal’s own plain aliases (see the one narrow, deliberate exception above) rather than guessing. Ledgeline detects a .xlsx export dropped onto New Transactions and switches to a dedicated panel. The same file also works from the command line (ledgeline import -i Journal.xlsx -j main.journal, with no -o/-r; see ledgeline import --help).

How to export the report and map accounts is on the user page, Importing from QuickBooks.

Re-imports are deduplicated by QuickBooks’ own Trans #, which every imported transaction carries as an id: tag. The commit uses the same id index as the CSV/OFX path’s re-download matching: a transaction whose id is already in the journal is left alone, and one whose id is present but whose content differs is reported as a conflict and never overwritten. That is why re-running “All dates” every time is safe, and it is the recommended practice.

Security

A PUT keyed by a client-supplied path could write anywhere, which is worse than the read oracle the SEC-6 include guard defends against. Five independent layers guard it, and none depends on another.

  1. Syntactic id validation, before any filesystem call. The id may not contain .., a leading /, \, : or control characters, and must end in .rules. A hostile id never reaches the filesystem, and the choice between 400 and 404 is made on syntax rather than existence.
  2. Discovery-set membership. Discovery::resolve is the only place an id becomes a path. It uses exact string equality against a set scanned in that request. root.join(id) exists nowhere in either crate. RulesPath has a private field and no public constructor, so the type system enforces “you can only write to a file discovery returned”.
  3. Confinement, file type, symlinks. Writes are confined to the journal’s own directory (the same root include is confined to, via the shared parse::confine). Symlinks are refused outright, which is stricter than admit_include and removes cycles and a class of TOCTOU races. Only regular files are allowed, because a FIFO named x.rules would otherwise hang the request forever on read.
  4. Content provenance. Every byte written is either a byte read from that file moments earlier or renderer output over validated typed fields. The structure enforces this: the wire’s item type has no raw-text variant.
  5. No path is ever echoed. Errors quote only the caller’s own id. Every resolution failure returns the same string, so the route cannot be used to test whether a file exists.

The most important rule: hledger’s source directive accepts | CMD, which hledger import runs through the user’s shell. So source, archive and include can be kept, moved or deleted, but never written. Without that rule this endpoint would allow remote code execution. For the same reason the test suite never runs hledger against a user’s file, only against fixtures we author.

Creating a file: the one place a client string becomes a path

Layer 2 cannot serve a CREATE. Discovery::resolve only ever returns a file the scan already found; a file that does not exist yet cannot be found. So Discovery::resolve_new performs the only root.join(id) in either crate, and every guard below is there to make that safe.

  1. Shape, checked before any filesystem call. This deliberately repeats the check validate_id makes, because neither layer may assume the other ran.
  2. Discoverability. No path component may be hidden or in the scan’s SKIP_DIRS. This is less a security guard than a consistency one. A file the scan will never list is a file the user cannot then open, which is worse than refusing.
  3. Confinement, via the same parse::confine everything else here uses.
  4. A real, non-symlink parent directory. No directory is ever created, because a rules file goes beside a journal that already exists.
  5. Nothing already at the name.

Guard 5 is not what makes it safe, because its answer is stale the moment it returns. The write uses create_new (O_EXCL), so the kernel refuses an existing file, atomically at the open. edit::atomic_write is deliberately not used. It renames over the existing file, which is right for a save and wrong for a create.

Two of the four refusals return the ordinary 404. “Resolves outside the root” and “that directory is not there” are answers about the filesystem, and a route that told them apart would report whether /etc/ledgeline/ exists. “Already exists” is safe to report as itself, because it is only reachable for a confined, non-hidden *.rules name below the root, which is the set GET /api/rules already publishes.

Content provenance is unchanged, which is why the write goes through the ordinary PUT. A create is a revision: "" request over the same typed item vocabulary, rendered by the same renderer. POST /api/rules-create itself writes nothing at all. It drafts the file, and the user saves it. Drafting a file and writing one stay separate operations that are tested separately.

Sharing categorization between rules files (plan 43)

rules/share.rs splits a manual rules file’s if blocks into <account>.categories.rules, which the manual file and the bank-sync rules file both include as their last line. It works purely on text over the item partition. Moved items keep their exact bytes, everything else stays put, and SharePlan::moved_spans plus include_offset let a test reassemble the original byte for byte.

It relies on these facts (hledger 1.52, verified against the binary):

A file with no fields line and no include is never offered as an import candidate (matching::reads_csv_alone), because a categories file cannot read a CSV alone.

Concurrency

Each response carries a revision, a fingerprint of the file’s raw bytes. A save must echo it, and it is re-checked immediately before the write, so if someone edits the file in vim in the meantime the save gets a 409 instead of silently overwriting their change. The fingerprint uses raw bytes, never rendered text. A hash of rendered text would miss what we preserve but do not model (trailing whitespace, CRLF, a table’s interior), which is most of a real rules file.

Rules files stay out of the journal watcher, the snapshot and the ETag. A .rules change invalidates no transaction, so routing it through a reload would cost a full reparse for nothing.

Running the checks

just rules-check           # every fixture is a rules file REAL hledger accepts
cargo test -p ledgeline-core --test rules            # round-trip + isolation + properties
cargo test -p ledgeline-core --test rules_security   # the scan's guards
cargo test -p ledgeline-core --test rules_generate   # drafting a new file from a CSV
cargo test -p ledgeline --test rules_endpoints
cargo test -p ledgeline --test rules_create_endpoints  # the create boundary
just snapshot-rules-wire   # ONLY when the wire contract changed on purpose

# New Transactions
cargo test -p ledgeline-core --test convert_ofx      # OFX/QFX, incl. the entity matrix
cargo test -p ledgeline-core --test convert_tabular  # delimited + spreadsheet
cargo test -p ledgeline-core --test matching         # rules-file scoring
cargo test -p ledgeline-core --test sort             # format-preserving date sort
cargo test -p ledgeline-core --test journals         # target ranking, by content only
cargo test -p ledgeline-core --lib reimport          # the id classifier's four-way split
cargo test -p ledgeline-core --test reimport         # …over the committed re-download corpus
cargo test -p ledgeline --test prefs          # prefs store + hledger resolution
cargo test -p ledgeline --test import_endpoints  # the /api/import/* routes

The opt-in checks run a real hledger binary, so they are not part of cargo test, which stays hermetic. just hledger-checks runs all of them:

LEDGELINE_HLEDGER_RENDER_CHECK=1 cargo test -p ledgeline-core --test rules_hledger_render
LEDGELINE_HLEDGER_MATCH_CHECK=1  cargo test -p ledgeline-core --test matching
LEDGELINE_HLEDGER_GENERATE_CHECK=1 cargo test -p ledgeline-core --test rules_generate
LEDGELINE_HLEDGER_REIMPORT_CHECK=1 cargo test -p ledgeline-core --test reimport
LEDGELINE_HLEDGER_SORT_CHECK=1   cargo test -p ledgeline-core --test sort
LEDGELINE_HLEDGER_LAYOUT_CHECK=1 cargo test -p ledgeline-core --test journals
LEDGELINE_HLEDGER_IMPORT_CHECK=1 cargo test -p ledgeline --test import_endpoints
LEDGELINE_HLEDGER_IMPORT_CHECK=1 cargo test -p ledgeline --test import_cli

reimport’s variant is the only test of the one hledger grammar claim this feature makes: that comment id:%fitid becomes a tag hledger writes, hledger reads back, and our own parser reads back. The first two could hold while the third failed, and then nothing would ever match.

import_endpoints’ gated half tests the whole import sequence. It checks that the proposed entries come from stdout and the status line from stderr, that a row .latest would silently drop is reported, and that a commit writes exactly one CSV and one journal. Most importantly, it checks that balance assertions do not aggregate across two -f flags while the concatenation does. That failure gives a silent wrong answer rather than an error, so it is the only bug in this feature a user would never notice.

rules_hledger_render is the only check that proves our renderer emits syntax hledger accepts. The round-trip tests only prove we do not damage what we did not touch. sort’s variant proves every sorted output still passes hledger check --strict ordereddates, and matching’s compares our scoring against real hledger print -O json output.

journals’ variant is the corpus check: every root under fixtures/import/layouts/ passes hledger check --strict as committed. Separately, split-year-assert/’s target file fails on its own, for the assertion reason, while its root passes. Those two are asserted as a pair on purpose. “The fragment fails” alone could mean the fixture is broken, and “the root passes” alone could mean the fragment was harmless. Together they are the reason --ignore-assertions is safe, and if hledger ever stops behaving that way, this check fails before anyone’s books are affected.