Plan: open-holding accounting for the /portfolio Holdings rows
Every row in the signed-in /portfolio Holdings tables describes the holding that is open now and nothing else: its accruals, its entry basis, its dislocation, its price PnL and the day it was put on all start when the holding starts, blend on additions at an average entry, leave the row in proportion on a reduction, travel with the holding through a rotation (a wrap, a redemption request), and vanish with the row at a full close. The charts and the NAV history keep counting everything that ever happened. Today only some of the row's figures behave that way.
Grounded on staging at 8151349f (2026-10-16). Nothing in this plan is stored, migrated or backfilled: every figure is derived at read time from the ledger the engine already replays, as the entry basis, the PT lot book and the cross-currency price walk already are. There are no live users (test wallets only), so nothing ships behind a flag, no API field is kept for compatibility, and a one-shot cut-over per PR is the rollout.
0. Rulings (Fred, 2026-10-16; settled, not re-litigated here)
- Charts and NAV history: unchanged. The MTM PnL and Accrual only PnL lines and the Net asset value card keep realized and unrealized results as time passes, closed positions included.
- A row shows only the open holding. A full close removes the row from Holdings; its result lives in the charts and the Activity tab. Reopening the same market starts from scratch on every figure.
- Additions blend into an average entry (average, not FIFO). Reductions leave the average per unit unchanged and realize the exited share out of the row, basis and accruals both, in the proportion exited units / balance at that moment.
- A transfer out is a reduction at that moment's price; a tracked receiving wallet accounts for its own holding from then on (today's rule, kept).
- Carries: reductions per leg. The plain carry's expansion shows the split on its Net line: accruals, dislocation, total, the way the PT variant already shows MTM PnL · Accrual PnL · Total PnL.
- Rotations carry basis and accruals across (wrap, token to its redemption ticket). The In settlement row opens and shows At entry / Current / Dislocation PnL plus the carried Lifetime accruals.
- stETH is market-priced with a redemption value. Already true in the registry (migration 131 sets stETH and wstETH both to
staking); PR #1164 pinned it with a unit test.
Cross-currency Price PnL since entry already behaves this way (M36); only its Lifetime accruals figure changes. The dust floor's "has earned more than the floor" exemption goes away with ruling 2.
1. What the page does today (grounded, not assumed)
- Lifetime accruals is a whole-replay running sum.
legPerformance(src/lib/portfolio/v2/attribution.ts:837) groups bookings bypositionKeyalone, never by span, and adds every interval'saccrualandtotalReturn(:861-865). Nothing leaves on a reduction; a close plus reopen on the same market inherits the earlier holding's earnings; a dust residual keeps the full history. Its one production caller is the row builder (src/lib/portfolio/ledger-v2-api.ts:2612), served asyieldRedemption/yieldMarket(:2751-2758, wireapi-types.ts:581-582). - At entry resets per span (M30) but "exits net into At entry": every ordinary kind, exit kinds included, adds its signed basis to the span's
entered(src/lib/portfolio/v2/entry-basis.ts:1114-1119), so after a partial withdraw the figure shown against the remaining units carries the exited slice's realized dislocation. Rotations carryreleasedBasisandvintageTsthrough the link group (GroupCarry,:839) and nothing else; a DEX trade (meta.swapBook, #1077) starts fresh. - Already open-holding today: the PT lot book (
pt-accrual.ts, pro-rata disposal:599), the cross-currency price walk (price-since-entry.ts:enter:487blends an average,leave:491takes the ledger's own share, reset at close), Net APY and Projected daily accruals. - Charts and NAV come from
buildCurve(attribution.ts:261), which never callslegPerformance; Accrual only PnL iscurve.points[].cumulativeYield(ledger-v2-api.ts:3713). The All view's NAV line isallValueReadings(:1636-1642), which applies the SERVER dust rulehiddenAsDust(:577) at every point, and that rule's "never a return" exemption reads the whole-history booked return. So the server floor is part of ruling 1's surface and stays as is. - A ticket never opens.
dislocationApplies(src/components/portfolio/v3/model.ts:324) refusesinSettlement, andbasisSectionApplies(:337) is an alias of it. A ticket is priced as its payout asset (rowPricingFor,ledger-v2-api.ts:1808-1833), so every ether-queue ticket servesplain_token, whichNO_REDEMPTION_VALUE(model.ts:308) also refuses. Yet the ticket already carries a basis: the fixture's osETH ticket servesbasisEntered -0.0124beside its ownyieldRedemption 0.0184; the Lido ticket serves quantity 9.2179 andbasisEntered +0.0055. - The plain carry's Net line does not foot.
LegTablesums the legs'yieldRedemptionitself (CarryBlock.tsx:206) andNetRowprints that one number (:249), while the row's Lifetime PnL cell above usescarryPnlOf(accruals plus dislocation plus PT mark-to-market). On a wstETH/WETH carry the Net line is strictly smaller than the cell above it. - The identity test.
entryBasisIdentity(entry-basis.ts:1891) formsbridge = receiptContribution - nettedBasis + openingBridge, andenteredis the anchor plus the samereceiptContribution. The receipt term cancels out ofdislocation + bridge, so the identity is structurally blind to HOW a receipt contributes toentered: ruling 3 cannot break it, and it cannot bless ruling 3 either. What ruling 3 retires isexact(bridgeis no longer 0 on a reducing span). A new conservation law has to carry the guard (section 2.3).
2. The model
2.1 State, per open holding
Keyed by (positionKey, spanIndex), where the span index is the engine's own (M30: it advances once per block that drove the leg's quantity to zero, engine.ts:2754, and entry-basis.ts:766-775 walks the same rule), so basis and accruals always describe one holding, joined on the span key the engine books against (currentSpanBasis, ledger-v2-api.ts:1498).
| field | meaning |
|---|---|
unitsOpen | units put in, net of the shares that left, in the leg's OWN ledger unit (a scaled aToken count, a Fluid normalized amount, a pool share; never a token amount mixed with amountRaw) |
avgEntry | book per unit, average over the current holding, unchanged by a reduction |
enteredBasis | the remaining entry basis, equity-signed, in the book (M32's entered, re-scoped) |
accrualOpen, totalReturnOpen | the two cumulative lines, for the open holding only |
heldSinceTs | the span's vintage (vintageTs, entry-basis.ts:385, derived today and dropped on the floor) |
realizedAccrual, realizedTotalReturn, realizedBasis | what left the row on reductions, kept as internal state and as reconciler counts |
approximate | a reduction's share could not be read from the ledger, so the figure is a floor |
inherited | part of the figure came through a rotation (vintageInherited already exists for the vintage; the accrual reuses the same flag family) |
2.2 Events (one primitive, one rule each)
- Sub-interval boundary (the accrual credit): add the sub-interval's
bookedto the open holding whose absolutespanIndexit carries (WalkSubInterval.spanIndex,engine.ts:944). Filter on the sub-interval's absolute span index, never onbooking.spanKeyorspanKeysTouched: a bridged sub-interval anchored in an earlier span carries that earlier index and is correctly excluded. Credit before haircut, deliberately: a full exit then carries that interval's earnings out with the realization instead of stranding them on a row that no longer exists, which is what makes the conservation law exact at a close. The error against a true intra-interval split is bounded by share x one 6h interval's accrual on that leg; M37 states the bound as a number. A booking withbooksZeroor emptysubIntervalsis nothing to walk, never a close (engine.ts:2947; a W2 withhold can empty one line's sub-intervals while the other's are populated). - Inflow (deposit, borrow, transfer_in, internal_in, income, cost, adjustment up): the average-entry blend lifted verbatim from
walkHolding.enter(price-since-entry.ts:487),avg <- avg + (p - avg) q / (Q + q),Q <- Q + q, in the incremental form so a purchase struck at the current average leaves it bit-for-bit unchanged.income/costkeep booking zero return (classify.ts) and enter the basis as they do today; they are not re-cast as cost-basis additions. - Reduction (withdraw, repay, transfer_out, internal_out, adjustment down):
share = clamp01((before - after) / before)from the ledger's own two balance columns at that receipt;Q <- Q (1 - share), average unchanged;accrualOpen,totalReturnOpenandenteredBasiseach scaled by(1 - share)with the complement added to the matching realized accumulator.stateOnlyreceipts move nothing and are skipped. - Reduction whose share the ledger cannot state (
toBalancenull): never guess, never publish a measured zero. Fall back to the exit's own value off an entry-valued size exactly aswalkHolding.leavealready does, setapproximate, and serve the figure with the~marker and a tooltip (section 8, Q3). - Full close (quantity to zero at end of block): share 1, everything realizes out, the span index advances, the next holding starts from scratch on every figure. No row is served at zero balance anyway; ruling 2's reset is what makes the REOPEN correct.
- Rotation (internal_out / internal_in in a link group: wrap, token to its redemption ticket, GHO to stkGHO/sGHO): the released slice's accruals ride the basis.
GroupCarrygainsreleasedAccrualbesidereleasedBasisandvintageTs, distributed by the same returned-quantity shares, the same hand-back split and the same fixed-point convergence, measured net of the span's own group-derived accrual the waySpanRun.fromGroupalready does for basis. Gated oncarriedByGroup(entry-basis.ts:580) and nothing else, soentry-basis-source.test.ts's one-place link-kind test stays green. An unreadable carry marks the destination partial, never a silent zero, and degrades PER GROUP, not per wallet. The RUNNING accrual at a mid-interval rotation receipt is the open holding's accrual through the sub-interval that ends at that receipt (the engine seals a sub-interval at every receipt, so the figure exists); M37 names this input. - DEX swap (#1077,
meta.swapBook): strikes fresh on both sides. The paying leg is a full realization, the received leg a new holding with its own average, basis, held-since and zero accruals. Reached throughisTradeRow(entry-basis.ts:569), nowhere else. - Restatement (a second
opening, or a reading correction): only the change it states moves: a positive change enters at the opening's own price pro-rated to the change, a negative change leaves as a share (price-since-entry.ts:515-532). PT'sstatesPtset-to stays PT's own. - Seizure / debt_relief: a reduction of units for the accrual walk and the basis walk (the units are gone, so their share of earnings and basis goes with them), while staying out of the basis as an entry and one-sided in the law's flow sets (
seizureis in the accrual set and NOT the total-return set,classify.ts:376-398). The total-return line therefore keeps the liquidation loss booked on the survivors' span and is NOT haircut by the seizure's share, so a partial liquidation does not realize part of its own loss out of the row at the moment it books it. Composition with a cross-book netting delta on the same sub-interval (cross-book-seizure.ts:636-672) is decided in PR 2's design note. Needs Fred's confirmation (section 8, Q2). - As-of read: the loader already truncates both stored relations at
asOf.endSec(ledger-v2-loader.ts:899-900), and the entry basis and the PT lot book both stop at the day's LAST READING (asOfCheckpointBlock,ledger-v2-api.ts:1224, threaded aslotBookThroughBlock:1245) while the engine books over the rest of the day. The open-holding walk takes the SAMEcheckpointBlock(receipts after it do not haircut, a close after it does not advance the span the row describes), so At entry, Dislocation PnL and Lifetime accruals describe one holding on a dated statement. - Multi-wallet account: one engine run per wallet, one open holding per (wallet, positionKey, span). The like-for-like merge (
signed-in-model.tscoalesceLikeLegs,:1883-1960) sums each wallet's open-holding figures and takes the OLDESTheldSinceTs(the derivation's N-to-M vintage rule);approximateandinheritedare OR-ed. Each new field gets an explicit merge rule at every one of the fiveDisplayPositionassembly sites, because...firsthas already shipped two misstatements there (:1908-1920). - Transfer to a tracked wallet of the same account: an ordinary reduction at that moment's marks, never a rotation (
transfer_outis in both flow sets, capital at wallet scope only; thecross_walletgroup exists for the account roll-up). The receiving wallet's run accounts from itstransfer_inon. Ruling 4, asserted in PR 2, no code change. - Look-alike incoming dust tagged spam (#1167): still a ledger receipt, still enters the walk, so the share is computed against the ledger's balance, not the display's.
2.3 The guards
entryBasisIdentityis kept verbatim. It keeps reportingholds;exactadditionally requiresrealizedBasis === 0, and the assertions pinningexact === trueon a reducing or closing span (swap-entry-basis.test.ts:199-201, :234) are restated. The PR body says plainly that the identity never tested the exit rule and does not bless the new one.- The conservation law, new, per open holding, with its two sides from different code:
accrualOpen + realizedAccrual(the walk) equals the ENGINE's own per-span accrual read offsubIntervals[accrual][].spanIndex; summed over a leg's spans it equalslegPerformance's whole-leg cumulative, which is that leg's contribution tobuildCurve.totalYield. Same law fortotalReturnand forenteredBasis + realizedBasisagainst the pre-change span figure. The population is stated: the law is evaluated on every booking the row sums (W4 position-attributed intervals included, because the row publishes them today), NOT onbookedGapBySpan's blocked set (entry-basis.ts:2035-2048blocksbooksZero, withheld lines andpositionAttributed), and the non-vacuity test proves the Fluid smart-pair and financed wallets are inside it. Mutation discipline: the law must go red by at least 10x tolerance when the span filter or the haircut is perturbed (src/lib/portfolio/v2/fixtures/mutation.ts). - Ruling 1's proof:
buildCurve's points,totalYield,totalReturn,twrandrealizedApybyte-identical before and after, on the close-and-reopen fixture; and the golden gate'shistory.json,summary.json,activity.json,events.json,coverage.jsonempty of diffs on every PR of this plan. - Bridge decomposition, named:
SpanEnteredBasispublishesrealizedBasisandexitGapNetted(whatsignedFlowBasiswould have netted), and a cell assertsbridge === openingBridge - realizedBasis - exitGapNetted + rotationTerms. This cannot catch a wrong share (a proportional split is sum-preserving for any share); it turns the identity's silent absorption into an inspectable statement. The share itself is tested by the unit cells. - An ops-visible count. The open-holding figure is a read-time layer no alarm evaluates, the same situation as cross-book netting, whose precedent is a counted line on
BookedWallet(reconcile/booked.ts,BookedWallet.crossBookNettings). PR 1 addsopenHoldingReductions(reductions haircut, realized-out total, legs whose open-holding figure differs from the whole-replay one), reported by the 6h ledger self-check, emitted at zero, never paged.
3. Architecture
One new pure module, src/lib/portfolio/v2/open-holding.ts, with explicit input and output types and no I/O: the reduction-share primitive (shareFromBalances, shareFromDelta, both returning { share, stated } over one clamp and one documented fallback) and the walk (legOpenHolding(result, points, opts) -> OpenHoldingFigures[], span-scoped by absolute span index, credit-then-haircut, throughBlock for as-of). The existing walks become consumers of the primitive rather than keeping their own copy of the share arithmetic: price-since-entry.ts leave, entry-basis.ts releaseInto's fraction, pt-accrual.ts disposePro / sliceLots. The PT lot book itself is NOT rewritten onto a shared accumulator: per-lot invariance is what makes the cross-leg settlement pairing order-independent (pt-accrual.ts:545), and the PT block already satisfies rulings 2 and 3 structurally. capital.ts's nonCapitalShareAfter is a share-of- composition rule, not a reduction share, and is left alone with a comment naming the primitive.
legPerformance is never narrowed, then retired. buildCurve never reads it, so the row builder's single call site switches to the open-holding walk and ruling 1 is provable by a golden diff confined to positions.json; once nothing reads the old reducer, PR 2 deletes it rather than keeping two per-position reductions of the same bookings. The conservation law's independent side is the engine's sub-intervals, so the guard does not need it.
Wire contract rewritten in one place (src/lib/portfolio/api-types.ts, PositionRow): yieldRedemption, yieldMarket, basisEntered keep their names with rewritten contracts; realizedApyMarket, realizedApyRedemption, observedDays are re-scoped to the open holding (section 8, Q4); heldSinceTs, accrualsApproximate, accrualsInherited are added with M9 null contracts. No compat fields, no optional-for-old-clients shims.
Display reads flags, never recomputes. signed-in-model.ts carries the new fields through its five assembly sites with an explicit merge rule each; the blocks render them; category-model.ts decides which rows open; CarryBlock.tsx lifts the PT table's formatter out so the plain table and the PT table print identically instead of growing a second one.
Untouched, and why: buildCurve, buildV2History, allValueReadings, hiddenAsDust, bookedReturnIndex (the NAV coupling); the engine's bookings (runEngine, W4 re-split); the PT lot book; the Activity reader (R11, token amounts only, section 8, Q1); the server dust floor's exemption (a test pins it as whole-history so a later unification goes red instead of moving the NAV line, and its comment at ledger-v2-api.ts:564-567 is rewritten to say the two floors are now different rules on purpose).
4. PRs, in order (each independently green, reviewed, explainable)
| # | PR | days |
|---|---|---|
| 1 | Share primitive, fixtures the rulings are measured on, reconciler count, this plan | 2.5 |
| 2 | Accruals: a row states its open holding (engine, wire, goldens, M37) | 4 |
| 3 | Display plumbing: the new fields through the model, the ~ marker, the dust floor's exemptions | 2 |
| 4 | Basis: At entry states the units still held; a reduction realizes its basis share out | 3 |
| 6 | The plain carry's Net line foots: Accrual PnL · Dislocation PnL · Total PnL | 2 |
Scope cut 2026-10-16 (Fred): PR 5 (a rotation carries its earnings with its basis) and PR 7 (the In settlement row opens; Held since) are out of this plan and filed as the enhancement issue named in section 7. Their sections below stay as the record of the design. PR 5 shipped on 2026-10-17 as part A of that issue (#1179): a rotation carries basis, vintage and accruals across, accrualsInherited is served and drawn as a tooltip note on the Lifetime accruals figure, and the total-return line does not carry (the deviations are recorded in M37). PR 7 shipped on 2026-10-17 as part B (#1181): the In settlement row opens onto its basis and every basis table closes on Held since (the deviations are recorded in the header).
Dependencies and the parallel schedule (two implementers at a time is the ceiling on the 8 GB machine, and only one of the two may be building a fixture database or driving a browser at any moment, serialized by a lock; reviewers are read-only and do not count):
| wave | lane A | lane B | why these two can overlap |
|---|---|---|---|
| 1 | PR 1 (primitive, fixtures, count) | PR 6 (carry Net line) | PR 6 is display-only and reads figures that exist today |
| 2 | PR 2 (accrual walk) | PR 4 (basis realization) | both need only PR 1; different modules (open-holding.ts vs entry-basis.ts); both move positions.json, so whichever merges second rebases on staging, regenerates the goldens and rewrites its per-wallet explanation |
| 3 | PR 3 (display plumbing, dust floor) | needs PR 2's fields |
Three waves. Never two PRs in flight that both edit the row builder's served fields (2 and 3).
Legacy removal is part of every PR (Fred, 2026-10-16): each PR deletes, in the same diff, every code path, type, test, comment, tooltip and doc sentence the change makes dead or false. No compat shims, no "kept for reference". In particular PR 2 retires legPerformance / V2LegPerformance (attribution.ts:785-937) once the row builder, the realized rates and the impairment path read the open-holding walk, and moves the curve-equality cells (attribution.test.ts:566/:616) onto the conservation law, whose independent side is the engine's own sub-intervals, not the old reducer. PR 1's fixture wallet 5 (the readable carried-accrual ticket) moves to the enhancement.
Decisions taken 2026-10-16 (Fred): section 8's Q2 to Q10 as recommended. Q1: a closed position's result stays in the charts; the Activity tab keeps its token-amounts-only rule. Q10: issue #1171 filed.
PR 1. Groundwork with no figure movement
open-holding.ts(new):shareFromBalances,shareFromDelta,ReductionShare; unit tests for the clamp at both ends, a share the ledger cannot state, a set-to restatement, a share on a scaled balance, a mutation cell per rule;boundary.test.tspins its import boundary.- Re-point
price-since-entry.tsleave,entry-basis.tsreleaseInto,pt-accrual.tsdisposePro/sliceLotsat the primitive. Behaviour bit-identical; every existing test green (price-since-entry.test.ts:130/:154/:588, the group-carry fixed point and its share denominator summing to exactly 1,pt-detail.test.ts). reconcile/booked.ts: theopenHoldingReductionscount line besidecrossBookNettings, zero until PR 2, so the first open-holding deploy is observable in ops.- Fixtures (
scripts/fixture/seed.sql, isolated wallets, magnitudes unique per seed rule 3;generate-values.tsthengolden-portfolio.ts, each alone):- a full close followed by a reopen on one position key inside the window (replaying end-of-block occupancy over the fixture finds one such leg, 0xaaaa…'s movement-only wstETH, closed into the Lido queue and reopened from it, which no reading holds and so serves no Holdings row; none a row shows);
- a carry that reduces its collateral leg only;
- a carry that repays its debt in full and re-borrows (the leg's funding cost resets; the row leaves and re-enters Carry trades);
- a partial reduction on a dislocation-bearing asset whose market-to-redemption gap MOVED between entry and exit (on a constant gap, netting and proportional realization coincide and PR 4 would produce an empty diff on the wallet meant to prove it; the PR body writes both answers);
- (moved to the enhancement issue with PR 5) a redemption ticket whose carried accrual is readable and magnitude-distinct from the ticket's own.
src/lib/portfolio/v2/fixtures/matrix.ts: the new scenario cells registered asscaffolded(the registry's status for a cell with no test yet);matrix-coverage.test.tsmakes each flip in the PR that implements it.- Two decisions written here so implementation order cannot set them: the walk stops at
checkpointBlockon an as-of read; the conservation law's population is the row's (W4 included). - Docs: this plan to
executing, index regenerated. No metrics or portfolio page change. - Review focus: every re-point arithmetically identical, clamp order and fallback branch included; no existing wallet's figures move on any surface (the PR's whole claim); the new wallets are isolated (
tests/e2e/portfolio-v3-holdings.spec.tsrow and block counts are the canary).
PR 2. Accruals: a row states its open holding
open-holding.ts:legOpenHolding(the walk of section 2.2, withthroughBlock).ledger-v2-api.ts:2612: the sibling call;:2751-2758serveyieldMarket/yieldRedemptionfrom the open-holding figures inside the UNCHANGED withhold chain (noReturnLine,routeWithheld,c5AnyAt,withheld), so no row gains a measured zero on an unproven wallet. ServeheldSinceTs,accrualsApproximate,accrualsInherited(from the span's existingvintageInheritedfamily). Re-scoperealizedApyMarket/realizedApyRedemption/observedDaysto the open holding's observed span with M8's 30-day gate applied to that span (section 8, Q4); keepimpairedIntervalswired sopt-accrual.test.ts:1979-1981(the only end-to-end assertion that a PT impairment withhold reaches a served cell) stays green and is listed in the PR body.price-since-entry.tstokenAccrual(:306-316) re-scoped to the current holding via the exportedcurrentHolding, its header rewritten (its whole-history justification dissolves);price-since-entry.test.ts:650-663restated; theetherMomentslockstep test re-pinned against the walk the figure now reads; the dollar-book short-circuit kept.api-types.ts: the rewritten contracts; the stale module path at:587corrected;:616's "not shown on the page yet" corrected in PR 7.attribution.ts:legPerformanceuntouched; the stale comment atpnl.ts:527corrected.- Stale claims removed wherever the repo asserts row = chart:
signed-in-model.ts:836-838,ledger-v2-api.ts:506,:565,:2748-2749(made TRUE instead: the open-holding accruals and the open-lot carry finally agree),api-types.ts:568,:726-731,docs/data-pipeline.md:5216. quarantine-alert.ts:191andquarantine-alert.test.ts:57: the impact sentence still names the realized rates (they are re-scoped, not dropped); re-read and re-pin.scripts/ops/comparator-classify.ts:1092: one note that the realized-rate class now recomputes over the open holding's observed days.- Tests: the walk (reset at close, haircut at a reduction, credit-then-haircut at a close, bridged sub-interval excluded,
booksZerois nothing to walk, as-of checkpoint); the conservation law with its population and mutation cells; ruling 1's byte-identical curve proof on the close-and-reopen fixture;attribution.test.ts:566/:616kept green and annotated;ledger-v2-api.test.ts's exact served accruals re-pinned; ruling 4 asserted on the tracked-to-tracked transfer wallet; the row- versus-card span difference (the summary keeps its whole-viewrealizedApy/observedDays,api-types.ts:337, :354) named in one sentence in M37. - Goldens:
positions.jsonmoves on about 21 wallets plus the three account views, each capture (live plus two as-of) explained per wallet: which reduction, close or rotation moved which figure.history.json,summary.json,activity.json,events.json,coverage.json,activity-filters.json: empty diff, which is ruling 1's evidence.ptDetaildoes not move (ptDetailForRow,ledger-v2-api.ts:2318-2348, never reads the two cumulatives). - Docs:
docs/metrics.mdnew M37, the open holding (state, events, credit-then-haircut with its bound as a number, the conservation law and its population, the~rule, the as-of checkpoint, the row-versus-card span); M36b restated; M22/M24/M30 cross-references;docs/portfolio.md:1036and:1296-1301(the sentence equating a row's Lifetime accruals with the Accrual only PnL line is false and is replaced by why the two legitimately differ). - On-screen: Lifetime accruals (every block with the column; same label, narrower meaning), Lifetime PnL (Carry trades) moves with its accrual term, Net value (the Cross-currency expansion) moves with its accruals figure while Price PnL since entry does not. Net asset value, Net APY, Projected daily accruals, both chart lines: unchanged, proven unchanged.
- Browser specs that assert accrual figures and run only on the release PR, run locally by the author on the affected pages:
portfolio-cross-book-liquidation.spec.ts:226-253,portfolio-v3-asof.spec.ts,portfolio-v3-positions-holdings.spec.ts,portfolio-cross-currency-taxonomy.spec.ts,repo-lending.spec.ts,portfolio-fund-identity.spec.ts. - Review focus: the span filter uses the sub-interval's ABSOLUTE index; the withhold chain is byte-identical; the share is read in the leg's own ledger unit; the conservation law's two sides come from different code and its population is the row's; a full exit's final-interval accrual leaves with the realization.
PR 3. Display plumbing and the dust floor
signed-in-model.ts: the three new fields throughstandaloneOf, the carry fuse, the smart-pool fuse,mergeStandalonesandcoalesceLikeLegs, each with its stated rule (oldest held-since, OR-ed flags,observedDayskeepsMath.minover the re-scoped figure).positionPassesMinValue(:943-944): the earnings clause deleted; the withheld-mark, debt-leg, annotation and matured-PT carve-outs stay. It does NOT collapse intoallHoldingPassesMinValue(:1658): the denomination rule exempts any row with a debt leg while the All rule exempts only an entry holding both an asset and a debt leg, and the matured-PT carve-out has no All equivalent. The copy becomes four classes on USD/ETH and three on All.dashboard-model.tsMIN_VALUE_TIP(:142): "Five kinds of row" becomes four, the earnings sentence goes;tests/e2e/portfolio-v3-floor.spec.ts:293follows;signed-in-model.test.ts's two earnings-exemption cells (:2135, :2245, :2253) deleted, the four survivors re-pinned; the deadwalletMetricsyield sum (:2492) dropped.cells.tsxReturnFigure: a~prefix with its own tooltip ("Approximate: the share of this holding that left could not be read from the ledger for part of its history") on the eight accruals cells, distinct from the basis table's existing~meaning (BasisTable.tsx:31), with a block render test.- A
ledger-v2-api.test.tscell pinning that the server dust verdict still reads the whole-history booked return; thehiddenAsDustcomment rewritten;docs/portfolio.md:1131-1143(four exemptions, the five/three asymmetry paragraph goes);docs/data-pipeline.md:5216already handled in PR 2. - Goldens: untouched (display only).
- On-screen: the Min position value field's help text; previously visible residual rows leave Holdings on USD and ETH (correct under ruling 2; the release notes say so).
PR 4. Basis: At entry states the units still held
entry-basis.ts:1114-1119: the per-receipt tail splits into the inflow blend and the outflow decay using the PR 1 primitive and the arithmeticreleaseIntoalready proves;SpanEnteredBasisgainsrealizedBasis,exitGapNetted,unitsOpen;receiptContributionkeeps its definition (what the receipts actually contributed toentered), sobridgeneeds no new term;exactadditionally requiresrealizedBasis === 0; the header block at:119-126stating the old rule rewritten; a newENTERED_BASIS_NOTESentry for an unreadable reduction share (every published note is emitted,entry-basis-source.test.ts).ledger-v2-api.ts:basisEnterednow the open holding's remaining basis;basisEnteredIncompletealso set by an unreadable share. The all-or-nothing refusal per wallet (:1340) is pre-existing and deliberately out of scope; the PR body says the basis blast radius now reaches the row's headline PnL term.- Tests:
entry-basis.test.ts:271rewritten to the proportional answer;:537(bought, sold, bought again) closed span'senteredbecomes 0;:3452(a reading that found fewer units blends out as a withdrawal would) both sides move together; the 2,954-case population and the identity (:2954/:2999/:3015) stillholds, with a cell asserting WHY and a cell assertingexactis now false on a reducing span; the bridge decomposition cell (section 2.3, item 4); the basis conservation cell with its mutation;swap-entry-basis.test.ts:199-201/:234restated;scenarios/rotation-absence.test.ts:542-586re-read;category-model.test.ts:283-306holdingBasisarithmetic unchanged, meaning re-documented. - Goldens:
basisEnteredmoves on every wallet with a partial reduction on a market-priced-with- redemption asset, led by PR 1's moved-gap wallet;history.jsonandsummary.jsonunchanged. - Docs: M32's exit rule replaced, the realized term named, the identity's blindness stated so no reader believes it blessed the change; M18's exit caveat restated in the same PR (M32 is written as a diff against it);
docs/portfolio.md's "an exit at today's prices realises it" wording and the At entry definition. - On-screen: At entry (the entry of the units still held), Dislocation PnL (unrealized only), Lifetime PnL on Carry trades moves with its dislocation term; the Collateral basis to redemption and Market basis to redemption section titles unchanged.
- Held back deliberately: the pre-existing PT-collateral asymmetry in
entryBasisLegs(ledger-v2-api.ts:1376-1390, recorded there as a follow-up) stays a separate PR so this diff stays attributable.
PR 5. A rotation carries its earnings with its basis (built: #1179, issue #1172 part A)
entry-basis.ts:GroupCarryandLinkGroupBasisgainreleasedAccrual/inheritedAccrual;releaseInto/handBack/bookReleasecarry it on the same fraction;sameCarry's convergence test compares it (or a round could carry money without carrying earnings); measured net of the span's own group-derived accrual the waySpanRun.fromGroupdoes for basis, so no self-edge is reintroduced; an unvalued carry marks the destination partial via a new note and degrades per group.open-holding.ts: the walk seeds a span'saccrualOpenwith the group's inherited accrual and subtracts the released slice at the rotation receipt (the running accrual through the sub-interval that ends there), inheritsheldSinceTsfrom the same carry. Gated oncarriedByGroup.ledger-v2-api.ts: the carried figure reaches the ticket leg'syieldRedemptionthrough the existing withhold chain;accrualsInheritedset.- Tests:
scenarios/escrow-in-transit.test.ts(the carried accrual on the ticket distinguishable in magnitude from the ticket's own, or the cell is vacuous);scenarios/rotation-absence.test.ts(unreadable carry makes the destination partial, never a silent zero); the group fixed point with four carried fields, the share denominator still exactly 1, the hand-back rule, the multi-hop stkGHO to sGHO episode;swap-round-trip.test.tsandswap-entry-basis.test.ts(a trade still carries nothing);entry-basis-source.test.ts(one link-kind comparison, every note emitted);derive/escrow-request-valuation.test.ts:365-401(the ticket's inherited entry and vintage unchanged, now joined by its inherited accrual). - Goldens: the queue wallets' In settlement rows gain a carried accrual (0x05e7's osETH ticket is the clearest:
basisEntered -0.0124already,yieldRedemptionmoves from its own 0.0184 to the carried figure); wrap rotations move on both sides;history.json/summary.jsonunchanged. - Docs: M37's carry rule and partial-carry note; M32's rotation section (the carry now moves basis, vintage AND earnings).
- Review focus: the accrual rides the SAME shares and hand-back as the basis;
sameCarrycompares the new field; a DEX trade carries nothing; the refusal populations of basis and accrual are the same or the asymmetry is stated (the accrual rides the engine's bookings and degrades per interval; a refused basis corpus must not take the whole Lifetime accruals column down).
PR 6. The plain carry's Net line foots
CarryBlock.tsx: the plainLegTable(:202) replaces its single Lifetime accruals column with Accrual PnL · Dislocation PnL · Total PnL per leg;NetRow(:249) takes aLifetimePnlfromcarryPnlOf(p)and prints the trio; the PT table'sret()helper and thepf3c-tottotal column lifted out ofPtLegTableso the two tables share one formatter; the~marker and the one-unstated-term-makes-it-a-dash rule kept.category-styles.ts.pf3c-lggrid from six to eight columns (the PT table already runs nine).dislocationAppliesuntouched, so no carry's Lifetime PnL moves in a display-only PR.- Tests:
blocks.test.tsx:614(the plain carry's columns),:394's PT invariant (every leg's Total is its two terms, the Net row foots to the row's Lifetime PnL) extended to the plain table;tests/e2e/portfolio-v3-carry.spec.tsasserts the Net line equals the Lifetime PnL cell above it on the fixture's dislocating wstETH/WETH carry (today they disagree, so the assertion is the fix stated as an equality);portfolio-v3-positions.spec.ts:410/:494track counts follow the grid; the narrow-900 and zoom-sweep projects on the carry page are the width gate. - Goldens: untouched. Docs:
docs/portfolio.md:1358(the plain carry's Net row description); the Lifetime PnL hover notes (CarryBlock.tsx:150-156) and the section info tips re-read; the em-dash guard (model.test.ts:444) over the new copy. - On-screen: Carry trades, Position details, the plain leg table head becomes Leg · Asset · Balance · Value · 24h APY · Accrual PnL · Dislocation PnL · Total PnL, closed by the Net row carrying all three. The PT table keeps MTM PnL · Accrual PnL · Total PnL (a PT's mark-to-market is not a dislocation; section 8, Q7). The Fluid smart carry table keeps its accruals-only shape (no dislocation applies to a smart side) and the difference is documented.
PR 7. The In settlement row opens; Held since (built: #1181, issue #1172 part B)
model.ts:basisSectionAppliesstops being an alias ofdislocationApplies; one shared helper for the pricing/kind/book test, differing only in theinSettlementclause, with a test pinning the single intended difference.category-model.tsvariableRateExpands(:579): an In settlement row opens when it carries a STATED basis in its own book (basisEntered != null && !basisEnteredUnstated, both marks read) AND the holding it came from passes the dislocation rule (so a sUSDat ticket, whose origin is a stablecoin, stays closed; an ether-queue ticket, whose origin is stETH / osETH / ezETH / ETHx, opens, whatever its payout asset's kind). The three fixture ticket shapes each get a stated answer: quantity present at par (Lido); quantity null at par (StakeWise, Stader, Renzo, Binance, Saturn); quantity null with marks apart (apyx). A stated basis of exactly 0 opens and prints 0.00% (a true statement, not a dash). The bare redemption-priced wBETH beside its own ticket is the control proving the split did not open everything (section 8, Q5).holdingBasis(:171): gainsheldSinceTs,accrualsInherited; driven off the SERVED quantity, not off "it is a ticket": the price cells render where the row serves a quantity (the Lido ticket does) and are omitted, not dashed, where it serves null.VariableRateBlock.tsxBasisExpansion(:134): the ticket variant (the three basis figures, Held since, Lifetime accruals with the inherited-earnings tooltip, the live executable- basis button suppressed: a queued claim has no market to quote); the block's header comment promising a ticket does not open corrected.BasisTable.tsx: a Held since row (with the predates-tracking caveat, reusingsinceFirstObservation, and the N-to-M oldest-vintage caveat) and an optional Lifetime accruals row, shared by the carry's collateral, the Variable rate asset and the ticket.src/components/portfolio/v3/CONTRACTS.md: R7 no longer an alias.- Tests:
model.test.ts:266/:273;category-model.test.ts:309flips for a stated-basis ticket and stays false for the stablecoin-origin one; the ticket specs (portfolio-stakewise-ticket.spec.ts:157,portfolio-renzo-ticket.spec.ts:152,portfolio-stader-ticket.spec.ts:152,portfolio-apyx-ticket.spec.ts:145,portfolio-saturn-ticket.spec.ts:106,portfolio-binance-ticket.spec.ts:148,portfolio-fxsave.spec.ts:149) become opening-row assertions where the gate opens them, with the Saturn one andportfolio-binance-ticket.spec.ts:155(the bare wBETH) asserting closed;portfolio-held-back-ticket.spec.ts(the route-held-back Lido ticket keeps its N/A chip, and now opens onto its basis with the chip beside it, stated as intended);portfolio-rebasing-tokens.spec.ts(ruling 7: the stETH row opens as its wrapper's does). - Goldens: untouched. Docs:
docs/portfolio.md:1748(which In settlement rows open and onto what, what the entry basis means for a claim, which actions its expansion carries); the Held since line;api-types.ts:616corrected; this plan tobuilt. - On-screen: Variable rate assets, an In settlement row (for example stETH · Redemption requested · ~2d to claim) gains a chevron and opens onto Market basis to redemption with At entry, Current, Dislocation PnL, Held since, Lifetime accruals; 24h APY on a ticket stays a dash.
5. Tests and fixtures, the discipline
- Every PR lists each test it adds or changes with its local result (AGENTS.md "What runs locally"); a new cell is seen red with the change reverted.
- The conservation law and the bridge decomposition carry mutation cells at 10x tolerance.
- Goldens regenerate only via
generate-values.tsthengolden-portfolio.ts, each alone; every PR body explains every moved figure per wallet and per capture (live, two as-of), and names the surfaces that did NOT move as the evidence for ruling 1. - Fixture rule: a scenario cell is vacuous if the figure it pins is not magnitude-distinct from the figure the old rule would produce (the smooth-rates trap). PR 1's four wallets are designed for that distinctness and the PR body writes both answers.
- Browser specs run locally only for the pages a PR moves, one at a time; the release PR runs all.
6. Docs kept in sync (same PR as the change)
docs/metrics.md: new M37 (PR 2, extended PR 5); M32 and M18 (PR 4); M36b (PR 2); M22/M24/M30 cross-references. docs/portfolio.md: :1036, :1296-1301 (PR 2); :1131-1143 (PR 3); the basis section wording (PR 4); :1358 (PR 6); :1748 and Held since (PR 7). docs/data-pipeline.md:5216 (PR 2). src/components/portfolio/v3/CONTRACTS.md R7 (PR 7). Code comments that assert row = chart (PR 2). docs/plans/index.md regenerated on every status change (cd docs && npm run plans:index).
7. Out of scope, named
- PR 5 (rotations carry earnings) and PR 7 (the In settlement row opens, Held since): cut 2026-10-16, filed as enhancement issue #1172; PR 5 built as its part A (#1179), PR 7 as its part B (#1181).
- A realized figure on the Activity tab (section 8, Q1).
- The PT-collateral asymmetry in
entryBasisLegs(ledger-v2-api.ts:1376-1390): issue #1171, its own PR after PR 4. - The withdraw-stranding follow-up Fred parked on 2026-10-09 (#1077 review): still parked.
- The basis derivation's all-or-nothing refusal per wallet (
ledger-v2-api.ts:1340): pre-existing, named in PR 4, not fixed here. - Renaming Lifetime accruals / Lifetime PnL (section 8, Q6): only if Fred wants it.
8. Decisions Fred makes before PR 2 (recommendation first)
- Q1. Where a closed position's result shows. Ruling 2 says the charts and the Activity tab. The Activity line is token amounts only by rule (R11,
docs/portfolio.md:2112: no dollar figure, no enrichment) and its reader is a plain SQL path with no engine. Recommend: keep R11; a closed holding's result is visible as the bend in the MTM PnL and Accrual only PnL lines, and the realized-out amounts stay internal state plus the reconciler count. A realized line on Activity would be its own later plan. - Q2. Liquidation (seizure) as a reduction. Recommend yes for accruals and basis (the seized units take their share of earnings and basis with them), with the total-return line keeping the liquidation loss on the survivors' span (not haircut). The alternative (not a reduction at all) overstates what the surviving units earned.
- Q3. A reduction whose share the ledger cannot read. Recommend publishing the accrual as a marked floor (
~with a tooltip) rather than a dash: the earnings are real, the basis table already uses the same convention. - Q4. The two realized APY fields and observedDays (served, rendered nowhere in v3, read by agents, named in the quarantine alarm's impact line, asserted by the PT impairment test). Recommend re-scoping them to the open holding rather than dropping them, with M8's 30-day gate applied to the open holding's own span (a freshly reopened holding dashes its rate until it has 30 days; the Summary card keeps its whole-view rate and the docs say the two spans differ).
- Q5. Which In settlement rows open. Recommend: a ticket opens when it carries a stated basis in its own book and the holding it came from passes the dislocation rule; a stated basis of 0 opens and prints 0.00%; stablecoin-origin tickets and unstated ones stay closed. The route-held-back Lido ticket opens onto its basis with the N/A accruals chip beside it.
- Q6. The word "Lifetime". Lifetime accruals and Lifetime PnL now state the open holding's life. Recommend keeping the labels (it is the lifetime of the holding) and saying so in the tooltip and docs; renaming costs a wider spec and copy diff for no new information.
- Q7. Column vocabulary. The plain carry gets Accrual PnL · Dislocation PnL · Total PnL; the PT table keeps MTM PnL · Accrual PnL · Total PnL. Recommend keeping both: a dislocation and a PT's mark-to-market are different things and today's Lifetime PnL definition already names them apart.
- Q8. Held since. Recommend adding it inside the basis expansion (otherwise ruling 2's reset is correct and unverifiable in a browser), with the predates-tracking and oldest-vintage caveats in its tooltip.
- Q9. Inherited earnings on a ticket. Recommend a tooltip note on the ticket's Lifetime accruals ("includes accruals carried from the holding this claim came from"), no extra column.
- Q10. The PT-collateral asymmetry stays a separate PR (recommend yes).