Skip to content

fix: use cargo fmt in treefmt for consistent formatting - #11

Merged
robcohen merged 1 commit into
mainfrom
fix/treefmt-rustfmt-config
Jan 6, 2026
Merged

robcohen merged 1 commit into
mainfrom
fix/treefmt-rustfmt-config

Conversation

@robcohen

@robcohen robcohen commented Jan 6, 2026

Copy link
Copy Markdown
Member

Summary

Fixes the recurring formatting mismatch between treefmt (pre-commit hook) and CI (cargo fmt --check).

Root cause: treefmt invoked rustfmt --edition 2021 directly, ignoring rustfmt.toml settings like max_width = 100.

Fix: Use cargo fmt instead, which respects rustfmt.toml.

Changes

# Before
[formatter.rust]
command = "rustfmt"
options = ["--edition", "2021"]

# After  
[formatter.rust]
command = "cargo"
options = ["fmt", "--"]

Test plan

  • Pre-commit hook passes
  • CI formatting check passes

treefmt was invoking rustfmt directly without the rustfmt.toml config,
causing different formatting than CI's 'cargo fmt --check'. This led to
recurring formatting conflicts where treefmt would reformat code
differently than what CI expected.

Using 'cargo fmt' ensures treefmt respects rustfmt.toml settings
(max_width=100, etc.) and produces identical output to CI.
@robcohen
robcohen enabled auto-merge January 6, 2026 17:21
@robcohen
robcohen added this pull request to the merge queue Jan 6, 2026
Merged via the queue into main with commit 59c801a Jan 6, 2026
@robcohen
robcohen deleted the fix/treefmt-rustfmt-config branch January 6, 2026 17:32
robcohen added a commit that referenced this pull request Jan 14, 2026
fix: use cargo fmt in treefmt for consistent formatting
robcohen added a commit that referenced this pull request Jan 14, 2026
fix: use cargo fmt in treefmt for consistent formatting
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 May 31, 2026
…ard cases

Address all 16 findings from the second deep review. On review feedback
"use best-in-class libraries to solve difficult edge cases", several
hand-rolled subsystems are replaced with established crates.

LSP correctness (severe / buffer-corruption fixes):

1. `minimal_diff_edits` now uses `similar::TextDiff::ops()` (structured
   `DiffOp` API with explicit `old_range` / `new_range` byte-indexed
   line ranges) instead of a hand-rolled state machine over
   `iter_all_changes()`. The state machine corrupted the buffer on any
   pure insertion: probe-confirmed `"a\nb\n" → "a\nX\nb\n"` produced
   `"X\na\nb\n"` (X went to BOF). Three regression tests pin the fix.

2. `clip_edit_to_range` was replaced with `edit_inside_range`: the LSP
   convention "rangeFormatting returns only edits fully inside the
   selection" is the only architecturally sound choice — slicing the
   reformatter's output by source byte counts produces semantically
   wrong content when the canonical formatter changes column positions.
   Tests confirm canonical edits straddling the boundary are dropped;
   zero-width edits at boundaries are kept.

3. `ropey` is now pinned to `default-features = false, features =
   ["cr_lines", "simd"]`. With default features ropey treats
   NEL/VT/FF/LS/PS as line breaks; `similar::TextDiff::from_lines`
   splits on LF/CRLF/bare-CR only. The disagreement caused wrong byte
   ranges for any source containing those Unicode line-break chars.

LSP edge cases:

7. Half-open range filter accepts zero-width edits at the selection
   boundary (a pure insertion at byte == range_start is semantically
   inside the selection). Regression test added.

8. `lsp_position_to_byte` now correctly handles `Position(line ==
   line_count, character == 0)` — the LSP-spec end-of-document
   position — by returning `rope.len_bytes()` instead of clamping to
   the last line's end.

9. `clean_line` normalizes pathological `"...\r\r"` to a single trailing
   `\r` via `trim_end_matches('\r')` instead of `strip_suffix` once, so
   trailing whitespace before the embedded CR is correctly stripped.
   Also switched to `out.trim_end_matches([' ', '\t', '\r']).len()` +
   `truncate` (O(n)) replacing the `chars().next_back()` loop (O(n²)
   worst case).

10. `handle_execute_command` returns a new `ExecuteCommandResponse`
    struct carrying both the JSON response and an optional
    `ShowMessageParams` notification. `handle_align_amounts` now
    surfaces "Cannot align: source has N parse error(s)" via
    `window/showMessage` so VS Code and other clients actually display
    it (executeCommand has no spec-defined way to carry textual
    errors). main_loop dispatcher sends the notification alongside the
    response.

11. `byte_to_lsp_position` and `lsp_position_to_byte` each grew a
    rope-accepting variant (`rope_byte_to_lsp_position`,
    `rope_lsp_position_to_byte`). Hot callers (`minimal_diff_edits`,
    `handle_range_formatting`) build the rope once at the top and
    thread it through, eliminating the O(K·N) per-call rope
    construction the previous review flagged.

12. The `.expect("Delete has old_index")` is gone — the new `DiffOp`
    API exposes byte ranges directly, no Option to unwrap.

doctor / parser:

4, 5, 6, 13. `cmd_roundtrip` rewritten:
  * BOM stripping moved to the parser's lexer
    (`#[logos(skip r"\u{FEFF}")]`) — the doctor no longer needs a
    bespoke strip helper, and the CLI/LSP/FFI/WASM all benefit
    transparently (a BOM'd file is now invisible to every consumer).
  * `Loader::new().with_path_security(true)` confines the include graph
    to the entry file's tree — a malicious ledger with
    `include "/etc/passwd"` can no longer make the doctor read outside
    the user's selection.
  * Errors are split by variant: `LoadError::ParseErrors` aborts;
    infrastructure errors (cycles, glob no-match, IO) are advisory and
    the per-file round-trip continues on files that did load.
  * BOM regression test in the parser pins the new
    transparent-skip behavior (replacing the prior
    test_bom_produces_invalid_token_error).

14. `cmd_roundtrip` gains 5 regression tests
    (`stable_single_file_reports_success`,
    `bom_prefixed_file_does_not_abort`,
    `multi_file_include_graph_walked`,
    `glob_no_match_continues_with_advisory`,
    `parse_errors_abort`) covering the rewrite paths.

FFI:

15. `format_source_to_response` returns a single-line message and
    attaches the full list of errors as a structured `data: { errors:
    [...] }` field on the `RpcError` per JSON-RPC 2.0 — log-friendly
    message text, structured access for clients that want
    per-error inspection. `RpcError::with_data` builder added.

16. `line_byte_range` is gone — `minimal_diff_edits` constructs a
    single rope at the top and threads it through (covered by #11).

Library swaps summary (the "don't reinvent the wheel" theme):
  * Line-based diff: hand-rolled state machine → `similar::DiffOp::ops()`
    (Myers diff over lines, byte-range-indexed).
  * LSP position math: hand-rolled UTF-16 walks → `ropey` (pinned to
    cr_lines feature for line-break parity with similar).
  * Showing messages from executeCommand: hand-rolled "stuff a message
    in JSON" → `lsp_types::ShowMessageParams` notification via main_loop.
  * Structured JSON-RPC error data: hand-rolled multi-line message
    string → JSON-RPC `data` field with structured payload.

Verify suite green: workspace clippy `-D warnings`, fmt, RUSTDOCFLAGS=
-Dwarnings cargo doc, full cargo test --workspace --all-features.

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

* fix(format)!: byte-compatible output with bean-format (closes #1242)

rledger format and Python bean-format produced divergent layouts, so a
file touched by both tools churned in editors and CI. Rework the formatter
into a two-phase, file-wide aligner and default to bean-format's auto-width.

- Phase 1 renders each directive to a Vec<FormatLine> (Plain | Aligned);
  Phase 2 resolves column widths across the whole file and emits.
- Default alignment is now Auto (matches bean-format's default); -c <col>
  selects fixed currency-column mode. A file formatted by either tool is a
  fixed point of the other.
- LSP shares the core path: resolve_alignment fixes file-wide widths once,
  then per-line TextEdits align to those columns, so editor output matches
  rledger format byte-for-byte while preserving the per-line edit model.

BREAKING CHANGE: default `rledger format` output changes from fixed
column-60 to auto-width. Pass `-c 60` to restore the old layout.

Tests: golden output, idempotence/fixed-point on a corpus, and live
bean-format (beancount 3.2.3) parity via the podman compat image.

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

* refactor(format)!: canonical format_source/format_directives API

Closes the architectural gap exposed during deep review of PR #1244: only
the CLI and LSP were migrated to whole-file two-phase alignment; every
other format consumer (WASM, FFI, extract, add, synthetic, roundtrip) was
still looping the per-directive self-aligning `format_directive`, which
after the default flip from `CurrencyColumn(60)` to `Auto` produced
ragged, divergent output.

The fix routes every caller through one of two canonical APIs:

* `rustledger_core::format::format_directives(&[&Directive], &FormatConfig)`
  for directive lists with no surrounding source (extract, add, synthetic,
  doctor/roundtrip, FFI entry/entries).
* `rustledger_parser::format_source(source, &ParseResult, &FormatConfig)`
  for whole-file formatting that preserves comments, blank lines,
  options/includes/plugins, and trailing newlines (CLI, LSP, WASM, FFI
  format.source/format.file).

The old self-aligning `format_directive` is deleted so no future caller
can reintroduce the per-directive footgun. The LSP now delegates to
`format_source` and emits a single minimal contiguous line-diff edit;
parity with `rledger format` is by construction.

FFI `handle_format_source` no longer hand-rolls option/plugin emission,
which previously silently dropped comments and includes.

Cross-path identity test (`cli_matches_format_source_direct`) pins that
the CLI binary bytes equal a direct `format_source` call across the
corpus, in both auto and `-c 60` modes. Live bean-format parity (podman)
remains green.

Drive-by: fix a pre-existing rustdoc unresolved-link in
`rustledger-wasm::types::MetaValueTagged` introduced by PR #1241 that was
blocking `RUSTDOCFLAGS=-Dwarnings cargo doc`.

Verified: workspace clippy -D warnings clean, fmt --check clean, cargo
doc -Dwarnings clean, full `cargo test --workspace --all-features` green
(zero failures), and all 7 format_compat tests including bean-format
parity.

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

* fix(format): preserve trailing blanks after non-directive items + drop dead trim

Two Copilot review findings on PR #1244:

1. `format_source` dropped trailing blank lines when the last item was a
   standalone comment, options, include, or plugin. The lexer's
   `;[^\n\r]*` regex (and the parser's option/include/plugin spans)
   exclude the terminating newline, so `source[prev_end..]` held the
   file's trailing blanks but was never processed. Directives masked the
   bug because their spans capture trailing newlines and the in-match
   walk-back already accounted for them.

   Fix: after the items loop, process `source[prev_end..]` with the same
   "first newline is the previous item's terminator, extras are blank
   lines" rule used between items. The directive case stays correct
   because the in-match walk leaves `prev_end == source.len()` and the
   trailing slice is empty.

2. The `Comment` arm's `.trim_end_matches('\n')` was dead code (comment
   spans never contain a newline). Dropped, with the doc comment
   rewritten to cite the lexer regex.

Regression tests pin both behaviors: `preserves_trailing_blank_lines_after_comment`
and `preserves_trailing_blank_lines_after_option`.

Also regenerates `crates/rustledger-wasm/bindings/{index.schema.json,types.py}`
to absorb the `MetaValue` doc-link fix from the previous commit, which the
Wire-format bindings freshness CI check requires.

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

* fix(format): address 15-finding deep PR review

Phase 1 — correctness (severe):

1, 2. LSP `minimal_diff_edit` no longer emits malformed `TextEdit` ranges
   (range.end < range.start) when the source lacks a trailing newline or
   when only the trailing-newline count differs. Rewritten as a byte-based
   diff over the longest common UTF-8-safe prefix and suffix, with LSP
   positions computed in UTF-16 code units (LSP 3.17 default). Non-ASCII
   content now round-trips correctly. Probes that previously yielded
   malformed/no-op edits are pinned as regression tests.

3. FFI `handle_format_source` / `handle_format_file` now gate on parse
   errors, matching CLI/LSP/WASM. Without the gate, `format_source`
   silently dropped unparsable content and FFI callers had no way to
   detect it. Returns a `parse_error` RpcError with the first 3 error
   messages summarized.

4. `doctor roundtrip` now bails on parse errors instead of running
   `format_directives` over the partial parse and reporting SUCCESS on
   count equality. Also switched to `format_source` (the path the CLI
   uses) so the diagnostic measures what users actually invoke. New
   `byte-stable: YES/NO` line and `PARTIAL` outcome when bytes differ
   but structure is preserved.

Phase 1 — additional correctness:

8. `format_source` skips `Spanned::synthesized` directives (file_id ==
   SYNTHESIZED_FILE_ID, Span::ZERO). Without the filter they sort to the
   top of the file regardless of where the caller placed them in the
   Vec, since stable-sort on collision-key 0 preserves only insertion
   order.

9. `format_source` no longer collapses blank-only files (e.g.
   "\n\n\n\n") to a single "\n". The trailing-gap block now runs even
   when no items were rendered.

Phase 2 — architecture:

7. `rangeFormatting` now routes through `format_document` (the canonical
   `format_source` path) and filters returned edits by line range,
   instead of using its own per-line indent heuristics. Parity-by-
   construction with the CLI now covers both LSP formatting requests.

10. `format_directives` separator policy is documented explicitly:
    no blank line is inserted between adjacent directives; callers
    needing inter-directive blanks should compose at the
    `format_directive_lines` + `render_lines` level (extract_cmd is the
    canonical example).

11. LSP `format_document` no longer returns `None` for files with parse
    errors. A `fallback_cleanup_edits` pass emits per-line tab→spaces
    and trailing-whitespace edits on lines unaffected by the broken
    directive — preserving the pre-PR "format-on-save still does
    something useful" behavior.

12. LSP emits per-hunk edits when the changed region has the same line
    count on both sides (the common case for indent/alignment changes),
    preserving editor cursor and undo granularity around unchanged
    regions. Falls back to a single contiguous edit when line counts
    differ.

Phase 3 — quality:

13. The #1142 interleaved-metadata regression test grew a positive
    assertion that the misaligned posting indent is actually normalized
    (currency columns line up across postings), guarding against a
    degenerate no-op formatter that would have passed the
    metadata-preservation check alone.

14. `format_posting_line` doc-comment is now explicit that it's
    self-aligned only and not equivalent to what
    `format_directives`/`format_source` write.

15. Replaced the tautological `cli_matches_format_source_direct` test
    (which compared the CLI to `format_source` — but the CLI literally
    calls `format_source`) with a real cross-aggregator check:
    `format_source` (CLI path) must agree with `format_directives`
    (core path) on a directives-only corpus where neither aggregator
    has anything to disagree about.

All 7 format_compat tests pass including live bean-format parity
(podman); workspace test suite green; clippy -D warnings clean; cargo
doc -Dwarnings clean.

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

* fix(format)!: second-round deep-review fixes + library-based LSP edits

Address the 15-finding second deep review and replace hand-rolled LSP
position math and line-diff with library primitives (ropey, similar) on
review feedback.

LSP correctness:

1, 3. `surface_cleanup_edits` (new) preserves CRLF line endings and only
   replaces *leading* tabs. The previous `fallback_cleanup_edits` used
   `line.trim_end()` (stripping `\r` as Unicode whitespace) and
   `line.replace('\t', "  ")` (eating tabs inside string literals).
   Tests pin both behaviors.

2, 9. `rangeFormatting` now clips canonical edits to the actual selected
   byte range using half-open `[start, end)` semantics — matching what
   editors (VS Code, Helix) send. Multi-line canonical edits no longer
   spill outside the user's selection.

6, 7, 8. `format_document` is now canonical-only: returns `None` on
   parse errors. `handle_formatting` opts into `surface_cleanup_edits`
   as a fallback; `handle_align_amounts` and `handle_range_formatting`
   deliberately do not — alignment-named commands return a "cannot
   align" message on broken parse instead of silently mutating
   whitespace under their name.

12. `handle_align_amounts` doc no longer claims delegation to
    `format_posting_line` (stale since the canonical refactor).

doctor / multi-file:

4. `doctor roundtrip` walks the include graph via the Loader's
   `SourceMap` and runs the canonical `format_source` per file,
   classifying each as `[stable]`, `[reflow]`, or `[MISMATCH]`. Multi-
   file ledgers are no longer silently treated as single-file.

5. Strips a leading UTF-8 BOM before parsing so editor-added BOMs don't
   cause a spurious "round-trip aborted: parse errors" exit.

parser:

10, 11. `format_source` docstring spells out the contract: parse_result
   MUST come from `parse(source)`. Synthesized directives
   (`SYNTHESIZED_FILE_ID`) are filtered; non-directive items
   (options/includes/plugins/comments) carry no `file_id` and are
   assumed source-derived. Callers wanting to format a directive list +
   synthesized extras should compose at `format_directive_lines` +
   `render_lines` level via `rustledger_core::format::format_directives`.

FFI / test quality:

13. `handle_format_source` and `handle_format_file` share a new
    internal `format_source_to_response` helper. The JSON re-
    serialization round-trip (which contained an `unwrap()` latent
    panic across the WASI boundary) is gone.

14. `cli_matches_format_directives_on_directives_only_corpus` now
    asserts the filtered input parses to the same directive count as
    the original corpus entry — prevents the test passing on a future
    filter accident that produces degenerate input.

15. `lsp_position_to_byte` and `byte_to_lsp_position` are now in
    `handlers::utils`, used by every test helper and production caller.
    No more duplication.

Library swaps (on review feedback that we were hand-rolling too much):

* LSP position ↔ byte offset conversion now uses `ropey` (already a
  workspace dep), replacing two hand-rolled UTF-16 walks.
* Line-based diff for `minimal_diff_edits` now uses
  `similar::TextDiff::from_lines` (Myers diff), replacing the
  hand-rolled byte-prefix/suffix + per-hunk algorithm. `similar` was
  already a transitive dep via `insta`; promoted to a direct
  dependency.

Verify suite green: workspace clippy `-D warnings`, fmt `--check`,
`RUSTDOCFLAGS=-Dwarnings cargo doc --workspace --no-deps`, full
`cargo test --workspace --all-features`.

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

* chore: regenerate cargo-vet exemptions

* fix(format)!: third-round deep-review fixes - lean on libraries for hard cases

Address all 16 findings from the second deep review. On review feedback
"use best-in-class libraries to solve difficult edge cases", several
hand-rolled subsystems are replaced with established crates.

LSP correctness (severe / buffer-corruption fixes):

1. `minimal_diff_edits` now uses `similar::TextDiff::ops()` (structured
   `DiffOp` API with explicit `old_range` / `new_range` byte-indexed
   line ranges) instead of a hand-rolled state machine over
   `iter_all_changes()`. The state machine corrupted the buffer on any
   pure insertion: probe-confirmed `"a\nb\n" → "a\nX\nb\n"` produced
   `"X\na\nb\n"` (X went to BOF). Three regression tests pin the fix.

2. `clip_edit_to_range` was replaced with `edit_inside_range`: the LSP
   convention "rangeFormatting returns only edits fully inside the
   selection" is the only architecturally sound choice — slicing the
   reformatter's output by source byte counts produces semantically
   wrong content when the canonical formatter changes column positions.
   Tests confirm canonical edits straddling the boundary are dropped;
   zero-width edits at boundaries are kept.

3. `ropey` is now pinned to `default-features = false, features =
   ["cr_lines", "simd"]`. With default features ropey treats
   NEL/VT/FF/LS/PS as line breaks; `similar::TextDiff::from_lines`
   splits on LF/CRLF/bare-CR only. The disagreement caused wrong byte
   ranges for any source containing those Unicode line-break chars.

LSP edge cases:

7. Half-open range filter accepts zero-width edits at the selection
   boundary (a pure insertion at byte == range_start is semantically
   inside the selection). Regression test added.

8. `lsp_position_to_byte` now correctly handles `Position(line ==
   line_count, character == 0)` — the LSP-spec end-of-document
   position — by returning `rope.len_bytes()` instead of clamping to
   the last line's end.

9. `clean_line` normalizes pathological `"...\r\r"` to a single trailing
   `\r` via `trim_end_matches('\r')` instead of `strip_suffix` once, so
   trailing whitespace before the embedded CR is correctly stripped.
   Also switched to `out.trim_end_matches([' ', '\t', '\r']).len()` +
   `truncate` (O(n)) replacing the `chars().next_back()` loop (O(n²)
   worst case).

10. `handle_execute_command` returns a new `ExecuteCommandResponse`
    struct carrying both the JSON response and an optional
    `ShowMessageParams` notification. `handle_align_amounts` now
    surfaces "Cannot align: source has N parse error(s)" via
    `window/showMessage` so VS Code and other clients actually display
    it (executeCommand has no spec-defined way to carry textual
    errors). main_loop dispatcher sends the notification alongside the
    response.

11. `byte_to_lsp_position` and `lsp_position_to_byte` each grew a
    rope-accepting variant (`rope_byte_to_lsp_position`,
    `rope_lsp_position_to_byte`). Hot callers (`minimal_diff_edits`,
    `handle_range_formatting`) build the rope once at the top and
    thread it through, eliminating the O(K·N) per-call rope
    construction the previous review flagged.

12. The `.expect("Delete has old_index")` is gone — the new `DiffOp`
    API exposes byte ranges directly, no Option to unwrap.

doctor / parser:

4, 5, 6, 13. `cmd_roundtrip` rewritten:
  * BOM stripping moved to the parser's lexer
    (`#[logos(skip r"\u{FEFF}")]`) — the doctor no longer needs a
    bespoke strip helper, and the CLI/LSP/FFI/WASM all benefit
    transparently (a BOM'd file is now invisible to every consumer).
  * `Loader::new().with_path_security(true)` confines the include graph
    to the entry file's tree — a malicious ledger with
    `include "/etc/passwd"` can no longer make the doctor read outside
    the user's selection.
  * Errors are split by variant: `LoadError::ParseErrors` aborts;
    infrastructure errors (cycles, glob no-match, IO) are advisory and
    the per-file round-trip continues on files that did load.
  * BOM regression test in the parser pins the new
    transparent-skip behavior (replacing the prior
    test_bom_produces_invalid_token_error).

14. `cmd_roundtrip` gains 5 regression tests
    (`stable_single_file_reports_success`,
    `bom_prefixed_file_does_not_abort`,
    `multi_file_include_graph_walked`,
    `glob_no_match_continues_with_advisory`,
    `parse_errors_abort`) covering the rewrite paths.

FFI:

15. `format_source_to_response` returns a single-line message and
    attaches the full list of errors as a structured `data: { errors:
    [...] }` field on the `RpcError` per JSON-RPC 2.0 — log-friendly
    message text, structured access for clients that want
    per-error inspection. `RpcError::with_data` builder added.

16. `line_byte_range` is gone — `minimal_diff_edits` constructs a
    single rope at the top and threads it through (covered by #11).

Library swaps summary (the "don't reinvent the wheel" theme):
  * Line-based diff: hand-rolled state machine → `similar::DiffOp::ops()`
    (Myers diff over lines, byte-range-indexed).
  * LSP position math: hand-rolled UTF-16 walks → `ropey` (pinned to
    cr_lines feature for line-break parity with similar).
  * Showing messages from executeCommand: hand-rolled "stuff a message
    in JSON" → `lsp_types::ShowMessageParams` notification via main_loop.
  * Structured JSON-RPC error data: hand-rolled multi-line message
    string → JSON-RPC `data` field with structured payload.

Verify suite green: workspace clippy `-D warnings`, fmt, RUSTDOCFLAGS=
-Dwarnings cargo doc, full cargo test --workspace --all-features.

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

* fix(format)!: fourth-round deep-review fixes — 15 findings addressed

Severe correctness:

1. Doctor `cmd_roundtrip` now aborts on every LoadError except
   GlobNoMatch. Previously Io/PathTraversal/Decryption/IncludeCycle/
   GlobError were classified as advisory and the doctor reported
   SUCCESS on whatever files DID load — silently hiding format-
   instability bugs in unread files. GlobNoMatch alone stays advisory
   (intentionally-empty `include "2025/*.bean"` is a real ledger
   pattern). New `path_traversal_blocks_diagnosis` regression test.

2. `handle_range_formatting` snaps `range.end` past a trailing `\n`
   when the user click+shift-end-selects a line. Editors send
   `Position(N, eol_char)` — the byte BEFORE the `\n` — while
   canonical line-replacement edits end at the start of line N+1
   (one byte past). Without the snap every typical EOL selection
   dropped every relevant edit. New
   `end_of_line_selection_keeps_line_replace_edit` test.

3. FFI `handle_load_file` opts into `Loader::with_path_security(true)`,
   matching the doctor's stance. The FFI is the most security-
   sensitive surface (untrusted JSON-RPC callers can pass arbitrary
   paths); leaving include resolution unconstrained was inconsistent.

4. `format_source` preserves CRLF line endings AND a leading UTF-8
   BOM. `render_lines` always emits LF; format_source now rewrites
   the output to match source's line-ending style and re-prepends a
   BOM if present, so Windows / Excel exports round-trip
   byte-stable through `rledger format`. New regression tests:
   `preserves_crlf_line_endings`, `preserves_leading_bom`,
   `preserves_bom_and_crlf_together`.

LSP behavior + UX:

7, 11. Sub-line edit precision restored: `narrow_single_line_replace`
   strips common UTF-8 prefix/suffix from single-line Replace ops,
   so a 1-byte change inside a line emits a 1-byte edit instead of
   a full-line replacement. Editor cursors and inline decorations
   outside the changed bytes are preserved. Asymmetric-terminator
   shapes (pure Insert, pure Delete, tail-of-file) fall through to
   line-granular emit so we never invent or drop a terminator.

7 (sort/balance). `handle_sort_transactions` and
   `handle_show_account_balance` migrate to `ExecuteCommandResponse`
   + `window/showMessage`, matching what `handle_align_amounts`
   already did. The half-migrated convention from the previous
   commit is now consistent across all four commands.

9. `clean_line` reverts to `strip_suffix('\r')` (single CR only) and
   stops trimming `\r` from the body trailing-whitespace pass.
   Surface cleanup must be byte-conservative on parse-error
   documents; a paste-in-progress with `...\r\r\n` no longer gets
   silently normalized while the user is editing.

12. `handle_range_formatting` reverts the empty-range guard to
   `range_end <= range_start → None`. A cursor position (start ==
   end) is no longer treated as a selection that could receive a
   pure-insertion edit. New `empty_range_is_a_noop` test.

13. Doctor hoists `entry.canonicalize()` above the per-file loop and
   threads `entry_parent: Option<&Path>` into `relative_path`. For
   N-file include graphs this drops from N canonicalize syscalls to
   one.

API contracts and quality:

5. New `show_account_balance_unknown_account_surfaces_show_message`
   pins the documented `response=None` + `show_message=Some(...)`
   contract for the no-data path.

6, 14. Lexer comment honesty: the `#[logos(skip)]` directive matches
   BOM anywhere (not just at start) — the comment now says so. Dead
   BOM-error-classification branch in `parser.rs` removed (the lexer
   skip means the parser never sees a BOM as an error token).

8. OpenRPC schema documents the new `parse_error` data shape for
   `format.source` and `format.file`: `{ errors: string[], total:
   number, truncated: boolean }`. Schema-codegen consumers
   (TypeScript, Python types) will surface the structured field.

10. FFI parse-error response caps the `errors` array at 100 entries
    and exposes `{ errors, total, truncated }` so a pathological
    binary fed to `format.file` can't DOS the embedder's transport.

15. New `similar_compact_pass_keeps_replacements_atomic` test pins
    that a line replacement emits ONE DiffOp::Replace (not
    Delete+Insert). A future similar release that changes the
    compact heuristic will surface a clear failure instead of
    silently doubling per-hunk edit counts.

Verify suite green: workspace clippy `-D warnings`, fmt,
`RUSTDOCFLAGS=-Dwarnings cargo doc`, full
`cargo test --workspace --all-features`.

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

* fix(format)!: fifth-round deep-review fixes — 12 findings addressed

Severe correctness:

1. range_formatting EOL snap now handles CRLF. The previous snap only
   matched `b'\n'`; on a Windows-encoded ledger the byte at the visual
   EOL position is `b'\r'`, not `b'\n'`, so every typical EOL
   selection silently dropped its line-replace edit. New
   `crlf_end_of_line_selection_keeps_line_replace_edit` test.

2. range_formatting empty-range guard now runs BEFORE the EOL snap.
   Cursor on an empty line had `range_end_byte == range_start_byte`
   pointing at `\n`; the snap widened it to a 1-byte selection,
   bypassing the guard. New `cursor_on_empty_line_does_not_get_widened`
   regression test.

3. FFI `format.source` / `format.file` parse errors now use code
   -32000 (`BeancountParseError`) — the existing application-level
   variant — instead of -32700 (JSON-RPC-reserved "request envelope
   was unparsable"). Conflating the two causes JSON-RPC client
   libraries to misclassify content errors as transport faults.
   New `RpcError::beancount_parse_error` constructor + OpenRPC
   schema updated.

API contracts and wire-format:

4. CRLF rewrite in `format_source` first collapses any existing
   `\r\n` in the rendered output to `\n` before rewriting every
   `\n` to `\r\n`. Defensive: a future renderer or directive Display
   impl that emits embedded `\r\n` would otherwise become `\r\r\n`.
   The line-ending policy is documented explicitly: CRLF wins on
   mixed-ending files; bare-CR (classic Mac) round-trips as LF.

5. FFI `handle_load_file` adds `path_security: bool` parameter
   (defaults to `true`). Ledgers that legitimately need cross-tree
   includes via `include "../shared/accounts.bean"` can opt out;
   default stays safe-by-default. OpenRPC schema declares the new
   field.

6. Lexer BOM handling moved from blanket `#[logos(skip)]` to a
   `bom_filter` callback that skips only when `lex.span().start ==
   0`. Mid-file BOMs (concatenated files, embedded BOM payloads) are
   now emitted as `Token::Bom`; the parser's error classifier
   surfaces a clear "Invalid token: UTF-8 BOM detected mid-file"
   diagnostic so concatenation mistakes don't pass silently. New
   `test_mid_file_bom_produces_error` regression test.

Behavior and UX:

9. `handle_sort_transactions` no longer emits a window/showMessage
   warning for the `<2 transactions` no-op path. Format-on-save
   hooks no longer pop notifications on every save of a single-entry
   or empty file.

10. `handle_show_account_balance` argument validation now has tests
    pinning the new behavior for missing arg, `null` arg, and
    object-shaped arg — all surface a `window/showMessage` warning
    so misbehaving clients see the diagnostic.

11. Doctor `cmd_roundtrip` includes a note in the abort output when
    `IncludeCycle` is among the blocking errors: "include cycles
    now block the doctor (previously advisory). Break the cycle to
    enable diagnosis." Explicit hint for users hitting the
    behavior change.

Quality:

7, 8. Line-ending policy is fully documented in `format_source`'s
    doc-comment (CRLF wins on mixed; bare CR round-trips as LF
    because the platform is extinct in practice).

12. `minimal_diff_edits` filters out no-op edits (zero-width range
    with empty new_text). similar's compact pass can produce a
    Replace whose slices become byte-identical after the
    common-prefix/suffix strip; pushing those as TextEdits pollutes
    clients that count any returned edit as a dirty-document
    signal.

Verify suite green: workspace clippy `-D warnings`, fmt,
`RUSTDOCFLAGS=-Dwarnings cargo doc`, full
`cargo test --workspace --all-features` (zero failures).

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

* fix(format)!: sixth-round deep-review fixes — 12 findings addressed

Severe correctness bugs (1-3):

1. Parser BOM error classifier uses `error_text.contains('\u{FEFF}')`
   instead of `starts_with`. The previous check only fired when the BOM
   was at byte 0 of the recovered error span, missing mid-line BOMs
   (where `error_text` starts with the directive's date/account). New
   `test_mid_line_bom_produces_error` pins the case the previous
   classifier silently dropped to "unexpected input". The error
   message now mentions "directive body" since the location isn't
   necessarily at start.

2. `Token::Bom`'s Display impl emits the visible placeholder `<BOM>`
   instead of a literal U+FEFF byte sequence. Any future error-rendering
   path that interpolates the token via Display now produces a
   human-readable diagnostic instead of three invisible bytes that
   silently corrupt copy/paste, GitHub renders, and log aggregation.

3. Mid-file Token::Bom is now layout-transparent in the lexer.
   tokenize()'s new explicit `Ok(Token::Bom) =>` arm pushes the token
   without resetting at_line_start or last_newline_end. Subsequent
   content on the same line keeps its indent classification (so a
   concatenated second file's metadata indent isn't swallowed by the
   accident-BOM).

API contract clarity (4-5):

4. `format_source_to_response`'s rustdoc updated to match the
   implementation: returns `beancount_parse_error` RpcError (-32000,
   application-level), NOT `parse_error` (-32700, JSON-RPC reserved
   for malformed transport envelope). Doc-vs-code drift introduced in
   the previous commit is closed.

5. The lone remaining `Response::parse_error` miscategorization
   (jsonrpc/mod.rs's stdin read failure) switched to
   `Response::internal_error`. Failing to read from the transport is
   a server-side fault (-32603 InternalError), not "I received bytes
   that weren't valid JSON" (-32700 ParseError). Per the new docstring
   contract, parse_error is now only emitted at sites that genuinely
   handle malformed JSON envelope bytes.

UX consistency (6):

6. `handle_sort_transactions`'s "already sorted" path now returns
   `ExecuteCommandResponse::none()` to match the silent <2-transactions
   path. Format-on-save hooks chained to `rledger.sortTransactions`
   no longer pop a notification on every save of a sorted ledger.

Test coverage (7-9):

7. Four new tests pin the sort_transactions silent contract:
   `sort_transactions_empty_file_is_silent`,
   `sort_transactions_single_transaction_is_silent`,
   `sort_transactions_already_sorted_is_silent`, and
   `sort_transactions_out_of_order_produces_edit` (positive case).

8. New integration-test crate-level file
   `tests/load_file_path_security.rs` (with `tempfile` as a new
   dev-dependency) drives `ledger.loadFile` end-to-end through
   `process_request`. Three tests pin the
   `path_security: bool` parameter's effect:
   - default rejects cross-tree includes
   - `false` allows them
   - explicit `true` matches the default
   The polarity-flip bug class (loader's `with_path_security(false)`
   semantics silently inverted in a refactor) now surfaces immediately.

9. (covered by the path-security integration tests above, and the
   `minimal_diff_edits` no-op-filter has the existing
   `similar_compact_pass_keeps_replacements_atomic` test plus the
   `sub_line_precision_for_single_byte_change` regression test —
   together they exercise the filter on real inputs.)

Type-system invariant (10):

10. `tokenize()` now has an explicit `Ok(Token::Bom) => ...` arm. The
    "mid-file BOM emits an error" invariant is enforced at the lexer
    layer first (where the token is created and pushed) rather than
    purely via parser-side string sniffing on the recovered error
    span. A future parser refactor that adds a "skip non-significant
    tokens" helper would need to explicitly opt to drop Token::Bom
    (visible at the type-system level), not just absorb it
    accidentally.

Performance (11):

11. CRLF rewrite in `format_source` short-circuits the defensive
    `replace("\r\n", "\n")` pass when `formatted` doesn't contain
    `\r`. `render_lines` never emits CR today, so the universal case
    drops from O(2N) to O(N). The defensive pass still runs for the
    pathological case (a future renderer or directive Display emits
    CRLF directly).

Edge case (12):

12. The bare-CR (no trailing LF) rangeFormatting case is documented as
    out of scope in `format_source`'s docstring already, so no code
    change. The platform is extinct and the LSP layer's silent drop
    is consistent with the formatter's silent normalization. Flagged
    in the docstring for future readers.

Verify suite green: workspace clippy `-D warnings`, fmt,
`RUSTDOCFLAGS=-Dwarnings cargo doc`, full
`cargo test --workspace --all-features` (zero failures).

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

---------

Co-authored-by: Claude Opus 4.7 <[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 20, 2026
- Resolve cli_commands_test.rs conflict: keep both the #11 broken-pipe
  test (from main) and the new #18 empty-extract test.
- Count EXTRACTED transactions right after importer.extract() and bail
  only when that is zero — before duplicate filtering (--existing) or
  --balance augmentation, which could otherwise mask the cause (all
  duplicates, or a lone balance directive).
- Base the "Extracted N transactions" count on Directive::Transaction
  values rather than directives.len().
- Use OsStr-safe .arg(file.path()) in the regression test.

Co-Authored-By: Claude Opus 4.8 <[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