csv2journal Milestone 1 Requirements #
Document Purpose #
This document defines the testable product requirements for milestone one of csv2journal. It is
subordinate to the project vision in VISION.md. Implementation design may choose data
structures and internal techniques, but must not weaken these requirements without first updating
this document.
Normative Language #
The words MUST, MUST NOT, SHOULD, SHOULD NOT, and MAY are normative:
- MUST and MUST NOT describe behavior required for milestone one.
- SHOULD and SHOULD NOT describe expected behavior from which a documented design decision may deviate.
- MAY describes optional behavior.
Examples are explanatory unless a requirement explicitly makes them normative.
Terminology #
Project manifest : The YAML configuration entry point. It defines one recursively scanned input root and one import profile, and identifies that profile's rules file.
Import profile : The configuration applied to every discovered CSV. It defines CSV parsing, field aliases, transaction mappings, a default source account, templates, and one ruleset.
Rules file : The YAML file containing the import profile's individually named classification rules.
Ruleset : The non-empty collection of rules in the rules file.
Aliased field : A stable identifier assigned by the profile to a CSV column selected by decoded header name or zero-based index.
Physical row number : A CSV record's zero-based ordinal in the source, including skipped preamble and header records. A quoted field containing a line break remains part of one record and does not increment the ordinal.
Data row : A parsed record remaining after configured preamble and header handling. Every data row represents one transaction. A CSV may contain zero data rows.
Target path
: The path formed by appending .journal to a source path ending in .csv. For example,
bank/2026.csv has target path bank/2026.csv.journal.
Current import : The sole discovered CSV whose target path does not exist.
Historical pair : A discovered CSV and its existing colocated target journal.
Approved journal
: The journal in a historical pair. It has been reviewed outside csv2journal and is immutable to
this application.
Candidate configuration : The loaded profile and the rules currently being evaluated, including unsaved interactive rule edits.
Candidate journal : The structured journal output calculated from a CSV using the candidate configuration. It need not have been written to disk.
Structural equality : Equality of the supported parsed journal data, including transaction and posting order, while disregarding source formatting that does not change that data.
Operation snapshot : The immutable file contents read once for an invocation or interactive session. Re-evaluation uses these contents rather than rereading source or approved journal files.
Finalization : Validation followed by atomic creation of the current import's target journal.
Milestone Workflow #
Milestone one MUST support this workflow:
- The user invokes
csv2journalwith a project manifest. csv2journalloads the sole profile and recursively discovers the sole current CSV and every historical pair beneath the configured input root.- It reads the relevant files into an operation snapshot and evaluates the candidate configuration against the current and historical CSVs.
- The user inspects and optionally edits rules through the local web interface, or runs the same checks non-interactively.
- Finalization succeeds only when the rules file is saved, every data row is classified unambiguously, every row can be rendered, and every historical candidate journal is structurally equal to its approved journal.
- A successful finalization atomically creates the current target without modifying any other CSV or journal.
YAML Configuration #
M1-YAML-001: The project manifest and rules file MUST be UTF-8 without a byte-order mark. Invalid UTF-8, a UTF-8 byte-order mark, and UTF-16 input MUST be rejected.
M1-YAML-002: Each YAML file MUST contain one implicit document. Document markers --- and ...,
YAML directives, and multiple documents MUST be rejected.
M1-YAML-003: The supported YAML syntax MUST consist of block mappings, block sequences, comments, plain scalars, single-quoted scalars, double-quoted scalars, literal block scalars, and folded block scalars.
M1-YAML-004: Flow mappings, flow sequences, anchors, aliases, merge keys, and explicit tags MUST be rejected even if the underlying YAML parser can process them.
M1-YAML-005: Plain scalars MUST be resolved according to the YAML 1.2 Core Schema. Quoted and block
scalars MUST resolve as strings. A resolved scalar MUST have the exact type required by its schema
field; for example, quoted "true" is not a boolean and quoted "1" is not an integer.
M1-YAML-006: Configuration mapping keys MUST be scalar strings. Unknown keys, missing required keys, values of the wrong type, and invalid enum values MUST be rejected with a diagnostic.
M1-YAML-007: Duplicate mapping keys are unsupported input. Milestone one does not guarantee whether such input is rejected or one occurrence is selected, and users MUST NOT rely on either behavior.
M1-YAML-008: The manifest root MUST contain exactly the schema, project, and profile mappings.
The rules-file root MUST contain exactly the schema mapping and rules mapping. In both files,
schema MUST contain exactly version: 1.
M1-YAML-009: Parsing MUST use libyaml 0.2.5 through the pinned zig-build-libyaml package. The
application MUST use libyaml's token or event information to enforce the smaller syntax subset rather
than accepting every construct supported by libyaml.
M1-YAML-010: Configuration syntax diagnostics SHOULD include libyaml's one-based line and column when available. Schema diagnostics MUST identify the configuration file and key path.
M1-YAML-011: Comments and source formatting are not configuration data. Loading MUST ignore them, and a canonical rules-file save MAY discard or replace them.
M1-YAML-012: The manifest's nested mapping shapes MUST be:
project: exactlyinputPath.profile: exactlyname,rulesFile,csv, andtransaction.profile.csv: exactlydelimiter,lineEnding,skipRecords,header, andfields.- Each entry in
profile.csv.fields: exactly one ofheaderorindex. profile.transaction: exactlydate,amount,currency,sourceAccount, andnarrationTemplate, with optionalpostingCommentTemplates.profile.transaction.date: exactlyfieldandformat.profile.transaction.amount: exactlyfieldanddecimalSeparator, with optionalgroupSeparator.profile.transaction.currency: exactly one offixedorfield.profile.transaction.postingCommentTemplates, when present: any non-duplicated subset ofsourceanddestination.
Every field value in the transaction mapping and every alias used by an expression or template MUST
name an entry in profile.csv.fields.
Project, Profile, And Discovery #
M1-PROJ-001: The project manifest MUST contain exactly one import profile. Selecting among multiple profiles is not supported in milestone one.
M1-PROJ-002: project.inputPath MUST be a non-empty relative path naming the recursively scanned
input root. The root MUST exist and be a directory.
M1-PROJ-003: profile.name MUST be a non-empty string, and profile.rulesFile MUST be a non-empty
relative path naming the rules file.
M1-PROJ-004: project.inputPath and profile.rulesFile MUST be resolved relative to the directory
containing the manifest, independent of the process working directory.
M1-PROJ-005: Absolute inputPath and rulesFile values MUST be rejected. Relative paths containing
.. components MUST be accepted when their resolved targets otherwise satisfy these requirements.
M1-PROJ-006: Discovery MUST recurse beneath inputPath and classify names case-sensitively. A path
ending in .csv.journal is a journal; a path ending in .csv is a CSV. Other names MUST NOT affect
pairing.
M1-PROJ-007: A CSV and journal MUST pair only when the journal is colocated with the CSV and its
path is exactly the CSV path with .journal appended.
M1-PROJ-008: Discovery MUST find exactly one CSV without its target journal. That CSV MUST be the current import. Finding zero or more than one unpaired CSV MUST fail the operation.
M1-PROJ-009: Every discovered .csv.journal MUST have its corresponding .csv. An orphan journal
MUST fail the operation. Every discovered pair MUST be treated as approved history.
M1-PROJ-010: Directory symlinks encountered during recursive discovery MUST NOT be traversed.
M1-PROJ-011: A symlink encountered at a path classified as a CSV or journal MUST be treated as the
file at that discovered path. Its target MAY be outside inputPath. A broken link or a target that
cannot be read as a regular file MUST fail the operation.
M1-PROJ-012: Non-regular filesystem objects at paths classified as CSVs or journals MUST fail the operation. Unrelated filesystem entries MUST be ignored.
M1-PROJ-013: Detecting multiple discovered names or symlinks that resolve to the same underlying file is not required in milestone one. Inputs relying on such aliases are unsupported.
M1-PROJ-014: check, convert, and interactive MUST all require successful discovery. An
existing current target, including one created after discovery but before finalization, MUST never be
treated as writable output.
M1-PROJ-015: Each invocation or interactive session MUST read the manifest, rules file, every discovered CSV, and every approved journal at most once into immutable operation snapshots. Candidate re-evaluation MUST reuse those snapshots.
M1-PROJ-016: An interactive save establishes the in-memory candidate rules as the session's new saved rules state. External changes to files after the session snapshot is established need not be incorporated into that session.
M1-PROJ-017: csv2journal MUST use files in the larger project directly. It MUST NOT create a
private history store or persistent copies of CSVs or approved journals.
M1-PROJ-018: Malformed, incomplete, or internally inconsistent configuration MUST fail checking and conversion and MUST prevent finalization. Interactive mode MAY start with rules-file errors when enough valid manifest and profile configuration remains to present and correct those errors.
CSV Input #
M1-CSV-001: Every discovered CSV MUST be valid UTF-8. A leading UTF-8 byte-order mark MUST be ignored and MUST NOT appear in any decoded cell. Invalid UTF-8 MUST be rejected. Decoding MUST NOT otherwise perform character-set conversion or Unicode normalization.
M1-CSV-002: profile.csv.delimiter MUST be exactly one of comma, semicolon, or tab, denoting
,, ;, or an ASCII tab respectively.
M1-CSV-003: profile.csv.lineEnding MUST be exactly lf or crlf. Every line break in the CSV,
including a line break inside a quoted field, MUST use that byte sequence. Mixed endings, the other
configured ending, and a lone carriage return MUST be rejected.
M1-CSV-004: A complete final CSV record MAY end at end-of-file without a configured line-ending sequence.
M1-CSV-005: CSV parsing MUST use zarko with a double quote as the quote byte. A quote MUST open a
quoted field only when it is the field's first byte. A quote elsewhere in an unquoted field MUST be
treated as literal data. CSV lexical behavior not explicitly overridden in this document MUST match
the pinned zarko revision.
M1-CSV-006: A quoted field MUST support delimiters and line breaks as data and MUST represent a literal quote with a doubled quote. Malformed or unclosed quoting MUST be rejected.
M1-CSV-007: Decoded cell values MUST preserve their exact UTF-8 contents. Parsing MUST NOT implicitly trim whitespace, case-fold text, or normalize line endings in cells.
M1-CSV-008: profile.csv.skipRecords MUST be a non-negative integer count of leading CSV records
to skip. Skipped records still contribute to physical row numbers.
M1-CSV-009: profile.csv.header MUST be a boolean. When true, the record after the skipped records
MUST exist and be the header; all later records are data. When false, all records after the skipped
records are data.
M1-CSV-010: A physically blank record MUST be rejected. A syntactically present record containing empty fields, including a quoted empty field or delimiters separating empty fields, is not physically blank.
M1-CSV-011: The profile's fields mapping MUST be non-empty. Every key MUST be an alias using the
identifier grammar in M1-RULE-003. Every value MUST contain exactly one selector: a non-negative
index or a string header.
M1-CSV-012: An index selector MUST address a zero-based column and MAY be used in either header or
headerless mode. A header selector MUST be rejected unless profile.csv.header is true and MUST match
the exact decoded header cell. In header mode, every selected index MUST be within the header width.
M1-CSV-013: In header mode, every header cell MUST be unique, including cells not selected by an alias. Every header selector MUST resolve exactly once. Every data row MUST have exactly the same field count as the header.
M1-CSV-014: In headerless mode, every data row MUST contain the highest indexed aliased column. Additional fields beyond the highest aliased index MUST be ignored unless later selected by an alias.
M1-CSV-015: Rule expressions and templates MUST reference aliases rather than raw indexes or header strings.
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 last one implicitly means a year in the 21st century.
The selected cell MUST represent a valid Gregorian calendar date in that exact format.
Generated dates MUST use YYYY-MM-DD.
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-CSV-019: Amounts MUST be represented and compared as exact decimals, not binary floating point.
Output MUST remove a leading + and redundant integer zeroes while preserving the source fractional
scale. Negative zero MUST lose its sign, so -0.00 renders as 0.00.
M1-CSV-020: profile.transaction.currency MUST contain exactly one of fixed or field. A fixed
value is used for every row; a field value is read exactly from the selected cell.
M1-CSV-021: Supported currencies MUST be exactly the strings USD and EUR. A generated amount
MUST place the currency after the quantity.
M1-CSV-022: Every successfully decoded data row containing all condition-referenced fields MUST enter rule evaluation, including rows with date, output-amount, currency, action, or template errors. Filtering or intentionally ignoring rows is not supported.
M1-CSV-023: A CSV with zero data rows MUST be valid when all preamble and header requirements are satisfied. Its candidate journal contains zero transactions.
M1-CSV-024: Invalid CSV structure, line endings, decoding, field widths, headers, dates, amounts, or currencies MUST prevent finalization and MUST identify the source file and physical row where applicable.
Rule Configuration And Matching #
M1-RULE-001: rules MUST be a block mapping containing at least one resulting rule. Each retained
mapping key MUST be a non-empty rule name. Source-level duplicate mapping keys remain governed by
M1-YAML-007; the in-memory candidate and every saved rules file MUST have unique names.
M1-RULE-002: Each rule value MUST contain exactly match and set. match MUST be a string.
set MUST contain a string targetAccount and MAY contain a string sourceAccount; no other action
keys are supported.
M1-RULE-003: Each rule's matching condition MUST use this grammar:
expression := or_expression
or_expression := and_expression ("or" and_expression)*
and_expression := unary_expression ("and" unary_expression)*
unary_expression := "not" unary_expression
| "(" expression ")"
| comparison
comparison := identifier ("==" | "!=") (string | decimal)
| identifier ("<" | "<=" | ">" | ">=") decimal
| identifier "~=" regex
identifier := [A-Za-z_][A-Za-z0-9_]*
decimal := [+-]?[0-9]+("." [0-9]+)?
regex := "/" pattern "/" flags?
flags := any non-repeating combination of "i", "m", and "s"
M1-RULE-004: The left operand of every comparison MUST be one aliased CSV field. The right operand
MUST be one literal allowed for that operator by M1-RULE-003. Field-to-field comparisons and
literals on the left are not supported.
M1-RULE-005: Comparisons form boolean values. not MUST bind more tightly than and, and and
MUST bind more tightly than or. Parentheses MUST override that precedence and MAY be nested.
M1-RULE-006: Rule matching MUST be independent of rule declaration order. Reordering otherwise unchanged rules MUST NOT change which rules match a row or the candidate journal.
M1-RULE-007: Milestone one MUST NOT use priorities, first-match-wins behavior, or a dedicated fallback-rule feature. An ordinary condition that matches every row has no special status and remains subject to the exactly-one-rule invariant.
M1-RULE-008: Once configuration parsing has succeeded, condition aliases have been resolved, and every rule name, expression, and regular expression is valid, each decoded row containing all condition-referenced fields MUST be evaluated against every rule. Invalid or missing actions MUST NOT by themselves prevent condition evaluation.
M1-RULE-009: When every rule result for a row is available, the row MUST be classified as matching zero, exactly one, or multiple rules. Zero or multiple matches for any current or historical data row MUST prevent finalization.
M1-RULE-010: Diagnostics for a multiply matched row MUST identify every matching rule. Diagnostics for zero and multiple matches MUST identify the source file and physical row.
M1-RULE-011: A matching rule MUST provide the destination account through targetAccount.
M1-RULE-012: The profile MUST provide a default source account. A matching rule MAY override it
through sourceAccount.
M1-RULE-013: Invalid expression syntax, unknown aliases, invalid regular expressions, and invalid rule names MUST make row classification unavailable for the complete candidate configuration. An invalid or missing rule action MUST prevent generation and finalization but MUST NOT by itself prevent otherwise valid condition evaluation.
M1-RULE-014: Identifiers and the lowercase keywords and, or, and not MUST be case-sensitive.
Those keywords MUST NOT be field aliases. ASCII spaces, tabs, carriage returns, and line feeds MUST be
ignored outside literals. Other Unicode whitespace MUST be rejected. The language MUST NOT have
comments.
M1-RULE-015: String literals MUST be delimited by double quotes and MUST support only the escapes
\", \\, \n, \r, and \t. Literal line breaks and unknown escapes MUST be syntax errors.
String equality and inequality MUST compare exact decoded UTF-8 values without normalization.
M1-RULE-016: Decimal literals MUST use . and the grammar in M1-RULE-003, independently of the
CSV decimal separator. A CSV field reached by a numeric predicate MUST use the profile's amount-cell
grammar and separators. Comparison MUST use exact decimal values, and trailing fractional zeroes MUST
be insignificant.
M1-RULE-017: The ~= operator MUST search anywhere in the exact decoded field value. Patterns MUST
use ^ and $ for a full-field match. Regex literals MUST use /pattern/ with optional i, m, and
s flags for case-insensitive, multiline, and dot-all matching. \/ MUST represent a literal slash;
other regex backslashes MUST pass through to the regex engine. Literal line breaks MUST be rejected.
M1-RULE-018: Regex syntax and behavior MUST otherwise be those of the pinned zig-utils/zig-regex
revision, except that an empty pattern (//) MUST be rejected as an invalid regular expression.
M1-RULE-019: and and or MUST evaluate from left to right and MUST short-circuit. A predicate in
a skipped branch MUST NOT produce a row-level evaluation error.
M1-RULE-020: When a reached numeric predicate cannot parse its field, that rule's result for the row MUST be unavailable. Every other rule MUST still be evaluated. Known matches and all evaluation errors MUST be reported, but final zero/exactly-one/multiple classification MUST remain unavailable and MUST prevent finalization.
M1-RULE-021: Whitespace MUST separate tokens or be ignored between tokens but MUST NOT split an
identifier, keyword, operator, decimal, or literal. Operators MUST use their longest valid form. A
keyword MUST be recognized only as a complete token, so android MUST remain one identifier.
pattern in M1-RULE-003 is the sequence between regex delimiters after applying M1-RULE-017's
delimiter escape.
Templates And Comments #
M1-TPL-001: profile.transaction.narrationTemplate MUST be a string used for every generated
transaction. Rules MUST NOT override it.
M1-TPL-002: profile.transaction.postingCommentTemplates MAY contain independent string source
and destination templates. Omitting either template emits no comment on that posting.
M1-TPL-003: A placeholder naming an aliased field MUST render the exact decoded cell without trimming, normalization, or date, amount, or currency reformatting. An empty cell is available and MUST render as an empty string.
M1-TPL-004: Templates MUST provide {sourceFilename}, {physicalRow}, and {ruleName}.
sourceFilename MUST be the discovered lexical CSV path relative to inputPath, using / separators
even when the CSV is a symlink. physicalRow MUST be the zero-based physical row number in unsigned
decimal. ruleName MUST be the exact uniquely matching rule name.
M1-TPL-005: After YAML string decoding, template syntax MUST consist only of literal text,
placeholders of the form {identifier}, and {{ and }} for literal braces. Placeholder identifiers
MUST use M1-RULE-003's identifier grammar without whitespace. An unmatched single brace or invalid
placeholder MUST be an error.
M1-TPL-006: Field aliases MUST NOT use the reserved names sourceFilename, physicalRow, or
ruleName. Placeholder values MUST be inserted once and MUST NOT be recursively interpreted.
M1-TPL-007: Templates MUST NOT provide conditions, defaults, formatting directives, filters, transformations, nested expressions, or other interpolation behavior.
M1-TPL-008: Invalid syntax, an unknown placeholder, or a reserved-name collision MUST prevent configuration saving, rendering, generation, and finalization. It MUST NOT by itself prevent otherwise valid rule-condition evaluation.
M1-TPL-009: Templates MUST be rendered only after exactly one rule has matched a row. If a placeholder's selected column is unavailable, generation MUST fail with a diagnostic identifying the template, alias, source file, and physical row.
M1-TPL-010: A zero-length rendered narration MUST prevent generation. An unconfigured or zero-length rendered posting comment MUST emit no comment syntax. Rendered whitespace MUST NOT be trimmed, and a whitespace-only comment MUST NOT be treated as empty.
M1-TPL-011: Each rendered value MUST be represented losslessly in its hledger narration or posting-comment context. If hledger 1.52.3 has no lossless representation, generation MUST fail rather than replacing or discarding characters.
M1-TPL-012: Profile and rule account values MUST be static strings. Templates MUST NOT construct account names.
Journal Generation #
M1-JRN-001: Every generatable data row MUST produce exactly one transaction. Transactions MUST preserve source data-row order.
M1-JRN-002: Every transaction MUST contain the parsed date in YYYY-MM-DD form and the rendered
narration.
M1-JRN-003: Every transaction MUST contain exactly two postings in this order: source, then destination.
M1-JRN-004: The source posting MUST use the profile's default sourceAccount unless the matching
rule overrides it. It MUST contain the normalized signed quantity and resolved currency.
M1-JRN-005: The destination posting MUST use the matching rule's targetAccount and MUST omit its
amount so hledger infers the balancing amount. Explicit destination amounts are not emitted or
supported by the historical parser.
M1-JRN-006: An account MUST be a non-empty ordinary, non-virtual account name accepted by hledger 1.52.3 and losslessly representable in the emitted syntax. Virtual postings and empty accounts MUST be rejected.
M1-JRN-007: Generated syntax MUST be accepted by hledger 1.52.3 and MUST use only the supported milestone-one journal subset. Runtime operation MUST NOT invoke hledger.
M1-JRN-008: Automated compatibility tests MUST cover the complete range of narration, posting-comment, account, amount, and currency text the implementation claims it can emit against hledger 1.52.3.
M1-JRN-009: Posting comments emitted from templates MUST be part of the parsed journal model. The decoded comment payload excludes syntax indentation and delimiters but otherwise preserves exact text.
M1-JRN-010: Generated journals MUST use UTF-8 without a byte-order mark and LF line endings. A non-empty journal MUST end in LF.
M1-JRN-011: A current CSV with zero data rows MUST produce an empty candidate journal and, after successful finalization, a zero-byte target file.
M1-JRN-012: Prices, costs, balance assertions, transaction codes, statuses, tags, metadata, directives, periodic transactions, automated transactions, and three-or-more-posting transactions MUST NOT be emitted.
M1-JRN-013: Any generation or validation failure MUST NOT create a complete or partial target.
M1-JRN-014: Finalization MUST create the target atomically and MUST refuse when any file or other filesystem object exists at that path. It MUST NOT overwrite or rewrite an existing target even when the candidate would be structurally equal.
Historical Validation #
M1-HIST-001: Checking and finalization MUST validate every historical pair discovered in the operation snapshot. Having no historical pairs MUST be valid.
M1-HIST-002: Historical validation MUST apply the complete candidate profile and ruleset, not only the rule currently being edited.
M1-HIST-003: Every historical data row MUST satisfy the same evaluation, exactly-one-rule, output, and rendering requirements as a current data row.
M1-HIST-004: Approved journals MUST be parsed as UTF-8 using only the syntax constructs emitted by
csv2journal, while allowing whitespace and line-ending differences that do not alter parsed data.
An empty approved journal MUST be supported.
M1-HIST-005: Unsupported journal syntax, including an explicit destination amount, MUST fail with a diagnostic rather than being ignored or compared textually.
M1-HIST-006: Historical validation MUST compare each candidate journal with its approved journal using structural equality.
M1-HIST-007: Structural comparison MUST preserve transaction and posting order and MUST compare dates, narrations, account names, amount values, currencies, amount presence, and posting-comment presence and payload.
M1-HIST-008: Exact decimal quantities with the same mathematical value and currency MUST compare
equal regardless of sign spelling, leading integer zeroes, or fractional scale. Thus 100.0 USD and
100.00 USD are structurally equal.
M1-HIST-009: Account names, narrations, currencies, and decoded posting-comment payloads MUST use exact string equality without trimming or normalization.
M1-HIST-010: Any structural difference MUST prevent finalization and MUST identify the historical pair and differing transaction or posting data.
M1-HIST-011: csv2journal MUST NOT offer an option to accept, suppress, or record an exception for
a historical structural difference.
M1-HIST-012: csv2journal MUST NOT modify an approved journal or historical CSV.
M1-HIST-013: A journal created before csv2journal MAY be approved history only when every
construct belongs to the supported subset. Migration of other legacy journals is outside scope.
M1-HIST-014: Historical equality MUST concern generated data, not the identity of the rule that
previously classified a row. A rule-name change matters only when it changes generated data, such as a
comment containing {ruleName}.
Command-Line Interface #
M1-CLI-001: The CLI MUST provide these invocation forms:
csv2journal check MANIFEST
csv2journal convert MANIFEST
csv2journal interactive MANIFEST [--listen HOST:PORT]
M1-CLI-002: MANIFEST MUST be explicit on every operational invocation. Profile and current-CSV
selection arguments MUST NOT be required because the manifest and discovery convention identify them.
M1-CLI-003: check MUST validate the current import and all history without saving rules or
creating or modifying a journal.
M1-CLI-004: check MUST report the match status of every current row satisfying
M1-RULE-008's prerequisites and summarize complete historical validation. Unevaluable rows and
configurations MUST instead report their blocking diagnostics and all known row-level results.
M1-CLI-005: convert MUST perform every check performed by check, then create exactly one target
on success using the finalization requirements.
M1-CLI-006: A successful command MUST return status zero. Configuration, discovery, parsing, matching, historical validation, server startup, or finalization failure MUST return a non-zero status. No finer exit-code taxonomy is guaranteed.
M1-CLI-007: The CLI MUST NOT provide an option that bypasses the exactly-one-rule invariant, historical validation, saved-rules requirement, or no-overwrite requirement.
M1-CLI-008: Human-readable diagnostic wording and ordering are not stable interfaces in milestone one, but every diagnostic MUST contain the context required by the Diagnostics And Safety section.
Interactive Web Interface #
M1-UI-001: interactive MUST listen on 127.0.0.1:8080 by default. --listen HOST:PORT MUST
override the complete listen endpoint. Startup MUST fail rather than choosing another port when the
requested endpoint is unavailable.
M1-UI-002: Interactive mode MUST print its URL and MUST NOT open a browser automatically.
M1-UI-003: Authentication, authorization, and transport encryption are not required. Securing a non-loopback endpoint is the user's responsibility.
M1-UI-004: Normal server shutdown MUST be requested with SIGINT or SIGTERM. A browser control for stopping the server is not required.
M1-UI-005: The interface MUST display the current CSV's decoded data rows and support filters for zero, exactly-one, multiple, and unavailable match status.
M1-UI-006: The interface MUST search every decoded cell using a case-sensitive UTF-8 byte substring. A row matches when any cell contains the query. An empty query MUST show every row allowed by the active status filter.
M1-UI-007: For every displayed evaluable row, the interface MUST show whether zero, exactly one, or multiple rules match and MUST identify every matching rule. For an unevaluable row or configuration, it MUST show unavailable status and the blocking diagnostics.
M1-UI-008: The interface MUST provide structured controls to add, rename, modify, and delete rules, including text editing of their match expressions and account actions. It MUST NOT expose the rules file as a raw YAML editor.
M1-UI-009: The project manifest and profile settings MUST be read-only in interactive mode.
M1-UI-010: After an edit, the interface MUST re-evaluate affected current and historical results without a page reload or server restart. Pending evaluation MUST be distinguishable from results for the current candidate.
M1-UI-011: The interface MUST display expression, regular-expression, action, template, and other rule-configuration errors without attempting finalization.
M1-UI-012: The interface MUST identify every historical row with zero, multiple, or unavailable matching, including its source file, physical row, known matching rule names, and diagnostics.
M1-UI-013: The interface MUST display every other blocking historical diagnostic, including CSV errors, output conversion errors, unsupported approved-journal syntax, and structural differences.
M1-UI-014: The interface MUST provide a complete journal preview when every current row can be generated. It MUST show why no preview is available rather than presenting partial output. A preview MUST be visibly non-final while any other finalization check fails and MUST NOT be written to the target path.
M1-UI-015: Edits MUST remain in memory until explicitly saved. The interface MUST show whether the candidate rules differ from the last saved rules and whether displayed results represent the current candidate.
M1-UI-016: The rules file MUST have one explicit save action. Saving MUST validate YAML-schema representability, at least one rule, unique non-empty names, expressions, regexes, aliases, actions, templates, reserved names, and accounts. Current-row matching and historical equality MUST NOT be save prerequisites.
M1-UI-017: Saving MUST atomically replace only the configured rules file with the complete candidate ruleset. It MUST canonically rewrite the file, MAY discard comments and formatting, and MUST NOT modify the manifest, CSVs, or journals.
M1-UI-018: A canonical rules save MUST use the supported block-style YAML subset, UTF-8 without a BOM, LF line endings, deterministic field formatting, and ascending rule-name order by UTF-8 byte value.
M1-UI-019: The editor MAY temporarily contain zero rules, but saving and finalization MUST remain unavailable until at least one valid rule exists.
M1-UI-020: Interactive finalization MUST require the candidate rules to equal the successfully saved rules. The user MUST save dirty rules before finalization.
M1-UI-021: Interactive finalization MUST enforce the same validation, atomic creation, and
no-overwrite behavior as convert.
M1-UI-022: A guided expression builder, rather than a text field for the expression language, is not required.
Diagnostics And Safety #
M1-DIAG-001: Diagnostics associated with a CSV row MUST include its source path relative to
inputPath and physical row number.
M1-DIAG-002: Diagnostics associated with configuration MUST identify the configuration file and profile, rule, alias, action, field, or template involved where applicable.
M1-DIAG-003: Historical-difference diagnostics MUST identify the historical pair and differing transaction or posting data.
M1-DIAG-004: A failure in one row or historical pair SHOULD NOT prevent reporting independent errors that can still be determined from the same operation snapshot.
M1-SAFE-001: Given identical manifest and operation-snapshot contents, candidate rules, command arguments, and program version, matching, checking, preview, generation, canonical rules saving, and diagnostics MUST be deterministic.
M1-SAFE-002: Checking, previewing, and failed finalization MUST NOT modify CSVs, approved journals, or the target path.
M1-SAFE-003: Saving rules MUST modify only the configured rules file. Finalization MUST modify only the previously nonexistent current target.
M1-SAFE-004: Milestone one specifies no explicit CSV-size, record-length, history-count, or rule-count limits. Resource exhaustion MUST fail safely without creating a target or corrupting the rules file.
Packaging And Dependencies #
M1-PKG-001: Application code MUST be implemented in Zig and build with Zig 0.17.0. The bundled C implementation of libyaml is an allowed dependency.
M1-PKG-002: The repository MUST provide a Nix flake that builds the application and runs its automated tests using the pinned Zig toolchain and dependencies.
M1-PKG-003: YAML parsing MUST use zig-build-libyaml from
https://tangled.org/sh4pe.de/zig-build-libyaml pinned to commit
b1d5b607c84e8858c470db2aeae590d8a54c0c0b. That package pins libyaml 0.2.5 with upstream archive
SHA-256 c642ae9b75fee120b2d96c712538bd2cf283228d2337df2cf2988e3c02678ef4 and links it statically with
libc.
M1-PKG-004: CSV parsing MUST use zarko from https://codeberg.org/TynK/zarko pinned to commit
5080046497223c7a60d91f69f60a1f27b8adfbb2.
M1-PKG-005: Regular expressions MUST use zig-utils/zig-regex from
https://github.com/zig-utils/zig-regex pinned to v0.2.1 commit
13729a16469dcc79c59bf6092940088181fbd866.
M1-PKG-006: The interactive interface MUST be served by the CLI-started application. A separately deployed service is not required.
M1-PKG-007: hledger 1.52.3 MAY be a compatibility-test dependency but MUST NOT be a runtime dependency.
Deferred And Out-Of-Scope Features #
The following behavior is explicitly excluded from milestone one:
- Multiple profiles or input roots in one manifest.
- Explicit current-file selection.
- Ignoring selected data rows.
- Deriving an amount from separate debit and credit columns.
- Generating split transactions with three or more postings.
- Rule priorities, first-match-wins semantics, and fallback rules.
- Typed date comparisons in rule conditions.
- A general-purpose expression or transformation language.
- Complete hledger CSV-import feature parity.
- Parsing arbitrary hledger journals or directives outside the emitted subset.
- Sharing a ruleset between profiles.
- Persisting historical row-to-rule assignment metadata.
- Privately copying or snapshotting source CSVs or approved journals as a history store.
- Modifying, regenerating, or accepting semantic changes to approved historical journals.
- Editing the manifest or profile through the web interface.
- Authentication, authorization, TLS, hosted deployment, and multi-user editing.
- Managing the aggregate journal or invoking version-control operations.
- Detecting multiple filesystem aliases of one underlying file.
- Explicit application limits for input size, row length, history count, or rule count.
Acceptance Scenarios #
M1-AC-001: Successful conversion
Given one valid unpaired CSV whose rows each match exactly one rule, historical pairs that are all
structurally equal, valid saved rules, and a still-absent target, convert creates one parseable
journal containing one two-posting transaction per row in source order.
M1-AC-002: Discovery
Given zero or multiple unpaired CSVs, an orphan .csv.journal, or a non-regular relevant entry,
every operation fails without modifying project files. Unrelated files and untraversed directory
symlinks do not affect discovery.
M1-AC-003: Unmatched current row
Given a current row that matches no rule, check identifies its file and physical row, convert
returns failure, and no target is created.
M1-AC-004: Ambiguous current row
Given a current row that matches multiple rules, check identifies its file, physical row, and every
matching rule, convert returns failure, and no target is created.
M1-AC-005: Formatting-only historical difference
Given an approved journal whose whitespace, line endings, or decimal scale differ but whose supported parsed structure and exact decimal values equal the candidate, historical validation succeeds.
M1-AC-006: Structural historical difference
Given an approved journal whose account, amount value, currency, date, narration, comment, transaction order, or posting order differs, validation identifies the difference and prevents finalization.
M1-AC-007: Existing target
Given an otherwise valid operation and any filesystem object appearing at the target before atomic creation, finalization refuses to overwrite it and leaves it unchanged.
M1-AC-008: Saved incomplete draft
Given valid interactive rule edits that leave a row unmatched, explicit save atomically rewrites the rules file while finalization remains unavailable and non-interactive checking fails.
M1-AC-009: Dirty interactive draft
Given an unsaved rule edit for which all behavioral checks pass, interactive finalization remains unavailable until save succeeds for that candidate.
M1-AC-010: Rule reorder
Given rules whose definitions are only reordered, matching and candidate output remain unchanged. The next save writes the rules in ascending name order.
M1-AC-011: Match-language semantics
Given account == "DE23" or amount >= 100 and not posting ~= /refund/i:
- A row with account
DE23, amountN/A, and postingREFUNDmatches without a numeric error because the left side oforshort-circuits. - A row with account
DE24, amount100.00, and postingcard refunddoes not match becauseandbinds more tightly thanorand the regex findsrefundcase-insensitively. - A row with account
DE24, amount100.00, and postingmarketmatches. - A row with account
de23, amount99, and postingmarketdoes not match because string equality is exact and case-sensitive.
Given decimal separator comma, condition amount == 100.00, and cell 100,0, the predicate matches
because both operands represent the same exact decimal value.
M1-AC-012: Numeric predicate error
Given a reached condition amount >= 100 and exact cell N/A, checking evaluates the other rules,
reports known matches and the conversion error, marks final classification unavailable, and prevents
finalization.
M1-AC-013: Template interpolation
Given source bank/2026.csv, physical row 12, matching rule groceries, posting cell market, and
template {sourceFilename}:{physicalRow} {ruleName} {{source}} {posting}, interpolation produces
bank/2026.csv:12 groceries {source} market before hledger-context rendering.
M1-AC-014: Empty template results
Given a narration rendering to zero length, generation fails. Given an optional posting-comment template rendering to zero length, generation omits comment syntax for that posting. A comment rendering only spaces is emitted without trimming.
M1-AC-015: Invalid template configuration
Given {unknown}, { field }, an unmatched {, or an alias named ruleName, saving fails with a
specific diagnostic while otherwise valid rule conditions remain available for interactive matching.
M1-AC-016: Non-recursive interpolation
Given a posting cell containing {amount} and template {posting} {{amount}}, interpolation produces
{amount} {amount} rather than interpreting inserted or escaped text again.
M1-AC-017: YAML subset
Given flow syntax, an anchor, alias, merge key, explicit tag, directive, document marker, multiple
documents, a BOM, or UTF-16 configuration, loading fails. Given quoted "true" for the boolean
header field, schema validation fails because the value is a string.
M1-AC-018: CSV line endings and EOF
Given lineEnding: crlf, a lone LF anywhere in the CSV, including inside a quoted field, fails.
A complete final record ending directly at EOF remains valid.
M1-AC-019: Header and row width
Given header mode, any duplicate header or data-row width differing from the header fails. Given headerless mode, extra unaliased trailing fields are ignored but a row missing the highest aliased index fails.
M1-AC-020: Empty import
Given a valid current CSV with zero data rows and passing history, conversion atomically creates a zero-byte journal.
M1-AC-021: Interactive startup
Given no --listen, interactive mode listens on 127.0.0.1:8080 and prints the URL without opening a
browser. If that endpoint is unavailable, startup fails rather than choosing another port.
Key Decisions And Rationale #
| Decision | Rationale |
|---|---|
| One manifest defines one input root and one profile. | It keeps discovery and historical scope explicit for the initial workflow. |
The sole unpaired CSV is current; colocated .csv.journal files define history. |
No separate selection state or private history database is needed. |
| Each operation uses immutable read-once snapshots. | Current and historical results cannot silently mix file versions. |
| Exactly one ordinary rule must match every data row. | This removes hidden precedence and exposes missing and overlapping classifications. |
| YAML contains a small matching-expression language. | YAML handles configuration structure while the DSL keeps boolean conditions readable. |
| The web interface edits only rules through structured controls. | The highest-value authoring loop is supported without building a general YAML editor. |
| Draft rules may be saved before behavioral validation passes. | Users can preserve work without weakening finalization. |
| Historical comparison is structural and exact decimals compare by value. | Formatting is irrelevant while accounting data changes remain blocking. |
| The target is created atomically and never overwritten. | Approved history is protected and failed conversion leaves no partial output. |
| Libyaml, zarko, and zig-regex are pinned. | Their exact parser behavior becomes reproducible and testable on Zig 0.17.0. |
| A CSV's leading byte-order mark is ignored; a configuration file's is rejected. | Exporters add marks to CSVs the user cannot regenerate, and a mark would otherwise sit inside the first header cell and break an exact header match. Configuration files are the user's own, where a mark means a misconfigured editor. |
Vision Traceability #
| Vision goal | Milestone-one requirements |
|---|---|
| Convert one CSV into one deterministic journal. | M1-PROJ-006 through M1-PROJ-015, M1-JRN-001 through M1-JRN-014, M1-SAFE-001 |
| Support one reusable import profile. | M1-YAML-008, M1-YAML-012, M1-PROJ-001 through M1-PROJ-005, M1-CSV-001 through M1-CSV-021 |
| Provide expressive, order-independent named rules. | M1-RULE-001 through M1-RULE-021 |
| Diagnose every evaluable row's matching status. | M1-RULE-008 through M1-RULE-010, M1-RULE-020, M1-CLI-004, M1-UI-005 through M1-UI-007 |
| Generate a simple balanced transaction. | M1-TPL-001 through M1-TPL-012, M1-JRN-001 through M1-JRN-012 |
| Protect approved historical behavior. | M1-HIST-001 through M1-HIST-014, M1-DIAG-003 |
| Support non-interactive checking and conversion. | M1-CLI-001 through M1-CLI-008 |
| Provide interactive rule authoring and feedback. | M1-UI-001 through M1-UI-022 |
| Fit into a larger version-controlled project. | M1-PROJ-006 through M1-PROJ-017, M1-HIST-011, M1-HIST-012, M1-SAFE-002, M1-SAFE-003 |