{
  "kind": "static-proposals-not-release-evidence",
  "sourceSha": "b07da2b8762d3398683f3f2c481ee65a8caedc41",
  "areas": [
    {
      "name": "runtime",
      "indexedFiles": 698,
      "physicalLines": 161428,
      "focusedFiles": 24,
      "report": "# Runtime canonicalization review\n\nSource: `b07da2b8762d3398683f3f2c481ee65a8caedc41`.\n\nScope: all 698 assigned immutable TS blobs, 161,428 lines; 384 production files and 314 test/fixture files. Every blob was read mechanically for exact hash, imports, repeated 20-line windows, and tokenized TypeScript function bodies. No exact duplicate files. Semantic review covered sections of 24 assigned files plus 10 external boundary files, recorded in `runtime-coverage.json`; this is **not** a claim that 698 files were semantically audited. No tests or heavy stands ran; no tracked file changed.\n\n## R1. Remove QA ownership from the Runtime frame and public entrypoint\n\n**Recommended first architectural implementation.** Keep actual operational tracing; remove diagnostic rendering from the financial entrypoint.\n\n- `core/runtime/frame/apply.ts:2-5,66-73` and `core/runtime/frame/lifecycle/prepare.ts:5-8,76-79` call `summarizeRuntimeAccountCausality` and a trivial trace-length predicate from `core/qa/account-causal-trace.ts`. `process-profile.ts:1,56-59` imports its type. That 96-line module is pure and describes operational Account/Entity envelope tracing, so the canonical owner is `core/runtime/observability/account-causal-trace.ts`. Move once; remove the old path, no forwarding alias. Update the three Runtime imports, `core/scenarios/market/swap.ts:46-50`, and `core/__tests__/account/tooling/account-causal-trace.test.ts:2`.\n- `core/runtime/frame/lifecycle/start.ts:21-30` mixes pre-intake frame stopping with a dynamic import of the **465-line** `core/qa/runtime-ascii.ts` and five console log calls. Preserve the same `FRAME_STEP` rejection before ingress. Move formatting into the existing caller that sets the breakpoint: `core/scenarios/payments/lock-ahb.ts:1518,1527-1532`, around `await lockAhb(env)`. That scenario already imports `formatRuntime` at line24. Re-throw the original error; do not convert stop/failure to successful completion.\n- `core/api/public/runtime-public.ts:154` also re-exports `formatRuntime`, `formatEntity`, and `formatAccount`. Remove this unused production re-export, or the formatter remains reachable despite the frame change. Exact-symbol repository search found all real callers importing `qa/runtime-ascii` directly; no React, Svelte, or native caller consumes these exports.\n- Update `core/__tests__/jurisdiction/adapter/jadapter-rpc-startup-logging.test.ts:85-92`, which currently demands the five frame-start console lines. It should assert the frame module has no console renderer; preserve scenario diagnostics separately.\n\nAdversarial preservation: the stop still precedes intake, timestamp advancement, and WAL write; ordinary Runtime execution must have identical state/ordered outputs with tracing on/off. Causal traces must still retain both the ACK and proposal from an `ack_frame`, including swap resolution amounts/ids. Moving the pure helper does not change any financial state.\n\nMeasured reduction: 465 formatter source lines can leave the Runtime entrypoint dependency closure once **both** edges are removed; preserve the formatter itself for scenarios. Moving the 96-line trace module is ownership correction, **zero source reduction**. Net repository LOC reduction is not yet measured and must not be claimed from a move.\n\nSmallest existing commands:\n\n```sh\nbun test core/__tests__/account/tooling/account-causal-trace.test.ts core/__tests__/jurisdiction/adapter/jadapter-rpc-startup-logging.test.ts core/__tests__/api/runtime-adapter/radapter-command-frontier.test.ts core/__tests__/runtime/commit/runtime-frame-atomicity.test.ts\n```\n\nAdd the narrow real-runtime stop regression only if no existing semantic test covers it: at height N, breakpoint N rejects before applying the next queued input; height, queued input, and durable head stay unchanged. Then locked lock-ahb and browser runtime build, because the public browser surface changes.\n\n## R2. Retire QA HTTP control from both production servers\n\n- `core/orchestrator/orchestrator.ts:39,1846-1847` imports/calls `maybeHandleQaRequest`.\n- `core/api/server/index.ts:36,553` is the second production exposure (cross-scope boundary; coordinate with API owner).\n- `core/qa/api.ts:1-41,887-920` brings `bun:sqlite`, filesystem access, child-process spawning, history/report code, and HLT launch/restart control into both servers. The handler guards `/api/qa/` and authenticates before its reconciliation; this review does **not** assert an authentication bypass.\n\nCanonical owner: offline QA tooling. Remove the two production ingress imports/calls, preserving ordinary health, operator controls, wallet, and discovery handlers. Do not delete QA reports/tests merely to lower LOC. If a dedicated developer QA server is still wanted, its independent process should own this capability; adding it is not necessary for the release.\n\nMeasured audit surface: direct QA API file is 1,412 lines plus transitive reporting/HLT imports; do not add a transitive total without a reachability measurement. Repo deletion is only two imports/two call blocks; value is excluding subprocess/QA DB capabilities from the production server graph.\n\nPreservation checks: production `/api/qa/*` is absent under both server entrypoints; `/api/health`, `/api/hubs`, faucet and React account operations still work. Existing `prod-startup-wiring` checks and locked local production wallet smoke are the relevant boundaries. Existing direct QA handler tests can remain if the offline API remains supported.\n\n## R3. Remove the frozen engine selector from TS launch authority\n\nThe active TS launcher still has a second selectable financial engine:\n\n- `core/orchestrator/process/hub-engine-plan.ts:28-42` accepts `XLN_HLT_ENGINE=rust` and returns Rust for H1.\n- `core/orchestrator/process/spawn/hub.ts:66-143,177-183` writes Rust secrets/routes/genesis and spawns the native process.\n- `core/orchestrator/process/hub-runtime-env.ts:99-110` translates a per-hub flag into `XLN_RSCORE_AUTHORITY=1` plus worker/record options.\n- `core/support/process/child-secrets.ts:36-47` starts with **all parent environment keys**. Deleting just the twelve-line translation leaves raw `XLN_RSCORE_AUTHORITY` inherited.\n- `core/rscore/authority-driver.ts:91-101` still enables that authority from the raw flag. This is not dead configuration, even if default launch is TS.\n- `core/__tests__/operations/health/prod-startup-wiring-part-2.test.ts:114-145` currently asserts the retired Rust env forwarding.\n\nCanonical owner: TS process launch with explicit rejection of retired selectors, according to the owner release scope. Delete/retire the TS Rust launch branch and its callers atomically; preserve native Rust files/tag. Do not silently ignore an operator request for another engine. Reject retired engine/authority selectors before creating child processes or secret files. Coordinate with the core/rscore review: resident **TS** worker authority currently lives under that directory, so bulk deletion of every rscore import would break the supported engine and its WAL boundary.\n\nMeasured visible source: the per-hub forwarding block is12 lines, and `buildRustHubPeerRoutes` plus `buildRustHubInvocation` spans78 lines. Broader removal estimate is not asserted until import/call closure is validated.\n\nSmallest checks: `bun test core/__tests__/operations/health/prod-startup-wiring-part-2.test.ts` with updated assertion for loud retired selection, existing hub-engine-plan tests, TS W1/W4 recovery equality, then production smoke and `bun run check`. This is larger than R1/R4 and not a blind cleanup.\n\n## R4. One outbox deduplication implementation\n\n`core/runtime/delivery/plan.ts:26-51` and `core/runtime/delivery/pending.ts:387-409` repeat the same ordered algorithm: split Account deliveries, derive route key, copy the first accepted item, merge later evidence, invalidate prepared cache, preserve the Map's first slot.\n\nCanonical owner: the existing `pending.ts` module, where `mergeRoutedEntityOutput` and output identity semantics already live. Export the pure dedupe operation from there; `plan.ts` imports it. Keep the capacity warning at `pending.ts:410-420` in the pending-output wrapper only, because a mixed local/remote plan is not the pending network queue.\n\nBoth copies also maintain `mutableMergeTargets` and an unreachable fallback clone branch: every value inserted into `deduped` is immediately added to that set. Remove the set and merge into the already private copy. Preserve `graph.adopt`, invalidation, immutable caller objects, ACK/proposal evidence selection, and first-position ordering. Never sort financial outputs.\n\nCallers: `delivery/dispatch.ts:511-515`, `delivery/recovery-output.ts:41-46,65`, `frame/dispatch.ts:129`, plus public routing tests. Estimated net deletion:35\u201345 lines, pending actual patch; no new module required. This is the smallest safe implementation immediately.\n\n```sh\nbun test core/__tests__/runtime/transport/runtime-output-routing.test.ts core/__tests__/runtime/transport/prepared-output-graph.test.ts core/__tests__/storage/recovery/portable/cross-j-output-replay-route.test.ts\n```\n\n## R5. Consolidate identical audit fixture bodies, not assertions\n\nSix `core/__tests__/testing/audit/audit-failfast-regressions-part-*.test.ts` files repeat setup helpers. A tokenized AST scan found seven body-identical helper groups containing **447 redundant source lines before import overhead**:\n\n- `makeProposalAccount`: part1:374-420, part5:315-361, part6:269-315 (94 duplicate lines).\n- `makeEntityState`: part1:553-575, part3:450-472, part4:498-520, part6:388-410 (69).\n- `buildQuorumAuthorizedFrameTxs`: part1:496-526, part3:363-393, part4:436-466 (62).\n- `makeSingleSignerConfig` and `makeSingleSignerConfigFor`:12 lines each, each copied across all six parts (60+60).\n- `ensureCanonicalCommandBoardAuthority`: part1:468-494, part3:335-361, part4:408-434 (54).\n- `prepareJEventInput`: part1:528-551, part3:395-418, part5:410-433 (48).\n\nCanonical owner: an existing test fixture/helper location, with the same per-call fresh maps, keys and environment. Do not put test fixtures into runtime imports, deduplicate test assertions, share mutable globals, or replace real signed proofs with mocks. The `attachSigningReplica` helpers are not all identical; separate groups exist, so do not collapse them mechanically. The earliest safe subset is the two board-config builders; `makeSingleSignerConfig()` can call the parameterized builder with `'1'`.\n\nThis lowers **test audit burden**, not production financial-path LOC. Preserve every named test and assertion. Run all six audit regression files once after fixture consolidation; not before a working production artifact.\n\n## Rejected shortcuts\n\n- Do not replace recovery `normalizeRuntimeId` blindly with P2P normalization: the recovery helper explicitly checksum-validates with ethers `getAddress`; boundary semantics need a vector comparison first.\n- Do not remove every `core/rscore` dependency by its name: TS resident workers and exact checkpoint/WAL glue currently use it.\n- Do not treat a moved file, a green build, or a mechanically indexed file as semantic audit/deletion evidence.\n- Do not unify Runtime/Entity/Account reducers or full replacement DB views with overlay DB views; their authority and recovery contracts differ."
    },
    {
      "name": "entity",
      "indexedFiles": 357,
      "physicalLines": 78470,
      "focusedFiles": 34,
      "report": "# Entity and books canonicalization review\n\nSource: `b07da2b8762d3398683f3f2c481ee65a8caedc41`.\nRead-only review; no tracked edits and no tests run by this reviewer.\n\n## Coverage and limits\n\n- Indexed and mechanically scanned **357/357 assigned files**, **78,470 lines**: 245 production files / 51,507 lines and 112 test files / 26,963 lines.\n- Every assigned source was loaded from `git show <source>:<path>`, parsed using TypeScript AST, indexed for imports, retirement/compatibility flags, and exact token-normalized function bodies. 3,645 function bodies of at least 40 source characters yielded 78 duplicate groups, 33 with at least two production occurrences. These are candidates, not 33 confirmed design defects.\n- The accompanying coverage JSON distinguishes full-file reading from selected-range review. Mechanical coverage is **not semantic coverage of all 78,470 lines**. No assurance of complete correctness or release readiness is claimed.\n- Whole-repository pinned `git grep` was used to confirm enabling callers for the debug matcher and all callers for book hashes. A broad repeated-pattern export grep was stopped and replaced by a cheap lexical index; that exploratory current-tree index found no production function with just its declaration and is not accepted as immutable evidence.\n\n## 1. Remove the test-only alternate orderbook execution mode\n\n**Priority: first meaningful feature-path deletion.** `debugRebuildProjectionOnly` is an alternate financial behavior, not just logging. It forces post-only orders, suppresses Account resolutions, skips accepted USD price updates, and suppresses publishing book updates. The sole enabling callers in tracked non-archive sources at this SHA are two tests:\n\n- `core/__tests__/payments/orderbook/orderbook-matching-part-1b.test.ts:839\u2013905`, call at 899.\n- `core/__tests__/payments/orderbook/orderbook-matching-part-2.test.ts:345\u2013353`, call at 346.\n\nProduction spread:\n\n- `core/entity/tx/handlers/account/orderbook/index.ts:111\u2013137,159,173,181`: mode, rejects collection/dedup callback, result field.\n- `.../helpers.ts:54`, `.../cross/types.ts:31`, `.../same/pass.ts:39\u201355`: configuration and callback plumbing.\n- `.../same/admission.ts:54\u201365,75\u201386,111\u2013114,170`: alternate business rejection path.\n- `.../same/command.ts:31\u201334,75`: suppressed cancellation / forced post-only.\n- `.../same/offer.ts:36\u201338`: suppressed book publication.\n- `.../same/pass.ts:210\u2013213,251\u2013258`: swallowed pair failure and suppressed sweep.\n- `.../same/results.ts:142\u2013145,183\u2013192`: suppressed cancel, fee settlement and reference-price update.\n- `.../cross/offer.ts:67,224\u2013233`: forced post-only and suppressed progress.\n\n**Retain:** normal `processOrderbookSwaps` -> same/cross materialization -> the existing `applyCommand` / `matchPricePages` matcher -> canonical Account settlement. Preserve real caller effects and same-pass maker suspension. Delete the optional mode, callback/result fields, and branches atomically. Do not replace it with another test-only implementation. If an isolated preview is actually needed, use an isolated candidate and the exact normal transition; do not silently change financial behavior to make a preview.\n\n**Estimated reduction:** 80\u2013130 production lines plus approximately 140\u2013160 obsolete mode-specific test lines. Not a measured patch delta. Replace those tests with assertions that canonical preview/rejection does not mutate the input, preserving useful invariants.\n\n**Minimum verification:** `bun test core/__tests__/payments/orderbook/orderbook-matching-part-1.test.ts core/__tests__/payments/orderbook/orderbook-matching-part-1b.test.ts core/__tests__/payments/orderbook/orderbook-matching-part-2.test.ts core/__tests__/payments/orderbook/orderbook-lifecycle.test.ts`, then same-J swap scenario under the machine lock and `bun run check`.\n\n## 2. Collapse exactly identical unexpected-key validation\n\nFour token-identical 13-line bodies:\n\n- `core/entity/consensus/frame/validation.ts:39\u201351`.\n- `core/entity/consensus/j-prefix/prefix-validation.ts:20\u201332`.\n- `core/entity/replica/replica-submit-validation.ts:19\u201331`.\n- `core/entity/scheduler/validation.ts:32\u201344`.\n\n**Retain:** one `rejectUnexpectedKeys` in existing `core/protocol/boundary/validation-primitives.ts`, already imported by all four callers. Delete the four local bodies and import the canonical function. Keep `FinancialDataCorruptionError`, exact message, key enumeration order and `readonly string[]` allowance. This is a shared primitive, not a shared Runtime/Entity/Account reducer. Do not fold structurally similar validators that intentionally reject with different typed dispositions into it.\n\n**Measured duplicate body:** 52 lines -> one 13-line body. Estimated net reduction after imports: ~35 lines. Human audit benefit: one exact key-policy implementation instead of four.\n\n**Minimum verification:** `bun test core/__tests__/entity/boundaries/entity-frame-tx-boundary.test.ts core/__tests__/jurisdiction/history/j-prefix-consensus.test.ts core/__tests__/jurisdiction/submission/j-submit-receipt-evidence.test.ts`, plus relevant hydration/scheduler suite in final checks. Add only a small error-preservation vector if the existing tests do not exercise unknown keys.\n\n## 3. Retire the second, incomplete book hash and the cache-invalidation alias\n\n- `core/swapbook/core.ts:554\u2013559` `computeBookHash` hashes eventHash, trade counters and best prices. It does not directly cover all committed liquidity. Its callers are only `orderbook-lifecycle.test.ts:113,121` and the two benchmark scripts `core/scripts/operations/benchmark/bench-swap-orderbook-tps.ts:89` / `bench-swap-scenarios-tps.ts:133,316`, plus a re-export at `core/swapbook/types.ts:26`.\n- The real owner is `core/swapbook/commitment.ts:40\u201360` `computeBookCommitmentHash`: both radix roots and financial book metadata. Switch diagnostic callers to that function, delete the weak hash and re-export. The benchmark's emitted hash changes; historical hashes are not interchangeable and should retain their old source SHA.\n- `commitment.ts:62\u201368` exposes two functions with the identical `delete book.commitmentHash` operation (`invalidateBookCommitment` and `clearBookCommitmentCache`). Keep the former used by production mutations; update verification/tests and delete the latter.\n\n**Measured removable implementations:** 6 + 3 lines, plus re-export and whitespace. This is small but removes two competing meanings of \u201cbook hash\u201d and one redundant API. Do not substitute a diagnostic hash for the canonical commitment to save time.\n\n**Minimum verification:** `bun test core/__tests__/payments/orderbook/orderbook-lifecycle.test.ts core/__tests__/payments/orderbook/orderbook-incremental-commitment.test.ts`. Do not launch TPS to validate a hash rename; check benchmark types/build and run proper performance measurement only for a performance claim.\n\n## 4. Remove Rust authority hooks from Entity production as one coordinated TS cutover\n\nFive assigned production files import `core/rscore`:\n\n- `core/entity/consensus/frame/application.ts:93\u201396`.\n- `core/entity/consensus/state-root.ts:7`.\n- `core/entity/state/persistent-account-map.ts:1`.\n- `core/entity/tx/handlers/account/index.ts:35\u201338`.\n- `core/entity/tx/handlers/account/lifecycle/open-account.ts:32\u201335`.\n\nThis is not solved by moving imports to a new wrapper. Real alternate selection paths remain in `application.ts:577\u2013602,721\u2013727`, authority begin/outbound stages at `1329\u20131357,1490\u20131499,1594\u20131606`, prepared inbound genesis at `handlers/account/index.ts:161\u2013183`, plus create recording at `index.ts:230\u2013241` and `open-account.ts:170\u2013178`.\n\n**Retain:** TS Account transitions, canonical worklist, normal genesis path, and actual board-handover authorization. **Do not delete `authorityTransitionOnly` wholesale:** it names governance handover behavior as well as being adjacent to retired engine callbacks. Coordinate deletion with the Runtime/Account agent so types, optional callbacks, leaf-registry invalidation and engine caches disappear atomically. Rust source remains frozen.\n\n**Size:** no reliable whole-cutover LOC estimate from this scope; at least the listed branches disappear, and the transitive production import closure becomes smaller. Count actual removal after the coordinated diff rather than counting all frozen Rust as deleted product code.\n\n**Verification:** TS inline/W1/W4 roots and ordered outputs on the same immutable WAL; canonical open Account and ACK/proposal tests; same-J payment/swap L2; build graph proves zero imports of `core/rscore` from production entries. Preserve the freeze tag and parked changes.\n\n## False positives and boundaries to preserve\n\n- **Same-J and cross-J are not two matchers.** `swapbook/core.ts:272\u2013353` already contains their shared matcher. Adapters differ in authority, pricing and settlement. Cross-J returns price improvement and projects cumulative uint16 claims; same-J creates Account `swap_resolve` and enforces paired fee authorization. Combining adapters by cosmetic symmetry risks financial changes.\n- **Paybook / swapbook / lendbook must not share a generic lifecycle reducer.** Paybook tracks hashlock secrets and deadlines, swapbook price-time priority and bilateral fill authorization, lendbook signed credit products. Shared Account admission is already the right boundary. Lending stays frozen; signed legacy claims remain exit evidence.\n- **The four Map-like implementations are not proven interchangeable.** `BookBranchMap` is a RAM locator with `commitment:false` and O(1) size, while `EntityCollectionCandidateMap` owns committed radix leaves, freeze/clone behavior and sealing. Their duplicated `forEach`/`getOrInsert` are not evidence that one class can replace the other.\n- **Two payment termination helpers are phase-specific.** `programPaymentTermination` emits Book intents during Stage 2; `terminatePayment` handles Stage-3 proposal rejection after the Book fold. Removing one without preserving staging/order would be wrong.\n- **Normalization duplicates have different contracts.** Some trim, some only lowercase, some validate exact canonical representation. Do not mechanically replace them with one permissive `String(value || '')` helper.\n\n## Method adjustment for the next 30-minute review\n\nExact-clone ranking mostly found harmless Map interface methods and normalization one-liners. The useful next step was tracing optional financial branch enabling callers: it exposed the unused debug matcher mode. Prioritize (1) alternate financial switches with no live callers, (2) disconnected engine import closure, (3) duplicate hashes/validation policy; use token clones only to find candidates. For each accepted deletion, report removed production branches, actual line delta, and retained invariant tests. Do not turn the inventory or a subjective score into another release gate."
    },
    {
      "name": "account",
      "indexedFiles": 301,
      "physicalLines": 49244,
      "focusedFiles": 43,
      "report": "# Account/protocol canonicalization review\n\nSource: `b07da2b8762d3398683f3f2c481ee65a8caedc41`. Read-only; no source edits or test executions. Parent supplied last-green evidence: `bun run check` 38 source gates and reserve funding E2E 1/1 before checkpoint. The mechanical inventory is not a claim that all semantics were audited.\n\n## Coverage and method\n\n- All 301 assigned files (49,244 manifest lines) were read from the immutable Git object, hashed, and parsed with the TypeScript AST: 3,117 function nodes, 1,088 named export declarations. Import/export surfaces, legacy/fallback markers, normalized function-body matches and ten-line repeated blocks were indexed. See `account-scan.json` and `account-coverage.json`.\n- Candidate implementations and their financial/authority dependencies were deep-read; exact callers were checked with pinned `git grep`. Full-file and partial inspections are recorded separately. A repository-wide many-pattern export-reference query was terminated at its wall budget; switching to fixed-string search did not improve it, so I stopped broad reference scans and used targeted caller searches. No dead-export assertion relies on that incomplete scan.\n- Do not spend human audit time on mechanically equal copies, but do not delete independent test oracles, authority-specific validation, or separate R/E/A machines. Production-path LOC and total repository LOC are different metrics.\n\n## Five concrete reductions\n\n### 1. Delete the Hanko Buffer compatibility shim (recommended first implementation)\n\n`core/hanko/signing.ts:62-82` defines a 20-line function plus a comment, accepting string/Uint8Array/number[] and multiple encodings. Its only three callers are `parseQuorumDigest` at 433, `parseQuorumSignature` at 444, and its private copy at 464. The first two already validate exact 32-byte / 65-byte hex before decoding; the third only copies those bytes.\n\nUse the existing `core/support/bytes/hex-bytes.ts:8` `hexToBytes` with the full prefixed string, and `bytes.slice()` for the private recovery-byte copy. Change the local Buffer annotations at 429, 437, 440 and 507 to Uint8Array. `core/hanko/codec.ts:289` already accepts `readonly Uint8Array[]`. Remove the shim completely rather than retaining a forwarding alias.\n\nMeasured existing shim: 20 function lines, plus one comment. Estimated net deletion: about 20 lines after the import. This removes unused text-encoding and environment-selection branches and three unchecked Buffer casts. No wire bytes, signer authorization, board ordering, low-s policy, or nonce semantics should change. Keep all current signature checks and preserve a private copy before setting recovery to 27/28.\n\nSmallest check: `bun test core/__tests__/security/hanko/hanko-quorum-canonical.test.ts`. That file checks arrival-order independence, duplicate/unknown signers, malformed/high-s/recovery signatures, exact board binding and bigint weights. Related: canonical-envelope, Hanko ABI, short-form tests, `bun run build`, and browser-runtime verification before completion. No performance claim.\n\n### 2. One lexicographic byte comparator for production codecs and Patricia ordering\n\nFour local eight-line comparators implement the same ordering on Uint8Array:\n\n- `core/account/commitment/account-state-value.ts:29`; callers at 130/137 (oracle) and 292/302 (writer).\n- `core/protocol/serialization/binary-codec.ts:185`; callers at 293/300/309/412.\n- `core/protocol/state/persistent-radix-value-ops.ts:71`; caller at 265.\n- `core/protocol/state/radix-overlay.ts:53`; callers at 120/290.\n\nThe first pair is source-identical, as is the second pair. Between pairs, `.byteLength` versus `.length` and `Number(byte)` versus `byte ?? 0` are equivalent for validated Uint8Array indices. Put one browser-safe leaf helper beside existing byte utilities and import it directly; do not pull a higher-level serialization barrel into Patricia code. Measured duplicate bodies: 32 lines, reducible to 8; estimated net saving about 20 lines including four imports. An additional comparator in `core/storage/schema/rscore/checkpoint.ts:310` was located but is outside this assigned ownership; coordinate with its reviewer before touching it.\n\nRisk: ordering is hash/byte critical. Preserve empty/prefix/high-bit/subarray ordering exactly. Do not use locale/string conversion, sort financial outputs, or conflate equality and constant-time secret comparison. Existing checks: `account-state-root.test.ts`, `protocol/state/persistent-radix-value-map.test.ts`, `protocol/state/radix-overlay.test.ts`, `protocol/serialization/binary-codec-bytes-form.test.ts`, and frame-hash goldens. Add a small byte-order vector only if these miss empty/prefix/nonzero-offset views.\n\n### 3. Move the independent Account RLP oracle out of the production module\n\n`core/account/commitment/account-state-value.ts:11-27,78-83,115-151` contains the recursive reference encoder beside the production single-pass writer. `core/account/commitment/state-root.ts:31` re-exports both. Callers of `encodeAccountStateValueOracle` are only `core/__tests__/account/state/account-state-root.test.ts:7,68` and `proofs/fuzz/enc-diff/run.ts:18,164`.\n\nKeep `encodeAccountStateValue` and its byte contract canonical. Put the reference projection/encoder under the existing testing/proof support owner, then import it directly from those two consumers. Do not delete the differential oracle or point it at the implementation under test. The exclusive reference function bodies total 55 lines plus the RlpNode type; moving them reduces production audit surface by at least 56 measured lines, not necessarily repository LOC. `encodeRlpPayload`, `rlpLengthBytes` and `concatBytes` are also used by the production text encoder and must not be blindly moved/deleted. An independently owned ethers RLP encoder can avoid exposing production helpers, but its vectors must prove the exact existing oracle bytes.\n\nSmallest checks: existing account-state-root reference fixtures, followed by `proofs/fuzz/enc-diff/run.ts` under its documented budget. Preserve all golden roots, Map/Set sorting, omitted undefined fields and signed bigint encoding. Bundle inspection should confirm the oracle is unreachable from production; source relocation alone is not a measured bundle reduction.\n\n### 4. One authenticated external-finality envelope constructor\n\n`core/account/input.ts:11-38` and `40-65` duplicate the same owner-membership check, from/to orientation, domain copy and dispute-config canonicalization. They differ only in the two members of the existing `AccountFinality['finality']` union (`core/types/account.ts:436`). Production callers are `core/entity/tx/j-events.ts:730` and `1359`; the focused test imports both.\n\nReplace both with one `createAccountExternalFinalityInput(account, owningEntityId, finality)` and migrate both callers atomically. Keep the existing union, no new protocol tag or abstraction across layers. Copy `finalizedTokenIds` only in the finalized variant; keep started's optional `batchNonce` absent when absent. Measured current constructors: 54 function lines. Estimated net saving 15-20 lines after adapting finalization callers and retaining the variant-specific copy.\n\nAuthority must remain owning-Entity authenticated J evidence; this must never create a peer-ingress path or permit network finality. `core/__tests__/account/consensus/account-external-finality-input.test.ts` is the smallest existing check: owner mismatch, exact J clock, invalid input byte identity, zero-window semantics and staged recovery transfer. Keep started/finalized state transitions separate; they perform different financial work.\n\n### 5. One AccountState collection-field declaration, two distinct checks\n\n`core/account/state/account-replica-shell.ts:13-23` and `core/account/state/commitment/value-seal.ts:6-16` repeat the exact nine AccountState map fields. Each is used once by its local collection check (shell at 64/73, seal at 19). Share just the readonly field declaration under the Account state owner.\n\nMeasured repeated declaration: 11 lines. Estimated net saving 8-10 lines, depending on an existing suitable leaf module. Avoid a new broad registry or a generic clone/seal framework. Do not merge the validators: the seal checks own properties, traverses bounded graphs and rejects raw Maps/Sets; the shell preserves immutable collection identity and transfers a derived root memo. Those are distinct operations. Keep diagnostic codes unchanged and preserve optional fields.\n\nSmallest related checks: `core/__tests__/account/state/account-transition-overlay.test.ts` and `account-overlay-publish.test.ts`; then commitment/incremental and recovery tests. A new AccountState map should be added once to this declaration and independently covered by hash/storage tests.\n\n## Rejected naive deletions and boundaries\n\n- **Default credit helper is not yet a behavior-neutral delete.** `createSettlementDeltaValue` calls `createDefaultDelta`, then overwrites both zero limits from `getDefaultCreditLimit`. Only one production caller exists, but the latter rejects token 0 while `assertSettlementTokenId` accepts token 0. Removing it silently broadens new-row admission. Preserve that existing rejection explicitly or settle token-0 semantics from canonical vectors first; do not hide this behavior change in cleanup. Existing regression location: `core/__tests__/payments/settlement/settlement-transition.test.ts:1341-1360` currently compares against the helper instead of independently asserting zero.\n- `validateObject` and `requireBoundaryRecord` are not equivalent: the latter rejects Maps and custom prototypes, and their error types differ. Mechanical replacement can change reject/fail-stop behavior. The generic `validateArray<T>` merits later authority review, not a drive-by rename.\n- `deriveDisputeTokenFinalization` mirrors contract settlement including reserves and existing FIFO debt; it cannot be replaced by the live credit-capacity `deriveDelta` view. Native/noble signature backends likewise are platform implementations, not two financial authorities.\n- Optimistic proposal batching and per-transaction retry already share `applyProposalTransaction`/`applyAccountTx`; deleting one without production measurements may remove a valid optimization or change rejected-tx granularity. No recommendation to unify Account/Entity reducers.\n- Lending proof support remains necessary for existing signed claims even with production admission disabled. No lending edits proposed."
    },
    {
      "name": "jurisdiction",
      "indexedFiles": 565,
      "physicalLines": 147709,
      "focusedFiles": 17,
      "report": "# Jurisdiction, API and watchtower canonicalization review\n\nSource: `b07da2b8762d3398683f3f2c481ee65a8caedc41`. Read-only; no tracked files changed, no protected flags changed, no Solidity/Rust/lending changes. Parent's baseline: `bun run check` 38 gates and reserve-funding regression 1/1.\n\n## Coverage and limits\n\n565/565 assigned files were read from immutable Git blobs and parsed for import edges, function bodies, token-normalized exact clones and local import references: 147,709 lines. This is **indexing/content screening, not 565 semantic audits**. Zero TS parser diagnostics. The accompanying coverage JSON lists the exact regions deeply inspected.\n\n- 249 nongenerated production/script files: 48,983 lines.\n- 216 test/fixture files: 63,998 lines.\n- 100 generated bindings: 34,728 lines. Their retained owner is Solidity + compiler artifacts + `jurisdictions/scripts/generate-typechain.cjs`, published atomically by `scripts/sync-contract-artifacts.sh`. `jurisdictions/hardhat.config.ts:10\u201316,49\u201351` keeps plain Hardhat output separate. Review generator/ABI parity and bytecode evidence, not 100 generated files manually; do not hand-delete generated fields or factories.\n- Conservative local AST scan: 589 unreferenced import-binding candidates in 17 tests; none in the 249 nongenerated production files. This is not full module/type reachability proof.\n\n## 1. Remove the retired cooperative finalization representation below Entity admission\n\n**Priority: first observable canonical mismatch; safe TS cleanup under existing protocol decision.**\n\nEvidence:\n\n- `core/jurisdiction/machine/batch/index.ts:123` still declares `cooperative: boolean`.\n- `core/jurisdiction/machine/batch-validation.ts:190` accepts either boolean.\n- `core/jurisdiction/machine/batch/index.ts:637\u2013648` retains a cooperative-specific preflight branch.\n- `core/entity/tx/handlers/dispute/finalize-proof.ts:52,282` already emits only `false`.\n- `jurisdictions/contracts/Account.sol:679,1369` unconditionally rejects `true` with E2.\n- `core/__tests__/payments/invariants/canonical-payment-surface.test.ts:71\u201376` proves only EntityTx's retired field rejection, leaving JBatch untested.\n\nActual reproduction on clean source SHA (no RPC, mocks, or chain mutation): create a normal one-token finalization with valid Int512 zero, response clocks 3600/86400, nonempty signature, then set `cooperative: true` and execute `decodeJBatch(encodeJBatch(batch))`. Output: `{\"cooperativeAcceptedByAbiRoundTrip\":true}`. This proves a dead accepted TS representation; it does not imply Solidity can execute a cooperative close.\n\nRetained owner: current Account.sol timed-dispute semantics, projected into the TS JBatch decoder. Require literal `false` there, type it `false`, remove the dead true branch. **Keep the ABI bool field encoded as false**; removing the ABI field changes current contract calldata and is outside this cleanup. Keep ordinary cooperative settlement/C2R behavior, which is a different live operation.\n\nExpected source reduction: ~3\u20138 lines net; more valuable is deleting one impossible semantic branch. Add malformed `true` regression while preserving exact `false` ABI bytes. Focused command: `bun test core/__tests__/jurisdiction/batches/j-batch-contract-limits.test.ts core/__tests__/payments/invariants/canonical-payment-surface.test.ts`. Then relevant watcher/receipt tests and unchanged-candidate `bun run check`.\n\n## 2. One production ProofBody encoding/hash owner\n\nEvidence:\n\n- Canonical optimized codec: `core/protocol/dispute/proof-builder.ts:84\u201390` (`encodeProofBodyStruct`, `hashProofBodyStruct`).\n- Alternate ethers hash: `core/jurisdiction/adapter/rpc-public.ts:88\u201393` (`hashCalldataProofBody`).\n- Alternate ethers hashes: `core/jurisdiction/machine/batch/index.ts:634,1349,1357`; separate proof encoding at375.\n- Alternate ethers hash: `core/watchtower/action.ts:239\u2013243`, used at767,931,948. Tower input legitimately needs scalar Int512\u2192ABI limbs at234\u2013237.\n\nRetained owner should be a low-level ProofBody codec beside `proof-body.ts`. Move the existing encoder/hash into that owner and let the builder, batch, watcher and tower reuse it. **Do not import proof-builder into batch**: proof-builder already imports `assertDisputeProofBodyWithinContractLimits` from batch at22, creating a cycle. Preserve the Tower scalar\u2192ABI conversion and RPC materialization of ethers Results. Independent ethers oracle code in tests must remain independent.\n\nSemantic differences: existing custom ABI encoder and ethers must remain byte-identical for all bounded valid inputs; malformed shapes may throw different errors. Do not silently accept a malformed value just to deduplicate. No wire/schema change is needed.\n\nExpected source reduction: ~10\u201325 lines net (estimate), but reduce four production encoding/hash owners to one. Focused commands: `bun test core/__tests__/protocol/abi-encode.test.ts core/__tests__/protocol/abi-money.test.ts core/__tests__/jurisdiction/batches/j-batch-contract-limits.test.ts core/__tests__/jurisdiction/rpc/rpc-watcher-dispute-calldata.test.ts`. Tower last-resort test additionally required. `rpc-public.ts` remains protected: root decides sequencing under existing owner authorization; this review did not touch it.\n\n## 3. Remove QA HTTP mounts from production hosts\n\nEvidence:\n\n- `core/api/server/index.ts:36` statically imports `core/qa/api.ts`; lines553\u2013554 dispatch every relevant request to it.\n- `core/orchestrator/orchestrator.ts:39,1846\u20131847` mounts the same feature again (cross-scope caller; coordinate its owner).\n- `core/qa/api.ts:1\u20136` brings child-process spawning, filesystem and SQLite; `:887\u2013916` serves QA catalog, restart, HLT and retention concerns. Authorization does not remove this production dependency.\n\nRetained owner: development/QA CLI and QA modules, not the production money server. Remove both imports/mounts atomically; retain QA reports/tests as development tools. Do not add a new production environment flag or fallback branch to keep the unwanted feature reachable.\n\nMeasured direct deletion: 6 nonblank production lines across the two callers, plus surrounding whitespace. Transitive audit-footprint reduction is not yet measured and must not be described as thousands of deleted source lines. Production health, operator control and monitoring remain live distinct features.\n\nFocused command after implementation: `bun test core/__tests__/api/server/server-rpc-startup-gate.test.ts core/__tests__/api/product/node-http-access.test.ts`, then actual production smoke and dependency gate. Add one owning dependency assertion that the production entrypoint graph cannot import QA; do not test only a string deletion.\n\n## 4. Delete copied test setup and share exact repeated fixtures\n\nConcrete immediate cut:\n\n- `core/__tests__/api/runtime-adapter/radapter-part-3.test.ts` is178lines with one test beginning119. Almost all copied imports/constants/setup before it are unused.\n- Retain protocol version, `bun:test`, three codec functions, `RemoteRuntimeAdapter`, `decodeTestRuntimeAdapterMessage`, and the existing test. Remove unused Entity IDs/challenge and unused `XLN_RADAPTER_AUTH_SEED` mutation (the test only runs the remote client).\n- Estimate ~95\u2013105 lines deleted with no removed assertion or new mock. Run `bun test core/__tests__/api/runtime-adapter/radapter-part-3.test.ts` plus the adapter group to detect removed setup side effects.\n\nMeasured exact function clones (token-identical bodies, excluding comments/whitespace):\n\n- `makeBidirectionalSalvageRuntimeFixture`: `cross-jurisdiction-swap-part-3.test.ts:280\u2013462` and `...part-3b.test.ts:267\u2013449`: 183 duplicated lines.\n- `makeTargetDisputeRouteSelectionFixture`: `...part-1.test.ts:293\u2013351`, `...part-2a.test.ts:214\u2013272`, `...part-2b.test.ts:246\u2013304`: 118 excess lines across three copies.\n- `installActivePullRegistrationProof`: `...part-3.test.ts:238\u2013278` and `...part-3b.test.ts:225\u2013265`: 41 excess lines.\n- `makeTestViewPageLoader`: `radapter-part-1.test.ts:265\u2013315` and `...part-2.test.ts:309\u2013359`: 51 excess lines.\n\nThese four groups contain **393 excess source lines before helper export/import overhead**, not a committed reduction. Nested clone bodies were excluded from that total to avoid double counting. Retained owner is one fixture per existing test domain under `core/__tests__/helpers` or `fixtures`; preserve fresh per-test state and keep independent expected-result oracles in their tests. Cross-J is deferred: do this only after the release-critical cuts, without changing its protocol implementation. The full 589 unused-binding candidate list is in `jurisdiction-imports.json`; do not auto-delete imports that intentionally initialize required side effects without checking them.\n\n## 5. Share the three identical EntityProvider submission-context builders\n\nEvidence: `core/jurisdiction/adapter/rpc/write/rpc-submission.ts:480\u2013494,504\u2013518,528\u2013542` repeats the same 13-field object for action, board proposal and activation. The exact type already exists at `rpc-submit-entity-provider.ts:25\u201343`: `RpcEntityProviderSubmitContext`.\n\nRetained owner: a local `entityProviderSubmitContext(context): RpcEntityProviderSubmitContext` factory in rpc-submission. Call it in those same three branches. Build it at dispatch time, not once during adapter creation: stack contract getters can depend on deployment/attachment timing. Keep the three authority-specific submission handlers separate; do not introduce a generic signer/action reducer.\n\nEstimated reduction: ~25\u201328 lines net. This is the smallest safe production TS dedup now. Focused command: `bun test core/__tests__/registration/invariants/entity-provider-action-flow.test.ts`; current adapter/submission integration required afterward. No new test is required merely to mirror the object mapping, but existing branch behavior must remain covered.\n\n## Explicitly rejected blind deletions\n\n- Reserve faucet's authoritative balance poll plus event observation are not redundant: an old cached event can match a balance previously spent. Preserve the shared60second deadline fix and both observations.\n- `decodeTowerProofBody` in recovery consumes ABI Int512 limbs/number clocks; watchtower `normalizeFinalProofbody` consumes encrypted scalar bigint fields and enforces exact keys. They are different ingress formats. A future shared validated internal body is possible, but replacing one decoder with the other directly would be wrong.\n- BrowserVM and RPC own different execution backends. Similar deployment/write methods are not proof that one is dead. Keep real-EVM scenario coverage and don't replace it with fakes to reduce files.\n- TypeChain output is generated evidence, not duplicate hand-maintained financial logic."
    },
    {
      "name": "rust",
      "indexedFiles": 661,
      "physicalLines": 258786,
      "focusedFiles": 23,
      "report": "# Rust and TS bridge canonicalization review\n\nSource: `b07da2b8762d3398683f3f2c481ee65a8caedc41`.\n\nScope: all 661 assigned files, 258,786 physical lines: 545 Rust and 116 TS files. All committed blobs were read and mechanically indexed; SHA-256 is recorded per file in `rust-coverage.json`. Import/legacy-flag searches and exact normalized 10-line windows produced 64 distinct duplicate-path groups. Focused manual inspection covered ranges in 23 assigned files, plus five production callers. This is **not** 661-file semantic verification. Inline Rust tests are included in the physical line total. No source files changed, no tests/builds or external models ran, and the parked Rust stash was not touched.\n\n## 1. Remove retired Rust execution hooks from the TS production graph; preserve active TS workers\n\n- Evidence: `core/rscore/ts-worker/provider.ts:741` rejects embedded Rust before installing TS workers; line 752 also rejects shadow execution. Nevertheless, `core/orchestrator/process/hub-runtime-env.ts:99-110` converts a hub-specific flag into `XLN_RSCORE_AUTHORITY=1`. `core/rscore/authority-driver.ts:91-115` still reads the retired flags, and production Runtime/admission/storage imports its lifecycle functions. `core/runtime/composition.ts:44-49`, `core/runtime/frame/intake/reducer.ts:12-16`, `core/runtime/frame/process.ts:31-37`, and `core/storage/recovery/journal/index.ts:52` are concrete callers.\n- The directory is not wholly dead: `core/rscore/ts-worker/` contains 14 files / **3,857 measured lines** of active TS execution. `core/rscore/authority/entity-stage.ts` supplies its Entity boundary. `core/rscore/engine-leaf/` contains three files / **74 measured lines** used by the active provider and account maps. A mass deletion would destroy the sole TS engine. Worker count changes distribution, not financial transition ownership.\n- Canonical ownership: place TS Account workers and their orchestration under Runtime/Entity owners, and the committed leaf cache under Entity state ownership. Keep `applyAccountInput` as the financial transition. Remove the retired driver's hooks from the production graph atomically; frozen diagnostic exporters may remain isolated tooling. The current `core/rscore/` total is 40 files / **14,491 measured lines**, not a deletion estimate.\n- Smallest safe first change: delete the 12-line hub flag propagation branch, replacing it with an explicit startup configuration rejection if preserving fail-fast operator feedback requires one. Preserve the existing Runtime guard. This prevents the launcher from constructing a configuration known to fail at its first frame. Estimated net reduction: **5-10 lines**, not yet measured on a patch.\n- Larger reduction: the driver alone is **1,154 measured lines**; its production removal substantially shrinks the auditor's reachable code, but cannot honestly be claimed as physical deletion until test/diagnostic callers and persisted Rust checkpoints have been classified. `concrete-checkpoint-source.ts:30,130-150` imports the Rust process client only for a fingerprint and creates empty Rust metadata for export; move that import-only dependency behind its offline export owner. Do not silently reinterpret old persisted rows.\n- Proof required: existing `ts-worker-installation`, account stage/root, checkpoint restore, and inline/W1/W4 replay vectors; one real WAL with identical roots and positional outputs. Add a small launcher test proving retired flags fail before child spawning. A file move alone is not this proof.\n\n## 2. One Rust decoder for the same Account ABI and exact checkpoint rows\n\n- Duplicate production implementations: `rscore/crates/process/src/wire/decode.rs:889-922` dispatches AccountTx ABI tags; `rscore/crates/runtime/src/restore/account/account_tx.rs:434-470` repeats that dispatch and its transaction decoders. Concrete duplicate: `requestCollateral` at process lines 1019-1031 and restore lines 307-319 reads the same six fields with the same financial constructors. Direct payment, HTLC, swap, J claim and rebalance paths likewise appear in both.\n- Checkpoint duplication: `process/src/checkpoint_wire/decode.rs:39-137` and `runtime/src/restore/account/account_checkpoint.rs:262-354` both reconstruct the same 13-field Account restore row, including owner/counterparty binding, carried sections, J-claim nodes, and consensus. Process calls it from `wire/decode.rs:237-241`; Runtime calls it through `restore/mod.rs:59` and `decode_account_rows` at checkpoint line 377.\n- Canonical owner: existing `xln-rscore-batch::checkpoint_wire`, which already owns Account ABI **encoding** and shared J-event decoding. Move one Account ABI decoder there and map errors at the process/restore boundaries. Do not create another codec crate or duplicate the financial constructors.\n- Relevant differences: errors are `ProcessError` versus `AccountWireRestoreError`; restore inputs begin as persisted JSON rows while the shared decoding stage consumes `AbiValue`. Seed policy snapshots use an empty tuple for absence (`process/wire/decode.rs:832`); checkpoint policy snapshots use `Nil` (`process/checkpoint_wire/decode.rs:368`, restore/account_tx.rs:560). Keep these distinct envelope formats at their boundary; merging them into a permissive fallback decoder would weaken validation.\n- Measured source surfaces: Account restore decoder 596 lines; Account checkpoint decoder 385 lines; process checkpoint decoder 380 lines; process wire decoder 1,289 lines (also owns unrelated commands). Estimated removable duplicated logic after adapters: **500-900 lines**, not all 2,650 lines.\n- Future proof after freeze lift: identical encoded AccountTx vectors through process and persisted-restore callers, valid and malformed; exact field count, unknown tag, unsafe integer, J-event hash mismatch, owner/counterparty mismatch, and pending ACK/proposal restoration. Then immutable TS/Rust WAL comparison. No parity result is claimed now; lending remains deferred.\n\n## 3. Share ProofBody ABI encoding between Rust signing and J submission\n\n- `rscore/crates/engine/src/dispute.rs:739-812` manually lays out `abi.encode(ProofBody)`, including dynamic offsets, nested transformer allowances and padding. The signed proof hash consumes it at line 410. `rscore/crates/entity-kernel/src/j_batch/encode.rs:54-94,334-336` builds the equivalent value through `ethabi`, consumed by `j_batch/mod.rs:184-187`. Engine consensus and settlement use the former; Entity dispute submission, J ingress and Runtime watcher use the latter.\n- `j_batch/mod.rs:47-84` maps `DisputeProofBody` into another `ProofBody` struct; `:133-182` converts event boundary strings into that second type. The single Account state-to-proof builder is already correctly centralized in `build_dispute_proof_body`; preserve it. The remaining duplication is the signed ABI representation and encoding, not two Account builders.\n- Canonical owner: existing engine dispute/contract boundary (Engine already depends on `ethabi`; Entity depends on Engine). Expose one validated proof value and one ABI token encoder there, consumed by both signing and JBatch. No reverse Engine-to-Entity dependency and no shared R/E/A reducer.\n- Semantic constraints: Account token IDs currently use `u32`, JBatch uses `U256`; watcher events must retain the full contract width. Account offsets are signed Int512, allowances are uint256, and transformer order is positional. Do not narrow the J boundary merely to share a type. Manual Int512 bounds and `ethabi` signed-byte validation use different code paths today; equality must be proved with edge vectors before selecting one.\n- Measured duplicated encoder surface: **74 lines** of manual body layout plus **41 lines** of token layout, with a **38-line** Engine-to-J projection. Estimated net removal **70-130 lines** after consolidating types/adapters. The more important improvement is one signed preimage implementation to audit. No observed hash mismatch is alleged.\n- Future proof after freeze lift: byte-for-byte golden ABI and Keccak equality for empty/multi-token proofs, zero and nonzero transformers, dynamic bytes of lengths 0/1/31/32/33, multiple allowances, Int512 extrema and one-beyond rejection, full uint256 allowances. Retain Solidity-generated vectors as an independent oracle.\n\n## 4. Consolidate strict persisted-value primitives within the Rust restore boundary\n\n- The same `exact_fields` body is present in `runtime/src/leveldb/rscore_checkpoint.rs:46-60`, `restore/certified_board_registry.rs:81-95`, `restore/entity/entity_graph.rs:65-79`, `restore/orderbook/orderbook_graph.rs:51-65`, and `restore/orderbook/orderbook_metadata.rs:31-45` (five copies; **75 physical lines** including signatures).\n- Strict tagged BigInt decoding repeats in `restore/entity/entity_consensus.rs:67-79`, `restore/entity/entity_snapshot.rs:81-93`, `restore/orderbook/orderbook_graph.rs:82-94` and `restore/orderbook/orderbook_metadata.rs:79-91`. These all validate exactly two tagged fields before parsing.\n- Canonical owner: a small shared persisted-value decoder in the existing Runtime codec/restore boundary. Keep module-specific typed error mapping and exact schema field lists at the call site. Do not replace strict decoders with the permissive optional cross-J readers or turn errors into defaults.\n- Estimated net removal for these verified primitive families: **60-100 lines** after common code and adapters. Lower priority than removing the retired execution graph and duplicate proof/checkpoint logic.\n- Future proof: parameterized malformed persisted values (extra/missing fields, wrong tag, wrong scalar type, bad numeric string) produce the same accept/reject result and retain caller context. Preserve distinct normalization: Entity consensus text lowercases/trims, Orderbook metadata text does not; they are not interchangeable helpers.\n\n## Deletion discipline\n\nCount a reduction only after the old definition and all production callers are removed, the necessary adversarial vector remains green, and an immutable WAL/exit artifact proves the financial behavior. Do not count moves, whitespace, generated files, test deletion, frozen code exclusion, or a scanner's duplicate match as saved verified logic. Report both reachable production audit surface and physical source delta. Keep layer trust boundaries, independent format oracles, and negative tests even where they resemble each other."
    },
    {
      "name": "wallet",
      "indexedFiles": 794,
      "physicalLines": 199649,
      "focusedFiles": 33,
      "report": "# Wallet canonicalization review\n\nSource: `b07da2b8762d3398683f3f2c481ee65a8caedc41`. Source content was obtained with `git cat-file --batch` at this immutable SHA, not from a moving checkout. Line references below name this SHA unless marked implementation.\n\n## Coverage and limits\n\n- Mechanically scanned **794/794 assigned files, 199,649 lines**: contents, hashes, imports, exported names, financial/storage/fallback patterns, exact normalized 12-line duplicate windows. No exact 12-line duplicates among non-test React source; this does not establish semantic uniqueness.\n- Focused semantic reads: **33 files / 4,115 lines**, listed in `wallet-coverage.json`. Remaining files were indexed and pattern-scanned, not manually proven correct. This is not complete human-equivalent review of 794 files.\n- Inventory: 408 frozen Svelte files, 139 non-test React files, 246 test files, one other config. The React source contains **48 import references in 36 files** into frozen frontend helpers (including tests, types, `$lib` aliases, and one service-worker resource). Frozen does not mean unreachable or deletable.\n- No Rust, lending implementation, frozen Svelte, network service, browser session, or heavy test was changed/run. Adjacent agent owns the brainvault collector finding; this report does not duplicate it.\n\n## 1. Delete the second outgoing-debt calculation \u2014 implemented with authorization\n\n**Evidence:** `ui/src/runtime/financial/move.ts:110\u2013115` scans `core.outDebtsByToken`; `availableAt` at line119 calls it to subtract debts from reserve. `core/api/runtime-adapter/read/compact-view.ts:23\u201336` already defines full `debtTotals` before truncating detailed rows. Home consumes those exact totals through `ui/src/runtime/views.ts:216\u2013218` and `financial/token-totals.ts:36`.\n\n**Divergence proved:** 21 claims of50 against reserve1,500 must leave450. The old Move code reads20 detail rows and reports500. A twenty-first token is absent altogether from the bounded detail map. This is an actual financial display/admission-guidance bug, although runtime remains the spending authority.\n\n**Canonical owner:** runtime projection owns debt aggregation; React reads `core.debtTotals.outgoing.get(tokenId)`. Full repayment retires a debt through the existing J-event transition; the wallet does not redefine what open means.\n\n**Changed paths:** `ui/src/runtime/financial/move.ts`, `ui/src/runtime/financial/move-balance.test.ts`.\n\n- Deleted `openOutgoingDebt`, replaced its only call with exact totals lookup.\n- Three existing async effect functions load adapter/tx dependencies at use, preventing pure Move projections from initializing the browser store. No mock DOM or second projection module was introduced.\n- `availableAt` input narrowed to the three WalletView members it actually reads.\n- Measured production diff **6 additions / 12 deletions, net \u22126 lines**. Regression test adds code intentionally; total repository LOC is not the sole objective.\n- Before fix: targeted regression **1 pass / 1 fail**, expected450, received500. After fix: `bun test ui/src/runtime/financial/move-balance.test.ts ui/src/runtime/financial/balance.test.ts` **15 pass / 0 fail / 48 assertions** (237ms).\n- Checks: outer token bound, inner claim bound, full repayment retirement, missing token, reserve-below-debt clamps to zero.\n- Parent still must run strict UI types, browser integration, and source gates before release evidence. Unit logs are diagnostic under `.logs/canonical-review-20261012/wallet-move-{red,green}.log`; these dirty-tree logs are not release evidence.\n\n## 2. One runtime payment-route reader for embedded and remote wallets\n\n**Duplicate:** `ui/src/runtime/adapter.ts:150\u2013197` locally implements `findEmbeddedPaymentRoutes`; callback at144 installs it. `core/api/server/network/rpc-ws.ts:47\u2013111` implements `findPaymentRoutes` for the same query/response contract.\n\n**Already divergent:** the UI copy omits the server's committed-read lease, `syncProfiles`, explicit failure when `ensureGossipProfiles` returns false, and relay `ensureRoutes` retry. UI also uses different query validation/error typing. Thus \u201cmirrors the server\u201d is currently false in relevant branches.\n\n**Replacement:** move the existing canonical runtime query into a browser-safe runtime/API read module, expose that query through the browser runtime facade, and invoke it from both server and embedded adapter. Network refresh must remain outside the committed-read lease; only the graph lookup holds it. Do not import the server socket module into the browser. Do not copy missing branches into the UI again.\n\n**Estimate:** eliminate roughly45 UI implementation lines, plus duplicate policy maintenance; exact net savings depend on exports/wiring. This is a next implementation candidate, not a verified patch.\n\n**Existing tests:** `bun test core/__tests__/runtime/commit/runtime-committed-read-barrier.test.ts`; real `ui/tests/e2e-payment.spec.ts` / `e2e-payment-h3.spec.ts` through the locked stand. A focused no-profile/no-route/relay-refresh unit is still needed; existing barrier tests alone do not prove route parity.\n\n## 3. Remove wallet copies of canonical swap units and pair orientation\n\n**Duplicates:**\n\n- `ui/src/runtime/financial/orderbook-quote.ts:4\u201310` defines its own10,000 price scale and raw quote formula. Canonical implementations already exist at `core/swapbook/types.ts:38` and `:122\u2013131` (`ORDERBOOK_PRICE_SCALE`, `quoteAmountAtPriceForDecimals`). Callers: `Swap.tsx:101`, `native/market.ts:41`, and `quoteAtBestLevel` in the same module.\n- `ui/src/runtime/financial/orderbook.ts:41\u201350` invokes core orientation if loaded, otherwise silently reimplements it using token IDs1/3. `getSwapPairOrientation` already belongs to core token identity. The fallback is a second token-policy owner.\n\n**Replacement:** use core quote conversion/scale and canonical pair orientation; retain display-level indicative quote composition and executable `planSwapCommand` distinctions. No new generic arithmetic framework. Eliminate the fallback rather than blessing its hardcoded token list.\n\n**Caveat:** core returns0 for nonpositive size/price and validates decimals; existing UI arithmetic does not. Verify user-input boundary/empty-book cases, mixed6/18 decimals, and integer flooring. Buying indicative quote currently uses level-size/proportional cost; replacing that whole calculation would change rounding, so leave it outside this deletion.\n\n**Estimate:** 12\u201318 net implementation lines removed across modules/callers. No edits made.\n\n**Smallest existing tests:** `bun test ui/src/runtime/financial/orderbook-quote.test.ts ui/src/native/market.test.ts`; then browser swap quote/order flow under the stand lock.\n\n## 4. Use the existing batch schema counter\n\n**Duplicates:** `ui/src/runtime/financial/move.ts:147\u2013163` and frozen `frontend/src/lib/components/Entity/payments/pending-batch-preview.ts:54\u201368` enumerate the same eleven batch operation arrays already enumerated by `core/jurisdiction/machine/batch/index.ts:780\u2013794` (`batchOpCount`). UI callers are `hasSentBatch` and `ui/src/components/PendingBatch.tsx:67\u201368`.\n\n**Replacement now:** import the canonical count for present, validated JBatch values; handle absence at the UI call site. Retain frozen Svelte unchanged for this release. Do not preserve a compatibility alias or add an array registry solely for this count.\n\n**Caveat:** the UI copies silently accept malformed partial batches via optional chaining. Runtime's committed JBatch is complete. A present malformed DTO should fail loudly, not render \u201cnothing pending\u201d. Null/no batch is legitimate loading state and still renders zero.\n\n**Estimate:** ~12 net React lines removed. No edits made.\n\n**Smallest existing tests:** `bun test tests/frontend/payments/pending-batch-preview.test.ts core/__tests__/jurisdiction/batches/j-batch-contract-limits.test.ts`; React pending batch / Move browser flow still needed because the existing count unit names the frozen helper.\n\n## 5. Stop rebuilding hosted book depth from bounded Account details\n\n**Duplicate surface:** `ui/src/runtime/financial/orderbook.ts:62\u2013115` folds Account swap offers into price levels; `useOrderbook` at235 reads a bounded Account page at250 and labels the result live. Core already emits exact `bidLevels`/`askLevels` from committed BookState in `core/api/runtime-adapter/read/compact-view.ts:478\u2013490`. The code explicitly preserves exact level quantities while bounding order detail.\n\n**Replacement:** read the runtime's canonical Book projection for hosted markets, convert lot quantities for presentation, and keep UI depth/spread/own-order highlighting as view concerns. Relay and hosted transport can remain distinct while using the same canonical depth semantics. Never turn a bounded sample of Accounts or order rows into a financial total.\n\n**Caveat:** own-order marking and account-side offers not yet admitted to the Book are not identical to market depth. Show pending local offers separately if needed; do not include them as executable market liquidity. Current static review establishes separate calculations and bounded inputs, not a reproduced wrong-depth execution.\n\n**Estimate:** 40\u201355 lines of duplicate fold/scan logic removed, with adapter wiring/own-order presentation to account for before claiming net savings. No edits made.\n\n**Existing test entry:** `ui/tests/e2e-swap-quote.spec.ts` and `ui/tests/e2e-swap.spec.ts` under the locked real stand. Add a focused case beyond account/detail bounds against exact core Book levels; no existing wallet unit covers `bookFromHostedAccounts`.\n\n## Method recommendation\n\nRank by duplicate authority plus observed divergence, not text similarity or total LOC. The completed Move fix found a better target than cosmetic wrappers: one less calculation and one fewer financial inconsistency. For every next deletion: immutable source, exact callers, one canonical owner, first failing semantic counterexample, smallest patch, same check green, then production/browser flow. Keep mechanical coverage and semantic review counts separate. A shared import into frozen Svelte is an ownership-placement problem, not proof that its implementation is duplicated; do not mass-delete that tree while React still imports it."
    },
    {
      "name": "tooling",
      "indexedFiles": 462,
      "physicalLines": 112472,
      "focusedFiles": 23,
      "report": "# Canonical tooling review\n\nSource: `b07da2b8762d3398683f3f2c481ee65a8caedc41`. Read-only review; no source edits, tests, chain effects, or external models.\n\nCoverage: all **462 assigned files / 112,472 physical lines** were read mechanically from Git blobs at the source SHA (4,614,939 bytes including batch framing). Each file has an import/export/signal index and a content digest in `tooling-index.json`. Cross-file normalized 12-line windows identified candidates; these are leads, not proof of semantic equivalence. `tooling-coverage.json` distinguishes mechanical indexing from targeted/full semantic reading. This is not a claim that every line was manually audited.\n\n## 1. Delete the unreachable copy of backend readiness (safe first fix)\n\n- Delete `scripts/dev/wait-dev-backend-ready.ts:1\u201359`.\n- Retain `scripts/dev/readiness/wait-dev-backend-ready.ts:1\u201359`; the files differ only at import line 3 (`./wait-dev-ready` versus `../wait-dev-ready`). The CLI parser, time budget, fatal handling and probe loop are otherwise identical.\n- Caller evidence: `scripts/dev/run-dev-child.sh:201` executes the retained path. `core/__tests__/dev-startup-hardening.test.ts:145` asserts it. Whole tracked-tree `git grep wait-dev-backend-ready` finds those two references and none to the retired path.\n- Measured deletion: **59 physical lines, one executable entry point**, no replacement abstraction.\n- Small existing regressions: `bun test core/__tests__/dev-startup-hardening.test.ts core/__tests__/testing/tooling/script-entrypoints.test.ts`; then normal `bun run check` before push. These were not run by this reviewer.\n- Caveat: a user's untracked shell history could name the old path; the repository has no contractual consumer, and canon explicitly rejects compatibility aliases. No frozen-core change needed.\n\n## 2. Make the existing release runner the only owner of acceptance execution\n\n- `core/scripts/release/mainnet-gate-constants.ts:9\u201318` hardcodes missing lending origination features. `run-mainnet-preflight-gate.ts:139\u2013145,216` unconditionally rejects non-dry-run mainnet verification before any evidence is checked. `core/__tests__/operations/release/mainnet-preflight-gate.test.ts:35\u201342` preserves the obsolete assumption. Lending admission is already deferred by the current owner scope; do not repair or reopen lending.\n- `run-mainnet-preflight-gate.ts:97\u2013115` and `run-capped-testnet-gate.ts:174\u2013180` both execute `gate:release` and then independently request security/watchtower/full legacy-browser evidence. `run-release-gate.ts:140\u2013203` already owns the relevant security, watchtower and React group execution. A successful legacy Svelte suite is not additional React launch evidence.\n- Execution duplication is separately concrete: `run-release-gate.ts:226\u2013255`, `run-mainnet-preflight-gate.ts:170\u2013195`, and `run-capped-testnet-gate.ts:213\u2013236` each own subprocess/timeout/termination/output forwarding. Their environment behavior has drifted: mainnet/release clear cleanup-done state; capped uses only `sanitizeChildProcessEnv`.\n- Retain `run-release-gate.ts` as the actual suite runner and `mainnet-gate-constants.ts` for applicable operational constants. Preflight should add only genuinely deployment-specific health, soak and public evidence requirements. Delete the lending-only blocker table/function/test expectation, preserve typed rejection tests in release suite; retain explicit owner signoff and all actual recovery/exit requirements. Do not replace the obsolete lending list with an invented new blocker catalog.\n- Reduction estimate (not an implemented diff): **60\u2013100 LOC** by reusing the existing subprocess execution and deleting obsolete lending readiness code. Whole-wrapper removal could be larger but is not proven safe; policy validation and operational reports differ and must remain. Before importing its runner, put the existing run-release-gate.ts main invocation (lines 318\u2013321) behind import.meta.main; importing it currently executes the gate.\n- Small existing regressions: `bun test core/__tests__/operations/release/mainnet-preflight-gate.test.ts core/__tests__/operations/release/capped-testnet-gate.test.ts tests/release-integrity/release-gate-order.test.ts`. Update semantic expectations to actual scope, not fewer assertions. Verify planned steps before running the heavyweight release gate.\n- Related stale methodology: `docs/improvement-loop.md:6\u20138` still says the Rust book-refactor exception and lending are in scope. Replace that repeated policy prose with the current AGENTS scope link. The document already has the requested 30-minute review loop; extend it only with actual findings instead of creating another process document.\n\n## 3. Reuse the real repository fingerprint implementation for QA restart and soak\n\n- `core/qa/api.ts:310\u2013350` and `core/scripts/release/run-soak-gate.ts:281\u2013321` independently implement the same repo file list + content hash, silently skip missing tracked files, and use the same legacy delimiter encoding. Their sole call sites are `api.ts:1106` and `run-soak-gate.ts:688`.\n- Retain `core/qa/tools/code-fingerprint.ts:229\u2013253` (`computeRepositoryCodeFingerprint`). It already has explicit failure handling, bounded status, missing-file markers, symlink handling, byte-safe ordering, domain separation and a file-change check. It is used by `core/scenarios/run.ts:492` and `code-fingerprint-cli.ts`; regressions exist in `core/__tests__/testing/qa/qa-code-fingerprint.test.ts`.\n- Replace the two bodies and retire their duplicate fingerprint types after updating consumers. Estimated net saving: **60\u201380 LOC**; 82 lines of duplicate function bodies are measured, adapters/type changes have not been implemented.\n- Caveat: canonical hash encoding differs. New reports must identify the canonical schema; never compare a new hash with an old unversioned report and claim source drift/equality. Old reports remain historical evidence.\n- Do **not** blindly fold `core/scripts/e2e/harness/e2e-isolated-runtime.ts:165\u2013255` into this deletion. Its code-input policy excludes generated bundles and its build hash includes Bun version; those are deliberate distinctions. A future unification must preserve this separately identified input set and drift contract, not pretend all four fingerprints are identical.\n- Small existing regression: `bun test core/__tests__/testing/qa/qa-code-fingerprint.test.ts`; identify and run QA restart/soak consumer tests before changing report shape. No new fingerprint framework is needed.\n\n## 4. One bilateral assertion in the scenario harness\n\n- `core/scenarios/consensus/ahb-helpers.ts:237\u2013296` duplicates `core/scenarios/harness/helpers.ts:702\u2013756` (`assertBilateralSync`). Both compare exactly the same seven Delta fields and reject missing Account/Delta evidence.\n- Retain the shared harness assertion; import it directly in `core/scenarios/consensus/ahb.ts:56` rather than exporting another wrapper. Existing retained-path consumers are `payments/lock-ahb.ts:22` and `settlement/processbatch.ts:22`.\n- Measured removable body: **60 lines**; estimated net deletion **58\u201359 LOC** after import changes. No production financial formula changes.\n- Caveat: AHB currently prints fuller missing-side and Delta diagnostics. Preserve useful first-divergence evidence in the retained helper where necessary, or the final net reduction will be smaller. Exact error strings differ, so check any consumers before deleting.\n- Small existing test: `bun test core/__tests__/testing/scenarios/scenario-helpers-time.test.ts`; L2 must run both real `ahb` and `lock-ahb` scenarios under the stand lock because the existing small test does not prove this assertion. Do not delete the AHB scenario as a duplicate: it covers distinct stress/settlement behavior.\n- Adjacent non-equivalence: `ahb-helpers.ts:134\u2013163` manually drains J events once; the shared `helpers.ts:767\u2013771` uses `drainJWatcherBacklog`. That needs a behavioral investigation and cannot be included in a cosmetic helper merge.\n\n## 5. Retire the source-string E2E surrogate from launch acceptance\n\n- `core/scripts/checks/policy/check-flow-e2e-coverage.ts:33\u2013215` checks substrings in frozen Svelte/cross-J code, a hand-maintained list of test titles, and a synthetic old cross-J filename. A comment containing a marker satisfies it; it executes no financial behavior.\n- Called by `run-release-gate.ts:142` through `test:e2e:coverage`. Actual current React execution is already in `run-release-gate.ts:158\u2013174`; its membership is checked by `tests/release-integrity/release-gate-order.test.ts` and its browser results provide evidence.\n- Retain the actual React execution/results as the launch authority. Remove this surrogate from release acceptance, while keeping frozen feature tests runnable for their own maintenance. If no independent caller needs the checker, delete its file and package command after searching all callers.\n- Measured potential deletion: **231 LOC** in the checker, plus its command/step. This is conditional on completing the caller search; no claim that all old browser tooling can be removed.\n- Caveat: the React launch matrix must actually include each required live financial journey. Removing a marker list is not permission to remove swap, funding, exit or restoration assertions. It should not wait on an all-repo test taxonomy.\n- Small existing regression: `bun test tests/release-integrity/release-gate-order.test.ts`; then the existing React groups under the stand lock. This change is not proven by a grep-only test.\n\n## Kept deliberately\n\n- Frozen-core check/history: owner explicitly retained it even with zero protected files.\n- Rust/TRON benchmark and archived acceptance tools: indexed, no source edits or speculative deletion. Frozen scope does not mean historical evidence can be erased.\n- XLN-1000 and binary release coverage have different purposes by owner decision; do not merge them into one flattering score. `tools/xln1000/measure.ts` already assembles one set of axes. The useful reduction is removing stale parallel scope definitions, not inventing another metric."
    },
    {
      "name": "adjacent",
      "indexedFiles": 213,
      "physicalLines": 74479,
      "focusedFiles": 39,
      "report": "# Adjacent sources: canonicalization review\n\nSource: `b07da2b8762d3398683f3f2c481ee65a8caedc41`.\nScope: all 213 assigned TS/TSX/Rust blobs (74,479 physical lines). No source edits, tests, benchmarks, external models, or service changes were made. Every blob was read mechanically for immutable content hash, imports, exports, duplicate windows, and scope flags. Semantic review is explicitly limited to the deep/section path lists in `adjacent-coverage.json`; indexing is not a claim of reviewing every line for correctness.\n\n## Highest-value change: one Brainvault shard admission boundary\n\n**Priority:** production React/hosted identity correctness. **Confidence:** high on the duplication and divergent rejection behavior; implementation still needs the tests below.\n\n- Canonical owner already exists: `brainvault/src/native/shard-collector.ts:17\u201341` (`acceptShard`), with `createShardSlots` at 10 and `finalizeShards` at 44. It uses strict `brainvault/src/core/primitives/encoding.ts:9\u201320` decoding, checks spec, exact index/range, duplicates, request fingerprint, and output length.\n- CLI already consumes it at `brainvault/src/cli/index.ts:1309\u20131316` and finalizes at 1350.\n- React independently decodes hex at `ui/src/runtime/brainvault.ts:47\u201354` and accepts worker results at 139\u2013142. This decoder permits an optional `0x`, does not validate odd length/non-hex, and converts failed `parseInt` values to zero bytes in a typed array. React ignores `specId` on `ready` (136\u2013137) and ignores `specId`/`requestId` on `shard_complete`. The browser worker supplies both at `brainvault/src/native/workers/browser.ts:67\u201372` and documents stale cached worker identity drift at 8\u201310.\n- Hosted native derivation repeats the collector checks at `brainvault/src/native/index.ts:191\u2013228`, plus missing-slot validation at 264\u2013266. This is mostly stricter duplicate code, not a different required financial rule.\n- Callers: `ui/src/screens/Gate.tsx` / `ui/src/native/brainvault.ts` call React derivation; `core/api/server/ownership/brainvault.ts` calls hosted native derivation. These paths are reachable in the release despite the separate `brainvault/` directory.\n\n**Change:** use the existing collector in React and hosted native; adapt browser message `resultHex` to the collector's `result` at the transport edge. Verify the ready spec before dispatch. Keep browser/native worker pools separate: native worker isolation prevents an already-documented native Argon concurrency corruption (`native/index.ts:16\u201320`). Preserve root domain, NFKD, factor, shard order, and all V1 bytes. Do not introduce a generic worker framework.\n\n**Semantic differences requiring explicit preservation:** native rejects request mismatch before duplicate while the collector checks duplicate first; malformed-multi-fault precedence will change unless retained intentionally. Native missing-slot error is `BRAINVAULT_NATIVE_SHARD_MISSING`, collector uses `BRAINVAULT_WORKER_SHARD_MISSING`. Neither is a consensus hash, but tests/error UX must be checked. React gains intentionally stricter boundary rejection. Native wipes shard/master/entropy buffers; React currently does not wipe those buffers at 161\u2013170: use existing try/finally conventions while integrating, without claiming strings can be erased.\n\n**Size:** native redundant validation is 38 physical lines plus a 3-line missing check; estimated net native saving 25\u201335 lines after canonical call/imports. React deletes an 8-line lax decoder; strict transport handling may increase its LOC. The stronger metric is 3 semantic admission implementations becoming 1, not a promised net total.\n\n**Proof needed:** existing collector malformed scheduling and no-secret-error tests (`brainvault/tests/core.test.ts:286\u2013330`); actual React stale-spec and malformed-result handling; browser/native deterministic frozen mnemonic agreement; duplicate/out-of-range/wrong-request result must fail before wallet creation; abort/error cleanup; `bun run check`. No mocks or test-only crypto path. Wallet reviewer has acknowledged this as this report's finding to avoid duplicate counting.\n\n## Retire the adjacent debates daemon dialect before re-enabling that app\n\n**Priority:** deferred, outside the Ethereum/React release. Do not repair custody/debates as a release prerequisite.\n\n- `debates/xln-client.ts:155\u2013156` sends a private `{id,type,key,...}` WebSocket envelope; methods at 163\u2013192 use `get_frame_receipts`, `find_routes`, `queue_payment`. It duplicates a 116-line transport/request lifecycle (78\u2013193), response types (3\u201341), and capability creation (49\u201374).\n- Its caller is `debates/server.ts:8,31`. The only matching legacy server in the inspected repository scope is the application fixture `debates/tests/fixtures/fake-daemon.js:14\u201327`; production runtime-adapter exact request schema and server dispatch consume `op`/versioned requests. Existing fake-backed E2E therefore does not establish compatibility with current production.\n- Canonical transport is `core/api/runtime-adapter/remote.ts:RemoteRuntimeAdapter`. `custody/daemon-client.ts:127\u2013232` already wraps that adapter and requires an owner-bound command lane for durable payments; payment admission at 307\u2013380 includes `maxSenderDebit`, `commandId`, `commandSequence` and exact route validation. Debates' old result/request types lack those fields and retain `mode: 'direct' | 'htlc'` versus current payment delivery modes.\n- Capability duplication has already drifted: `debates/xln-client.ts:49\u201374` generates expired/arbitrary-TTL capabilities; `core/api/runtime-adapter/security/auth.ts:118\u2013150` checks expiry, TTL, normalized fields. `debates/tests/unit/capability-token.test.ts:9` deliberately passes the historical timestamp `123456`, so replacing the function requires changing that test to a valid future expiry plus rejection cases, not weakening the canonical creator.\n\n**Change when app scope reopens:** replace the app's private protocol with `RemoteRuntimeAdapter`, canonical token derivation, and canonical response types. Preserve app-local ledger/reservation/idempotent withdrawal intent; do not make `custody/` the shared transport owner and do not blindly alias its payment method without durable owner-command storage. Keep the app outside the production deployment in the meantime.\n\n**Size:** 194-line file is the gross obsolete surface, not a proven net saving. Capability-only replacement could remove 26 lines plus the local HMAC dependency (estimated net 20\u201325). Full migration net LOC is unknown because required durable command handling is currently absent. Do not sum capability savings separately if the whole client is replaced.\n\n**Proof needed:** connect the real current adapter, authenticated read, exact once withdrawal after lost response/reconnect and capability renewal; expiry/TTL rejection. No fake-daemon pass as financial evidence.\n\n## Fold the two Metal benchmark drivers into one parameterized invocation\n\n**Priority:** low; tooling only, must not delay public P6 or unfreeze the production Rust engine.\n\n- `brainvault/src/native/source/experimental/benchmark.ts` and `brainvault/src/native/source/metal/benchmark.ts` are each 302 lines. Immutable `diff -u` has only two semantic hunks: executable selection (experimental line 67 versus metal 67\u201370) and the experimental 10,000-shard expected-root assertion (experimental 263\u2013265).\n- Mechanical duplicate-window check found 213 identical eight-line windows between them, the largest adjacent first-party duplicate. This is an actual duplicated harness, not two required cryptographic oracles.\n- Invocation references are recorded in `brainvault/docs/evidence/benchmarks/gpu/lookahead-10000-2026-09-05.json:97\u2013202` and `lookahead-method.md:16`; packaged canonical Metal driver is listed in `brainvault/docs/manifest.sha256:58`.\n\n**Change:** retain one benchmark entrypoint under `source/metal/benchmark.ts`, accepting explicit executable path and expected root, and delete the experimental copy. Do not change native hashing kernels. Preserve historical evidence documents and their SHA; update only future-run instructions and package manifest through its existing generator.\n\n**Size:** 302 gross duplicate lines; estimated 280\u2013295 net lines after two explicit options and validation. Not measured until implemented. This does not reduce the production wallet financial audit surface.\n\n**Proof needed:** argv rejection, explicit path resolves to intended backend, expected-root mismatch fails, tiny real CPU/Metal parity under the machine stand lock. No performance claim from source comparison.\n\n## Explicit non-deletions\n\n- 69 vendored Rust dependency files / 42,416 LOC belong to Argon2/memchr. They are dependency review inventory, not duplicate first-party account engines. Preserve hashes and upstream provenance; do not rewrite SIMD implementations to cosmetically shrink the tree.\n- 37 archived sources / 5,541 LOC are historical reference. `.archive/2024_src/app/Channel.ts` is explicitly normative for bilateral semantics in AGENTS. It is not a second production route.\n- 28 proof sources / 8,270 LOC are fuzz/differential/bounded verification artifacts. `proofs/kani/src/lib.rs:1\u201330` explains why a bounded delta mirror and independent equivalence transcription exist. Sharing the implementation under test would destroy the oracle. The radix proof already includes pinned production files. Rust proofs remain outside active release gates while rscore is frozen.\n- `brainvault/src/core/bip39-english.ts` deliberately vendors the exact wordlist and tests its hash/order. Replacing it with an npm-sourced convenience encoder is not a justified reduction of recovery risk.\n- `native/__tests__/watchtower-recovery-flow.test.ts` is a 734-line core recovery test with Svelte adapter wiring, not an iOS binary. Folder-name exclusion would discard recovery evidence. Preserve or port its unique assertions before removing a frozen frontend dependency.\n- Custody and debates stores share 22 eight-line windows, but business balances and withdrawal intents have distinct owners. No safe whole-ledger merge established; no generic financial reducer recommended.\n\n## Method adjustment\n\nTrack active production reachability separately from total repository size. Every proposed deletion should name the surviving owner, semantic differences, unique tests and bytes/authority that must remain unchanged. Preserve independent oracles and platform boundaries. Re-evaluate every 30 minutes whether a finding yields a tested production reduction; defer benchmark or adjacent-app work if it displaces the current public exit boundary."
    }
  ]
}
