# WP05 language package ledger

Status: **verified**

## Current language-provider state

| Area | Current contract |
|---|---|
| Typed query state | Semantic-token, completion, and definition results use typed wrappers. Each wrapper preserves its `RequestKey`; token results also preserve the requested optional range, while completion and definition results preserve the requested position. Initial `None` means no accepted result and is distinct from accepted-empty `Some(wrapper)` state. |
| Fresh requests | A successful fresh query clears only its accepted feature lane, and only after request validation and request-ID allocation succeed. Invalid requests and exhausted request-ID allocation preserve both accepted and pending state. |
| Terminal responses | A matching terminal response—valid, invalid, over-budget, or failed—is consumed exactly once. Replays and stale responses cannot mutate state. |
| Token containment | For a ranged semantic-token request, every returned token range must be contained in the requested range in addition to satisfying document/revision and coordinate validation. |
| Retained budget | The retained-response budget is aggregate across result lanes and documents, rather than a separate allowance per lane or document. |
| Array ownership and accounting | Public result getters return detached arrays. Internal retained-unit accounting reads the wrappers' private arrays without copying, and skip-before-evaluate control flow ensures a skipped lane is never evaluated. |
| Definition invalidation | Accepted definitions are invalidated atomically when their exact target `DocumentKey` and revision is successfully replaced, when that target is closed, or when a same-URI reopen retires the old target key. Unrelated results, accepted-empty wrappers, and pending queries survive. Released wrapper units are returned to the aggregate budget. |

These contracts preserve the distinction between absence and an accepted empty response while preventing stale, duplicate, or unaffordable provider traffic from partially changing session state.

## Problem/fix ledger

| Problem | Fix |
|---|---|
| Equal `SessionKey` values let distinct `LanguageSession` objects collide | A private monotonic `SessionInstanceId` is allocated once per session and embedded in each `DocumentKey`; `RequestKey` inherits uniqueness. |
| URI identity permits stale reopen traffic | Opaque `DocumentKey` adds a monotonically unique generation. |
| Requests can outlive edits or supersession | Private per-feature lanes are cleared synchronously and emit cancellation effects. |
| Provider integration can leak mutable state | Pure effects and detached public result arrays; mutable records remain private. |
| Partial synchronization complicates revision correctness | WP05A supports full-text synchronization only. |
| Provider-owned arrays could mutate accepted result values | Result constructors copy array inputs and public getters return detached arrays. Internal accounting uses private arrays zero-copy without weakening the public ownership boundary. |
| Unbounded provider payloads can exhaust editor resources | Positive configurable provider, parser/validation, and retained-response limits are implemented and enforced with explicit failures; transport byte/framing limits remain mandatory for future host adapters. |
| Core document revisions could overflow and corrupt stale-revision ordering or mutate history partially | A checked 2147483647 ceiling rejects valid nonempty edits and nonempty undo/redo atomically; stale/validation errors and empty operations retain precedence. |
| Fallible session operations could regress into partial mutation on exhausted identities, invalid UTF-16 queries, or revision failures | Atomicity coverage verifies generation/request exhaustion, UTF-16 position/range validation, and replacement revision validation. |
| Repeated provider ranges caused O(results*document) coordinate scans | A sparse line index makes containment O(log supplementary-scalars-in-line), with rebuild O(document) on edit and storage O(lines+supplementary-scalars). |
| Definitions could retain references to replaced or retired target snapshots | Exact target-key/revision invalidation is coupled atomically to successful replacement, close, and same-URI retirement, with retained units released. |

## Development scope and product safety

Development effort is intentionally unbounded by lines of code, planner turns, or elapsed time. This policy does **not** remove positive parser, provider, transport, or resource limits for untrusted input. Safety bounds remain product requirements and must not be traded away to simplify development or testing.

## Verification evidence

The current full-repository evidence is **122 wasm**, **122 wasm-gc**, **123 JavaScript**, and **122 native** tests, all passing. The all-target check with warning list `+73` also passed before final interface regeneration.

The exact targeted language-package run is **41/41 tests on each of wasm, wasm-gc, JavaScript, and native**, verified directly rather than inferred from the repository totals.

Core revision-exhaustion coverage includes maximum/no-op behavior, atomic apply/undo/redo rejection, preserved redo state, maximum-minus-one success, and stale/invalid precedence.

## MoonCode trial failures and recoveries (commands 108–136)

These entries describe controller/runtime trial behavior unless a repository defect is explicitly identified. Intermediate compile/test errors came from partial or faulty trial edits; they are not the final repository status.

| Command | Failure / recovery chronology |
|---:|---|
| 108 | Partial typed migration left 75 compile errors; the run ended at the eight-planner-step cap. |
| 109 | Partial repair reduced the count to 69. |
| 110 | Read paths from the wrong root; produced no useful edit. |
| 111 | Added request methods and reduced errors to 63. |
| 112 | Broad snapshot/budget edits introduced parser and test errors, leaving roughly 70. |
| 113 | Repaired syntax/results and reduced errors to 62. |
| 114 | Repaired getter collisions and reduced errors to 55. |
| 115 | Partially migrated acceptance, but bad accessors and incomplete stores left 56 errors. |
| 116 | `old_string` mismatch meant no effective edit. |
| 117 | Added `Position`/`Range` fields and fixed a test typo; 45 errors remained. |
| 118 | Partially added the token wrapper/range contract; 44 remained. |
| 119 | Partially added completion/definition wrappers; 42 remained. |
| 120 | Repaired typed failed-pending handling; product source was green, while old tests still needed migration. |
| 121 | Adapted existing tests; check became green, then runtime testing exposed a token-getter alias leak. |
| 122 | Restored detached-copy behavior in `SemanticTokenResult::tokens()`; the full existing suite passed. |
| 123 | An adversarial test hallucinated APIs and produced 29 compile errors; product source was untouched. |
| 124 | An over-broad replacement inserted erroneous unwraps and corrupted parentheses, causing 63 errors; recovery used a rewrite. |
| 125 | The clean rewrite compiled; one budget assertion failed, and the final line edit landed after the controller reported the eight-step failure. |
| 126 | Corrected token/completion strings but incorrectly assumed an empty completion ID was valid; 36/37 passed. |
| 127 | Corrected the minimum valid budget to three units with a one-character ID; 37/37 passed. |
| 128 | Added zero-copy internal retained charging and skip-before-evaluate behavior; all four language targets passed. |
| 129 | The definition-invalidation product fix landed, but verification hit the eight-step controller ceiling; subsequent controller verification passed. |
| 130 | Initial invalidation tests hallucinated `Location`/replace/close APIs; they were repaired before the step ceiling and reached 39/39. |
| 131 | Added failure/budget tests; a bad warning argument and two close unwraps remained. |
| 132 | Removed the close unwraps; 41/41 language tests and the full suite passed. |
| 133 | Wrote the durable WP05 ledger/progress update; review found one unsupported transport-enforcement wording and omission of the directly verified JavaScript targeted count. |
| 134 | Corrected the transport claim to a host-adapter requirement, not implemented transport, and recorded 41/41 on all four backends. |
| 135 | The runtime exposed no repository tools, returned finish-only, and made no change. |
| 136 | A fresh-daemon retry removed the recurring generated workspace-interface EOF blank; `git diff --check` passed. |

Recurring causes were the eight-planner-step cap, stale or hallucinated API assumptions, an invalid `moon_cmd fmt` target, and over-broad mechanical rewrites. Reliable recoveries were a fresh daemon, narrow commands, exact compiler/test diagnostics, line-local repairs, and full target reruns. Controller ceilings, command-shape mistakes, and daemon/runtime behavior are operational failures; only reproducible source/test behavior should be classified as a repository defect.

## Current limitations

WP05 is an in-memory language-provider orchestration layer with full-text synchronization. It does not claim a user interface, host LSP transport, persistence, a syntax parser, or production latency benchmarks. Host adapters must supply transport and I/O while respecting the identity, validation, terminal-consumption, and resource contracts above.

See the broader project status in [`PRODUCTION_PROGRESS.md`](PRODUCTION_PROGRESS.md) and the preceding workspace identity contract in [`WP04_IDENTITY_CONTRACTS.md`](WP04_IDENTITY_CONTRACTS.md).

## Provenance

Independently authored. Zed commit `3cee61d75f582e345faa43e2291e371534f223dd` (GPL) was consulted concept-only. OpenSeek commit `d38d4633ab81d0a98d50c5058174c5bfb7b51442` (Apache) was used for architecture study. No source or tests were copied.
