Skip to content

feat(wasm): ADR-0004 Phase 3 -- JSON Schema + Python types (closes #1232) - #1241

Merged
robcohen merged 5 commits into
mainfrom
feat/specta-migration-1232
May 29, 2026
Merged

robcohen merged 5 commits into
mainfrom
feat/specta-migration-1232

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Closes #1232. Adds JSON Schema and Pydantic v2 outputs alongside the existing ts-rs TypeScript generation, completing ADR-0004's single-source-of-truth arc for wire-format DTOs.

What

  • New json-schema feature on rustledger-wasm mirrors ts-export. Pulls in schemars 1.x as a host-only optional dep behind the same cfg(not(target_arch = "wasm32")) guard.
  • Every DTO that has #[derive(ts_rs::TS)] now also has #[derive(schemars::JsonSchema)] (35 new derives, mechanical). schemars respects the existing serde attributes natively (tag = "type", rename, rename_all, skip_serializing_if, untagged enums) — no per-field annotation needed.
  • New export_index_schema test (#[ignore] by default) walks the DTO graph from ParseResult and writes a single draft-2020-12 schema. All other types appear under $defs.
  • scripts/regen-ts-bindings.sh renamed to scripts/regen-bindings.sh and extended with two new phases:
    • Phase 2: run the schema export test, prettier the output to bindings/index.schema.json.
    • Phase 3: pipe the schema through datamodel-code-generator (Pydantic v2 BaseModel, target Python 3.12) into bindings/types.py. Three invocation paths tried in order: datamodel-codegen, pipx run, uvx.
  • CI's ts-bindings-fresh job renamed to bindings-fresh and now diffs all three artifacts (index.d.ts, index.schema.json, types.py). Adds actions/[email protected] with Python 3.12; pipx is preinstalled on ubuntu-latest.
  • should_build path filter now includes scripts/regen-bindings.sh and crates/rustledger-wasm/bindings/** — closes the gap PR fix(wasm): pipe ts-rs output through prettier (closes #1226) #1228 review flagged (script-only changes used to skip the freshness job).

Why

Phase 1 + 2 (#1218 → #1223 → #1225) closed TypeScript drift but two surfaces stayed hand-maintained:

  1. crates/rustledger-ffi-wasi/python/compat.py — same drift class ADR-0004 closed for TS was still live for Python.
  2. No machine-readable schema for external integrators (LLM tool builders, third-party SDKs, MCP server).

This PR closes both.

Alternatives ruled out

Documented in ADR-0004's new Phase 3 section. The short version:

Option Verdict
specta wholesale migration Still 2.0.0-rc.25 after 14 months. specta-jsonschema planned but unpublished. Python listed as "planned" with no crate.
serde-generate (Diem/Aptos) Doesn't support serde(tag = ...) tagged enums. DirectiveJson is exactly that.
pyo3-stub-gen / rustantic Require DTOs as PyClasses.
quicktype TS→Python No Pydantic v2 output (open issue glideapps/quicktype#1474).

There is no ts-rs analogue for Python in May 2026. The hybrid (schemars + datamodel-code-generator) is what the ecosystem actually supports.

Trade-offs

  • TypedValueJson narrowing is applied only on the TS side (hand-tuned override in the regen script). JSON Schema and Python see the wide {type, value} form. Pydantic v2's discriminated-union ergonomics don't map cleanly from a TS literal-union override; maintaining two narrowings wasn't worth it for one type.
  • One additional cargo deny check review: schemars 1.x has a clean license + advisory profile.

Verified locally

  • cargo check -p rustledger-wasm --features json-schema --lib — all 35 DTOs compile.
  • cargo test ... export_index_schema — writes bindings/index.schema.json (669 lines, draft-2020-12). Doc-comments propagated as description fields. LedgerJson / BeancountError renames picked up. anyOf+null for Option<Ledger>. required excludes skip_serializing_if fields.
  • uvx datamodel-code-generator ... — emits 451-line types.py with DirectiveJson as RootModel[Union[DirectiveJson1..12]] and per-variant type: Literal["transaction"|...] discriminators. Pydantic v2 narrowing works.
  • RUSTLEDGER_TS_CHECK=1 ./scripts/regen-bindings.sh — passes.
  • CI: bindings-fresh job stays green
  • CI: existing TS / WASM consumers unaffected

🤖 Generated with Claude Code

)

Adds JSON Schema and Pydantic v2 outputs alongside the existing ts-rs
TypeScript generation, completing ADR-0004's single-source-of-truth
arc for wire-format DTOs.

## What

- New `json-schema` feature on `rustledger-wasm` -- mirrors `ts-export`.
  Pulls in `schemars` 1.x as a host-only optional dep behind the same
  `cfg(not(target_arch = "wasm32"))` guard.
- Every DTO that has `#[derive(ts_rs::TS)]` now also has
  `#[derive(schemars::JsonSchema)]` (35 new derives, mechanical).
  schemars respects the existing serde attributes natively
  (`tag = "type"`, `rename`, `rename_all`, `skip_serializing_if`,
  untagged enums) so no per-field annotation was needed.
- New `export_index_schema` test (`#[ignore]` by default) walks the
  DTO graph from `ParseResult` and writes a single draft-2020-12
  schema. All other types appear under `$defs`.
- `scripts/regen-ts-bindings.sh` renamed to `scripts/regen-bindings.sh`
  and extended with two new phases:
  - Phase 2: run the schema export test, prettier the output to
    `bindings/index.schema.json`.
  - Phase 3: pipe the schema through `datamodel-code-generator`
    (Pydantic v2 BaseModel, target Python 3.12) into
    `bindings/types.py`. Three invocation paths tried in order:
    `datamodel-codegen`, `pipx run`, `uvx`.
- CI's `ts-bindings-fresh` job renamed to `bindings-fresh` and now
  diffs all three artifacts (`index.d.ts`, `index.schema.json`,
  `types.py`). Adds `actions/[email protected]` with Python 3.12;
  `pipx` is preinstalled on ubuntu-latest.
- `should_build` path filter now includes `scripts/regen-bindings.sh`
  and `crates/rustledger-wasm/bindings/**` -- closes the gap that
  PR #1228 review flagged (script-only changes used to skip the
  freshness job).

## Why

Phase 1 + 2 (#1218 -> #1223 -> #1225) closed TypeScript drift but two
surfaces stayed hand-maintained:

1. `crates/rustledger-ffi-wasi/python/compat.py` -- same drift class
   ADR-0004 closed for TS was still live for Python.
2. No machine-readable schema for external integrators (LLM tool
   builders, third-party SDKs, MCP server).

This PR closes both.

## Alternatives ruled out (documented in ADR-0004 Phase 3 section)

- **specta wholesale migration** -- still `2.0.0-rc.25` after 14
  months, sister crates at `0.0.x`. `specta-jsonschema` planned but
  unpublished. Python listed as "planned" with no crate.
- **`serde-generate` (Diem/Aptos)** -- single tool with Python output
  but doesn't support `serde(tag = ...)` tagged enums (our entire
  `DirectiveJson` is one).
- **`pyo3-stub-gen` / `rustantic`** -- both require DTOs as PyClasses,
  not plain serde-deriving structs.
- **`quicktype` TS->Python** -- no Pydantic v2 output path
  (glideapps/quicktype#1474).

There is no ts-rs analogue for Python in May 2026. The hybrid
(`schemars` + `datamodel-code-generator`) is what the ecosystem
actually supports.

## Trade-offs

- `TypedValueJson` narrowing is applied only on the TS side
  (hand-tuned override in the regen script). JSON Schema and Python
  see the wide `{type, value}` form. Pydantic v2's discriminated-union
  ergonomics don't map cleanly from a TS literal-union override;
  maintaining two narrowings wasn't worth it for one type.
- One additional `cargo deny check` review: `schemars` 1.x has a clean
  license + advisory profile; small dep graph.

## Verified locally

- `cargo check -p rustledger-wasm --features json-schema --lib` --
  all 35 DTOs compile with the new derive.
- `cargo test -p rustledger-wasm --features json-schema --lib --
  --include-ignored export_index_schema` -- writes
  `bindings/index.schema.json` (669 lines, draft-2020-12, with
  doc-comments propagated as `description` fields, `LedgerJson` /
  `BeancountError` renames picked up, `anyOf+null` for
  `Option<Ledger>`, `required` excludes `skip_serializing_if` fields).
- `uvx datamodel-code-generator ...` -- emits 451-line `types.py`
  with `DirectiveJson` as `RootModel[Union[DirectiveJson1..12]]` and
  per-variant `type: Literal["transaction"|...]` discriminators.
  Pydantic v2 narrowing works.
- `RUSTLEDGER_TS_CHECK=1 ./scripts/regen-bindings.sh` -- passes after
  initial bootstrap.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Copilot AI review requested due to automatic review settings May 28, 2026 21:02
@robcohen
robcohen requested a review from a team as a code owner May 28, 2026 21:02
@codecov

codecov Bot commented May 28, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR completes ADR-0004 Phase 3 by extending the existing Rust-DTO-driven TypeScript binding generation to also produce a draft-2020-12 JSON Schema and generated Python (Pydantic v2) models, with CI enforcing freshness of all generated artifacts.

Changes:

  • Add a host-only json-schema feature to rustledger-wasm, deriving schemars::JsonSchema for the wire DTOs and adding an ignored schema export test.
  • Replace scripts/regen-ts-bindings.sh with scripts/regen-bindings.sh to regenerate TS, JSON Schema, and Python outputs in one flow.
  • Update CI and path filters to run a renamed bindings-fresh job that diffs all three generated artifacts; add Python 3.12 setup for the Python generation step.

Reviewed changes

Copilot reviewed 11 out of 15 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
supply-chain/imports.lock Adds cargo-vet audit entry for dyn-clone delta.
supply-chain/config.toml Adds cargo-vet exemptions for new transitive deps (schemars stack).
scripts/regen-ts-bindings.sh Removes the old TS-only regen script (superseded).
scripts/regen-bindings.sh New unified regen script: TS bundle + JSON Schema + Python Pydantic models.
docs/reference/adr/0004-ts-types-from-rust-dtos.md Updates ADR-0004 to cover Phase 3 outputs and rationale.
crates/rustledger-wasm/src/types.rs Adds JsonSchema derives and a schema export test module.
crates/rustledger-wasm/src/lib.rs Updates contributor guidance to the new regen script / CI job name.
crates/rustledger-wasm/Cargo.toml Adds json-schema feature and host-only optional schemars dependency.
crates/rustledger-wasm/bindings/types.py Adds generated Pydantic v2 models from the JSON Schema.
crates/rustledger-wasm/bindings/index.schema.json Adds generated draft-2020-12 schema rooted at ParseResult.
crates/rustledger-wasm/bindings/index.d.ts Updates header to reference the new regen script.
Cargo.toml Adds workspace dependency on schemars = "1".
Cargo.lock Locks schemars and its transitive dependencies.
.gitignore Updates ignored ts-rs intermediate output notes to reflect new binding set.
.github/workflows/ci.yml Renames/extends freshness job to include schema + Python outputs and adds Python setup.
Comments suppressed due to low confidence (1)

crates/rustledger-wasm/src/types.rs:41

  • Schemars treats Option<T> fields as non-required properties in JSON Schema, but ledger: Option<Ledger> is intentionally always present on the wire (serialized as null when absent). The generated index.schema.json currently omits ledger from required, which makes the schema/Python models more permissive than the actual output and than the TS bindings. Consider forcing this field to be required in the schema export (or, if you actually want it optional, add skip_serializing_if and update the doc/TS shape accordingly).
pub struct ParseResult {
    /// The parsed ledger (if successful). Emitted as JSON `null` when
    /// parsing failed entirely; no `skip_serializing_if`, so the field
    /// is always present on the wire (TS: `Ledger | null`, not
    /// `ledger?`).
    pub ledger: Option<Ledger>,

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread scripts/regen-bindings.sh Resolved
Comment thread scripts/regen-bindings.sh Resolved
Comment thread crates/rustledger-wasm/src/types.rs Resolved
Comment thread crates/rustledger-wasm/src/types.rs Resolved
Comment thread crates/rustledger-wasm/src/types.rs Resolved
@github-actions

github-actions Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 33.1ms ± 0.5ms 25.4 MB
beancount 869.7ms ± 4.8ms 50.3 MB
Comparison 26.3x faster 2.0x less

vs main branch (2026-05-29)

Metric main this PR Change
Time 36.4ms 33.1ms -9.1% 🟢
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@github-actions

github-actions Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 791
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen and others added 2 commits May 28, 2026 23:28
Fixes all 15 correctness/quality findings from the high-effort review of
PR #1241 (ADR-0004 Phase 3). Schema-level changes regenerate the three
artifacts; the regen script itself gets tightened up.

## Critical

1. **CI: bindings-fresh now blocks merge.** The aggregate `build` gate
   omitted `bindings-fresh` from its `needs:` list, so wire-format
   drift could land on main even with a red bindings-fresh check. Add
   it to needs + the result-check.

2. **Schema `required` arrays match the documented wire contract.**
   `ParseResult.ledger`, `LedgerOptions.title`, `BeancountError.line`,
   `BeancountError.column` are `Option<T>` without
   `skip_serializing_if` -- always present on the wire as null. The
   Rust DTO docstrings have always said so; schemars 1.x defaulted
   Option<T> to non-required, contradicting that. Use
   `schemars(extend("required" = [...]))` (which preserves the
   nullable type, unlike per-field `schemars(required)` which drops
   the null arm).

3. **Schema root broadened from `ParseResult` to a new
   `RustledgerBindings` wrapper** so the schema $defs covers every
   public DTO, not just the parse subgraph. Was 11 of 34 TS types
   covered; now 33 of 34 with 53 Pydantic classes generated.
   `RustledgerBindings` is a codegen-only struct (no Serialize, no
   wasm_bindgen export) -- its sole purpose is to give
   `schema_for!` a single root that reaches the full surface.

4. **Removed `sed '/^WARNING/d'` filter on datamodel-code-generator
   output** -- this was exactly the pattern `feedback_no_error_swallowing.md`
   warns about. Warnings now flow to stderr where they belong.
   Replaced with a final `[ ! -s "$PY_OUTPUT" ]` sanity check so a
   0-exit + empty output still fails the regen.

5. **`cargo test` schema invocation uses `--exact` plus an mtime
   guard.** Was a substring filter that exits 0 on zero matches --
   silently leaving the committed schema stale if `fn
   export_index_schema` is ever renamed. The mtime guard catches
   any non-write.

## Medium

6. **`rm -rf "$RAW_DIR"`** before Phase 1's `cargo test --features
   ts-export` so stale per-type `.ts` files from removed/renamed
   DTOs don't leak into the concatenated bundle.

7. **`export_index_schema` test requires `RUSTLEDGER_REGEN_SCHEMA=1`**
   in addition to `#[ignore]`. A developer running `cargo test
   --include-ignored` no longer silently mutates the checked-in
   schema; the test no-ops with an explanatory message.

8. **EXIT trap covers all sidecar files** (`.new`, `.fmt`, `.err` for
   both TS and schema outputs), not just `$TMP_OUT`. SIGINT or
   mid-script failure no longer leaks files into `bindings/` that
   could be accidentally committed.

9. **Freshness check fixes:**
   - Drop `2>&1` swallow on `git diff` so genuine git errors (not a
     repo, ambiguous ref, etc.) surface instead of being misdiagnosed
     as drift.
   - Add `git ls-files --error-unmatch` per path so a future binding
     added by the regen but not `git add`-ed gets caught instead of
     silently escaping (git diff only reports tracked-file changes).
   - `cd "$REPO_ROOT"` before the loop so absolute paths resolve
     regardless of CWD.

10. **Pinned versions** for both schemars (`Cargo.toml`:
    `schemars = "=1.2.1"`) and datamodel-code-generator (script:
    `DATAMODEL_CODEGEN_VERSION="0.32.0"` propagated to `pipx run
    --spec` and `uvx --from`). The TS phase already pinned
    `prettier@3`; the new tools now match.

## Minor

11. **CHANGELOG.md**: `regen-ts-bindings.sh` -> `regen-bindings.sh`
    reference at line 37.

12. **`BeancountError.line`/`column`**: schema now emits `minimum: 1`
    via `schemars(range(min = 1))`, matching the doc-comment "1-based"
    instead of the u32-default `minimum: 0`.

13. **Dropped `--no-semi=false` from prettier invocation** -- prettier
    3 silently ignored it (warning in every CI log: "Did you mean
    --semi?"). Prettier's default is semis-on; the flag was both
    wrong syntactically and unnecessary.

14. **Import-strip rewritten as awk block-mode** so multi-line `import
    type { ... }` blocks (which ts-rs can emit for long import lists)
    don't leak continuation lines into the bundle as orphan TS syntax.
    The old `sed '/^import type/d'` only handled single-line imports.

## Verified

- `nix develop -- ./scripts/regen-bindings.sh` regenerates all three
  artifacts cleanly.
- `RUSTLEDGER_TS_CHECK=1 ./scripts/regen-bindings.sh` reports "OK: TS
  / JSON Schema / Python bindings match the committed state" --
  regen is idempotent on the committed output.
- Schema $defs count: 11 -> 33 (32% -> ~97% coverage).
- Pydantic class count in types.py: 28 -> 53.
- `ParseResult.required = ["ledger", "errors"]`, ledger property still
  `anyOf: [LedgerJson, null]`. Same shape for LedgerOptions.title and
  BeancountError.line/column.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Addresses the 5 critical findings from the second deep review pass:

1. **FormatResult.formatted required.** The first round's `schemars(extend)`
   sweep caught ParseResult/LedgerOptions/Error but missed FormatResult,
   which has the same documented-always-present-Option pattern
   (Option<String> without skip_serializing_if). Schema now correctly
   reports `required: [formatted, errors]`.

2. **EditorLocation now in $defs + types.py.** RustledgerBindings missed
   it (no other DTO transitively references it), so ts-rs was emitting
   `export type EditorLocation` while the schema and Python had no
   counterpart. Added `editor_location: EditorLocation` to the wrapper.

3. **RustledgerBindings no longer leaks as a public Pydantic class.**
   The wrapper struct exists only to seed `$defs` with every public
   DTO; its own `type: object, properties, required` shape was not
   intended as wire format. The export test now strips the wrapper's
   own root-level keys (`type`, `title`, `properties`, `required`,
   `additionalProperties`, `description`) before writing the schema.
   datamodel-code-generator's residual `class Model(RootModel[Any])`
   placeholder is awk-stripped in the regen script, with an assertion
   to fail loudly if the placeholder shape ever drifts. Net result:
   types.py contains exactly the 53 real public DTO classes, no
   wrapper artifacts.

4. **export_index_schema now panics when RUSTLEDGER_REGEN_SCHEMA is
   unset.** Was previously a silent `return;` that made cargo report
   the test as PASS even though no schema was written -- the eprintln
   advisory was invisible without `--nocapture`. Verified locally:
   `cargo test --include-ignored ... export_index_schema` now reports
   FAILED with a clear panic message.

5. **mtime guard replaced with a stdout sentinel.** The previous
   `[ $mtime_after -le $mtime_before ]` comparison used `stat -c %Y`'s
   whole-second resolution; a warm-cache regen completing in <1s
   could trigger a false-positive failure. The schema export test
   now `println!`s a sentinel (`EXPORT_INDEX_SCHEMA_RAN_OK`) on
   success, and the regen script pipes cargo output through `tee`
   and greps for it. No timing dependency; works on any filesystem.

The latent maintenance hazards from the same review (extend overrides
auto-detect, schemars exact-pin, etc.) are documented but not
addressed here -- they're trade-offs rather than bugs.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Three follow-ups to the PR #1241 review work:

1. extend("required") sync guard. schemars(extend("required" = [...]))
   REPLACES the auto-detected required array rather than merging, so a
   field added to a struct without updating its extend list would
   silently drop out of the schema's required set. Added a test module
   (schema_required_invariants) asserting required == all properties for
   each of the four structs using the pattern (ParseResult,
   LedgerOptions, BeancountError, FormatResult). The tripwire fires if
   any extend list drifts out of sync.

2. clippy::doc_markdown fix on the RustledgerBindings doc comment
   (backticked the type name). Was never linted before because CI
   doesn't build with --features json-schema.

3. Replaced the hardcoded sed Any-strip with a pinned autoflake pass.
   The Model(RootModel[Any]) placeholder strip leaves an orphaned Any
   import (the CodeQL finding); autoflake==2.3.1
   --remove-all-unused-imports is a Python-aware prune rather than a
   line-delete band-aid. autoflake (pure Python) chosen over ruff
   because ruff's prebuilt dynamically-linked binary can't run on NixOS
   via uvx/pipx. Regenerated types.py drops the unused Any import.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@robcohen
robcohen merged commit ec4a351 into main May 29, 2026
40 of 41 checks passed
@robcohen
robcohen deleted the feat/specta-migration-1232 branch May 29, 2026 07:47
robcohen added a commit that referenced this pull request May 30, 2026
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]>
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>
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.

Phase 3 of single-source-of-truth: Python stubs + JSON Schema from Rust DTOs (follow-up to ADR-0004)

3 participants