Skip to content

refactor: extract evaluate_function into category-based helpers - #3

Merged
robcohen merged 1 commit into
mainfrom
refactor/query-executor
Jan 6, 2026
Merged

robcohen merged 1 commit into
mainfrom
refactor/query-executor

Conversation

@robcohen

@robcohen robcohen commented Jan 6, 2026

Copy link
Copy Markdown
Member

Summary

Refactor the monolithic 667-line evaluate_function method into smaller, focused helper methods organized by function category:

  • eval_date_function: YEAR, MONTH, DAY, WEEKDAY, QUARTER, YMONTH, TODAY
  • eval_string_function: LENGTH, UPPER, LOWER, SUBSTR, TRIM, STARTSWITH, ENDSWITH
  • eval_account_function: PARENT, LEAF, ROOT, ACCOUNT_DEPTH, ACCOUNT_SORTKEY
  • eval_math_function: ABS, NEG, ROUND, SAFEDIV
  • eval_position_function: NUMBER, CURRENCY, GETITEM, UNITS, COST, WEIGHT, VALUE
  • eval_coalesce: COALESCE

Also adds require_args helper to reduce argument validation boilerplate.

The main evaluate_function now dispatches to these helpers based on function category, improving readability and maintainability.

Test plan

  • All 37 existing query tests pass
  • cargo clippy passes
  • Code formatted with cargo fmt

Refactor the monolithic 667-line evaluate_function method into smaller,
focused helper methods organized by function category:

- eval_date_function: YEAR, MONTH, DAY, WEEKDAY, QUARTER, YMONTH, TODAY
- eval_string_function: LENGTH, UPPER, LOWER, SUBSTR, TRIM, STARTSWITH, ENDSWITH
- eval_account_function: PARENT, LEAF, ROOT, ACCOUNT_DEPTH, ACCOUNT_SORTKEY
- eval_math_function: ABS, NEG, ROUND, SAFEDIV
- eval_position_function: NUMBER, CURRENCY, GETITEM, UNITS, COST, WEIGHT, VALUE
- eval_coalesce: COALESCE

Also add require_args helper to reduce argument validation boilerplate.

The main evaluate_function now dispatches to these helpers based on
function category, improving readability and maintainability.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@robcohen
robcohen force-pushed the refactor/query-executor branch from 6d61a18 to f4425d0 Compare January 6, 2026 16:51
@robcohen
robcohen added this pull request to the merge queue Jan 6, 2026
Merged via the queue into main with commit da34da8 Jan 6, 2026
@robcohen
robcohen deleted the refactor/query-executor branch January 6, 2026 17:27
robcohen added a commit that referenced this pull request Jan 14, 2026
refactor: extract evaluate_function into category-based helpers
robcohen added a commit that referenced this pull request Jan 14, 2026
refactor: extract evaluate_function into category-based helpers
robcohen added a commit that referenced this pull request Feb 16, 2026
- Sort metadata keys for deterministic output order (#3)
- Escape strings in option/include/plugin formatting (#2)
- Preserve leading blank lines at file start (#1)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
robcohen added a commit that referenced this pull request Mar 31, 2026
Fixes several issues identified in PR #624 review:

1. Yahoo f64 precision (issue #3): Use pattern matching with
   serde_json::Value::Number to preserve decimal precision instead of
   converting through f64.

2. ECB cross-rate handling (issue #2): Rewrite fetch_price to correctly
   handle EUR→X, X→EUR, and X→Y cross-rate conversions.

3. --source-cmd early return (issue #4): Move external command handling
   after symbol discovery so -f flag works with --source-cmd.

4. Hardcoded timeout (issue #7): Use config timeout for --source-cmd
   instead of hardcoded 30 seconds.

5. External source naming (issue #8): Derive source name from command
   binary name instead of always returning "external". Add with_name()
   constructor for configured sources.

6. Unknown sources warning (issue #5): Track and report unknown sources
   in fallback chains when price fetching fails.

7. Timeout limitation (issue #6): Document that timeout is stored but
   not enforced due to std::process::Command limitations.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
robcohen added a commit that referenced this pull request Apr 12, 2026
- Fix #1: Build SourceMap with buffer content in single-file mode so
  run_plugins() can preserve directive source locations
- Fix #2: Anchor Python plugin warning to the plugin directive span
  and filter by current_file_id to avoid noise in multi-file mode
- Fix #3: Only show plugin errors in the main file (file_id 0) to
  prevent duplication across open documents
- Fix #4: Correct diagnostic message — non-native plugins are skipped
  in LSP, not "may be slower" (run_plugins only runs native plugins)
- Fix #5: Merge fresh buffer plugin declarations with ledger plugins,
  mirroring the directive overlay approach for unsaved edits

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request Apr 23, 2026
…tability

- Change ValidationOptions.document_dirs from Vec<String> to Vec<PathBuf>
  to store resolved paths instead of raw values
- Add #[non_exhaustive] to ValidationOptions to prevent breaking changes
  when new fields are added
- Resolve document paths against source_map base_dir in run_validation()
  and build_validation_options_from_loader() to match run_plugins() behavior
- Use Path::join() instead of string concatenation for portable paths
- Fix test to use doc_subdir.join() instead of format! for path construction

Addresses Copilot review comments #1, #2, #3, #4, #5, #7 on PR #899
robcohen added a commit that referenced this pull request Apr 23, 2026
…tability

- Change ValidationOptions.document_dirs from Vec<String> to Vec<PathBuf>
  to store resolved paths instead of raw values
- Add #[non_exhaustive] to ValidationOptions to prevent breaking changes
  when new fields are added
- Resolve document paths against source_map base_dir in run_validation()
  and build_validation_options_from_loader() to match run_plugins() behavior
- Use Path::join() instead of string concatenation for portable paths
- Fix test to use doc_subdir.join() instead of format! for path construction

Addresses Copilot review comments #1, #2, #3, #4, #5, #7 on PR #899
robcohen added a commit that referenced this pull request Apr 23, 2026
…tability

- Change ValidationOptions.document_dirs from Vec<String> to Vec<PathBuf>
  to store resolved paths instead of raw values
- Add #[non_exhaustive] to ValidationOptions to prevent breaking changes
  when new fields are added
- Resolve document paths against source_map base_dir in run_validation()
  and build_validation_options_from_loader() to match run_plugins() behavior
- Use Path::join() instead of string concatenation for portable paths
- Fix test to use doc_subdir.join() instead of format! for path construction

Addresses Copilot review comments #1, #2, #3, #4, #5, #7 on PR #899
robcohen added a commit that referenced this pull request Apr 23, 2026
…tability

- Change ValidationOptions.document_dirs from Vec<String> to Vec<PathBuf>
  to store resolved paths instead of raw values
- Add #[non_exhaustive] to ValidationOptions to prevent breaking changes
  when new fields are added
- Resolve document paths against source_map base_dir in run_validation()
  and build_validation_options_from_loader() to match run_plugins() behavior
- Use Path::join() instead of string concatenation for portable paths
- Fix test to use doc_subdir.join() instead of format! for path construction

Addresses Copilot review comments #1, #2, #3, #4, #5, #7 on PR #899
robcohen added a commit that referenced this pull request Apr 28, 2026
…elf-review)

Self-review of PR #945 surfaced five issues; this commit addresses all of
them.

1. **Match Python beancount on `BEANCOUNT_DISABLE_LOAD_CACHE`.** Python's
   check is `os.getenv(...) is None`, which means *any* presence — empty
   string included — disables the cache. We required a non-empty value;
   that's a silent divergence for users who write `EXPORT FOO=` in their
   shell. Switched to `is_some()` to match.

2. **Normalize the disable check between loader and CLI.** Both now go
   through the new `cache_disabled_by_env()` helper, exported from the
   loader so any downstream consumer (LSP, MCP, future tools) gets the
   same semantics for free.

3. **`invalidate_cache` now also removes the legacy sidecar.**
   `save_cache_entry` already cleans up the pre-#939 visible file when
   it writes a new dotfile cache; `invalidate_cache` was missing the
   same logic, so a `rledger check --invalidate-cache` (hypothetical or
   programmatic invalidate) would leave the legacy file behind.

4. **`with_env` is now panic-safe.** Replaced the inline save/restore
   pattern with an `EnvGuard` Drop type. A test that panics mid-body no
   longer leaks its mutated env into the next test in the binary.

5. **`disable_env_makes_load_return_none_and_save_no_op` was vacuous.**
   It asserted `load_cache_entry → None`, but the cache file didn't
   exist (because save was a no-op), so the test would have passed even
   if `load_cache_entry` ignored the env entirely. Restructured to:
   (a) write a real cache with the env unset, (b) set the env and
   verify load returns None despite the cache being on disk, (c) verify
   save doesn't touch the existing file (mtime invariant).

Plus one new test: `empty_disable_env_value_still_disables` locks in
the Python-beancount-compatible empty-value semantics from #1.
And one new test: `test_invalidate_cache_removes_legacy_sidecar`
covers the new behavior in #3.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request Apr 28, 2026
…loses #939) (#945)

* fix(cache): hide cache file as dotfile and honor beancount env vars (closes #939)

`rledger check` wrote a visible `<file>.cache` next to every ledger,
creating clutter that surprised users (#939). Match Python beancount's
established convention instead:

- Default cache filename is now `.<file>.cache` (hidden dotfile),
  mirroring beancount's `.{filename}.picklecache`.
- Honor `BEANCOUNT_DISABLE_LOAD_CACHE` to opt out persistently.
- Honor `BEANCOUNT_LOAD_CACHE_FILENAME` to redirect the cache; supports
  `{filename}` substitution and resolves relative paths against the
  source directory, matching beancount semantics.
- Empty `BEANCOUNT_LOAD_CACHE_FILENAME` is treated as unset to prevent
  every ledger's cache from collapsing onto the same file.
- After writing the new dotfile cache, opportunistically delete the
  legacy visible `<file>.cache` (silent on failure) so upgrading users
  don't have to clean up by hand.

The `--no-cache` / `-C` CLI flag continues to work for one-shot opt-out.

Tests:
- New unit tests for `resolve_cache_pattern` and `legacy_cache_path`.
- New `tests/cache_env_var_test.rs` integration test that exercises
  the env var path end-to-end. Lives in a separate test binary because
  mutating process env requires `unsafe` since Rust 2024 and the
  workspace forbids `unsafe_code`.
- Updated `test_load_cache_invalid_magic` to write the malformed cache
  at the new dotfile path so it actually exercises the load path.

Docs:
- `docs/commands/check.md` — added a Cache File section with naming,
  env vars, and migration note.
- `docs/reference/architecture.md` — refreshed the Binary Cache section
  with the dotfile location, content-based invalidation note, and env
  var pointer.
- `cache.rs` module-level rustdoc updated.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(cache): refresh remaining stale references to old cache filename

Pick up two spots missed in the initial #939 fix:

- `.gitignore`: keep matching legacy `<file>.beancount.cache` (gitignored
  for users upgrading from earlier versions) and add an explicit dotfile
  pattern with a comment explaining the rationale. The bare `*` pattern
  already matched dotfiles per gitignore semantics, but the explicit
  pattern makes the intent clear.
- `performance-roadmap.md`: cache location example was still showing the
  visible filename — updated to the dotfile form with an env-var pointer.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(cache): address Copilot review feedback on #945

Five substantive issues raised by the Copilot review on PR #945:

1. **Custom cache directories now created automatically.**
   `BEANCOUNT_LOAD_CACHE_FILENAME` patterns can resolve to a directory
   that doesn't exist (e.g. `~/.cache/rledger/{filename}.cache` on a
   fresh install). `save_cache_entry` now `create_dir_all`s the parent
   eagerly so caching isn't silently disabled.

2. **`BEANCOUNT_DISABLE_LOAD_CACHE` is now honored at the loader level.**
   Previously only the CLI checked it, so any external consumer of
   `rustledger-loader::{load,save}_cache_entry` would silently bypass
   the kill switch. Both functions now early-return when the env var
   is set to a non-empty value (matching Python beancount semantics).
   The CLI check stays as an early-out optimization.

3. **`default_cache_path` exposed as a pure helper.**
   `cache_path()` reads process env, which makes any test that calls
   `save_cache_entry`/`invalidate_cache` env-sensitive.
   `default_cache_path()` returns the dotfile path with no env lookup —
   useful for tests and library consumers that need determinism.

4. **Doc accuracy.** I had claimed cache invalidation was "content-based"
   in `docs/commands/check.md` and `docs/reference/architecture.md`,
   but `compute_hash` actually hashes file path + mtime + size.
   Reworded both pages to describe the real metadata-based behavior
   (and noted content-based hashing as a possible future improvement).

5. **Module rustdoc clarified** to state explicitly that the env vars
   are honored at the loader level, not just by CLI callers.

Tests:
- New integration test `save_creates_missing_parent_directory` covers
  the regression in #1.
- New integration test `disable_env_makes_load_return_none_and_save_no_op`
  covers the loader-level enforcement in #2.
- In-module roundtrip/invalidate tests now `assert_clean_cache_env()` at
  the top so a developer with locally-set cache env vars sees a clear
  failure rather than mysterious behavior.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(cache): tighten env handling and panic-safe test plumbing (#945 self-review)

Self-review of PR #945 surfaced five issues; this commit addresses all of
them.

1. **Match Python beancount on `BEANCOUNT_DISABLE_LOAD_CACHE`.** Python's
   check is `os.getenv(...) is None`, which means *any* presence — empty
   string included — disables the cache. We required a non-empty value;
   that's a silent divergence for users who write `EXPORT FOO=` in their
   shell. Switched to `is_some()` to match.

2. **Normalize the disable check between loader and CLI.** Both now go
   through the new `cache_disabled_by_env()` helper, exported from the
   loader so any downstream consumer (LSP, MCP, future tools) gets the
   same semantics for free.

3. **`invalidate_cache` now also removes the legacy sidecar.**
   `save_cache_entry` already cleans up the pre-#939 visible file when
   it writes a new dotfile cache; `invalidate_cache` was missing the
   same logic, so a `rledger check --invalidate-cache` (hypothetical or
   programmatic invalidate) would leave the legacy file behind.

4. **`with_env` is now panic-safe.** Replaced the inline save/restore
   pattern with an `EnvGuard` Drop type. A test that panics mid-body no
   longer leaks its mutated env into the next test in the binary.

5. **`disable_env_makes_load_return_none_and_save_no_op` was vacuous.**
   It asserted `load_cache_entry → None`, but the cache file didn't
   exist (because save was a no-op), so the test would have passed even
   if `load_cache_entry` ignored the env entirely. Restructured to:
   (a) write a real cache with the env unset, (b) set the env and
   verify load returns None despite the cache being on disk, (c) verify
   save doesn't touch the existing file (mtime invariant).

Plus one new test: `empty_disable_env_value_still_disables` locks in
the Python-beancount-compatible empty-value semantics from #1.
And one new test: `test_invalidate_cache_removes_legacy_sidecar`
covers the new behavior in #3.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 7, 2026
Items from the third deep review of #1022. All polish; no production
behavior change.

1. Multi-currency-key first-wins test
   The previous test only verified "currency is found in multi-column
   key" — it would pass under "first match", "last match", or any
   matching strategy. New test
   `test_currency_hint_for_row_first_currency_wins_when_multiple` uses
   a key with TWO currency-shaped + tracked-precision strings (`[EUR,
   USD]` and reversed `[USD, EUR]`) so the assertion discriminates
   iteration order. Pins the contract documented on `add_aggregate_row`.

2. `sort_by` pre-allocation
   `Vec::reserve_exact(n)` on the now-empty `rows` and `row_group_keys`
   before the push-back loop. Skips incremental-grow allocations.
   Sub-millisecond at typical N; trivial cleanup.

3. `currency_hints` cache short-circuit
   Skip the per-row hint Vec allocation entirely when the result has
   no aggregate rows (the common case for non-aggregate queries).
   New `QueryResult::has_aggregate_rows()` accessor encapsulates the
   check (rather than reaching into `pub(crate)` field). Access pattern
   in the renderer changes to `currency_hints.get(i).copied().flatten()`
   so the empty-Vec case returns `None` cleanly.

4. Cache-lifetime documentation
   One-paragraph comment on the `currency_hints` declaration explaining
   the borrow constraint (`&str` entries borrow from `result`; safe
   while `result` is `&`-borrowed). Future refactors that mutate
   `result` mid-stream would break this; the comment makes the
   constraint visible without reading the borrow checker's mind.

5. Direct `add_row` test
   `test_add_row_records_none_in_sidecar` standalone (was covered
   indirectly by the mixed-row test). Pins the contract isolated from
   other helpers' behavior.

6. `group_key` returns `&[Value]` not `&Vec<Value>`
   Callers no longer tied to the specific container type. Test
   assertions updated to use `Some(&[...][..])` for the slice
   coercion. Also tightens `pub(crate) row_group_keys` access:
   external consumers MUST go through `group_key()` /
   `has_aggregate_rows()` accessors.

137 query tests + 14 renderer tests pass. Clippy + fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 7, 2026
…1022)

* fix(query): quantize SUM-aggregate text output via GROUP BY currency

`SUM(number) GROUP BY currency` (and equivalent implicit-grouping
patterns) emit a `Value::Number` that carries no currency context, so
text rendering went through the fallback `format_default` path that
preserves rust_decimal's natural scale. When inputs had varying scales
(e.g. one 0.00 + one 5.213), the sum kept the wider scale and rendered
`0.000` / `5.213` instead of bean-query's `0.00` / `5.21`. Of the ~99
post-#986 BQL compat mismatches, ~15 fell into this bucket.

Issue #988 recommended Option A (quantize at aggregation time), but
that conflicts with its own AC #4 ("CSV/JSON output of aggregates
remains lossless") — quantizing in the aggregator mutates inputs for
ALL output paths, not just text. This PR implements Option B as
described in the issue body: plumb GROUP BY currency through to the
renderer, quantize at text-render time only.

Implementation:
- `QueryResult` gains `row_group_keys: Vec<Option<Vec<Value>>>` — a
  parallel sidecar to `rows`. Aggregate path populates it via the new
  `add_aggregate_row(row, group_key)`; non-aggregate path still calls
  `add_row(row)` and gets `None` slots.
- `cmd/query/output.rs::write_text` looks up the row's sidecar, finds
  the first currency-shaped string in the GROUP BY key (heuristic:
  uppercase initial, `[A-Z0-9'._-]`, ≤24 chars), and passes it as a
  hint to a new `format_value_with_hint`.
- `format_value_with_hint` routes `Value::Number` cells through
  `DisplayContext::format(n, currency)` when a hint is present —
  per-currency precision via the same path used for `Value::Amount`.
- CSV / JSON / beancount renderers still call `format_value`
  unchanged: lossless preserved, satisfying AC #4.

Tests added in cmd::query::output:
- `test_looks_like_currency_accepts_typical_currencies`
- `test_looks_like_currency_rejects_non_currencies`
- `test_format_value_with_hint_routes_number_through_per_currency_ctx`
  — pins the central dispatch: same Value::Number(0.000) renders as
  "0.00" with USD hint vs "0.000" without.
- `test_format_value_with_hint_unknown_currency_falls_back_safely` —
  defense-in-depth for false-positive currency detection.

All 131 rustledger-query tests still pass; existing rustledger CLI
query snapshots unchanged.

Closes #988.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(query): address PR #1022 review — sidecar sync + false-positive hint gate

Copilot flagged four issues on the original commit. All real:

1. **`row_group_keys` desynchronizes after ORDER BY / LIMIT.** The
   sidecar is parallel to `rows`, but `sort_results` and the four
   `result.rows.truncate(limit)` sites mutated only `rows` — after
   sort or pagination, `row_group_keys[i]` no longer corresponded
   to row `i`, so currency hints would be applied to the wrong rows.
   Fixed by encapsulating the invariant inside `QueryResult`:
   - New `QueryResult::truncate(len)` truncates both vectors.
   - New `QueryResult::sort_by(F)` pair-sorts both vectors via a
     single `mem::take` + `zip` + `sort_by` + push-back, with
     `debug_assert_eq!` guarding the lengths.
   - `sort.rs` and all four LIMIT sites now go through these helpers.

2. **False-positive currency hint silently STRIPS trailing zeros.**
   `DisplayContext::format(n, currency)` falls back to
   `n.normalize().to_string()` when the currency has no tracked
   precision — `normalize()` strips trailing zeros, turning `0.000`
   into `0`. So a heuristic-only currency check ("uppercase, looks
   right") would render output WORSE than the pre-fix state for
   any unrecognized currency-shaped string in a GROUP BY key.
   Fixed by gating on `ctx.get_precision(s).is_some()` in the new
   `currency_hint_for_row` helper — only currencies with tracked
   precision become hints. Test
   `test_currency_hint_for_row_filters_untracked_currencies` pins
   the contract end-to-end (USD with samples → hint; MADEUP without
   samples → no hint, even though it passes the shape check).

3. **Hint-extraction logic was duplicated** between the width-pass
   and the row-print pass in `write_text`. Factored out into the
   new `currency_hint_for_row(result, row_idx, ctx)` helper.

4. **(Implicit) `looks_like_currency` docstring overstated safety.**
   The original comment claimed false positives were "no-op";
   they're not, per #2 above. Rewrote the docstring to call out
   the two-step gate (shape check + precision check) and pointer
   to the `currency_hint_for_row` site that enforces it.

Net change: +119 / -55 across 4 files. All 131 query tests still
pass; new test pins the precision-gate contract.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(query): close test gaps + tighten invariants from deep review

Self-review of #1022 surfaced real gaps that Copilot's first pass
missed. All addressed in this commit; no production-code behavior
change beyond visibility tightening and the `debug_assert!` →
`assert!` upgrade in `QueryResult::sort_by`.

API hardening:
- `QueryResult::row_group_keys` marked `#[doc(hidden)]` and the
  invariant (parallel to `rows`, never reach in directly) is now in
  the struct's docstring. New public accessor `group_key(row_idx)`
  is the canonical read path; the renderer goes through it instead
  of touching the field.
- `sort_by`'s `debug_assert_eq!` is now an unconditional `assert!`
  with a descriptive message — the lockstep invariant is load-bearing
  for correctness, not a debug-only sanity check.

Test coverage:
- `test_sort_by_keeps_row_group_keys_in_lockstep` — pins ORDER BY
  preserves row↔key alignment.
- `test_truncate_keeps_row_group_keys_in_lockstep` — pins LIMIT.
- `test_add_row_and_add_aggregate_row_mixed` — pins the invariant
  across interleaved aggregate/non-aggregate inserts.
- `test_add_aggregate_row_empty_key_records_none` — pins the
  empty-key-becomes-None contract.
- `test_csv_aggregate_output_preserves_unquantized_decimal` — pins
  AC #4 lossless contract for CSV.
- `test_json_aggregate_output_preserves_unquantized_decimal` — same
  for JSON.
- `test_beancount_aggregate_output_preserves_unquantized_decimal` —
  same for beancount output.
- `test_text_aggregate_output_quantizes_via_currency_hint` — pins
  the divergence: text quantizes, the others don't.
- `test_e2e_sum_group_by_currency_text_output_matches_per_currency_precision`
  — full pipeline: real BQL through Executor + write_text. The
  canary that fires if anyone reverts `add_aggregate_row` to
  `add_row` in the executor (helper-level tests stay green in that
  scenario; this one wouldn't).

Docs:
- Multi-currency-column GROUP BY rare-case behavior now documented
  on `add_aggregate_row` and the renderer's `currency_hint_for_row`.
- Misleading "two `0.00 USD` values sum to `0.000`" example replaced
  with the real cause (mixed-scale inputs like `0.000` + several
  `0.00`s).
- "Caught by Copilot review on PR #1022" self-references dropped —
  they would read awkwardly post-merge.

135 query tests + 11 renderer tests pass. Clippy + fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(query): apply remaining deep-review improvements (13 items)

Closes the 13 items from the second deep review of #1022. No
production-behavior change beyond the visibility tightening, the
heuristic narrowing, and the debug-only tripwire — all defensive.

Encapsulation:
- A: `row_group_keys` demoted from `pub` (with `#[doc(hidden)]`) to
  `pub(crate)`. External crates now MUST go through `group_key()`,
  closing the loophole where the renderer (or a future contributor)
  could violate the parallel-vector invariant by direct field access.

Heuristic & perf:
- B: `looks_like_currency` lower bound bumped from 1 to 2. Single
  uppercase letters aren't real currencies; the precision gate would
  filter them anyway, but tightening the heuristic makes the intent
  clearer and shrinks the false-positive surface.
- C: per-row currency hints now resolved ONCE into a `Vec<Option<&str>>`
  before the width-calc and print passes, instead of recomputed per
  pass. Eliminates duplicate work + duplicated extraction code.

Safety net:
- L: `format_value_with_hint` gains a `debug_assert!` inside the
  `Value::Number + hint` branch that fires if a caller forgets the
  precision-gate filter. Discovered (and fixed) a false-fire when
  width-calc passes the hint to non-Number cells — the assert now
  scopes correctly to the dispatch branch where the hint is consumed.

Test cleanups:
- D: vacuous JSON assertion (`A || A`) replaced with a single clean
  check using raw strings + clearer reasoning comment.
- E: dead `let _ = ctx;` in JSON test removed (write_json doesn't
  take a DisplayContext, so building one is dead code).
- F: CSV assertion no longer relies on `\n` substring matching —
  parses by lines + commas, robust to CRLF on any platform.
- G: e2e test asserts on the SUM cell anchored by row position +
  whitespace tokenization, instead of a global negative substring
  scan that could false-fire on unrelated `0.0001`-shaped output.
- H: dropped the last "Copilot review on PR #1022" self-reference
  from a test docstring.

New coverage:
- I: `test_e2e_implicit_group_by_currency_text_output_quantized` —
  pins the implicit-GROUP-BY path (`SELECT currency, SUM(number)`
  without `GROUP BY`) also populates `row_group_keys`. Different
  executor code path (`extract_implicit_group_by_exprs`) that the
  explicit-GROUP-BY e2e test wouldn't catch.
- J: `test_sort_by_panics_on_lockstep_violation` — `#[should_panic]`
  test that deliberately corrupts the parallel-vector invariant and
  verifies `sort_by`'s `assert_eq!` actually fires.
- K: `test_currency_hint_for_row_finds_currency_in_multi_column_group_by_key`
  — pins the documented contract that `find_map` over the GROUP BY
  key correctly skips non-currency-shaped strings (account names) to
  reach the currency.

Docs:
- M: `add_row` docstring expanded to explain the sidecar consequence.

136 query tests + 13 renderer tests pass. Clippy + fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(query): apply review #3 fixes (6 items)

Items from the third deep review of #1022. All polish; no production
behavior change.

1. Multi-currency-key first-wins test
   The previous test only verified "currency is found in multi-column
   key" — it would pass under "first match", "last match", or any
   matching strategy. New test
   `test_currency_hint_for_row_first_currency_wins_when_multiple` uses
   a key with TWO currency-shaped + tracked-precision strings (`[EUR,
   USD]` and reversed `[USD, EUR]`) so the assertion discriminates
   iteration order. Pins the contract documented on `add_aggregate_row`.

2. `sort_by` pre-allocation
   `Vec::reserve_exact(n)` on the now-empty `rows` and `row_group_keys`
   before the push-back loop. Skips incremental-grow allocations.
   Sub-millisecond at typical N; trivial cleanup.

3. `currency_hints` cache short-circuit
   Skip the per-row hint Vec allocation entirely when the result has
   no aggregate rows (the common case for non-aggregate queries).
   New `QueryResult::has_aggregate_rows()` accessor encapsulates the
   check (rather than reaching into `pub(crate)` field). Access pattern
   in the renderer changes to `currency_hints.get(i).copied().flatten()`
   so the empty-Vec case returns `None` cleanly.

4. Cache-lifetime documentation
   One-paragraph comment on the `currency_hints` declaration explaining
   the borrow constraint (`&str` entries borrow from `result`; safe
   while `result` is `&`-borrowed). Future refactors that mutate
   `result` mid-stream would break this; the comment makes the
   constraint visible without reading the borrow checker's mind.

5. Direct `add_row` test
   `test_add_row_records_none_in_sidecar` standalone (was covered
   indirectly by the mixed-row test). Pins the contract isolated from
   other helpers' behavior.

6. `group_key` returns `&[Value]` not `&Vec<Value>`
   Callers no longer tied to the specific container type. Test
   assertions updated to use `Some(&[...][..])` for the slice
   coercion. Also tightens `pub(crate) row_group_keys` access:
   external consumers MUST go through `group_key()` /
   `has_aggregate_rows()` accessors.

137 query tests + 14 renderer tests pass. Clippy + fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 8, 2026
* fix(query): align PIVOT BY semantics with bean-query (closes #1034)

Comprehensive fix for all four items in #1034 by aligning rledger's
PIVOT BY with bean-query's semantics. Items #1 (underflow), #2
(value==pivot), #3 (semantic divergence), and #4 (ORDER BY hidden-col
strip) all collapse into one design: match upstream.

CHANGES:

1. PIVOT BY now requires exactly TWO columns
   `PIVOT BY <pivot_value_col>, <group_by_col>` — first column's values
   become new column headers, second is the GROUP BY column to keep as
   the row key. Pre-fix rledger took ONE column and synthesized the
   row-key dimension from "all other GROUP BY columns"; bean-query's
   two-column form is more explicit and the upstream-compatible path.

2. Three new validation errors (matching bean-query's wording verbatim):
   - `PivotWrongArity(n)` — "PIVOT BY requires exactly two columns"
   - `PivotSameColumn` — "the two PIVOT BY columns cannot be the same
     column" (subsumes item #2)
   - `PivotSecondNotInGroupBy` — "the second PIVOT BY column must be a
     GROUP BY column"

3. Parser clause order flipped: ORDER BY before PIVOT BY (matches
   bean-query grammar). Pre-fix rledger had PIVOT BY before ORDER BY,
   which is bean-query-incompatible at the grammar level.

4. Execution pipeline reordered:
   pre-fix:  aggregate → PIVOT → sort → strip-hidden → LIMIT
   post-fix: aggregate → sort → strip-hidden → PIVOT → LIMIT
   PIVOT now operates on the visible-only, sorted shape. The strip-
   hidden step always sees hidden cols at the trailing position
   (pre-pivot), so it correctly removes them. Item #4 (strip-from-end
   silently dropping pivot values when num_hidden > 0) dissolves.

5. Item #1 (`result.columns.len() - 1` underflow) was already
   addressed by #1033's `targets.len() - 1` change. The new apply_pivot
   no longer needs the value_col_idx heuristic at all — the value
   columns are derived from "everything except pivot and key columns".

REWRITTEN apply_pivot:
- Validates arity, distinctness, GROUP-BY membership before any work.
- Collects pivot values in first-seen order (preserves user's ORDER BY
  through to the new column header order).
- Generalizes to multiple value columns: with exactly one value col
  (the typical SUM(number) case), the pivot value alone is the new
  column header; with multiple, columns are qualified
  `<value_col_name> / <pivot_value>`.
- Bug fix from PR #1033 (column-name fallback for precision via #1023)
  remains intact — pivoted column names are still currency strings.

TESTS:
- Updated `test_parse_pivot_by` → `test_parse_pivot_by_two_columns`.
- New: `test_parse_pivot_by_one_column_parses_but_executes_with_arity_error`.
- New: `test_pivot_by_same_column_rejected` (item #2).
- New: `test_pivot_by_second_column_must_be_in_group_by`.
- New: `test_pivot_by_with_order_by_works` (regression for item #4).
- New: `test_pivot_by_with_order_by_on_hidden_column_works` (the
  killer — pre-fix this silently dropped the pivot values).
- Updated existing renderer e2e tests to use two-column form.

511 query tests + 307 rustledger lib tests + 20 renderer tests pass.
Clippy --all-targets clean. fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(query): address self-review on #1037

Five concerns from the deep review, all landed in this PR:

1. Multi-column GROUP BY migration limitation — clarified in PR body.
   Bean-query's two-arg form means rledger users with a multi-column
   GROUP BY must pick ONE column to keep as the row key; can't preserve
   a composite. Pre-fix rledger kept all non-pivot, non-value GROUP BY
   columns as the composite key, so users restructuring need to either
   drop the extra dimension or aggregate further.

2. Hash-only dedup risk fixed. Two paths:
   - `pivot_values` collection: linear-scan with structural PartialEq
     (Value is Eq but not Hash; pivot values are typically small,
     so O(N) per insert is fine).
   - `group_index` and `pivot_lookup`: hash-bucket + structural
     PartialEq inside the bucket. Same correctness as a HashMap<Value, …>
     would give but works around Value's missing Hash impl.

3. Multi-value-column case now tested. New
   `test_pivot_by_multi_value_column_qualifies_headers` exercises the
   `value_col_idxs.len() > 1` branch with `SUM + COUNT` side-by-side.
   Confirmed the qualified-header format `<value_col_name> / <pivot_value>`
   actually fires.

4. Implicit GROUP BY + PIVOT now produces a specific error. New
   `PivotWithoutGroupBy` variant fires when `query.group_by` is None.
   Pre-fix this would fall through to the misleading
   `PivotSecondNotInGroupBy` message. New test
   `test_pivot_by_without_group_by_clause_rejected` pins the message.

5. `QueryError` is now `#[non_exhaustive]`. Adding variants no longer
   breaks downstream exhaustive matches.

Bonus: removed the dead `pivot_exprs.is_empty()` early return (parser
guarantees ≥ 1; replaced with `debug_assert!`) and added a comment
about the hidden-cols-trailing invariant the default-sort-by-first-column
block depends on.

518 query tests pass (137 lib + 365 integration + 13 prop + 3 doc).
Clippy --all-targets clean. Fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(query): address self-review v2 on #1037

Five items from the second deep review:

1. Docstring drift on apply_pivot. Validation rules block now lists 4
   rules (was 3), with the bean-query parity claim narrowed to rules
   1-3 — `PivotWithoutGroupBy` is rledger-specific because bean-query's
   grammar typically rejects PIVOT-without-GROUP-BY earlier.

2. Multi-row same `(key, pivot_value)` pair: documented as "first wins"
   in the function's new "Input contract" section. Aggregate queries
   (the typical caller) always satisfy uniqueness via GROUP BY; the
   contract is for non-aggregate or pre-aggregation callers. Test
   `test_pivot_by_duplicate_key_pivot_pairs_first_wins` pins the happy
   path; the policy itself is documented + asserted via `find` returning
   the first match.

3. `Vec<&&Row>` → `Vec<&Row>` cleanup. Use `for &row in &group_rows`
   to destructure the iter item once. Same behavior, one fewer borrow
   level — pure readability.

4. Edge case test added: `test_pivot_by_empty_result_yields_key_column_no_rows`.
   When the pre-pivot result is empty (e.g. WHERE filters everything),
   PIVOT now produces a single-column header (the key column) with
   zero rows. Pinning so a future "skip PIVOT on empty input"
   optimization doesn't accidentally also skip the header.

5. The `value_col_idxs.len() == 1` special case in column-name
   construction now has an inline comment explaining the bean-query
   alignment: single-aggregate users expect bare pivot value as
   header (e.g. `USD`), multi-aggregate qualifies with the value
   column name to disambiguate.

Bonus: clippy `--all-targets` flagged a 2-arm `match` on `Option`;
converted to `if let` per `clippy::single_match`.

10 pivot tests pass (was 8), 518 total query tests pass. Clippy
clean. Fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(query): handle Function exprs in find_pivot_column + tighten test

Address Copilot inline comments on PR #1037:

- Comments 1-3 (hash-only dedup): already addressed by commit 6813f31
  in this PR. New code uses hash-bucket + structural-eq verify inside
  the bucket — defense against u64 collisions.

- Comment 4: find_pivot_column's `_` arm rejected ALL non-Column non-
  Literal exprs with "PIVOT BY must reference a column name or index",
  meaning Function exprs (like `YEAR(date)`) couldn't resolve at all.
  This had two fallout consequences:
    * `PIVOT BY YEAR(date), account` would error before even reaching
      the GROUP BY membership check.
    * `GROUP BY YEAR(date)` exprs would silently fail to resolve via
      `find_pivot_column(...).ok()` in the membership iteration,
      misreporting `PivotSecondNotInGroupBy` for valid queries.
  Added an explicit `Expr::Function` arm that mirrors `sort_results`'s
  ORDER BY two-tier resolution: try the function name first
  (e.g. column `YEAR` for expr `YEAR(date)`), then fall back to the
  full expression string. The `_` arm now also handles other complex
  exprs by string-match (matches the hidden-column alias convention).

- Comment 5: `test_pivot_by_with_order_by_works` previously asserted
  only "result non-empty" + "account column present" — would have
  passed even if PIVOT didn't run. Strengthened with four assertions:
  the key column (`account`) survives, at least one pivoted column
  (`USD`) appears, and the original `currency` and `SUM` columns are
  GONE (their values moved into the pivoted cells).

10 pivot tests + 518 total query tests pass. Clippy --all-targets
clean. Fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 17, 2026
…ew tests

Six Copilot inline comments triaged:

| # | Issue | Status |
|---|-------|--------|
| 1 | max_memory unenforced | already fixed in 41dc97c (on older commit) |
| 2 | fuel calc can overflow u64 | FIXED |
| 3 | input length truncates >4 GiB; no output cap | FIXED (output cap was 41dc97c; input cap here) |
| 4 | typed_func errors masquerade as MissingExport | FIXED |
| 5 | CSV projection doc claims full but ships subset | FIXED (doc) |
| 6 | "duplicated here" comment lies about implementation | FIXED |

# Fuel saturation (Copilot #2)

`config.max_time_secs.max(1) * 1_000_000` would panic in debug and
silently wrap in release for very large `max_time_secs` (technically
possible at u64 values >18T, which is ~580K years — extreme but the
wrap is a real bug). Now uses `saturating_mul` — `u64::MAX` clamps
to `u64::MAX` which `set_fuel` accepts as "effectively unlimited."

# Input length cap (Copilot #3)

Added `MAX_INPUT_BYTES` (64 MiB, symmetric with `MAX_OUTPUT_BYTES`)
and `WasmImporterError::InputTooLarge { len, max }`. Extracted the
check into a `const fn validate_input_size(len) -> Result<u32, _>`
helper so the cap can be unit-tested without standing up wasmtime
and allocating 64 MiB. The host caps before the `as u32` cast so a
truncated input can't corrupt the import.

# ExportSignatureMismatch (Copilot #4)

Previously `get_typed_func::<u32, u32>("alloc").map_err(|_|
MissingExport("alloc"))` collapsed two distinct failure modes into
one misleading error. Since `validate_module` proves presence by
name at load time, any subsequent typed_func failure is necessarily
a signature mismatch — surfaced now as
`WasmImporterError::ExportSignatureMismatch { name, source }` which
names the export and chains the wasmtime type-mismatch detail.

Applied at all 3 typed_func sites (`alloc`, the dispatched entry,
`metadata`).

# CSV projection honesty (Copilot #5)

`CsvConfig` has 18 fields; this PR projects 8 (the simple
String/bool/number ones). Updated `build_wasm_input` and
`project_csv_config_into_options` docs to say "subset" + list
exactly what's projected and what's deferred to wave 2.3e (column
specs, locale, mappings — encoding decisions best driven by a real
WASM CSV importer, not guessed here). No behavior change.

# Stale duplication comment (Copilot #6)

The comment in `output_to_import_result` claimed the wrapper→directive
converter was "duplicated here so this crate doesn't need to depend
on the full `rustledger-plugin` graph" — but the code actually calls
`rustledger_plugin::convert::wrapper_to_directive` directly, with
the explicit dep added in this PR's Cargo.toml. Rewrote to say
"delegates … so the WASM importer path and directive-plugin path
share a single converter."

# Tests

3 new wasm:: tests (158 importer total, was 155):

- validate_input_size_accepts_at_cap_and_rejects_above —
  boundary test for MAX_INPUT_BYTES and the InputTooLarge surface.
- fuel_calc_saturates_instead_of_overflowing — regression for
  Copilot #2; loads with u64::MAX max_time_secs and asserts no
  panic + successful execution.
- wrong_signature_export_surfaces_export_signature_mismatch — WAT
  module with metadata: () -> i32 (wrong: should be -> i64);
  asserts ExportSignatureMismatch { name: "metadata" } rather than
  the previously-misleading MissingExport.

# Verification

- 26 wasm:: tests pass (was 23)
- 158/158 rustledger-importer tests pass
- cargo check --workspace --all-targets clean
- cargo clippy --workspace --all-targets -- -D warnings clean
- cargo fmt --all -- --check clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 17, 2026
Addresses the four substantive items from the second-round review of
the sandbox refactor in 52dd0b6.

# Doc (#1): breaking-change notice

Added a "Breaking change for user WASM plugins" section to the
`sandbox` module rustdoc, naming the five most impactful disabled
proposals (`wasm_threads`, `wasm_multi_memory`, `wasm_memory64`,
`wasm_component_model`, `wasm_gc`). Plugin authors targeting earlier
rustledger versions will see a wasmtime validation error at load
time and need to recompile against the new sandbox profile.

# Panic message (#2): preserve wasmtime error

`shared_engine` previously used `.expect("failed to build shared
wasmtime engine")`, which swallowed the underlying error detail.
Now uses `.unwrap_or_else(|e| panic!("wasmtime engine init failed:
{e}"))` so a process-start failure preserves the cause for
debugging. Still a panic (same semantics); just more useful when it
fires.

# Regression coverage (#3): 3 new tests

Added rejection tests for three more disabled features:

- `sandbox_config_rejects_memory64_module` — `(memory i64 1)`
- `sandbox_config_rejects_component_module` — `(component)` top-level
- `sandbox_config_rejects_gc_module` — `(type $s (struct …))`

Sandbox test count: 3 → 6. The remaining disabled flags
(`wasm_function_references`, `wasm_stack_switching`, `wasm_tail_call`,
`wasm_shared_everything_threads`) are minor variants of the tested
ones; explicit tests would be duplicative.

# Maintenance comment (#4): wasmtime upgrade audit

Added a MAINTENANCE NOTE atop `sandbox_config` calling out that
wasmtime's `Config::new()` defaults evolve across versions and new
proposals routinely land as default-on. On every wasmtime bump in
`Cargo.toml`, this function must be re-audited against wasmtime's
release notes — wasmtime has no "deny by default" mode, so the
audit is structurally required, not optional.

# Verification

- 6/6 sandbox tests pass (3 new in this commit)
- cargo clippy --workspace --all-targets -- -D warnings clean
- cargo fmt --all -- --check clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 17, 2026
* feat(importer): WasmImporter host loader (wave 2.3b)

Host-side loader for `.wasm` importer modules. Implements the
`Importer` trait by serializing inputs to MessagePack, calling into
the module via wasmtime, and deserializing outputs.

# Sandbox model

Mirrors `rustledger-plugin/src/runtime.rs`:

- All imports rejected at load time — no WASI, fs, net, env, syscalls
- Memory limit (default 256 MiB) and fuel-based time limit (default 30s)
- Fresh `Store` per call — concurrent extracts don't share state
- Module + Engine shared via `Arc` — `WasmImporter` is cheap to clone

# Wire protocol

WASM module exports: `memory`, `alloc(u32) -> u32`, `metadata() -> u64`,
`identify(ptr,len) -> u64`, `extract(ptr,len) -> u64`,
`extract_enriched(ptr,len) -> u64`. All u64 returns pack
`(out_ptr << 32) | out_len`.

`ImporterConfig` (CSV-specific fields) is projected into the wire
format's free-form `options: HashMap<String, String>`. Trade-off
documented inline: keeps the ABI minimal at the cost of string
parsing in the guest.

`extract_enriched` round-trips `EnrichmentWrapper`/`AlternativeWrapper`;
the `method: String` field parses via `parse_method()` with unknown
strings falling back to `Default` — forward-compat for hosts adding
new categorization methods.

`metadata` is called once at load and cached for `name()`/`description()`,
avoiding wasmtime instantiation on every property access.

Errors/warnings round-trip via `PluginError` reusing the same shape the
directive-plugin path uses (`LedgerError::location` flows naturally).

# Verification

- 4 `wasm::tests::*` pass (validate_module rejects imports / missing
  exports, parse_method round-trip + unknown fallback)
- `cargo check --workspace --all-targets` clean
- `cargo clippy --workspace --all-targets -- -D warnings` clean
- `cargo fmt --all -- --check` clean

# What's next (waves 2.3c-2.3e)

- 2.3c: registry discovery (`--wasm-importer` flag + directory scan)
- 2.3d: guest macros re-exported from `rustledger-plugin-types`
- 2.3e: reference sample importer + integration tests

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(importer): WasmImporter — enforce memory cap + output bound + zero-legacy review fixes

Addresses the 8 issues from the deep PR review of #1131. Changes are
scoped to wasm.rs (no API surface changes for downstream crates).

# Security / soundness

**Memory limit now actually enforced.** Added `MemoryLimiter`
implementing `wasmtime::ResourceLimiter`, wired via
`Store::limiter()`. Without this, `WasmRuntimeConfig::max_memory` was
silently ignored — a malicious or buggy WASM importer could
`memory.grow` until the host OOMed. (The same gap exists in
`rustledger-plugin/src/runtime.rs`; fixing both is queued as a
separate follow-up to keep this PR focused on the importer path.)

**Output size capped.** New `MAX_OUTPUT_BYTES` (64 MiB) plus
`WasmImporterError::OutputTooLarge`. Previously a module returning
`out_len = u32::MAX` would trigger a ~4 GiB `Vec` allocation before
`memory.read` ever ran. Validated centrally in a new
`read_packed_output` helper shared by all entry points.

**Fuel clamped at min 1.** `max_time_secs = 0` previously produced
`fuel = 0` → immediate trap on first instruction. Now `.max(1) *
1_000_000`. Regression test pins this.

# Correctness

**PluginError severity preserved on the wire.** Refactored ad-hoc
`format!(...)` calls into `format_plugin_error()` which prefixes the
formatted line with the severity ("error " vs "warning ") so a
fatal-but-recoverable importer error remains distinguishable from
informational chatter in the shared `warnings` channel.

**Orphan-colon bug fixed.** Previous formatter produced `": message"`
when both `source_file` and `line_number` were `None`, and `":42:
message"` when only `line_number` was set. New formatter builds the
location segment conditionally: `"file:42: msg"` / `"file: msg"` /
`"line 42: msg"` / `"msg"`.

**Fingerprint round-trip now works.** `EnrichmentWrapper.fingerprint`
(hex string) is parsed back into `Fingerprint` via `from_hex`.
Malformed hex surfaces as a bridge warning instead of silently
dropping to `None`. Closes the comment-flagged "wave 2.3+" deferral
— this *is* wave 2.3b.

**parse_method no longer silently degrades.** Returns
`Result<_, &str>` instead of `_`; unknown method strings surface as
warnings naming the unknown value. This is the exact failure mode
Copilot caught in #1130 (`merchant_dict` underscore typo vs
`merchant-dict` hyphen wire encoding) — silent fallback would have
re-introduced it.

# Tests

15 wasm:: tests now pass (was 4):

- 3 pre-existing (validate_module imports/exports, basic parse_method)
- `parse_method_round_trips_via_as_meta_value` — guards drift between
  the host enum and the wire-format string set
- `parse_method_unknown_surfaces_the_unknown_string` — pins the
  no-silent-degradation contract
- 5 `format_plugin_error_*` — full / warning / orphan-colon-free /
  file-only / line-only-uses-human-phrasing
- `end_to_end_wat_module_round_trips_all_entry_points` — minimal WAT
  module with pre-baked MessagePack outputs, exercises metadata +
  identify + extract + extract_enriched end-to-end through wasmtime
- `oversized_output_is_rejected_before_allocation` — module returns
  `out_len = u32::MAX`, host rejects at load (via metadata)
- `memory_limiter_rejects_grow_above_max` — direct unit test of
  `ResourceLimiter::memory_growing` boundary behavior
- `zero_max_time_secs_does_not_starve_fuel` — regression for the
  fuel-clamp

# Verification

- 147/147 rustledger-importer tests pass (was 132)
- cargo check --workspace --all-targets clean
- cargo clippy --workspace --all-targets -- -D warnings clean
- cargo fmt --all -- --check clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(importer): WasmImporter — cap tables + close review coverage gaps

Addresses the 4 substantive issues + polish from the second-round
review of #1131.

# Security

**Table growth now bounded.** Added `MAX_TABLE_ELEMENTS` (1M) +
limiter enforcement. wasmtime accounts `Memory` and `Table`
separately; without this, `table.grow` would bypass the memory
limiter. Each ref-typed slot is pointer-sized, so the cap puts a
~8 MiB worst-case ceiling on indirect-call tables — well under the
memory cap but plenty for any plausible dispatch pattern.

# Coverage

**`initial_memory_above_cap_is_rejected_via_limiter_wiring`** —
pins the `store.limiter(|s| &mut s.limiter)` wiring against
refactor regression. Previous test (`memory_limiter_rejects_grow_above_max`)
only exercised the trait method directly. New test loads a module
declaring 5000 pages (320 MiB) initial memory against a 64 MiB
cap and asserts instantiation fails — proves wasmtime is
actually consulting our limiter at instance creation.

**`table_limiter_rejects_grow_above_max`** — direct trait-method
test for the new table cap boundary.

# Refactor

**Extracted `bridge_enriched_output` free function** from
`WasmImporter::extract_enriched`. The lossy paths (unknown method
strings, malformed fingerprint hex) were buried inside the
trait-method body, untestable without wasmtime scaffolding. Now
the wasmtime round-trip and the wire-format bridge are independent
concerns.

Also documented the warning-emission order (bridge → output.warnings
→ output.errors) on the function rustdoc — it's a contract any
downstream consumer that filters warnings depends on.

5 new bridge tests:
- `bridge_round_trips_valid_fingerprint_hex` — closes the
  fingerprint-untested gap. Uses `Fingerprint::compute` + `to_hex`
  + bridge → assert host-side fingerprint equals original.
- `bridge_warns_on_malformed_fingerprint_hex_and_drops_to_none` —
  pins the bridge-warning emission for the malformed-hex path.
- `bridge_warns_on_unknown_method_and_falls_back_to_default` —
  uses `"merchant_dict"` (underscore typo, exact #1130 bug shape)
  to demonstrate the no-silent-degradation contract.
- `bridge_warns_on_unknown_method_in_alternative` — same path
  but in the `alternatives` slot, verifies the distinguishing
  "alternative" text.
- `bridge_warning_ordering_is_bridge_then_output_warnings_then_errors`
  — pins the documented order.

**`output_to_import_result_uses_severity_aware_formatter`** —
integration test proving `format_plugin_error` is wired into the
production path, not just unit-tested. A refactor switching back
to raw `format!()` would regress this.

# Polish

- Switched `parse_method_round_trips_via_as_meta_value` from
  `mem::discriminant` to plain `assert_eq!` — CategorizationMethod
  derives PartialEq, so the discriminant indirection was unwarranted.
- Added caveat comment on test fixture's bump allocator that real
  importers must bounds-check `bump + size` against memory bounds
  and call `memory.grow` (subject to limiter approval).

# Verification

- 155/155 rustledger-importer tests (was 147; +8 new in this commit)
- 23 wasm::tests pass (was 15)
- cargo check --workspace --all-targets clean
- cargo clippy --workspace --all-targets -- -D warnings clean
- cargo fmt --all -- --check clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(importer): address Copilot review of #1131 — 5 valid issues + 3 new tests

Six Copilot inline comments triaged:

| # | Issue | Status |
|---|-------|--------|
| 1 | max_memory unenforced | already fixed in 41dc97c (on older commit) |
| 2 | fuel calc can overflow u64 | FIXED |
| 3 | input length truncates >4 GiB; no output cap | FIXED (output cap was 41dc97c; input cap here) |
| 4 | typed_func errors masquerade as MissingExport | FIXED |
| 5 | CSV projection doc claims full but ships subset | FIXED (doc) |
| 6 | "duplicated here" comment lies about implementation | FIXED |

# Fuel saturation (Copilot #2)

`config.max_time_secs.max(1) * 1_000_000` would panic in debug and
silently wrap in release for very large `max_time_secs` (technically
possible at u64 values >18T, which is ~580K years — extreme but the
wrap is a real bug). Now uses `saturating_mul` — `u64::MAX` clamps
to `u64::MAX` which `set_fuel` accepts as "effectively unlimited."

# Input length cap (Copilot #3)

Added `MAX_INPUT_BYTES` (64 MiB, symmetric with `MAX_OUTPUT_BYTES`)
and `WasmImporterError::InputTooLarge { len, max }`. Extracted the
check into a `const fn validate_input_size(len) -> Result<u32, _>`
helper so the cap can be unit-tested without standing up wasmtime
and allocating 64 MiB. The host caps before the `as u32` cast so a
truncated input can't corrupt the import.

# ExportSignatureMismatch (Copilot #4)

Previously `get_typed_func::<u32, u32>("alloc").map_err(|_|
MissingExport("alloc"))` collapsed two distinct failure modes into
one misleading error. Since `validate_module` proves presence by
name at load time, any subsequent typed_func failure is necessarily
a signature mismatch — surfaced now as
`WasmImporterError::ExportSignatureMismatch { name, source }` which
names the export and chains the wasmtime type-mismatch detail.

Applied at all 3 typed_func sites (`alloc`, the dispatched entry,
`metadata`).

# CSV projection honesty (Copilot #5)

`CsvConfig` has 18 fields; this PR projects 8 (the simple
String/bool/number ones). Updated `build_wasm_input` and
`project_csv_config_into_options` docs to say "subset" + list
exactly what's projected and what's deferred to wave 2.3e (column
specs, locale, mappings — encoding decisions best driven by a real
WASM CSV importer, not guessed here). No behavior change.

# Stale duplication comment (Copilot #6)

The comment in `output_to_import_result` claimed the wrapper→directive
converter was "duplicated here so this crate doesn't need to depend
on the full `rustledger-plugin` graph" — but the code actually calls
`rustledger_plugin::convert::wrapper_to_directive` directly, with
the explicit dep added in this PR's Cargo.toml. Rewrote to say
"delegates … so the WASM importer path and directive-plugin path
share a single converter."

# Tests

3 new wasm:: tests (158 importer total, was 155):

- validate_input_size_accepts_at_cap_and_rejects_above —
  boundary test for MAX_INPUT_BYTES and the InputTooLarge surface.
- fuel_calc_saturates_instead_of_overflowing — regression for
  Copilot #2; loads with u64::MAX max_time_secs and asserts no
  panic + successful execution.
- wrong_signature_export_surfaces_export_signature_mismatch — WAT
  module with metadata: () -> i32 (wrong: should be -> i64);
  asserts ExportSignatureMismatch { name: "metadata" } rather than
  the previously-misleading MissingExport.

# Verification

- 26 wasm:: tests pass (was 23)
- 158/158 rustledger-importer tests pass
- cargo check --workspace --all-targets clean
- cargo clippy --workspace --all-targets -- -D warnings clean
- cargo fmt --all -- --check clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(importer): rustdoc — drop private-item intra-doc links in public docs

CI Documentation job (rustdoc with -Dwarnings) caught two intra-doc
links from public-API surface to private items, which I introduced
in the previous commit:

- `OutputTooLarge` variant doc → `MAX_OUTPUT_BYTES` (private const)
- `InputTooLarge` variant doc → `MAX_INPUT_BYTES` (private const)

`rustdoc::private_intra_doc_links` denies these because the rendered
docs would be useless to library consumers: the link target isn't
visible to them. The fix: drop the `[`…`]` link syntax for plain
backticks, and inline the literal byte value (64 MiB) so the doc
is self-contained.

Also fixed two adjacent rustdoc warnings that surface under
`--document-private-items` (not CI-blocking, but cheap to address):
- `Option<String>` in a doc comment was parsed as an HTML tag —
  wrapped in backticks.
- `[`CategorizationMethod::Default`]` on the private `parse_method`
  fn — switched to plain backticks for consistency with the visible
  text approach.

Verification: `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-importer`
clean. clippy + 26 wasm tests still green.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(plugin,importer): shared wasmtime sandbox config + 5 review fixes

Addresses the second-round deep review of #1131. Adds a workspace-
shared sandbox configuration module and applies the remaining
substantive review items.

# New: rustledger_plugin::sandbox (workspace-wide #6)

New module exporting:

- `sandbox_config()` — wasmtime Config with rustledger's locked-down
  feature set:
  - Enabled: consume_fuel + (defaults) wasm_simd, wasm_bulk_memory,
    wasm_reference_types, wasm_multi_value, wasm_extended_const,
    wasm_relaxed_simd
  - Explicitly disabled (security): wasm_threads,
    wasm_shared_everything_threads (concurrency bypass),
    wasm_multi_memory, wasm_memory64 (ABI/limiter invariants),
    wasm_component_model (we use custom MessagePack ABI),
    wasm_gc, wasm_function_references, wasm_stack_switching,
    wasm_tail_call (unused complexity / shrink attack surface)
- `shared_engine()` — process-wide `Arc<Engine>` via OnceLock.
  wasmtime docs recommend one Engine per process; sharing amortizes
  JIT/cache cost across all WASM-loaded modules.

3 unit tests pin the contract: `shared_engine` returns the same
Arc, modules requiring `wasm_threads` (shared memory) fail to
compile, modules requiring `wasm_multi_memory` fail to compile.

# rustledger-plugin/runtime.rs: adopt shared engine (#6)

Both `Plugin::load` and `Plugin::load_bytes` now use
`sandbox::shared_engine()` instead of constructing their own
fuel-only Config + Engine. Same security posture as importer.

# rustledger-importer/wasm.rs: review fixes 1-4, 7, 8, 9

**Item 1: identify() silently swallows errors.** Now logs to stderr
on failure, naming the importer + path + underlying error. Trait
contract still returns bool (matches OFX/CSV), but guest authors
get a signal for ExportSignatureMismatch / InputTooLarge / traps
instead of "never matches with no clue why."

**Item 2: MissingExport("memory") was dead code at call time.**
`validate_module` proves memory presence at load, so the
`.ok_or(MissingExport("memory"))` was unreachable post-load. Now
`.expect("validate_module verified `memory` export at load")` —
documents the invariant rather than guarding a real failure path.

**Item 3: warning-order doc on output_to_import_result.** Mirrored
the rustdoc section from bridge_enriched_output describing emission
order (output.warnings → output.errors via format_plugin_error),
plus a note that bridge_enriched_output additionally emits per-
entry bridge warnings first.

**Item 4: file-read error typing.** `extract` and `extract_enriched`
now construct `WasmImporterError::Io { path, source }` and convert
via anyhow at the trait boundary, symmetric with `load_with_config`.
The typed variant is unreachable to external callers (trait erases
to anyhow) but eliminates the inside-the-crate inconsistency.

**Item 7: load_embedded helper.** New
`WasmImporter::load_embedded(name_for_diagnostics, bytes)` for
embedders shipping `.wasm` inside a binary. Wraps `load_from_bytes`
with `WasmRuntimeConfig::default()` so the common case is a single
call instead of having to invent a `PathBuf` + pass a default
config.

**Item 8: runtime_config() accessor.** `WasmImporter` now exposes
`pub const fn runtime_config() -> WasmRuntimeConfig` for
diagnostics — useful when a user sees an
`InputTooLarge { max: 67108864 }` and wants to confirm the cap
matches the importer's intended config.

**Item 9: make_store unreachable-fuel comment.** The
`set_fuel(...)?` propagation only fires when `consume_fuel(false)`,
which our shared sandbox config never sets. Added a comment
explaining the path is defensive (so a future refactor flipping
the flag surfaces an error rather than panicking).

# wasm.rs: refactor consequences

- WasmImporter no longer constructs its own Engine + Config; pulls
  from `sandbox::shared_engine()` instead. Removes ~10 lines.
- Two pre-existing tests that built throwaway Engines for
  `validate_module` testing now use `sandbox::shared_engine()` —
  shorter and exercises the same wiring real loads use.

# Verification

- 107 + 176 + 8 rustledger-plugin tests pass (3 new in sandbox)
- 26 rustledger-importer wasm tests pass (unchanged count)
- 158 total rustledger-importer tests pass
- cargo check --workspace --all-targets clean
- cargo clippy --workspace --all-targets -- -D warnings clean
- cargo fmt --all -- --check clean
- RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(sandbox): note breaking change + harden tests + richer init panic

Addresses the four substantive items from the second-round review of
the sandbox refactor in 52dd0b6.

# Doc (#1): breaking-change notice

Added a "Breaking change for user WASM plugins" section to the
`sandbox` module rustdoc, naming the five most impactful disabled
proposals (`wasm_threads`, `wasm_multi_memory`, `wasm_memory64`,
`wasm_component_model`, `wasm_gc`). Plugin authors targeting earlier
rustledger versions will see a wasmtime validation error at load
time and need to recompile against the new sandbox profile.

# Panic message (#2): preserve wasmtime error

`shared_engine` previously used `.expect("failed to build shared
wasmtime engine")`, which swallowed the underlying error detail.
Now uses `.unwrap_or_else(|e| panic!("wasmtime engine init failed:
{e}"))` so a process-start failure preserves the cause for
debugging. Still a panic (same semantics); just more useful when it
fires.

# Regression coverage (#3): 3 new tests

Added rejection tests for three more disabled features:

- `sandbox_config_rejects_memory64_module` — `(memory i64 1)`
- `sandbox_config_rejects_component_module` — `(component)` top-level
- `sandbox_config_rejects_gc_module` — `(type $s (struct …))`

Sandbox test count: 3 → 6. The remaining disabled flags
(`wasm_function_references`, `wasm_stack_switching`, `wasm_tail_call`,
`wasm_shared_everything_threads`) are minor variants of the tested
ones; explicit tests would be duplicative.

# Maintenance comment (#4): wasmtime upgrade audit

Added a MAINTENANCE NOTE atop `sandbox_config` calling out that
wasmtime's `Config::new()` defaults evolve across versions and new
proposals routinely land as default-on. On every wasmtime bump in
`Cargo.toml`, this function must be re-audited against wasmtime's
release notes — wasmtime has no "deny by default" mode, so the
audit is structurally required, not optional.

# Verification

- 6/6 sandbox tests pass (3 new in this commit)
- cargo clippy --workspace --all-targets -- -D warnings clean
- cargo fmt --all -- --check clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(plugin,importer): lift limiter to sandbox + complete review polish

Closes the substantive gap from the third-round review: the workspace-
shared sandbox refactor (52dd0b6) only addressed Engine config, not
per-Store limiter wiring. The plugin runtime still ignored
`max_memory` even after the sandbox module landed. This commit lifts
the entire enforcement stack into `rustledger_plugin::sandbox` so
both call sites get identical per-Store enforcement.

# Item 1 (substantive): per-Store enforcement now workspace-wide

Moved from `rustledger-importer/src/wasm.rs` to `rustledger-plugin/src/sandbox.rs`:

- `pub struct MemoryLimiter` (with `MemoryLimiter::new` ctor)
- `pub struct StoreState`
- `pub const MAX_TABLE_ELEMENTS: usize`
- `pub fn make_sandboxed_store(engine, max_memory, max_time_secs)
  -> wasmtime::Result<Store<StoreState>>` — wires the limiter,
  clamps zero fuel, saturating-multiplies to avoid u64 overflow

`Plugin::execute` in `runtime.rs` now uses `make_sandboxed_store`
instead of constructing an unmetered `Store<()>` + bare
`store.set_fuel(config.max_time_secs * 1_000_000)`. The
multiplication could previously overflow and the limiter was never
wired — both fixed in one motion. `wasm.rs::make_store` becomes a
thin `WasmImporterError`-adapting wrapper.

3 new sandbox unit tests:
- `make_sandboxed_store_wires_fuel_and_limiter`
- `make_sandboxed_store_clamps_zero_max_time_secs`
- `make_sandboxed_store_saturates_huge_max_time_secs`

The two now-duplicated wasm.rs unit tests (`memory_limiter_…`,
`table_limiter_…`) are removed — sandbox.rs has authoritative
coverage. `wasm.rs::initial_memory_above_cap_is_rejected_via_limiter_wiring`
remains as the integration test proving the importer side wires
the helper correctly.

# Item 2: accessor tests

- `load_embedded_uses_name_as_path_and_default_config` — locks in
  the diagnostic-name → `path()` flow and default-config behavior.
- `runtime_config_returns_the_loaded_config` — locks in the
  `runtime_config()` accessor against custom configs.

# Item 3: manual Debug impl for WasmImporter

Hand-rolled `impl std::fmt::Debug for WasmImporter` printing
path/name/description/config (skipping wasmtime's Module/Engine
which produce noisy version-dependent output). New
`debug_impl_does_not_panic_and_redacts_wasmtime_types` test asserts
that the redaction holds.

# Item 4: hardcoded caps comment

Added a NOTE block above `MAX_OUTPUT_BYTES`/`MAX_INPUT_BYTES`
explaining that the caps are per-process, not per-importer, and
that per-importer tunability is a v1.0 surface decision.

# Item 5: MAINTENANCE NOTE moved to rustdoc

`sandbox_config`'s wasmtime-upgrade-re-audit note moved from an
inline body comment to a rustdoc `# Maintenance: re-audit on every
wasmtime bump` section so `cargo doc` surfaces it.

# Item 7: breaking-change doc lists all 8 disabled flags

Expanded the "Breaking change for user WASM plugins" section in
`sandbox.rs` to enumerate all 8 disabled proposals
(`wasm_threads`, `wasm_shared_everything_threads`,
`wasm_multi_memory`, `wasm_memory64`, `wasm_component_model`,
`wasm_gc`, `wasm_function_references`, `wasm_stack_switching`,
`wasm_tail_call`) instead of just the 5 most impactful.

# Verification

- 11 sandbox tests pass (was 6; +3 make_sandboxed_store + +2
  MemoryLimiter moved over from wasm.rs)
- 27 wasm:: tests pass (was 26; +3 new accessors/Debug, -2
  duplicates moved to sandbox)
- 115 rustledger-plugin tests total
- 158 rustledger-importer tests total
- cargo check --workspace --all-targets clean
- cargo clippy --workspace --all-targets -- -D warnings clean
- cargo fmt --all -- --check clean
- RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(plugin): align validator with sandbox, auto-validate on load, plug exec memory test

Addresses the fourth-round review of #1131 — closes the workspace-
consistency loose ends on the plugin runtime side.

# Item 1 — `validate_plugin_module` uses sandbox config

Previously `validate_plugin_module` constructed `Engine::default()`,
which has wasmtime's defaults (e.g. `wasm_threads(true)`). A module
using `wasm_threads` would pass validate but then fail
`Plugin::load_bytes` because the runtime uses the locked-down
`sandbox::sandbox_config()`. Users got contradictory answers.

Fixed: validate uses `Engine::new(&sandbox::sandbox_config())` so
the answer matches what the runtime will actually accept.

# Item 3 — Auto-validate on plugin load

Extracted a `fn validate_loaded_module(&Module) -> Result<()>`
inner helper. `validate_plugin_module(bytes)` and the new auto-
validation path in `Plugin::load`/`load_bytes` both call it,
avoiding the double-compile that would happen if load called the
public `validate_plugin_module(bytes)` directly.

Both `Plugin::load` paths now run `validate_loaded_module(&module)`
right after `Module::new`, so missing exports surface at load
time with the existing "must export 'X'" message instead of
showing up later as misleading "must export 'X' function" errors
from `get_typed_func` failures in `execute()`.

# Item 2 — `Plugin::execute` distinguishes wrong signature from missing

Now that presence is proven at load:

- `get_memory(...).ok_or_else(...)` becomes
  `.expect("validate_loaded_module verified ...")` — invariant,
  not failure path.
- `get_typed_func::<...>(...).context("plugin must export ...")?`
  becomes `.context("plugin export `X` has wrong signature
  (expected fn(...))")` — accurate, since absence was already
  ruled out.

Mirrors the importer's `ExportSignatureMismatch` story without
adding a new error variant (plugin runtime is anyhow-based; just
better context strings).

# Item 4 — Plugin::execute memory cap integration test

New `execute_rejects_initial_memory_above_max_memory_cap` in
runtime.rs's tests: declares 5000 pages (320 MiB) initial memory
in a WAT module, runs it via `Plugin::execute` with a 64 MiB
`max_memory` config, asserts the call fails. Mirrors the
importer's `initial_memory_above_cap_is_rejected_via_limiter_wiring`
test for the plugin runtime path — proves the `make_sandboxed_store`
limiter wiring actually applies to plugins, not just importers.

# Item 6 — Inline wasm.rs::make_store wrapper

`make_store` was a one-line adapter (`make_sandboxed_store` plus
`.map_err(runtime_err)`). Inlined at the two call sites in
`call_msgpack_with` and `call_metadata` — the local conversion is
more honest than a helper that exists only to shorten the line
slightly.

# Verification

- 116 rustledger-plugin tests (was 115; +1 memory-cap integration)
- 27 rustledger-importer wasm:: tests (unchanged; inlining is a
  zero-test-impact refactor)
- 159 rustledger-importer tests total
- 11 sandbox:: tests (unchanged)
- cargo check --workspace --all-targets clean
- cargo clippy --workspace --all-targets -- -D warnings clean
- cargo fmt --all -- --check clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(plugin): wrong-sig test + doc/contract polish from fifth-round review

Closes the small loose ends from the fifth-round deep review of
#1131. All changes scoped to runtime.rs.

# Item 1: test for wrong-signature export

New `execute_surfaces_wrong_signature_on_alloc`: WAT module with
`alloc(i64) -> i64` instead of `alloc(u32) -> u32`. Presence check
passes (the export exists), so the failure surfaces inside
`execute()` with the new "wrong signature" context. Pre-PR this
read "plugin must export 'alloc' function" — misleading, since it
DID export it. Pins the contract so a future refactor that
collapses the load-time validation can't silently re-introduce
the misleading message.

# Item 2: drop redundant type info from sig context

Was:
  "plugin export `alloc` has wrong signature (expected fn(u32) -> u32)"
  "plugin export `process` has wrong signature (expected fn(u32, u32) -> u64)"
Now:
  "plugin export `alloc` has wrong signature"
  "plugin export `process` has wrong signature"

wasmtime's underlying error already says expected-vs-found types
— our context was duplicating it and would have lied if the ABI
ever changes. Comment explains why we don't repeat the type info.

# Item 4: doc note on RuntimeConfig — applied at execute, not load

Made explicit that `Plugin::load`/`load_bytes` accept a
`&RuntimeConfig` for API symmetry but ignore it. Only
`Plugin::execute` consumes the caps, via `make_sandboxed_store`.
The field-level docs now also point at the helper.

# Item 5: symmetric `invalid plugin` context on Module::new

Previously: `Module::new` failure → "failed to compile <path>",
`validate_loaded_module` failure → "invalid plugin <path>". Inconsistent
prefix for two failure modes of the same load operation. Now both
use "invalid plugin <path>" so log scrapers / error-classifying
code can use one prefix.

Same in `load_bytes`: bare wasmtime error → "invalid plugin `name`"
wrapping.

# Item 7: tighten memory-cap test assertion

`execute_rejects_initial_memory_above_max_memory_cap` previously
asserted `!msg.is_empty()` — too weak. Now lowercases the message
and asserts `msg.contains("memory") || msg.contains("limit")`,
which would have failed if the limiter wiring silently broke
(error would be about an unrelated issue, not memory). Still
tolerates wasmtime wording variance across versions.

# Verification

- 117 rustledger-plugin tests (was 116, +1 wrong-signature)
- 159 rustledger-importer tests
- 11 sandbox tests
- cargo check --workspace --all-targets clean
- cargo clippy --workspace --all-targets -- -D warnings clean
- cargo fmt --all -- --check clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* test(plugin): symmetric coverage for fuel clamp + process wrong-sig

Closes the small coverage gaps from the sixth-round review.

# Test additions

- `execute_surfaces_wrong_signature_on_process` — sibling to
  `_on_alloc`. WAT with `process(i32, i32) -> i32` (should be
  `(u32, u32) -> u64`). Asserts the error message contains
  `process` + `wrong signature`. Covers the second of two
  `get_typed_func` call sites in `Plugin::execute`.

- `execute_with_zero_max_time_secs_clamps_to_min_fuel` — proves
  the `make_sandboxed_store` fuel-clamp fix is reachable through
  the plugin runtime path, not just the importer. WAT returns
  `(ptr=0, len=0)` which can't deserialize as PluginOutput;
  reaching the decode step proves no fuel-trap fired during
  execute. New `assert_not_fuel_trap` helper checks the error is
  the expected decode failure, not a "fuel"/"trap" wasmtime error.

- `execute_with_max_max_time_secs_saturates_fuel` — equivalent
  for the `saturating_mul` fix. `u64::MAX` config previously
  panicked in debug / wrapped in release; now saturates via the
  shared helper.

The shared helper has these tests in `sandbox::tests`. The plugin
versions are integration tests that prove the wiring from
`Plugin::execute` into the helper stays correct against future
refactor — if anyone reverts `Plugin::execute` to manual
`Store::new + set_fuel`, both fuel bugs return and at least one
of these tests fails.

# Polish

- Test imports tightened: `use crate::types::PluginOptions` at the
  top of `mod tests` instead of fully-qualified inline.

# Deferred

- wasm.rs file split into `wasm/{mod,limits,bridge,error,runtime}.rs`
  was a candidate fix but is a 2000-line refactor that belongs in
  its own focused PR — mid-stream is bad practice. Logged as a
  known follow-up.
- Commit squash (10 commits → ~3) is merger preference; GitHub's
  squash-merge handles this at merge time. Not destructively
  rewriting history.

# Verification

- 120 rustledger-plugin tests (was 117; +3 new)
- 159 rustledger-importer tests (unchanged)
- 11 sandbox tests
- cargo check --workspace --all-targets clean
- cargo clippy --workspace --all-targets -- -D warnings clean
- cargo fmt --all -- --check clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 17, 2026
…ed re-export

Six review items shipped; three deferred to wave 2.3e (where the
reference sample importer provides actual end-to-end validation).

# Item 1: type-annotated user-fn bindings

The macro now does:
```
let identify_fn: fn(&str) -> bool = $identify;
let extract_fn: fn(ImporterInput) -> ImporterOutput = $extract;
```
before calling the user fn, so a wrong signature surfaces at the
user's `fn` definition site with a clean "expected fn(&str) -> bool"
error instead of a cryptic message pointing inside the macro
expansion. (Trade-off: closures that don't coerce to fn pointers
hit a less precise error — guests should prefer free fns, which
the macro example already shows.)

# Item 2: optional extract_enriched with default passthrough

The macro now has two arms:

- Full: `wasm_importer_main! { name, description, identify, extract, extract_enriched }`
- Short: `wasm_importer_main! { name, description, identify, extract }`

The short form auto-generates `extract_enriched` that wraps the
user's `extract` output via the new `default_enriched_from` helper:
each directive gets a default (uncategorized, `"default"` method,
no alternatives, no fingerprint) `EnrichmentWrapper`. Matches the
host-side `EnrichedImportResult::from(ImportResult)` shape so the
round-trip is consistent. Saves ~10 lines per non-categorizing
importer.

3 new unit tests for `default_enriched_from`: empty passthrough,
per-directive default attachment, host-compatible method string.

# Item 5: narrow rmp_serde re-export

Was: `pub use rmp_serde;` (full crate, all major bumps affect our API)
Now: `pub use rmp_serde::{decode::Error as DecodeError, from_slice, to_vec};`

Just the symbols the macro needs + DecodeError for users handling
`decode_input`'s Result. Guests that want non-default Serializer
config still add `rmp-serde` to their own deps; default usage
unchanged.

# Items 4, 6, 7, 8, 9: doc-only improvements

Module-level rustdoc gained four new sections:

- **Required `Cargo.toml` setup** — `crate-type = ["cdylib"]` +
  the wasm32 build command. First-time authors will no longer hit
  "no .wasm output" or "function symbols mangled" surprises.
- **`std` is required** — explicit one-liner; `no_std` guests
  need to hand-roll the exports.
- **No `stdio` inside the guest** — surface diagnostics via
  `ImporterOutput::warnings` / `errors`, not println.
- **Sharing state across exports** — `OnceLock` pattern for the
  shared-parser-cache case the trait-based design would have
  handled naturally.

Tightened `pack_output`'s mem::forget rationale: the "leak" only
seems like one — the host's per-call wasmtime Store drops at
return, reclaiming the whole guest linear memory in one shot. The
guest never sees the Store.

# Verification

- 29 plugin-types lib tests (was 26; +3 for `default_enriched_from`)
- cargo check --workspace --all-targets --all-features clean
- cargo clippy --workspace --all-targets --all-features -- -D warnings clean
- cargo fmt --all -- --check clean

# Deferred (judgment / out-of-scope)

- #3 doctest validation via trybuild — deferred to wave 2.3e where
  the reference sample provides real end-to-end coverage
- #10 module-level `#![allow(unsafe_code)]` — appropriate for FFI module
- #11 `.to_string()` vs `.into()` — kept .to_string() for clarity

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 18, 2026
… 2.3d) (#1134)

* feat(plugin-types): wasm_importer_main! macro for guest authors (wave 2.3d)

Wave 2.3d of the v0.16.0 reshape: collapses WASM importer guest
boilerplate from ~150 lines to ~20 via a declarative macro. A user
writes three free functions (identify, extract, extract_enriched)
plus a single macro invocation; the macro emits the five
host-callable exports (alloc, metadata, identify, extract,
extract_enriched).

# Public API

New `guest` Cargo feature on `rustledger-plugin-types`:

```toml
rustledger-plugin-types = { version = "0.15", features = ["guest"] }
```

Enables `pub mod guest` with:

- `wasm_importer_main!` macro (exported at crate root via
  `#[macro_export]`) — the only thing most guest authors need
- `guest::pack_output(Vec<u8>) -> u64` — host-ABI packing helper
- `guest::decode_input<T>(ptr: u32, len: u32) -> Result<T, _>` —
  host-ABI decoding helper
- `guest::rmp_serde` re-export so guests don't need their own
  rmp-serde dep

# Example

```rust
use rustledger_plugin_types::{
    wasm_importer_main, EnrichedImporterOutput, ImporterInput,
    ImporterOutput,
};

fn identify(path: &str) -> bool { path.ends_with(".mt940") }
fn extract(_: ImporterInput) -> ImporterOutput { ImporterOutput::empty() }
fn extract_enriched(_: ImporterInput) -> EnrichedImporterOutput { /* ... */ }

wasm_importer_main! {
    name: "MT940",
    description: "MT940 bank statement importer",
    identify: identify,
    extract: extract,
    extract_enriched: extract_enriched,
}
```

The expansion handles:

- `#[no_mangle] pub extern "C" fn alloc(size: u32) -> *mut u8` —
  Vec-backed bump allocator, leaked via `mem::forget`
- `metadata() -> u64` — msgpack-encodes the name/description
  constants from the macro invocation
- `identify`/`extract`/`extract_enriched` — decode the host's
  msgpack input via `decode_input`, call user fn, encode output,
  pack pointer + length

# wasm32-only contract

The packing math (`(ptr << 32) | len`) only works when pointers
fit in u32. `pack_output` now uses `u32::try_from(ptr as usize)`
so it panics loudly on non-wasm32 targets instead of silently
truncating (which produced a SIGSEGV in earlier test iteration).
Documented in the function's rustdoc as wasm32-only by contract.

# Tests

6 unit tests in `guest::tests`:
- packing_math_round_trips_synthetic_values
- packing_math_handles_zero_and_max
- identify_input/output/metadata_output_msgpack_encoding_is_stable
- pack_output_panics_on_non_wasm32_targets (gated; pins the
  defense against silent pointer truncation)

End-to-end "load a real macro-generated .wasm via WasmImporter"
test lives in wave 2.3e — that's the wave specifically designed
to ship a reference sample importer + the full integration test
that exercises the macro through the host loader.

# Verification

- 26 plugin-types lib tests pass with `--features guest` (was 20;
  +6 new)
- All workspace tests still pass (52 result lines, all "0 failed")
- cargo check --workspace --all-targets --all-features clean
- cargo clippy --workspace --all-targets --all-features -- -D warnings clean
- cargo fmt --all -- --check clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(plugin-types): address review of #1134 — DX improvements + narrowed re-export

Six review items shipped; three deferred to wave 2.3e (where the
reference sample importer provides actual end-to-end validation).

# Item 1: type-annotated user-fn bindings

The macro now does:
```
let identify_fn: fn(&str) -> bool = $identify;
let extract_fn: fn(ImporterInput) -> ImporterOutput = $extract;
```
before calling the user fn, so a wrong signature surfaces at the
user's `fn` definition site with a clean "expected fn(&str) -> bool"
error instead of a cryptic message pointing inside the macro
expansion. (Trade-off: closures that don't coerce to fn pointers
hit a less precise error — guests should prefer free fns, which
the macro example already shows.)

# Item 2: optional extract_enriched with default passthrough

The macro now has two arms:

- Full: `wasm_importer_main! { name, description, identify, extract, extract_enriched }`
- Short: `wasm_importer_main! { name, description, identify, extract }`

The short form auto-generates `extract_enriched` that wraps the
user's `extract` output via the new `default_enriched_from` helper:
each directive gets a default (uncategorized, `"default"` method,
no alternatives, no fingerprint) `EnrichmentWrapper`. Matches the
host-side `EnrichedImportResult::from(ImportResult)` shape so the
round-trip is consistent. Saves ~10 lines per non-categorizing
importer.

3 new unit tests for `default_enriched_from`: empty passthrough,
per-directive default attachment, host-compatible method string.

# Item 5: narrow rmp_serde re-export

Was: `pub use rmp_serde;` (full crate, all major bumps affect our API)
Now: `pub use rmp_serde::{decode::Error as DecodeError, from_slice, to_vec};`

Just the symbols the macro needs + DecodeError for users handling
`decode_input`'s Result. Guests that want non-default Serializer
config still add `rmp-serde` to their own deps; default usage
unchanged.

# Items 4, 6, 7, 8, 9: doc-only improvements

Module-level rustdoc gained four new sections:

- **Required `Cargo.toml` setup** — `crate-type = ["cdylib"]` +
  the wasm32 build command. First-time authors will no longer hit
  "no .wasm output" or "function symbols mangled" surprises.
- **`std` is required** — explicit one-liner; `no_std` guests
  need to hand-roll the exports.
- **No `stdio` inside the guest** — surface diagnostics via
  `ImporterOutput::warnings` / `errors`, not println.
- **Sharing state across exports** — `OnceLock` pattern for the
  shared-parser-cache case the trait-based design would have
  handled naturally.

Tightened `pack_output`'s mem::forget rationale: the "leak" only
seems like one — the host's per-call wasmtime Store drops at
return, reclaiming the whole guest linear memory in one shot. The
guest never sees the Store.

# Verification

- 29 plugin-types lib tests (was 26; +3 for `default_enriched_from`)
- cargo check --workspace --all-targets --all-features clean
- cargo clippy --workspace --all-targets --all-features -- -D warnings clean
- cargo fmt --all -- --check clean

# Deferred (judgment / out-of-scope)

- #3 doctest validation via trybuild — deferred to wave 2.3e where
  the reference sample provides real end-to-end coverage
- #10 module-level `#![allow(unsafe_code)]` — appropriate for FFI module
- #11 `.to_string()` vs `.into()` — kept .to_string() for clarity

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(plugin-types): critical macro bugs caught by Copilot review of #1134

Three Copilot comments — all real bugs. The macro's headline example
did not compile until this commit. Caught + fixed before further
guest authors hit them.

# Bug 1: name collision (E0428)

The macro generated `#[no_mangle] pub extern "C" fn identify(...)`
at the SAME module scope as the user's `fn identify(...)`. Two
items with the same Rust name at the same scope = hard compile
error. The documented example would not compile.

Fix: rename generated fns to `__wasm_importer_alloc/metadata/
identify/extract/extract_enriched`. Set the WASM linker symbol
via `#[cfg_attr(target_arch = "wasm32", unsafe(export_name = "..."))]`
so the wasm32 export name still matches what the host expects,
without polluting the Rust namespace.

Why `cfg_attr(target_arch = "wasm32", ...)` rather than always-on
export_name: on native test targets, multiple macro invocations in
the same crate would collide at link time (e.g., 3 modules each
exporting "alloc"). Gating on wasm32 means the symbol-export only
applies where it's actually meaningful — production guest builds.

# Bug 2: Rust 2024 unsafe attributes

Workspace is on edition 2024. Bare `#[no_mangle]` is now a hard
error — must be `#[unsafe(no_mangle)]` or `#[unsafe(export_name = "...")]`.

Fix: all generated linker-affecting attributes wrapped in
`unsafe(...)`. (Same applies to `export_name` from bug 1's fix.)

# Bug 3: decode_input was safe fn with unsafe internals

`pub fn decode_input<T>(ptr: u32, len: u32)` constructed a slice
via `from_raw_parts(ptr as *const u8, len)` inside the body. Safe
Rust could call `decode_input(0, 100)` and trigger UB by reading
arbitrary guest memory.

Fix: `pub unsafe fn decode_input<T>(...)`. The macro's call sites
now wrap in `unsafe { ... }` blocks with SAFETY comments
documenting the host-memory contract that justifies the call.

# Compile-test fixture

New `tests/guest_macro_compiles.rs` integration test that invokes
`wasm_importer_main!` in three configurations (short form, full
form, with closures) — each in its own module so the test crate
compiling proves the macro doesn't collide with user fns of the
same name. If the macro ever regresses to bare `#[no_mangle] pub
extern "C" fn identify`, this test crate fails to compile.

Each test verifies the macro-generated fn signatures via
`extern "C" fn(...)` pointer coercion (compile-time check; the
fns aren't invoked because their pack_output panics on non-wasm32
targets by design).

This is the test that would have caught all three Copilot bugs
before push. Lesson: macro authors need compile-tests, not just
unit tests of the helper fns.

# Verification

- 29 plugin-types lib tests pass with --features guest
- 3 new compile-test integration tests pass
- cargo check --workspace --all-targets --all-features clean
- cargo clippy --workspace --all-targets --all-features -- -D warnings clean
- cargo fmt --all -- --check clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore(plugin-types): polish — expect-with-reason + sharper test rustdoc

Two small follow-ups to the Copilot critical-bug fix in 8a08ea1:

# `#[expect(dead_code, reason = ...)]` over `#[allow(dead_code)]`

Rust 1.81+ introduced `expect` as the documented-intent variant of
`allow`. The reason field makes the lint suppression self-explaining
("consumed by macro expansion; clippy can't see through") instead
of a bare `allow` a future reader has to puzzle out.

# Test-fixture rustdoc: explicit "what this doesn't verify" section

Added a "# What this test does NOT verify" block noting that the
`cfg_attr(target_arch = "wasm32", ...)` gate means on the native
test target the generated fns don't carry the host-expected
linker symbols (`alloc`/`metadata`/etc.) — only their Rust
identifiers (`__wasm_importer_*`). End-to-end host-visible
export-name correctness lands in wave 2.3e where a real `.wasm`
gets loaded via `WasmImporter::load` (which fails fast on missing
exports).

# Verification

- 29 plugin-types lib tests pass with --features guest
- 3 compile-test integration tests pass
- cargo clippy --workspace --all-targets --all-features -- -D warnings clean
- cargo fmt --all -- --check clean

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore(plugin-types): drop #[expect(dead_code)] — fix test instead

The previous fix used `#[expect(dead_code, reason = "...")]` to
silence a clippy warning on `extract_impl`/`enriched_impl` in the
`with_closures` test module. The real problem was the test itself:
`closures_compile` only referenced `__wasm_importer_alloc`, so
clippy's dead-code chain couldn't reach the user fns the macro
consumes.

Fix: reference all 5 generated fns in the closures test (same
shape as the `short_form`/`full_form` tests). The liveness chain
flows naturally:

  closures_emit_expected_signatures
    → with_closures::__wasm_importer_extract
    → extract_impl  // now considered used

No more dead-code suppression needed. Renamed the test to
`closures_emit_expected_signatures` to match the sibling tests'
naming.

This is what the reviewer's "why do we have dead code?" question
correctly poked at: suppression annotations are a smell, not a
solution.

# Verification

- 29 plugin-types lib tests + 3 compile-tests pass
- cargo clippy --workspace --all-targets --all-features -- -D warnings clean
- No #[allow] / #[expect] in the test module anymore

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(plugin-types): close remaining review items — constraints + symmetry + closures-everywhere test

Five items from the final-pass review:

# Item 1: single-invocation-per-crate constraint documented

The macro generates Rust idents (`__wasm_importer_alloc` etc.)
and wasm32 symbols (`alloc` etc.) — calling twice in one crate
collides on both. Added an "Invocation constraint" section to the
macro rustdoc making this explicit: each WASM importer should be
its own cdylib crate.

# Item 2: short-form's fn-pointer constraint surfaced

The short-form arm's auto-generated `extract_enriched` internally
requires `extract` to coerce to `fn(...) -> ...`. Capturing
closures don't coerce. The full-form arm has the same constraint
documented; the short form inherits it implicitly. Added an
explicit paragraph under "Required user-fn signatures" so users
hitting the cryptic capturing-closure error can find the
contract.

# Item 3: cross-crate "default" symmetry pinned

Reframed `default_enriched_uses_host_compatible_method_string`'s
rustdoc to call out the explicit symmetry:

- Host (`rustledger-ops::enrichment::tests`):
  `CategorizationMethod::Default.as_meta_value() == "default"`
- Guest (this test): `default_enriched_from` emits `"default"`

Both sides assert the literal — a future rename surfaces as a
test failure on whichever side wasn't updated. Reviewer sees the
asymmetry and knows to fix both ends.

# Item 4: closures-everywhere compile-test variant

New `mod all_closures` in `tests/guest_macro_compiles.rs` invokes
the macro with non-capturing closures for ALL THREE callbacks
(identify, extract, extract_enriched). Previously only `identify`
was tested with a closure; if the macro's fn-pointer bounds ever
broke closure coercion for extract or extract_enriched, that
regression would slip through.

# Item 5: native vs wasm32 symbol-name clarification

Added "Native vs wasm32 symbol names" section to the macro
rustdoc noting that the `export_name` attribute is gated off on
native targets, so `objdump`/`nm` on a native build shows only
the `__wasm_importer_*` Rust identifiers — not the `alloc`/etc.
symbols a user might expect from reading the ABI table.

# Verification

- 29 plugin-types lib tests + 4 compile-tests pass (+1 all_closures)
- cargo clippy --workspace --all-targets --all-features -- -D warnings clean
- cargo fmt --all -- --check clean

# Deferred (per my own framing)

- #6-#10 are nits / scope-creep documented in the review

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(plugin-types): two broken intra-doc links in guest module

CI Documentation job (cargo doc -Dwarnings) caught two broken
intra-doc links in `guest.rs`:

- `[``wasm_importer_main!``]` → `wasm_importer_main` macro lives
  at crate root via `#[macro_export]`, not in the `guest` module
  namespace. Path-prefixed to `[``crate::wasm_importer_main!``]`.
- `[``PluginError``]` → same root-vs-module mismatch.
  Path-prefixed to `[``crate::PluginError``]`.

Other intra-doc links in the same file (`ImporterOutput::warnings`,
`ImporterOutput::errors`, `DecodeError`, `default_enriched_from`,
etc.) already resolved correctly because they're either reachable
via Rust's `use crate::{...}` import at the top of `guest.rs` or
defined in the same module.

# Local repro

`RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-plugin-types
--features guest --no-deps` now passes. `RUSTDOCFLAGS=-Dwarnings
cargo doc --workspace --no-deps` also clean.

# Process note

I ran clippy locally but skipped cargo doc — CI caught what I
should have. Worth adding to the "before push" checklist:
`RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request Jun 6, 2026
…tightening, increasing-indent pin, test walker symmetry, doc tweaks)

Round-4 deep-review findings on #1276:

1. **Drift guard tightened to bidirectional invariant.** The test
   previously asserted only `is_trivia() ⊆ is_comment_token` (modulo
   the BOM/WHITESPACE/NEWLINE allow-list). A future edit that
   adds a non-trivia kind to `is_comment_token`'s match arm (or
   moves a kind out of `is_trivia` without updating
   `is_comment_token`) would silently extend indent-attribution to
   real content tokens. Added the complementary check
   `is_comment_token ⊆ is_trivia()`. Failure messages also now
   explicitly name the THIRD option for a new trivia kind that's
   neither comment-class nor whitespace-class: revisit whether
   the body-continuation predicates need a separate abstraction.

2. **Increasing-indent sibling POSTINGs pinned by test + rustdoc.**
   `emit_transaction_body`'s POSTING-line branch unconditionally
   closes any open POSTING regardless of indent, then opens a new
   one at `sub_line_indent`. Postings at non-uniform indents
   therefore produce sibling POSTING nodes, and subsequent META
   attributes against the most-recently-opened POSTING's indent.
   Pinned by `postings_at_increasing_indents_produce_siblings_and_meta_attributes_to_latest`
   so any future monotonic-indent refactor is a visible,
   intentional break. Rustdoc on the POSTING-line branch now
   states this defensive shape.

3. **Test walker symmetry fixed for the directive-body tests.**
   `directive_body_absorbs_indented_emacs_directive_when_block_has_meta`
   previously used `descendants_with_tokens` for the inclusion
   check but `children_with_tokens` for the orphan check — a
   future refactor wrapping SOURCE_FILE-level trivia in any
   nested node would pass the orphan check vacuously. Both tests
   now use `descendants_with_tokens` symmetrically and add a
   total-count sanity assertion. Test #3 also gained a META_ENTRY
   assertion so a regression in the META_KEY arm of
   `is_indented_directive_continuation` fails here, not silently.

4. **CST/AST divergence rustdoc tightened.** Line anchors
   `parser.rs:1225` and `parser.rs:1756` replaced with symbol
   names (`parse_posting_metadata`,
   `parse_transaction_directive`, `parse_directive` dispatch) so
   the rustdoc doesn't drift on refactors of the AST parser. The
   "nothing downstream" framing now explicitly names this crate's
   corpus baseline test AND `examples/dump_top_level_directives.rs`
   as the only `parse_structured` consumers (instead of glossing
   over the example). The rustdoc also takes a position on phase
   5 reconciliation: adopt the CST behavior (consistent with
   `is_trivia()`'s classification) rather than the AST behavior.

Manifest churn: 0 lines.

Verified:

- 84 structured-directive tests (was 83) + 172 unit + 4 + 1 + 1 +
  55 + 2 doctest pass.
- `cargo check --workspace --all-features --all-targets` clean.
- `cargo clippy -p rustledger-parser --all-features --examples
  --tests -- -D warnings` clean.
- `cargo fmt --all --check` clean.
- `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser
  --no-deps` clean.
- `STRICT_BASELINE=1 cargo test -p rustledger-parser --test
  cst_baseline` passes against the unchanged manifest.

Refs #1262.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request Jun 6, 2026
…ndent-aware metadata attribution (#1276)

* feat(parser): #1262 phase 2.2b POSTING wraps posting sub-lines, attributes metadata by indent

PR 2.2b of the parser-CST migration. Adds `POSTING` SyntaxKind and
wraps each posting sub-line inside `TRANSACTION` with indent-aware
metadata attribution.

Implementation:

- `POSTING` SyntaxKind variant added; both partition tests updated.
- `starts_posting_sub_line`: recognizes `WS [(FLAG|STAR|PENDING_KW|
  single-char CURRENCY) WS] ACCOUNT ...`. Single-char CURRENCY-as-
  flag arm mirrors `identify_directive`'s same treatment for the
  transaction header (lexer priority 3 makes single uppercase
  letters tokenize as CURRENCY, but they still function as flags
  by Beancount convention).
- `indent_width`: byte length of the leading WHITESPACE token.
  Sufficient for the strictly-greater comparison the metadata-
  attribution rule needs when the source uses uniform spaces.
- `emit_transaction_body` rewritten as a state machine tracking
  the most-recently-opened POSTING's indent depth:
  - Posting line: close any open POSTING, open a new one, consume
    through terminator.
  - Metadata sub-line: if a POSTING is open AND the indent is
    strictly greater, emit META_ENTRY INSIDE the POSTING (mirrors
    legacy AST parser's `parse_posting_metadata` DeepIndent loop).
    Otherwise close any open POSTING and emit META_ENTRY at
    TRANSACTION level.
  - Indented comment: close any open POSTING, emit flat at
    TRANSACTION level (matches the AST parser, which treats
    inter-posting comments as transaction-level).

Tests (14 new + 2 updated):

- `posting_wraps_account_only_line` — auto posting (account only)
- `posting_wraps_account_with_amount_and_currency` — full posting
- `posting_wraps_each_of_multiple_postings_in_a_transaction`
- `posting_with_pending_flag_wraps_flag_inside_node` — `!` flag
- `posting_attached_meta_entry_lives_inside_posting` — KEY: deeper
  indent → INSIDE POSTING (not TRANSACTION direct child)
- `posting_attached_meta_entry_at_same_indent_stays_at_transaction_level`
  — same-indent META_ENTRY is interspersed transaction-level
- `posting_attached_multiple_meta_entries_all_inside_posting`
- `posting_attached_meta_entry_terminates_at_next_posting` — new
  POSTING starts clean (no inherited metadata)
- `meta_entry_before_first_posting_stays_at_transaction_level` —
  no preceding POSTING to attach to, regardless of indent depth
- `posting_with_indented_comment_between_postings_terminates_posting`
- `posting_at_eof_without_trailing_newline_still_wrapped` — rule
  5 unterminated final case
- `star_flagged_posting_wraps_flag_inside_node` — `*` flag
- `flagged_posting_with_question_mark_wraps_flag_inside_node` — `?`
  flag (one of the few that actually emits FLAG, not CURRENCY)
- `single_char_currency_flagged_posting_wraps_currency_as_flag` —
  pins the lexer-priority-3 dual classification

Updated:

- `transaction_blank_line_inside_body_terminates_and_orphans_subsequent_postings`
  now counts POSTING nodes (not flat ACCOUNT tokens).
- `meta_entry_inside_transaction_body` adds POSTING-presence
  assertion; reworded to describe TRANSACTION-level shape.

Manifest: `cst-corpus.manifest` regenerated against the 714-file
corpus. The token_seq_blake3 column is byte-identical across all
files (phase-2 invariant: no token-classification change). Only
the node_shape_blake3 column churned — verified by diffing all
removed token_seq hashes against added ones (1-to-1 pairing).

Verified:

- 71 structured-directive tests (was 57) + 171 unit + 4+1+1+55+2
  doctest pass.
- `cargo check --workspace --all-features --all-targets` clean.
- `cargo clippy -p rustledger-parser --all-features --examples
  --tests -- -D warnings` clean.
- `cargo fmt --all --check` clean.
- `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser --no-deps`
  clean.
- `STRICT_BASELINE=1 cargo test -p rustledger-parser --test
  cst_baseline` passes against the regenerated manifest.

Refs #1262.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(parser): #1262 phase 2.2b deep-review findings (HASH-flagged postings, doc-comments, manifest header)

Three CONFIRMED findings from the round-1 deep review of #1276 plus
one PLAUSIBLE doc improvement:

1. **HASH-flagged postings now wrapped in POSTING.** The legacy
   `parse_flag` (`parser.rs:436-439`) accepts `Token::Hash` and
   `identify_directive` already treats HASH as a transaction
   trigger, but `starts_posting_sub_line` omitted HASH from its
   flag alternation. Source `2024-01-15 * "x"\n  # Assets:Cash
   -5 USD\n` produced zero POSTING nodes. Added HASH to the arm,
   plus `hash_flagged_posting_wraps_hash_inside_node` regression.
   The rustdoc now explicitly names the flag set as needing to
   stay in sync with `parse_flag`.

2. **Deeper-indented comments stay inside open POSTING.** The
   `else` branch in `emit_transaction_body` previously closed the
   open POSTING on ANY non-posting / non-meta indented sub-line,
   including deeper-indented `;`/`%` comments. That broke the
   doc-comment-for-following-posting-metadata idiom: a deeper-
   indented comment followed by deeper-indented `key: value` would
   close the POSTING after the comment, then the META_ENTRY would
   land at TRANSACTION level instead of attaching to the now-
   closed POSTING. Asymmetric with `emit_directive_body`'s
   `block_has_meta` continuation policy. Fixed by adding a
   dedicated comment branch with the same indent-attribution rule
   as META_ENTRY: deeper than open POSTING -> stay inside;
   same/shallower -> close POSTING and emit at TRANSACTION level.
   Added `starts_indented_comment` predicate and two regression
   tests pinning both attached (with/without following meta) and
   inter-posting cases.

3. **Manifest header bumped to phase 2.2b.** Both
   `cst_baseline.rs:47` and the regenerated manifest's line-1
   header had been carrying "phase 2.1a" through 2.1b / 2.2a /
   2.2b regenerations. Header now matches reality.

4. **`indent_width` rustdoc strengthened.** Plausible-finding
   doc-improvement: the byte-length-vs-visual-column divergence
   from the legacy lexer's `Indent(N)` / `DeepIndent(N)` semantics
   (`logos_lexer.rs:615-616`, where `\t` counts as 4 spaces) is
   now explicitly documented as a known divergence on both
   `indent_width` and `emit_transaction_body`, with the rationale
   for not fixing yet (no corpus file triggers the divergence in
   posting-attached-metadata position, round-trip stays byte-
   identical regardless of classification) and the fix recipe if a
   file shows up. Defensive doc, not a behavior change.

Manifest churn: 1 line (the header only) — neither the HASH-flag
nor the deeper-comment fix moved any corpus file's node_shape
hash, confirming neither case appears in the corpus today. The
fixes are forward-looking guards.

Verified:

- 74 structured-directive tests (was 71) + 171 unit + 4 + 1 + 1 +
  55 + 2 doctest pass.
- `cargo check --workspace --all-features --all-targets` clean.
- `cargo clippy -p rustledger-parser --all-features --examples
  --tests -- -D warnings` clean.
- `cargo fmt --all --check` clean.
- `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser
  --no-deps` clean.
- `STRICT_BASELINE=1 cargo test -p rustledger-parser --test
  cst_baseline` passes against the regenerated manifest.

Refs #1262.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(parser): #1262 phase 2.2b round-2 review fixes (is_comment_token helper, shared close-posting helper, 5 test additions)

Round-2 deep-review findings on #1276:

1. **SHEBANG / EMACS_DIRECTIVE now handled by the comment branch.**
   The Logos regexes `#![^\n\r]*` and `#\+[^\n\r]*` have no
   line-start anchor, so these tokens CAN appear at indent inside
   a transaction body. `is_trivia()` lists them as trivia, but
   `starts_indented_comment` only matched `COMMENT |
   PERCENT_COMMENT`, so a deeper-indented `#+STARTUP` etc. fell
   through to the catch-all `else` and closed the open POSTING —
   breaking the symmetry the comment branch was added to enforce.
   Fixed by factoring `is_comment_token(kind)` as the single
   source of truth for "is this a comment-class trivia token",
   covering all four comment-class kinds (COMMENT,
   PERCENT_COMMENT, SHEBANG, EMACS_DIRECTIVE), and routing the
   three existing call sites through it
   (`starts_indented_comment`, `upcoming_indented_block_has_meta`,
   `is_indented_directive_continuation`). Regression test
   `deeper_indented_shebang_or_emacs_directive_attaches_to_open_posting`.

2. **Extracted `close_open_posting_unless_attached` helper** so
   the META_ENTRY and indented-comment branches of
   `emit_transaction_body` no longer carry verbatim duplicates of
   the `attach_to_posting` / close-if-not-attached prelude. A
   future fix to the indent-attribution rule that updates one
   branch will auto-propagate to the other.

3. **Documented the catch-all `else` branch policy.** Added an
   inline comment naming PR 2.2c's relationship to this branch
   (AMOUNT continuations live INSIDE POSTING via
   `starts_posting_sub_line`, not via this branch) plus a
   regression test
   `catch_all_indented_unknown_content_closes_posting_and_emits_flat`
   pinning the current behavior on a stray indented STRING line.

4. **Five new tests pin previously-untested edges**:

   - `hash_flagged_posting_attached_meta_entry_lives_inside_posting`
     combines HASH-flagged posting with deeper-indented META so a
     future regression that drops HASH from
     `starts_posting_sub_line` fails AT ATTACHMENT, not just at
     basic shape.
   - `deeper_indented_trailing_comment_at_eof_stays_inside_posting`
     pins the EOF-without-newline case for the deeper-indent
     attachment rule.
   - `deeper_indented_shebang_or_emacs_directive_attaches_to_open_posting`
     pins the SHEBANG/EMACS_DIRECTIVE fix from (1).
   - `catch_all_indented_unknown_content_closes_posting_and_emits_flat`
     pins the catch-all `else` policy from (3).
   - `same_indent_comment_between_posting_and_deeper_meta_orphans_meta`
     pins Beancount's same-indent-break semantics: an explicit
     same-indent `;` comment between a posting and a deeper-
     indented META_KEY ends the posting-attached metadata block,
     and the META_ENTRY orphans to TRANSACTION level. Matches
     Python beancount's lex/yacc behavior; pinned so a future
     refactor can't silently flip the attribution.

Manifest churn: 0 lines — no corpus file exercises SHEBANG or
EMACS_DIRECTIVE indented inside a transaction body. The fixes are
forward-looking guards.

Verified:

- 79 structured-directive tests (was 74) + 171 unit + 4 + 1 + 1 +
  55 + 2 doctest pass.
- `cargo check --workspace --all-features --all-targets` clean.
- `cargo clippy -p rustledger-parser --all-features --examples
  --tests -- -D warnings` clean.
- `cargo fmt --all --check` clean.
- `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser
  --no-deps` clean.
- `STRICT_BASELINE=1 cargo test -p rustledger-parser --test
  cst_baseline` passes against the unchanged manifest.

Refs #1262.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(parser): #1262 phase 2.2b align POSTING-line shape summaries with predicate (Copilot review)

Three Copilot inline-review comments on #1276 flagged the same root
issue: the summary docstrings describing the POSTING-line
recognition shape omit `HASH` and single-char `CURRENCY` from the
flag set, even though `starts_posting_sub_line` accepts both.
`starts_posting_sub_line`'s own rustdoc was correct; three "higher-
level" summaries were stale.

Updated all three sites to list the full flag set
`FLAG | STAR | PENDING_KW | HASH | single-char CURRENCY`:

- `cst/parser.rs` module rustdoc phase 2.2b summary
- `cst/parser.rs` `emit_transaction_body` state-machine docstring,
  with a cross-reference to `starts_posting_sub_line` as the source
  of truth
- `cst/syntax_kind.rs` `POSTING` SyntaxKind variant comment, with a
  one-line note on HASH-as-flag and single-char CURRENCY-vs-Flag
  tie-break for self-contained enum-level grammar

No code changes. Tests, clippy, fmt, doc all clean (79 structured-
directive tests pass).

Refs #1262, #1276.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(parser): #1262 phase 2.2b round-3 review fixes (CST/AST divergence rustdoc, coverage gaps, drift guard, helper cleanup)

Round-3 deep-review findings on #1276:

1. **`is_comment_token` CST/AST divergence documented.** The
   round-2 widening (adding SHEBANG / EMACS_DIRECTIVE) put the
   CST in disagreement with the legacy AST parser, which only
   handles Comment/PercentComment in-body (`parser.rs:1225`).
   Phase-isolated (nothing downstream consumes `parse_structured`
   yet); reconciled in phase 5 when `parse_flat` and the AST
   converge. Documented as a known divergence on
   `is_comment_token`'s rustdoc so future readers don't read it as
   a bug.

2. **5 new tests pin previously-unverified branches**:

   - `deeper_indented_shebang_attaches_to_open_posting`: SHEBANG
     (`#!`) was claimed but not tested. Split from the previous
     `deeper_indented_shebang_or_emacs_directive_attaches_to_open_posting`
     (renamed to `deeper_indented_emacs_directive_attaches_to_open_posting`
     to drop the misleading "or shebang" claim) so each token kind
     has its own pin.
   - `deeper_indented_percent_comment_attaches_to_open_posting`:
     PERCENT_COMMENT (`%`) was in `is_comment_token` but every
     other attribution test used `;`. Adds coverage for the `%`
     path through all three predicates.
   - `directive_body_absorbs_indented_emacs_directive_when_block_has_meta`:
     pins the directive-body widening for OPEN_DIRECTIVE +
     EMACS_DIRECTIVE + META (a continuation when block_has_meta is
     true). The widening was a side effect of routing
     `upcoming_indented_block_has_meta` and
     `is_indented_directive_continuation` through `is_comment_token`;
     only the transaction-body case was previously pinned.
   - `directive_body_does_not_absorb_indented_emacs_directive_when_no_meta`:
     complementary case — header-only OPEN_DIRECTIVE followed by
     EMACS_DIRECTIVE then another OPEN_DIRECTIVE. The
     EMACS_DIRECTIVE is rule-2 inter-directive trivia leading the
     next directive, NOT absorbed by the header-only first one.

3. **Drift guard test `is_comment_token_covers_all_comment_class_trivia`**
   in `cst::parser::tests`. Iterates every valid SyntaxKind
   discriminant; for each one in `is_trivia()` that is not BOM /
   WHITESPACE / NEWLINE, asserts `is_comment_token` returns true.
   Forces an explicit decision when a future PR adds a new trivia
   variant (either add to `is_comment_token` or extend the allow-
   list in the test).

4. **`emit_directive_body` rustdoc updated** to reference
   `is_comment_token` instead of listing `COMMENT / PERCENT_COMMENT`
   (which was stale post-round-2 widening).

5. **`close_open_posting_unless_attached` return value removed.**
   Neither caller used it, AND `attach=false` conflated "no posting
   open" with "should close" — a footgun for a hypothetical third
   caller. Function is now `fn(...)` returning `()`.

6. **`same_indent_comment_between_posting_and_deeper_meta_orphans_meta`
   test comment softened.** The previous claim "Matches Beancount's
   lex/yacc semantics" was unverified (only the legacy AST parser
   was consulted). Updated to "Matches the legacy AST parser's
   `parse_posting_metadata` loop" (verified) with an explicit note
   that Python beancount parity is NOT verified and the test is
   the touch-point for a future compat audit.

Manifest churn: 0 lines — none of these fixes change parser
behavior on the corpus.

Verified:

- 83 structured-directive tests (was 79) + 172 unit (was 171, +1
  drift guard) + 4 + 1 + 1 + 55 + 2 doctest pass.
- `cargo check --workspace --all-features --all-targets` clean.
- `cargo clippy -p rustledger-parser --all-features --examples
  --tests -- -D warnings` clean.
- `cargo fmt --all --check` clean.
- `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser
  --no-deps` clean.
- `STRICT_BASELINE=1 cargo test -p rustledger-parser --test
  cst_baseline` passes against the unchanged manifest.

Refs #1262.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* refactor(parser): #1262 phase 2.2b round-4 review fixes (drift guard tightening, increasing-indent pin, test walker symmetry, doc tweaks)

Round-4 deep-review findings on #1276:

1. **Drift guard tightened to bidirectional invariant.** The test
   previously asserted only `is_trivia() ⊆ is_comment_token` (modulo
   the BOM/WHITESPACE/NEWLINE allow-list). A future edit that
   adds a non-trivia kind to `is_comment_token`'s match arm (or
   moves a kind out of `is_trivia` without updating
   `is_comment_token`) would silently extend indent-attribution to
   real content tokens. Added the complementary check
   `is_comment_token ⊆ is_trivia()`. Failure messages also now
   explicitly name the THIRD option for a new trivia kind that's
   neither comment-class nor whitespace-class: revisit whether
   the body-continuation predicates need a separate abstraction.

2. **Increasing-indent sibling POSTINGs pinned by test + rustdoc.**
   `emit_transaction_body`'s POSTING-line branch unconditionally
   closes any open POSTING regardless of indent, then opens a new
   one at `sub_line_indent`. Postings at non-uniform indents
   therefore produce sibling POSTING nodes, and subsequent META
   attributes against the most-recently-opened POSTING's indent.
   Pinned by `postings_at_increasing_indents_produce_siblings_and_meta_attributes_to_latest`
   so any future monotonic-indent refactor is a visible,
   intentional break. Rustdoc on the POSTING-line branch now
   states this defensive shape.

3. **Test walker symmetry fixed for the directive-body tests.**
   `directive_body_absorbs_indented_emacs_directive_when_block_has_meta`
   previously used `descendants_with_tokens` for the inclusion
   check but `children_with_tokens` for the orphan check — a
   future refactor wrapping SOURCE_FILE-level trivia in any
   nested node would pass the orphan check vacuously. Both tests
   now use `descendants_with_tokens` symmetrically and add a
   total-count sanity assertion. Test #3 also gained a META_ENTRY
   assertion so a regression in the META_KEY arm of
   `is_indented_directive_continuation` fails here, not silently.

4. **CST/AST divergence rustdoc tightened.** Line anchors
   `parser.rs:1225` and `parser.rs:1756` replaced with symbol
   names (`parse_posting_metadata`,
   `parse_transaction_directive`, `parse_directive` dispatch) so
   the rustdoc doesn't drift on refactors of the AST parser. The
   "nothing downstream" framing now explicitly names this crate's
   corpus baseline test AND `examples/dump_top_level_directives.rs`
   as the only `parse_structured` consumers (instead of glossing
   over the example). The rustdoc also takes a position on phase
   5 reconciliation: adopt the CST behavior (consistent with
   `is_trivia()`'s classification) rather than the AST behavior.

Manifest churn: 0 lines.

Verified:

- 84 structured-directive tests (was 83) + 172 unit + 4 + 1 + 1 +
  55 + 2 doctest pass.
- `cargo check --workspace --all-features --all-targets` clean.
- `cargo clippy -p rustledger-parser --all-features --examples
  --tests -- -D warnings` clean.
- `cargo fmt --all --check` clean.
- `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser
  --no-deps` clean.
- `STRICT_BASELINE=1 cargo test -p rustledger-parser --test
  cst_baseline` passes against the unchanged manifest.

Refs #1262.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request Jun 9, 2026
…ve-formatting fixtures (#1292)

* test(parser): #1262 phase 4.2 — format-compat suite with 30 destructive-formatting fixtures

Phase 4.2 of the CST migration: pin the formatter's promise on every
historical destructive-formatting bug class with file-pair golden
fixtures (input.bean / expected.bean) and a runtime-walking harness.

The file-pair shape complements the inline IDEMPOTENCE_MATRIX in
crates/rustledger-parser/src/cst/format.rs::tests:

- IDEMPOTENCE_MATRIX pins per-rule canonical-form behavior via
  property-style tests (idempotence, lexer agreement, round-trip
  through canonicalize_directives). Hand-edited in code review.

- tests/format_compat/cases/ is the user-facing contract surface.
  Browse the directory to see what rledger format promises on a
  given input. Reviewers can read input.bean and expected.bean side
  by side without running the test runner.

Both layers are load-bearing. The file-pair layer is the one
external users will read when they want to understand what the
formatter will do to their file.

## Coverage

30 fixtures across the bug classes that have caused destructive
formatting historically:

- issue_1252_destructive_repro — full reproducer from lutzky's
  issue. Pins the trailing-comment, pushtag/poptag, and
  cross-directive-tag-migration fixes from PR #1284.
- trailing_comment_on_directive_header, trailing_comment_eof_no_newline,
  posting_trailing_comment — the trailing-comment preservation
  rule from PR #1284 round-7 (Copilot #1).
- balance_leading_unary_minus_preserves_sign,
  balance_leading_parenthesized_expression,
  price_leading_unary_minus_preserves_sign,
  posting_arithmetic_with_parens — the sign-preservation rule
  from PR #1284 round-7 (Copilot #2).
- cost_spec_per_unit_plus_total_marker — pins the {# ... } marker
  preservation (Copilot #3 false-alarm).
- cost_spec_with_negative_amount, cost_spec_with_comma_and_date —
  cost-spec interior canonical form.
- pushtag_poptag_pair_preserved, pushmeta_popmeta_pair_preserved —
  pragma directives survive a round-trip.
- transaction_tags_and_links_source_order — source-order rule on
  transaction headers.
- multiline_note_string_preserved, non_latin_account_names —
  Unicode and multi-line string interior preservation.
- section_header_comments_tight, comment_with_unbalanced_quote —
  inter-directive comment positioning and state-machine
  agreement on stray quotes.
- metadata_unary_minus_value, metadata_arithmetic_value —
  metadata value canonical form.
- multiple_trailing_blank_lines_collapsed, missing_final_newline_added,
  bom_dropped — file-level whitespace canonicalization.
- crlf_outside_strings_folded, crlf_inside_strings_preserved —
  CRLF line-ending rule.
- balance_assertion_with_metadata, transaction_with_pending_flag,
  custom_directive_with_date_value, document_with_tags_and_links,
  options_includes_plugins_block — per-directive shape pins.

## Harness

tests/format_compat.rs walks tests/format_compat/cases/ at runtime
and asserts three properties per fixture:

1. format_source(input) == expected — the byte-exact contract.
2. format_source(expected) == expected — idempotence: re-formatting
   canonical text is a no-op.
3. parse(expected).errors is empty — the canonical output is itself
   parseable.

Asserts MIN_FIXTURES = 24 as a coverage floor so a future
contributor deleting cases by accident fails CI instead of
silently dropping the regression net.

## Authoring

A new fixture is two files: input.bean (what the user typed) and
expected.bean (what the formatter promises). The
bootstrap_format_compat example reads input.bean for every case
and writes expected.bean by running format_source on it. After
the initial bootstrap, expected.bean is the golden contract; the
example refuses to overwrite unless BOOTSTRAP_OVERWRITE=1 is set,
which keeps a stray re-run from silently re-baselining a fixture
whose expected output was hand-edited to pin a deliberate
canonical-form choice.

## Verified

- cargo test -p rustledger-parser — all 230+ tests pass including
  the new format_compat test
- cargo clippy -p rustledger-parser --all-features --all-targets
  -- -D warnings — clean
- RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser --no-deps
  — clean

Refs #1262.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix: address all 10 findings from the round-1 PR-1292 review

1. Stage-1 mismatch in format_compat.rs no longer `continue`s past
   the idempotence and parser-clean checks. All three stages run
   independently per fixture; a malformed expected.bean paired with
   a non-matching formatter output now surfaces both failures
   instead of hiding the unparsable golden file.

2. MIN_FIXTURES count floor (24 vs 30 actual) replaced with a
   REQUIRED_FIXTURES name-set. The count floor was too loose -
   six load-bearing fixtures could be silently deleted while
   passing CI. The name-set check forces removal of a critical
   bug-class fixture to be a deliberate, reviewable edit to the
   constant, not a silent disappearance from the cases directory.

3. Empty subdirectories no longer count toward the fixture set.
   The discovery filter requires each entry to actually contain
   input.bean, so a stray `mkdir` without a `git add` cannot mask
   coverage loss from a parallel deletion.

4. .gitattributes adds `crates/rustledger-parser/tests/format_compat/
   cases/**/*.bean -text` so a Windows contributor with
   core.autocrlf=true sees the CRLF-bearing fixtures
   (crlf_outside_strings_folded, crlf_inside_strings_preserved)
   byte-for-byte as committed. Without this, the literal \r bytes
   inside the in-string-CR fixture would be silently normalized on
   checkout and the test would either fail mysteriously or pass
   for the wrong reason.

5. README "Bump it when you add cases" rewritten to match the
   harness rustdoc: adding cases is free, only retiring a required
   fixture changes REQUIRED_FIXTURES.

6. issue_1252_destructive_repro narrative cleaned up. The previous
   input had load-bearing comments ("Commas should stay",
   "bean-format does not remove plus signs, neither should rledger
   format") that became passive-aggressive once the expected.bean
   pinned the opposite behavior. The fixture now pins ONLY the
   destructive-bug fixes (trailing comments, pushtag/poptag,
   cross-directive tag migration). The canonical-form choices on
   commas and unary `+` move to two dedicated fixtures:

   - commas_stripped_per_canonical_form
   - unary_plus_stripped_per_canonical_form

   These document the PR-4 decision explicitly and link the
   dispute back to #1252 in their input.bean comments. If the
   team later flips one of these choices, exactly one fixture's
   expected.bean changes - the historical destructive-bug pin
   stays stable.

7. posting_with_interleaved_metadata fixture added to cover the
   #1142 bug class (per-posting metadata interleaved between
   postings of the same transaction). The harness rustdoc claimed
   #1142 coverage but no fixture exercised the shape;
   balance_assertion_with_metadata only puts metadata on a balance
   directive, not interleaved between transaction postings.

8. README "what belongs here vs IDEMPOTENCE_MATRIX" section
   narrowed to acknowledge the overlap. Roughly half of the
   file-pair fixtures are reviewable mirrors of inline-matrix
   entries; the other half (issue_1252 repro, BOM, CRLF, pragma
   blocks, canonical-form-choice fixtures, posting-interleaved-
   metadata) are genuinely-new coverage shapes that don't fit the
   inline-string format ergonomically. Both layers are kept, the
   file-pair layer is the user-facing contract surface.

9. escape_for_diff no longer pass-throughs non-`\n\r\t` control
   bytes. NUL / BEL / VT / FF / DEL now render via
   `char::escape_debug` as visible escape sequences, so a fixture
   mismatch whose only delta is a stray control byte renders
   visibly in the failure output instead of looking byte-identical
   to the maintainer.

10. Bootstrap example gains BOOTSTRAP_FIXTURE=<name> for scoped
    re-baselining. The default (no env vars) skips fixtures with
    existing expected.bean. BOOTSTRAP_FIXTURE rewrites exactly
    one named fixture; an unknown name exits non-zero before
    touching any file. BOOTSTRAP_OVERWRITE=1 still rewrites the
    whole suite but the summary line warns to review `git diff`
    carefully before committing. The previous shape made
    BOOTSTRAP_OVERWRITE=1 the only way to re-baseline ANY fixture,
    which silently rebaselines unrelated golden files.

Verified: cargo test -p rustledger-parser (230+ tests including
the new format_compat shape), cargo clippy -p rustledger-parser
--all-features --all-targets -- -D warnings, RUSTDOCFLAGS=-Dwarnings
cargo doc -p rustledger-parser --no-deps. All clean. The harness
also passes with a bogus empty subdir present in cases/ (filter
confirmed).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix: address Copilot inline review comments on PR #1292

Replace `filter_map(Result::ok)` in the format-compat harness and the
bootstrap example with explicit `unwrap_or_else(|e| panic!(...))` on
each `read_dir` entry. Per-entry errors now panic with a diagnostic
instead of being silently dropped, matching the convention in
`tests/baseline_common::walk`.

The previous shape was a recall hole. If a permission or filesystem
fault hit one fixture directory (e.g. a stale `.partial` upload from
a backup tool, an inaccessible sub-tree on a CI runner), the entry
would be discarded with no diagnostic. The harness would still
pass the count floor and the bootstrap would print "wrote N files"
as if the run was complete, hiding the silent coverage drop.

Copilot's third comment (about missing `.gitattributes` rule for the
CRLF fixtures) was already addressed in the round-1 review fixes
(commit 30adb81). The bot's review fired against the pre-fix
commit; that finding is moot.

Verified: cargo test -p rustledger-parser --test format_compat,
cargo clippy -p rustledger-parser --all-features --all-targets
-- -D warnings. All clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix: address all 10 findings from the round-2 PR-1292 review

1. escape_for_diff now routes everything outside ASCII-printable
   through `char::escape_debug`, which renders BOM (U+FEFF), zero-
   width spaces (U+200B..=U+200D, U+2060), C1 controls
   (U+0080..=U+009F), and other format-category codepoints as
   visible `\u{...}` escapes. The previous shape passed those bytes
   through verbatim, so a regression that stopped stripping the
   BOM would have rendered `--- expected ---` and `--- got ---`
   panels byte-identical to the eye - undermining the bom_dropped
   fixture's whole purpose. Printable non-ASCII Unicode (Cyrillic,
   CJK, Greek, etc.) still passes through unchanged because
   escape_debug preserves printable categories.

2. `present_names` is now built via `to_string_lossy().into_owned()`
   instead of `.to_str().map(String::from)`. The previous shape
   silently dropped non-UTF-8 directory names from the set, so a
   present-but-non-UTF-8-named REQUIRED fixture would have been
   falsely reported as missing. Aligns with the bootstrap example's
   name-extraction policy.

3. REQUIRED_FIXTURES check now runs against the RAW directory
   listing (every subdir), not the filtered-for-input.bean set.
   A required fixture whose directory exists but is missing
   input.bean now surfaces as `[name] missing input.bean` in the
   per-fixture failure log, not as the misleading "required
   fixture missing from cases dir" assert. The two failure shapes
   correspond to two distinct contributor mistakes (forgot to
   create the dir vs. forgot to `git add` the input file); the
   error message now disambiguates them.

4. Bootstrap summary branch order swapped: target_fixture is
   checked BEFORE overwrite_all, so the combined
   `BOOTSTRAP_OVERWRITE=1 BOOTSTRAP_FIXTURE=<name>` invocation
   prints "only the named fixture's expected.bean was rewritten"
   instead of the previous misleading "rewritten across the whole
   suite". The actual write behavior was already correct; only
   the summary line was lying.

5. MIRROR_PAIRS constant added to tests/format_compat.rs listing
   17 (file_pair_name, matrix_name) bug-class twins across the
   file-pair suite and the inline IDEMPOTENCE_MATRIX. The
   integration test asserts every file_pair_name exists as a
   directory under cases/. A new inline unit test
   `idempotence_matrix_mirrors_format_compat_pairs` in
   cst::format::tests asserts every matrix_name exists in
   IDEMPOTENCE_MATRIX. A one-sided deletion now requires editing
   both lists (or fails CI on the unedited side), enforcing the
   "two audience" coverage coupling the README's split design
   previously left as documentation-only.

6. REQUIRED_FIXTURES grew from 20 to 25 entries. Promoted from
   non-required:
   - multiline_note_string_preserved (string-literal interior
     preservation, classic destructive-formatting class)
   - balance_assertion_with_metadata (per-directive metadata
     attachment, sibling of #1142)
   - transaction_tags_and_links_source_order (tag/link ordering
     preservation, sibling of #1252)
   - metadata_unary_minus_value (sign preservation on metadata
     values)
   - non_latin_account_names (Unicode column-alignment correctness)

   Each was identifiably load-bearing for a regression class but
   could previously be deleted without tripping the floor check.

7. Stale rustdoc on `canonicalize_directives` in cst/format.rs
   disambiguated. The reference to "the deleted format_compat
   test" was ambiguous now that PR #1292 reintroduces a
   format_compat test in a different crate. Rustdoc now names
   the OLD test (crates/rustledger/tests/format_compat.rs,
   deleted in phase 4.1) explicitly and clarifies the new
   file-pair suite does NOT exercise canonicalize_directives'
   reparse-error path.

8. Stages 2 and 3 of the harness now run inside `catch_unwind`.
   A panic in format_source or parse on a pathological expected
   no longer aborts the entire test and discards the stage-1
   failures recorded for earlier fixtures in the same loop. The
   panic is recorded as a per-fixture failure with a clear
   message ("format_source is contracted to be total over
   arbitrary input; this is a bug") so the contributor knows
   the regression is in the formatter, not the fixture.

9. Bootstrap's BOOTSTRAP_FIXTURE validation now requires the
   target fixture's input.bean to exist before allowing any I/O.
   The previous shape exited 0 with "wrote 0, missing input 1"
   on a BOOTSTRAP_FIXTURE=name where `cases/name/` was an empty
   directory (no input.bean), which a contributor could misread
   as "bootstrap succeeded". The new check exits with code 3 and
   a clear "directory has no input.bean" message. Distinct from
   the existing code 2 "directory does not exist" path.

10. issue_1252_destructive_repro/input.bean now opens with a
    cross-reference comment pointing forward to the
    commas_stripped and unary_plus_stripped sibling fixtures.
    A reviewer auditing the #1252 fixture no longer reads the
    `commas_stripped/input.bean` claim that "the dispute is
    tracked in #1252" and then finds zero comma cases in the
    #1252 fixture itself.

Verified: cargo test -p rustledger-parser (231+ tests; new
idempotence_matrix_mirrors_format_compat_pairs unit test green),
cargo clippy -p rustledger-parser --all-features --all-targets
-- -D warnings, RUSTDOCFLAGS=-Dwarnings cargo doc
-p rustledger-parser --no-deps. All clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request Jun 10, 2026
Addresses 10 deep-review findings + 5 Copilot inline comments
(all converging on the same byte-identity / doc-drift / cache-
reach themes).

## Correctness

- `format_source_with_parsed` now falls back to
  `format_source(source)` when `parse_result.errors` is non-
  empty. Preserves byte-identity for inputs whose CST diverges
  from what `format_source`'s pre-parse normalization would
  produce — concretely, bare-`\r` (classic Mac) line
  terminators that `crlf_to_lf_outside_strings` normalizes but
  `parse_via_cst` does not. Without this fallback, classic-Mac
  sources would emit different text on the cached path vs
  format_source.
- Defensive length-check `debug_assert_eq!` catches the most
  common form of `(parse_result, source)` mismatched pair (different
  documents have different lengths). Released as
  `debug_assert_eq!` so release builds pay no cost; debug
  builds panic on mismatched pair. New test
  `format_source_with_parsed_panics_on_length_mismatch` pins
  the debug-build behavior.

## More cache reach

- CLI `try_format_source` (the entry that backs `rledger format`)
  switched from `format_source(source)` to
  `format_source_with_parsed(&result, source)`. The CLI was the
  one consumer round-1 missed — same shape as the LSP/FFI/WASM
  migrations.
- `rledger doctor roundtrip` switched similarly. On a project
  of 200 included files the doctor pass roughly halves its
  parsing cost.

## Test fixture expansion

Added three new fixtures to
`format_source_with_parsed_matches_format_source`:
- **BOM + CRLF combination** — Windows-authored ledger with a
  UTF-8 BOM.
- **Parse-error file** — exercises the new error-gate fallback.
- **Bare-CR line terminators** — classic-Mac source; exercises
  the fallback (`parse_via_cst` errors out on bare CR).

## Hot-path costs

- `assert_eq!` → `debug_assert_eq!` in
  `format_node_with_alignment` and
  `format_node_range_with_alignment`. The bare `format_node` /
  `format_node_range` delegates already validated kind via
  `SourceFile::cast`, so on the most common call path (bare →
  with_alignment) the assert was a redundant release-build
  cost. External direct callers still get a debug-build panic
  on wrong-kind input.

## Rustdoc fixes (Copilot inline #1 / #3 / #4 / #5)

- Three rustdoc cites pointed at non-existent tests:
  `compute_alignment_matches_parseresult_cache` (lib.rs:309,
  format.rs:858 in `compute_alignment`, convert.rs:272 inline
  comment) and `format_node_range_with_alignment_matches_uncached`
  (format.rs:812). Renamed to point at actual test names
  (`parse_result_alignment_cache::*` and
  `format_node_range_matches_format_node_range_with_alignment`).
- `compute_alignment(node)` doc claim corrected: the function
  takes `&SourceFile`, not `&SyntaxNode`. Updated to
  `compute_alignment(&SourceFile::cast(node).unwrap())` in both
  occurrence sites.
- `syntax_node().cast::<SourceFile>()` invalid turbofish in
  rustdoc fixed to `SourceFile::cast(syntax_node()).unwrap()`.

## Public API path consistency (Copilot inline #2)

`ParseResult::alignment` field type spelled as
`crate::format::PostingAlignment` (via the public re-export
surface) instead of `crate::cst::format::PostingAlignment`
(the internal module path). Matches the documented
"sole import path" convention in
`crate::format` module rustdoc.

## CHANGELOG naming rationale tightened

Cited the live existing `rustledger_core::Alignment` (an
unrelated workspace type used by the legacy typed-Directive
emitter) as the concrete reason for naming the new type
`PostingAlignment` instead of bare `Alignment`. Round-1 only
mentioned hypothetical future collisions.

## Stale rustdoc reference

`Alignment::default()` → `PostingAlignment::default()` in the
`format_node_with_alignment` rustdoc.

## Criterion benchmark

New `bench_format_source_vs_with_parsed` group in
`benches/parser_bench.rs`. Compares `format_source(s)` against
`format_source_with_parsed(&pre_parsed, s)` on 10 / 100 / 1000
transaction synthetic ledgers. Provides an executable
witness for the PR's perf claim.

## Verified

- `cargo test -p rustledger-parser -p rustledger-lsp -p
  rustledger-ffi-wasi -p rustledger --all-features` — 224 LSP
  lib + 263 parser lib + 58 FFI lib + integration suites green
  (parser: 262 -> 263 with the new debug-build panic test).
- `cargo clippy --workspace --all-features --all-targets --
  -D warnings` clean.
- `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p
  rustledger-lsp --no-deps` clean.
- Baseline manifest unchanged.

Refs #1299.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request Jun 10, 2026
…es (#1299)

* chore(deps): #1262 unyank aes 0.9.0 -> 0.9.1

cargo deny check surfaced aes 0.9.0 (transitive via zip 8.6.0 -> rustledger-plugin) as a yanked version. cargo update -p aes resolves to 0.9.1, the immediate successor that drops the yank mark. Lockfile-only change, no source diff in the workspace, no semver impact on rustledger-plugin or its consumers.

cargo deny check now reports advisories ok, bans ok, licenses ok, sources ok across the workspace.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* feat(parser,lsp): cache formatter alignment on ParseResult

Pre-compute the formatter's file-wide alignment columns at parse
time and stash them on `ParseResult::alignment`, so hot formatting
paths (notably the LSP `range_formatting` fallback shipped in
#1298) don't re-walk every posting in the file on every call.

## Background

`format_node` and `format_node_range` (in
`rustledger-parser/src/cst/format.rs`) run a pre-pass over every
Transaction's postings to compute file-wide alignment columns:
`number_col` (where the right-justified number field starts) and
`number_width` (max rendered width of any number). The pre-pass is
`O(N_postings_in_file)` per call.

This is fine for the CLI's one-shot `rledger format`, but the LSP
`range_formatting` fallback path can be invoked per-keystroke by
format-on-type clients while the user is editing through a parse
error. A 10k-directive ledger with a typo means we walked 10k
directives' postings on every key press. The PR #1298 review
flagged this as a real concern (deferred at the time as
acceptable).

## What's in this PR

### Parser

- `format::Alignment` is now `pub` + `#[non_exhaustive]` + `Copy`,
  with public `number_col` / `number_width` fields. Construction
  via `Alignment::default()` is supported externally; the
  `#[non_exhaustive]` attribute reserves the right to add fields
  later without breaking downstream `match` arms.
- `format::compute_alignment(&SourceFile) -> Alignment` is now
  `pub` so consumers can pre-compute independently.
- `ParseResult::alignment: Alignment` populated by `parse_via_cst`
  during the existing `walk_descendants_once` pass. Same canonical-
  payload exclusion pattern as `syntax_root`: bound in the
  destructure for compiler-enforced exhaustiveness, discarded from
  the canonical hash. Pinned by `canonical_payload_excludes_alignment`.
- Two new `_with_alignment` variants:
  `format::format_node_with_alignment(node, alignment) -> String`
  and `format::format_node_range_with_alignment(node, range, alignment)`.
  The bare `format_node` / `format_node_range` delegate to them
  after computing alignment internally — no behavior change for
  existing callers, just a new opt-in fast path.
- Equivalence pinned: `format_node_equals_format_node_with_alignment`
  and `format_node_range_matches_format_node_range_with_alignment`
  assert byte-identical output across representative fixtures.
  The cache's freshness vs. a fresh `compute_alignment` call is
  pinned by `parse_result_alignment_cache::*` (6 fixtures
  including empty source, open-only, single transaction,
  multi-transaction with varying widths, arithmetic amounts,
  and a parse-error file).

### LSP

- `fallback_cst_snap_edit` in `range_formatting.rs` now calls
  `format_node_range_with_alignment(&node, cst_range, parse_result.alignment)`
  instead of `format_node_range(&node, cst_range)`. The per-call
  `O(N_postings)` walk is gone; per-fallback cost is now
  `O(N_cst_nodes covered by the user's range)`, independent of
  file size.

### Deps

- `cargo update -p aes` to unyank the transitive dependency `aes
  0.9.0 -> 0.9.1`. Surfaced by `cargo deny check`. Lockfile-only,
  no source diff anywhere in the workspace.

## Why both in one PR

The dependency unyank is a single-line lockfile change that would
otherwise sit in its own trivial PR. Keeping it next to the
substantive change is a closing housekeeping pass; the two
commits are clean (`chore(deps):` + `feat(parser,lsp):`) so they
can be split during review if desired.

## Verified

- `cargo test -p rustledger-parser -p rustledger-lsp
  --all-features` (224 LSP lib + 260 parser lib green; parser
  format module suite went 250 -> 260 with the 10 new tests
  spread across `cst::format::tests`,
  `parse_result_alignment_cache`,
  `canonical_payload_excludes_alignment`).
- `cargo clippy --workspace --all-features --all-targets --
  -D warnings` clean.
- `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p
  rustledger-lsp --no-deps` clean.
- `cargo deny check` now reports `advisories ok, bans ok, licenses
  ok, sources ok`.
- Baseline manifest unchanged (the canonical-payload exclusion
  works as designed; the new test pins it executably).

Refs #1262 (post-completion follow-up flagged in the closing
comment).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* chore: regenerate cargo-vet exemptions

* fix(parser,lsp,ffi,wasm): #1299 round-1 review findings

Addresses 10 deep-review findings on PR #1299. Same root cause
for the largest one: the original PR optimized only the rare
parse-error LSP fallback path; the much more common Format-on-
Save / FFI format.source / WASM ParsedLedger::format paths still
re-parsed the source and re-walked every posting, leaving the
cache mostly dead code.

## Cache reaches the happy path now

- New public entry `format::format_source_with_parsed(&ParseResult, &str)`
  reuses the cached `syntax_root` AND `alignment`, skipping both
  the duplicate parse and the duplicate alignment walk.
- LSP `handle_formatting` / `format_document` switched to
  `format_source_with_parsed`. The Format-on-Save / format-on-
  type-clean-file paths now pay only the per-call emit cost.
- FFI `format.source` (rustledger-ffi-wasi/src/jsonrpc/router.rs)
  switched: it already produced `parse_result` for the error
  gate; the second parse via `format_source` is gone.
- WASM `ParsedLedger::format` (already-cached `parse_result`
  field) and `api::format_source` (already-produced
  `parse_result`) both switched.
- Byte-identical output pinned by new
  `format_source_with_parsed_matches_format_source` test across
  LF / CRLF / BOM-prefixed fixtures. The two paths produce the
  same canonical text because the canonical form is rebuilt from
  typed values rather than echoing trivia.

## Type rename: Alignment -> PostingAlignment

The public type was just introduced this week (no shipped
consumers); the cheapest moment to rename. `Alignment` is too
generic for `rustledger_parser::format::Alignment` and would
compete with future text-justification or memory-layout helpers.
`PostingAlignment` is qualified by its semantic purpose. Re-
export, struct definition, field type on `ParseResult::alignment`,
all internal `align: Alignment` parameter sites, and the
`canonical_payload_excludes_alignment` test all updated.

## Cast cleanup in _with_alignment fns

`format_node_with_alignment` and `format_node_range_with_alignment`
each replaced their `SourceFile::cast(node.clone()).expect(...)`
+ misleading `let _ = source_file;` precondition with
`assert_eq!(node.kind(), SyntaxKind::SOURCE_FILE)`. Saves the
redundant Arc-bump clone on every hot-path call (the bare
`format_node` delegate already validated the kind) while keeping
the same panic guarantee for direct external callers. The
`format_node_with_alignment` body now uses
`node.children_with_tokens()` directly instead of
`source_file.syntax().children_with_tokens()`.

## Docs

- `compute_alignment` rustdoc grew a `Tree-shape precondition`
  section documenting the must-be-just-parsed contract:
  hand-built partial trees and ERROR_NODE-wrapped transactions
  silently fall back to `PostingAlignment::default()`. Behavior
  pinned by the new
  `parse_result_alignment_cache::mid_transaction_error_node`
  test.
- `ParseResult::alignment` rustdoc grew a `Producer-only cache
  invariant` section explaining what happens if a consumer
  mutates `directives` / `syntax_root` without refreshing the
  cache, and pointing them at `compute_alignment` for the
  manual refresh.
- CHANGELOG entry rewritten to list the three public entry
  points (node, node_range, source), document the
  `PostingAlignment` naming choice, and capture the
  producer-only invariant.

## Tests

- Existing 10 cache-equivalence tests still pass.
- 1 new test pins `format_source_with_parsed` byte-identity
  vs `format_source` across LF / CRLF / BOM fixtures.
- 1 new test pins cache equivalence under mid-transaction
  ERROR_NODE recovery — the scenario the LSP fallback
  actually traverses during format-on-type.

## Verified

- `cargo test -p rustledger-parser -p rustledger-lsp -p
  rustledger-ffi-wasi --all-features` — 224 LSP lib + 262
  parser lib + 58 FFI lib + integration suites green
  (parser: 260 -> 262 with the 2 new tests).
- `cargo clippy --workspace --all-features --all-targets --
  -D warnings` clean.
- `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p
  rustledger-lsp -p rustledger-ffi-wasi -p rustledger-wasm
  --no-deps` clean.
- Baseline manifest unchanged.

Refs #1299.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(parser,lsp,cli): #1299 round-2 review findings + Copilot inline

Addresses 10 deep-review findings + 5 Copilot inline comments
(all converging on the same byte-identity / doc-drift / cache-
reach themes).

## Correctness

- `format_source_with_parsed` now falls back to
  `format_source(source)` when `parse_result.errors` is non-
  empty. Preserves byte-identity for inputs whose CST diverges
  from what `format_source`'s pre-parse normalization would
  produce — concretely, bare-`\r` (classic Mac) line
  terminators that `crlf_to_lf_outside_strings` normalizes but
  `parse_via_cst` does not. Without this fallback, classic-Mac
  sources would emit different text on the cached path vs
  format_source.
- Defensive length-check `debug_assert_eq!` catches the most
  common form of `(parse_result, source)` mismatched pair (different
  documents have different lengths). Released as
  `debug_assert_eq!` so release builds pay no cost; debug
  builds panic on mismatched pair. New test
  `format_source_with_parsed_panics_on_length_mismatch` pins
  the debug-build behavior.

## More cache reach

- CLI `try_format_source` (the entry that backs `rledger format`)
  switched from `format_source(source)` to
  `format_source_with_parsed(&result, source)`. The CLI was the
  one consumer round-1 missed — same shape as the LSP/FFI/WASM
  migrations.
- `rledger doctor roundtrip` switched similarly. On a project
  of 200 included files the doctor pass roughly halves its
  parsing cost.

## Test fixture expansion

Added three new fixtures to
`format_source_with_parsed_matches_format_source`:
- **BOM + CRLF combination** — Windows-authored ledger with a
  UTF-8 BOM.
- **Parse-error file** — exercises the new error-gate fallback.
- **Bare-CR line terminators** — classic-Mac source; exercises
  the fallback (`parse_via_cst` errors out on bare CR).

## Hot-path costs

- `assert_eq!` → `debug_assert_eq!` in
  `format_node_with_alignment` and
  `format_node_range_with_alignment`. The bare `format_node` /
  `format_node_range` delegates already validated kind via
  `SourceFile::cast`, so on the most common call path (bare →
  with_alignment) the assert was a redundant release-build
  cost. External direct callers still get a debug-build panic
  on wrong-kind input.

## Rustdoc fixes (Copilot inline #1 / #3 / #4 / #5)

- Three rustdoc cites pointed at non-existent tests:
  `compute_alignment_matches_parseresult_cache` (lib.rs:309,
  format.rs:858 in `compute_alignment`, convert.rs:272 inline
  comment) and `format_node_range_with_alignment_matches_uncached`
  (format.rs:812). Renamed to point at actual test names
  (`parse_result_alignment_cache::*` and
  `format_node_range_matches_format_node_range_with_alignment`).
- `compute_alignment(node)` doc claim corrected: the function
  takes `&SourceFile`, not `&SyntaxNode`. Updated to
  `compute_alignment(&SourceFile::cast(node).unwrap())` in both
  occurrence sites.
- `syntax_node().cast::<SourceFile>()` invalid turbofish in
  rustdoc fixed to `SourceFile::cast(syntax_node()).unwrap()`.

## Public API path consistency (Copilot inline #2)

`ParseResult::alignment` field type spelled as
`crate::format::PostingAlignment` (via the public re-export
surface) instead of `crate::cst::format::PostingAlignment`
(the internal module path). Matches the documented
"sole import path" convention in
`crate::format` module rustdoc.

## CHANGELOG naming rationale tightened

Cited the live existing `rustledger_core::Alignment` (an
unrelated workspace type used by the legacy typed-Directive
emitter) as the concrete reason for naming the new type
`PostingAlignment` instead of bare `Alignment`. Round-1 only
mentioned hypothetical future collisions.

## Stale rustdoc reference

`Alignment::default()` → `PostingAlignment::default()` in the
`format_node_with_alignment` rustdoc.

## Criterion benchmark

New `bench_format_source_vs_with_parsed` group in
`benches/parser_bench.rs`. Compares `format_source(s)` against
`format_source_with_parsed(&pre_parsed, s)` on 10 / 100 / 1000
transaction synthetic ledgers. Provides an executable
witness for the PR's perf claim.

## Verified

- `cargo test -p rustledger-parser -p rustledger-lsp -p
  rustledger-ffi-wasi -p rustledger --all-features` — 224 LSP
  lib + 263 parser lib + 58 FFI lib + integration suites green
  (parser: 262 -> 263 with the new debug-build panic test).
- `cargo clippy --workspace --all-features --all-targets --
  -D warnings` clean.
- `RUSTDOCFLAGS=-Dwarnings cargo doc -p rustledger-parser -p
  rustledger-lsp --no-deps` clean.
- Baseline manifest unchanged.

Refs #1299.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: rustledger-bot[bot] <257329324+rustledger-bot[bot]@users.noreply.github.com>
robcohen added a commit that referenced this pull request Jun 15, 2026
Tier-1 public-API SemVer ratchet. `rustledger-plugin-types` is the crate
every plugin author compiles against, so an accidental breaking change
(renamed pub field, changed trait signature, enum variant without
`#[non_exhaustive]`) shipped without a major bump would break every plugin.

- Adds a `SemVer (plugin-types)` job using
  obi1kenobi/cargo-semver-checks-action (pinned to v2.8 by SHA, matching the
  repo's action-pinning convention). The action manages the nightly rustdoc
  toolchain itself, so no nightly is added to the flake.
- Baseline is the last crates.io release (plugin-types is published by
  release-publish.yml), resolving issue #1233's open question #3 — no
  git-tag baseline plumbing needed.
- ADVISORY: deliberately NOT wired into the `build` merge gate, so it
  surfaces breaks without blocking. Promote to required once it has proven
  stable on real PRs. Tier 1 = plugin-types only; core/parser later.
- Clears RUSTC_WRAPPER for the job (the workflow sets it to sccache globally
  and this job doesn't install the sccache-action).

Note: cargo-semver-checks needs nightly rustdoc JSON, which isn't in the dev
flake, so this could not be run locally — CI is the first real execution.
The YAML is validated and the job is confirmed out of the required gate.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request Jun 19, 2026
Follow-up to the review on #1435. Instead of running the plugin and
relabeling the failure by name-shape, detect a bare module-name reference
*before* invoking the runtime:

- Correctness (#1): the old error-path relabel discarded the real error `e`
  for any dotted/non-.py name — masking genuine failures such as a corrupt
  runtime download (`PythonRuntime::new()` fails before module discovery). Now
  module names are rejected up front, so the `Err(e)` arm only fires for real
  plugin files and surfaces `e` verbatim (E8002).
- Altitude (#2): no runtime is downloaded/compiled (and no "10-100x slower"
  warning printed) for a request that is rejectable from the name alone.
- Reuse/consistency (#3): both E8004 sites now share `module_ref_message`,
  so the "not supported by module name; reference the file directly" guidance
  is identical everywhere.
- Discriminator (#4): one `is_python_module_name` helper using
  `eq_ignore_ascii_case`, not the pre-lowercased `ext` (fixes a latent
  case-sensitivity coupling).
- Docs (#5): document E8002/E8004/E8005 in docs/reference/errors.md.
- Cleanup (#6,#7): static example path (drops the dead `unwrap_or` and the
  `./.py` trailing-dot edge); drop the redundant `is_python_available()` guard
  (`suggest_module_path` already handles a missing interpreter).

fmt + clippy (-D warnings, python-plugins) clean; loader suite 64/64.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
robcohen added a commit that referenced this pull request Jun 19, 2026
* fix(loader): actionable error for module-name Python plugin refs

A Python plugin declared by module name (beancount's `plugin "pkg.mod"`) is
unsupported by design — only file-path references load (see
`discover_module_source`). It routes into the Python-plugin branch (the name
contains a dot), runs, and fails inside `execute_module`, surfacing as
`E8002: Python plugin 'pkg.mod' execution failed: Python plugin module not
found: pkg.mod` — doubly misleading, reading as a venv/PYTHONPATH problem the
user cannot fix.

Detect the bare-module-name case in the error path and emit an actionable
`E8004` instead: name the unsupported form and point at the file path,
resolving it via system Python (`suggest_module_path`) when possible, else a
generic hint that also notes the sandbox cannot see the host venv (the plugin
must be self-contained). This also unifies the code with the parallel
unknown-plugin branch (both `E8004`).

The existing `suggest_module_path`/`E8004` hint was unreachable for real
module names because they always contain a dot and were diverted into the
Python branch first.

Closes #1432 (Gap 1).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(plugins): document Python plugin file-path + self-contained model

Gaps 2-3 of #1432. Document that:

- Built-in names resolve to the native Rust plugin regardless of the
  `beancount.plugins.` prefix (so `plugin "beancount.plugins.auto_accounts"`
  is unchanged), but a custom Python plugin must be referenced by file path —
  the module-name form is rejected.
- Python plugins run in a CPython-WASI sandbox that never mounts the host
  venv / site-packages, so they must be self-contained (stdlib + the bundled
  beancount compat shim); anything heavier needs a native Rust plugin.

Adds a "Referencing a Python Plugin" + "Plugin Sandbox" section to
docs/reference/plugins.md and a file-path note to docs/migration/from-beancount.md
(clarifying that the existing auto_accounts example works because it resolves
to a native plugin, not Python).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* refactor(loader): reject module-name plugins up front; address review

Follow-up to the review on #1435. Instead of running the plugin and
relabeling the failure by name-shape, detect a bare module-name reference
*before* invoking the runtime:

- Correctness (#1): the old error-path relabel discarded the real error `e`
  for any dotted/non-.py name — masking genuine failures such as a corrupt
  runtime download (`PythonRuntime::new()` fails before module discovery). Now
  module names are rejected up front, so the `Err(e)` arm only fires for real
  plugin files and surfaces `e` verbatim (E8002).
- Altitude (#2): no runtime is downloaded/compiled (and no "10-100x slower"
  warning printed) for a request that is rejectable from the name alone.
- Reuse/consistency (#3): both E8004 sites now share `module_ref_message`,
  so the "not supported by module name; reference the file directly" guidance
  is identical everywhere.
- Discriminator (#4): one `is_python_module_name` helper using
  `eq_ignore_ascii_case`, not the pre-lowercased `ext` (fixes a latent
  case-sensitivity coupling).
- Docs (#5): document E8002/E8004/E8005 in docs/reference/errors.md.
- Cleanup (#6,#7): static example path (drops the dead `unwrap_or` and the
  `./.py` trailing-dot edge); drop the redundant `is_python_available()` guard
  (`suggest_module_path` already handles a missing interpreter).

fmt + clippy (-D warnings, python-plugins) clean; loader suite 64/64.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(loader): recognize forward-slash plugin paths on Windows + unit tests

Addresses the Copilot review note: is_python_module_name checked only
std::path::MAIN_SEPARATOR (`\` on Windows), so a forward-slash file ref like
"plugins/foo" could be misclassified as a module name there. Check both `/`
and the platform separator.

Adds direct unit tests for is_python_module_name (module vs .py vs
path-separated vs existing-file, case-insensitive ext) and module_ref_message
(both the resolved-path and fallback branches — also covering the line codecov
flagged).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
robcohen added a commit that referenced this pull request Jul 1, 2026
…p oversell (#1666, #1668) (#1669)

#1666 — reducing a labeled cost lot dropped the matched lot's label (single-lot
path set label: None while the multi-lot path preserved it), so the reduction
didn't net against its augmenting lot and left a phantom unlabeled negative lot in
the holdings view. Carry the matched lot's label onto the reduction posting (as
the date already was). rustledger-booking/src/book.rs.

#1668 #2 — a balance asserted in a currency the account doesn't allow only got a
confusing 'Balance failed ... got 0 EUR'. Add a dedicated 'Invalid currency ...
for Balance directive' diagnostic (E-code CurrencyNotAllowed) in
validate_balance_early, mirroring the transaction currency check; only when the
account constrains its currencies.

#1668 #1 — an oversell reported 'Not enough units' twice via the FFI: booking
(inside load_source) reports it WITH transaction context, and the #1663 validation
session re-derived it context-free (its reduce-check is a standalone-validation
safety net). Drop the session's copy when a load error already conveys it. The CLI
never doubled (it partitions booking-failed txns out before late validation).

#1668 #3 — investigated, no change: rustledger already flags duplicate open across
includes (E1002 on the CLI), and #1663 made the FFI load path validate too, so it
is caught there as well; the report reflects the pre-#1663 non-validating load.

Tests: booking reduction-label netting; balance wrong-currency (+ unconstrained
no-false-positive); FFI parity oversell-single-error. 94 validate + 106 booking +
19 FFI parity pass; clippy -D warnings + fmt clean.

Closes #1666

Co-authored-by: Claude Opus 4.8 <[email protected]>
robcohen added a commit that referenced this pull request Aug 11, 2026
* fix(parser): reject transaction headers beancount refuses

Four of the seven constructs in #2008. All four live in the transaction
header, so one rule covers them:

  #3 `* #trip "Money from CC" ^610f`  string after a tag
  #4 `* "Dinner" A:*:B`               junk after the narration
  #6 `* "Mermaid Inn" "Nice dinner" "With Caroline"`
  #7 `* "A" "B" "C"`                  more than two strings

beancount's grammar is `DATE txn txn_strings tags_links eol`, so strings
come first and tags/links follow; more than two strings parses but the
builder rejects it with "Too many strings on transaction description".
Our CST parser is deliberately permissive - it is lossless and recovers
rather than rejecting - and nothing downstream re-imposed that shape.

Case 4 falls out of the same rule rather than needing lexer work: in
`* "Dinner" A:*:B` the `A` lexes as a one-character CURRENCY, which is a
valid flag in the flag position and junk after a string. Scoping the
flag position to "before any string/tag/link" is what catches it.

The rule is written once over `(SyntaxKind, Range)` pairs in a new
`cst::txn_header`, and the red and green walkers differ only in how they
enumerate tokens. The green/red mirrors are the drift source CLAUDE.md
names; the shared rule plus the parity corpus is the defense. Removing
the green call makes `parse_green_eq_red_corpus` fail, verified.

Kind and range are all the rule needs - even the one-character CURRENCY
flag is decided by `range.len() == 1` - so neither walker needs source
access to reach a verdict, only to word the message.

Scope was set by measurement, not by taste. Tallying every token kind
that appears in a transaction header across the 731-file corpus (~30k
transactions) gives DATE, STAR, PENDING_KW, TXN_KW, STRING, TAG, LINK,
WHITESPACE, COMMENT, one-character CURRENCY - and two COLONs, both
inside the case-4 fixture. So the allowlist is evidence, and sweeping
the corpus after the change produces exactly four diagnostics: the four
target fixtures, no false positives.

Deliberately NOT widened past the evidence: `2014-01-01 * * "x"` has two
flags and beancount rejects it, but it is not one of the seven and
guessing at extra strictness is how a compatibility fix starts breaking
real files. The `|` separator keeps its own DeprecatedPipeSymbol
diagnostic instead of being re-reported here.

Requires a cache bump, and this was observed rather than reasoned:
after the parser change the first `rledger check` against the fixtures
still reported only the old downstream E1001s, because the parse cache
held the permissive parse. Loader 24 -> 25, wasm 10 -> 11, the wasm pin
with it, and both archived-layout FIXTURE_VERSION tripwires - which fire
with instructions saying which case applies. This is v15's case: which
errors are emitted changed, how anything is archived did not.

`test_lima_tests_parse` did not catch any of this, and could not have.
Its allowlist branch is a bare `continue`, so listing a fixture only
permits an error and never checks one occurs. TagThenLink,
CostEmptyComponents and CostWithSlashes sat in that list for the
parser's whole life while producing no error at all. A new
LIMA_2008_CASES table replaces that with a two-sided assertion over all
seven cases: the three unfixed rows assert we are STILL permissive, so
finishing #2008 turns the test red and forces the row to flip.

28 allowlisted fixtures are in that same one-sided position today. 22
are `GrammarExceptions*`, whose intended semantics I have not verified,
so they are left alone and noted rather than guessed at.

Effect on compat: all four files now fail to load in `rledger query`
too (#1912), matching bean-query, which is the point - they were
returning rows here and erroring there.

Refs #2008

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG

* chore(baselines): regenerate parser manifest for the four #2008 fixtures

The parser-output baseline gate reported drift on exactly the four
fixtures this branch now rejects, with their SOURCE hashes unchanged -
which is the confirmation, not a surprise: same input, different parser
output, and nothing else in the corpus moved.

Only those four rows are updated. A full `regen-corpus-baselines.sh`
run also wanted to add 17 `interpolation/` rows and rewrite
`donearm-ledger/accounts.beancount`'s SOURCE hash, neither of which
belongs in this commit: the interpolation fixtures are in-tree and
absent from the committed manifest today, which CI tolerates and which
is unrelated to this change, and a differing source hash means my local
corpus copy differs from the one CI fetches. Committing either would be
drift smuggled in under a green checkmark.

The four new hashes are cross-checked: CI's strict run reported the same
16-hex prefixes that the local regeneration produced in full.

Refs #2008

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG

* fix(parser): address #2020 review

Four review comments, all taken.

The one that matters: `test_lima_2008_cases_have_expected_strictness`
skipped itself when the fixture directory was missing. Those 441
fixtures are committed to the repo, so a missing directory is a broken
checkout rather than an unavailable dependency - and a self-skipping
test is the exact failure mode CLAUDE.md warns about under
"Availability-gated tests must fail loudly somewhere". Worse, skipping
would hide the very thing this table exists to pin. Now a hard assert.
I quoted that same rule in the conformance test's module doc while
leaving this skip two files away.

Also:

- `first_header_defect`'s contract said tokens run "through (not past)"
  the terminating NEWLINE, which reads as "include it". Both callers
  exclude it. Says so now, and records that NEWLINE stays in the trivia
  set only so feeding one in cannot change the verdict.
- The `unwrap_or_default()` on a non-char-boundary slice would have
  rendered `unexpected "" in transaction header`, naming nothing. Token
  ranges are always char boundaries so it is unreachable, but the branch
  now falls back to the byte range and defect kind instead of an empty
  quote.
- "three constructs" then listed four cases. Cases 6 and 7 are two
  fixtures of one construct; the doc now says that instead of leaving
  the reader to work it out.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant