Participation

martinmr777_ · library · 3783 行 · 点赞 0 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
 
// @description Market Participation layer for the Opening Range indicator family (M11).
//              Holds the pre-signal environment producers (P1–P5, P8), the at-signal snapshot,
//              the post-signal engine and the participation
//              table renderer. Factored out of the host to relieve its compiled-token budget
//              (CE10117); the host keeps only the `var` state declaration, one call per bar,
//              and `table.new`.
//
//   Ownership line, and it is forced rather than chosen: LIBRARIES CANNOT HOLD `var` STATE, so
//   every persistent value lives host-side in the `ParState` object the host declares and this
//   library mutates. Libraries also cannot read globals initialised from script inputs, so every
//   input-derived value arrives as a parameter — that is why `step` takes eleven of them.
//
//   Timezone literals are inline rather than parameters on purpose: a string literal is a const
//   expression, not a global, so the rule above does not touch it. Only the session STRINGS come
//   from inputs and therefore must be passed in.
//
//   Usage (host):
//     import Mr_NSFT/Participation/1 as par
//     var par.ParState parState = par.newState(                        // once; the A4 birth-rung
//          rvolAdequate = 0.80, rvolStrong = 1.10,                     // thresholds and the three
//          dayExtended  = 0.90, chaseHigh  = 0.90,                     // lifetime settings are all
//          tgtName = i_parVerdictTgt, cutoffHours = i_parCutoffHours,  // HOST-owned; the
//          patienceMins = i_parPatienceMins, oiFloor = 0.10,           // ladder's calibration
//          s1Band = 0.05, s2Building = 1.20, s2Fading = 0.83,          // rides here too.
//          s4Hold = 3, s4Reject = 3, decayN = 3)                       // NEVER positional.
//     par.step(parState, isNewDay, i_parLookback, i_parVwapSlopeK,     // every bar, unconditional
//          i_parSessAsia, i_parSessLondon, i_parSessNY,
//          dayLv.highs, dayLv.lows, dayLv.curH, dayLv.curL)
//     if array.size(parStates) > 0 and barstate.isconfirmed            // the POST-signal engine —
//         par.advance(parStates, parState, barDelta, deltaSrc)         // note the gate differs
//                                                                      // from step's, deliberately
//     var par.ParticipationConfig parCfg = par.ParticipationConfig.new(...)
//     var table parTable = makeParTable()                              // host owns table.new
//     par.renderParticipation(parTable, parCfg, parState)
library("Participation")
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Constants
// ═══════════════════════════════════════════════════════════════════════════════════════════
// const globals are the one kind a library function may read (input-initialised ones are not).
 
const int MS_PER_MINUTE = 60 * 1000
const int BKT_MS        = 30 * 60 * 1000  // one time-of-day bucket, in ms
const int BUCKETS       = 48              // 30-min buckets covering a 24h session
const int BKT_LAST      = 47              // BUCKETS - 1; the clamp index
const int SECONDS_30MIN = 30 * 60         // P2's structural ceiling — see step()
 
// Shown in the value cell of every reading that depends on a volume feed. One constant so the
// wording cannot drift as Phase 3 adds volume-dependent rows.
const string NO_VOL_MSG = "No volume data available"
 
// ── M11-2 — at-signal snapshot constants ────────────────────────────────────────────────────
// Every one of these is a dimensionless RATIO, which is what keeps it out of the settings dialog:
// a ratio means the same thing on ES, on AAPL and on a crypto pair, so it can be a universal
// constant instead of a per-symbol knob. All are provisional engineering defaults to be validated
// by the client's backtests — and because M11 is informational, a miscalibrated one mutes or
// overstates a reading and can never block a trade.
 
// A2 — a corridor level counts as "SL-adjacent" only within this fraction of the stop distance.
// 0.15 R is close enough that ordinary noise around the level reaches the stop. The failure mode
// being avoided is a threshold so wide it flags everything: a 1R corridor can hold 5–15 levels, so
// at 0.33 a third of them would qualify and the descriptor would stop carrying information.
const float SL_ADJ_FRAC   = 0.15
// A2 — an SL-adjacent level at or above this share of the reference base cost reads as real cover.
const float PROTECTED_FRAC = 0.50
 
// A2 — inside this distance from the stop, expressed in R, the level IS the stop.
//
// ⚠️ THE VALUE IS TIED TO THE DISPLAY, not chosen for trading reasons, and that is the whole point.
// fmtRmult formats with "0.00", so any distance below 0.005 R already PRINTS as "0.00R". Setting the
// band to exactly that rounding boundary is what makes the geometry word incapable of contradicting
// the number beside it — which was the defect: a level sitting on the stop read
// "0.00R inside (protected)", claiming cover the number said did not exist.
// ⚠️ If fmtRmult's format string ever changes precision, THIS MUST MOVE WITH IT.
//
// Deliberately NOT MERGE_TICKS * mintick, the tolerance used for "two levels are the same level":
// that one is absolute, so a one-tick gap is invisible on a wide-R setup and significant on a tight
// one. The contradiction being fixed is stated in R, so the bound has to be too.
const float AT_STOP_FRAC = 0.005
 
// A4 — the birth-rung thresholds USED TO LIVE HERE. They are now host-side, arriving on ParState's
// cfg* fields via newState(). The move is not cosmetic: the four numbers are provisional and expected
// to be retuned from observation, and as library constants every tweak cost a republish plus an
// import bump.
//
// ⚠️ DO NOT REINTRODUCE A LOCAL DEFAULT FOR ANY OF THEM — not as a const, not as a ParState field
// default, not as a newState() parameter default. Two sources for one number means the day someone
// edits the host and sees nothing change is the day they start debugging the wrong file.
 
// Ladder rungs. Strings rather than ints so every display surface reads the state directly and no
// decoder table has to be kept in sync. STALLED is declared here but is unreachable in M11-2: it is
// a decay state, and at birth no time has elapsed and no evidence exists to decay.
//
// ⚠️ ABBREVIATED AT C18 (2026-09-07) — §7.7.3's lever 5, spent when a live tooltip clipped off the
// bottom of the chart. It was a CONSISTENCY DEFECT as much as ~9 characters of width: the long
// words disagreed with two surfaces that were already abbreviated — rollUp's table row (`2 DEV`)
// and ladderHist's stamps (`->STALL+5`).
// ⚠️ THESE FOUR STRINGS ARE NOW THE ONLY SOURCE. rollUp used to carry its own copies of the same
// four words; that was invisible while the two vocabularies differed and became live drift risk the
// moment they matched, so it now reads these. Do not reintroduce a literal rung word anywhere.
// ⚠️ They render in the SHIPPED `Birth:<rung>` row, so this changes M11-2 text → changelog line.
const string RUNG_AUCTIONING = "AUCT"
const string RUNG_DEVELOPING = "DEV"
const string RUNG_CONFIRMED  = "CONF"
const string RUNG_STALLED    = "STALL"   // [P3] a decay state; unreachable at birth
 
// How a signal's tracking ENDED, appended to the rung as a suffix — CONFIRMED(TP1), DEVELOPING(SL),
// AUCTIONING(EX). Two of the three are constants; the third is the verdict target's own name, which
// is a SETTING and therefore arrives on ParState.cfgTgtName rather than living here — the suffix has
// to say TP2 when the user tracks to TP2.
//
// ⚠️ The rung VALUE is never adjusted at resolution. A signal stopped out while Developing IS
// Developing; the suffix records how it ended, and conflating the two would destroy the very
// distinction the client buckets his outcomes on.
const string OUTCOME_SL = "SL"
const string OUTCOME_EX = "EX"   // tracking cutoff reached with no verdict
// ⚠️ DROPPED BY THE MAX_STATES BACKSTOP — a DIFFERENT fact from EX and deliberately not folded into
// it. Both end tracking without a verdict, but one is the configured clock expiring and the other is
// the engine running out of slots; conflating them would put a fabricated reason in the research
// record. Its whole purpose is that a failure which used to be silent now carries a token.
const string OUTCOME_CAP = "CAP"
// ⚠️ EVICTED BECAUSE ITS LABEL IS GONE, and it is the one outcome that NEVER RENDERS — by
// construction, since a state carrying it has no label for the write pass to reach. It exists so the
// eviction loop in render() states which of the two rules fired rather than reporting every eviction
// as CAP, which would put a false reason in a field the next reader will trust. Its string is
// therefore free — nothing displays it — and it gets NO changelog line, unlike CAP which does render.
// 📌 The eviction is lossless ONLY because the label IS the record: there is no telemetry, no alert
// and no retained result array, so a state whose label has been deleted can no longer be observed by
// anything (dev plan §7.9.2). ⚠️ IF TELEMETRY IS EVER BUILT, revisit this before it lands — at that
// point the outcome of a label-less signal becomes readable and evicting it becomes real data loss.
const string OUTCOME_GONE = "GONE"
 
// ── Component status words (M11-3). Strings for the same reason the rungs are: every display
//    surface reads the state directly and no decoder table has to be kept in sync.
//
// ⚠️ ST_UNKNOWN IS SHARED BY S1, S2 AND S4 AND MEANS "UNMET", NEVER "SKIPPED". A component that
// cannot be read makes its own clause FALSE — it blocks a conjunction and a veto, and simply fails
// to carry a disjunction. The permissive reading is the fail-open shape this project already shipped
// once, in A4's envKnown, where an unmeasurable day made CONFIRMED *easier*.
//
// ⚠️ S3 HAS NO UNKNOWN, and the asymmetry is correct — but ⚠️ ITS ORIGINAL PROOF WAS FALSE AND IS
// REPLACED HERE (2026-09-07, dev plan §7.8.4b). It read: "episodes cannot be unmeasurable without S1
// or S2 being unknown at the same time, because the admission test draws on the same two inputs."
// The expVol half holds. THE barDelta HALF DOES NOT: barDelta being na on a bar does not make S1
// unknown, because S1's unknown is the CUMULATIVE `cumVol == 0`, not a per-bar test — so a signal
// that had already folded bars read a frozen status while S3 was genuinely unmeasurable. That state
// was reachable on every overnight bar until §7.8 deleted the host's delta window.
//
// ✅ THE REAL REASON, which does not depend on the other components at all: S3's ladder input is the
// TALLY, an accumulator of REALIZED evidence over COMPLETED episodes. It is event-indexed, not
// bar-indexed, so on a bar where nothing resolves there is genuinely nothing to add and "nothing
// banked" is honestly `none` rather than "unknown". An episode that could not be measured
// contributes nothing at all — closeEpisode wraps the whole vote in `if not na(_E)`: no vote, no
// tally movement, no test counted, no baseline written. So the tally is never a partial reading
// dressed as a complete one, which is the failure mode `unknown` exists to prevent elsewhere.
// ⚠️ Do not "fix" the asymmetry by adding a fourth S3 status.
//
// The word is "unreadable" rather than "unknown" so it reads as English inside the reason phrase:
// "pace is unreadable", not "pace is unknown". (The phrase said "participation is …" until the
// C18 rename; the argument is about the WORD, so it survives the rename unchanged.)
const string ST_UNKNOWN  = "unreadable"
const string S1_ALIGNED  = "aligned"
const string S1_NEUTRAL  = "neutral"
const string S1_AGAINST  = "against"
const string S2_BUILDING = "building"
const string S2_STEADY   = "steady"
const string S2_FADING   = "fading"
const string S3_POSITIVE = "positive"
const string S3_NONE     = "none"
const string S3_NEGATIVE = "negative"
// ⚠️ THE TRAILING PREPOSITIONS WERE DROPPED AT C18 (2026-09-07) — "holding beyond" → "holding",
// "rejected back through" → "rejected", "rotating around" → "rotating". They duplicated the counter
// that follows them on the Acceptance row, which already names the side (`3/3 above VAH`), and cost
// 7–12 characters on the surface that clips.
// ⚠️ THE TRADE-OFF WAS WEIGHED AND ACCEPTED — do not "restore" the prepositions without re-reading
// this. reason()'s two "the origin was/is <word>" sites carry NO counter, so they read flatter:
// "the origin was rejected" no longer says back through what. Two things made that acceptable —
// the long forms were ALREADY grammatically loose (the origin is not what holds or rotates, price
// is, so "the origin was holding beyond" had the same defect and the short form only exposes it),
// and reason() is TOOLTIP-ONLY (one caller, liveTip), so the Acceptance row with its counter is
// always a few items away on the same wrapped line.
const string S4_HOLDING  = "holding"
const string S4_REJECTED = "rejected"
const string S4_ROTATING = "rotating"
 
// S3 tally thresholds. ⚠️ DERIVED, NOT TUNED — and that is what makes them library constants while
// OI_FLOOR is a host literal. The unit is already in the weighting scheme: one full vote at a
// top-tier level with typical participation is `±1 × wBase 1.0 × w(E) 1.0 = ±1.0`. Sign-only was
// considered and rejected because it falsifies a design statement — a 0.05 contribution from a muted
// vote at a minor level would then act alone, where SCOPE says such a contribution "only matters in
// aggregate". ⚠️ T⁻ is also what makes "S3 tally not negative" a real CONFIRMED conjunct rather than
// a near-vacuous one: a full-weight break at a strong level drags the tally ~1.5 and blocks it alone.
const float TALLY_POS = 1.0
const float TALLY_NEG = -1.0
 
// Patience multipliers, applied to the host's minutes input. LIBRARY-SIDE by decision, and the split
// from the §7.2.9 thresholds is deliberate: multipliers are STRUCTURAL — the ordering is the design —
// while thresholds are CALIBRATION and must be retunable in a host-only compile.
//
// ⚠️ FAMILY SEPARATION IS LARGER THAN THE WITHIN-FAMILY RETEST STEP, ON PURPOSE. The four-family
// hierarchy is the CLIENT'S; the retest split is OURS, so it must be the finer distinction. Ordering,
// slowest last: VEL 0.5 · MOM 1.0 · RETEST 1.1 · AC 1.3 · AC-RETEST 1.4 · INFL 1.6.
//
// ⚠️ Keyed on famIdx + a retest flag, NEVER on the sigType string — the type strings are host
// constants and a library comparing them to its own literals would mis-classify in silence the day
// one was renamed. That is the same rule famIdx itself exists for.
const float PAT_VEL    = 0.5
const float PAT_CONT   = 1.0
const float PAT_AC     = 1.3
const float PAT_INFL   = 1.6
const float PAT_RETEST = 0.1   // the within-family step, added to CONT and AC only
 
// Why a signal stalled. Stored because STALLED is ABSORBING — the ladder stops evaluating, while the
// episode engine keeps measuring for the dataset, so the tally can move afterwards and the reason
// would not be re-derivable at display time.
const int STALL_TALLY    = 1
const int STALL_REJECTED = 2
const int STALL_DECAY    = 3
const int STALL_PATIENCE = 4
 
// Which disjunct carried AUCTIONING → DEVELOPING; 0 = the signal has not been promoted.
// ⚠️ LATCHED FOR THE SAME REASON stallWhy IS, and the reason phrase was rebuilding it from live
// statuses until 2026-09-05. DEVELOPING is a DISJUNCTION — S4 holding OR S3 positive — and the
// statuses keep moving afterwards, so `S4 == holding ? "…origin…" : "…level tests…"` at display
// time attributes the promotion to whichever disjunct happens to be true NOW. Worse, both can be
// false at once: S4 `rotating` with a `none` tally is an ordinary DEVELOPING state, and the phrase
// then read "Developing because level tests are none" — a signal developing because of an absence.
const int DEV_ORIGIN = 1
const int DEV_TESTS  = 2
 
// Two levels within one mintick of each other are the same level. Mirrors the de-duplication in
// ContextScore's obstruction(), which matters more here: the universe now carries HTF horizontals,
// so a prior Daily low sitting on an old session's ORL is ordinary, and without the merge that one
// price would cast two votes.
const int MERGE_TICKS = 1
 
// Backstop. It existed because M11-2 shipped no resolution logic, so without a cap parStates would
// accumulate one entry per signal across the whole chart history.
//
// ⚠️ "THE TRACKING CUTOFF ALWAYS BITES FIRST" WAS WRONG, AND IS STRUCK (2026-09-05). The per-day
// maxima are inputs: Continuation 10 per direction (one counter for cont + AC + AC-Retest),
// Inflection 10, Velocity 20 — **80 signals a day** at the top of the ranges — while the tracking
// cutoff maxes at **240 market hours**. The cap is reachable by configuration alone, with no unusual
// market. At the DEFAULTS it is 8 a day and the cap never fires, which is what hid this.
//
// ⚠️ IT IS NOT RAISED TO COMPENSATE, and that is deliberate: each state carries its own `levels`
// array, so a cap sized for the worst case (240h × 80/day) is not a real option. The answer is that
// hitting the backstop is VISIBLE — enforcement moved out of seed() and into render(), where an
// evicted state resolves as OUTCOME_CAP and goes through the same final write, partner freeze,
// follower promotion and prune as any other resolution. See the note at the top of render().
const int MAX_STATES = 50
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Types
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// @type One main trading session's running summary.
//
//       rng / extPct / dir are LIVE — rewritten on every in-session bar, so mid-session they
//       describe the occurrence in progress rather than the previous one. That is what lets the
//       participation table show a session's extension while it is still running.
//
//       eff is the exception: |close − open| ÷ rng whipsaws while the close is still moving, so
//       it is a closed-session statistic only. Cleared to na when a session opens, computed once
//       when it closes. A na eff therefore means "this session has not finished yet", never
//       "no data".
//
//       seenAt is the timestamp of the most recent bar this session was open on — written every
//       in-session bar, so once the session exits it holds its final bar. It replaces a boolean
//       freshness flag, which could not survive one edge case: exit is detected on the first bar
//       OUTSIDE the session, so when that bar is also the day-roll bar, a session that traded
//       entirely within the outgoing day would be flagged as belonging to the incoming one. A
//       timestamp has no such ambiguity — the consumer decides recency for itself, and "traded
//       within the current trading day" is simply `seenAt >= p.sessOpen`.
//       Read seenAt together with `active`: active means the session is still moving.
//
//       The field is `rng`, not `range`: `range` is a Pine reserved word (CE10150), as are
//       catch, class, do, ellipse, in, is, polygon, return, struct, text, throw and try.
export type SessionLedger
    float open   = na
    float high   = na
    float low    = na
    float close  = na
    float rng    = na     // high − low (LIVE)
    float extPct = na     // rng ÷ ADR — share of the typical day this session spent (LIVE)
    float eff    = na     // |close − open| ÷ rng ∈ [0,1] — trend vs round trip (ON CLOSE ONLY)
    int   dir    = 0      // +1 up · −1 down · 0 flat (LIVE)
    int   seenAt = na     // time of the most recent in-session bar
    bool  active = false
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// REMOVED 2026-08-12 — `SessSnap`, the at-signal session snapshot. Kept as a design reference,
// because rebuilding it from scratch would mean rediscovering the roll/exit collision below.
// ═══════════════════════════════════════════════════════════════════════════════════════════
// It existed for exactly ONE consumer: the tooltip's "Sessions:" row, via `sessSummary(p.snapSess)`
// stored as `ParticipationState.a1Sessions`. That row moved to the Data Window (host plots, live
// per-bar values), which left the whole chain — the type, `ParState.snapSess`, its allocation in
// newState(), the per-bar copy loop in step(), sessSummary() and a1Sessions — with no reader, so it
// was deleted rather than left marked [P3]. Nothing in Phase 3 is scoped to use it.
//
// HOW IT WORKED, and the part that is not obvious:
//   • Five fields per session — ext, eff, dir, active, today — copied from the live SessionLedger in
//     step()'s snapshot block, ALL FIVE TOGETHER and never a subset. Only ext and dir diverge
//     live-vs-historical, which makes snapping just those two look sufficient; it is not, and the
//     resulting failure is worse. On the bar a session OPENS, a snapped ext still holds the PREVIOUS
//     occurrence's value while a live freshness test says "traded today", so yesterday's extension
//     is waved through as today's. Data and the metadata qualifying it must come from one instant.
//   • `today` was the RESOLVED freshness verdict (`seenAt >= sessOpen`), not the raw timestamp,
//     because both operands had to be read from the SAME frame. The snapshot ran BEFORE the session
//     roll, so a live `sessOpen` would already be tomorrow's while `seenAt` was yesterday's, and
//     every session would read stale — on exactly the signals that fired the evening before.
//   • That is also why it was a dedicated type and not a second SessionLedger: `today` has no live
//     equivalent, and it never reinstated the boolean that decision 8 removed from SessionLedger —
//     that one was written by the producer at exit time with no anchor, which is why it could not
//     survive the roll/exit collision. A session trading entirely within day D and exiting on D+1's
//     first bar resolves `seenAt(D) >= sessOpen(D)` = true on that bar, false from the next one on.
//
// ⚠️ IF ANYTHING EVER NEEDS AN AT-SIGNAL SESSION READING AGAIN, it needs the pre-roll frame, so it
// cannot be assembled from the live ledgers at read time. The surviving live consumers — the table
// via sessCells() and the host's Data Window plots via sessToday() — all want the POST-roll answer,
// which is why the freshness test they share is correct where it stands and would be wrong here.
 
// @type Pre-signal producer state (P1–P5, P8). One object, so the host pays one declaration.
//
//       bktTypical / bktToday — 48 fixed 30-minute buckets, indexed from the SESSION open (not
//           midnight), which is what lets cumulative RVOL run without a midnight wrap. 48 covers
//           a 24h symbol; RTH symbols simply never reach the high indices.
//       cumTyp — running Σ of bktTypical over buckets 0..bkt INCLUSIVE, maintained incrementally
//           on bucket entry so P3 costs no per-bar loop over 48 slots. It counts the current
//           bucket in full; P3 subtracts back the part of it that has not elapsed yet.
//       bkt = −1 means "no bucket entered yet this session", which is how entry into bucket 0 is
//           detected on the session's first bar.
export type ParState
    array<float>         bktTypical
    array<float>         bktToday
    array<SessionLedger> sess
    int   sessOpen   = na    // session open timestamp (ms) — the bucket-index anchor
    int   bkt        = -1    // bucket currently accumulating
    int   barsInSess = 0     // P8 slope warm-up guard
    int   sessCount  = 0     // sessions seen — how mature the RVOL baseline is
    float cumVol     = 0.0   // P3 numerator — session volume so far
    float cumTyp     = 0.0   // P3 denominator — expected volume to this point
    float barRvol    = na    // P2
    float cumRvol    = na    // P3
    // [→P3] P2's DENOMINATOR — the volume this bar was expected to print, on the same validity
    //       domain as barRvol itself. Episode RVOL (E = Σ actual ÷ Σ expected) needs the raw
    //       expectation, and the RATIO cannot supply it: barRvol is legitimately na above 30 min
    //       and wherever the expectation is not positive, so `volume / barRvol` cannot tell "no
    //       expectation available" from "no volume". Assigned in step() at the one site where the
    //       value already exists, and barRvol is then derived FROM it so the two can never drift
    //       apart about which bars are measurable — that shared domain is what makes Phase 3's
    //       episode admission test (barDelta and expVol both non-na) mean what it says.
    float expVol     = na
    // [P3] S2's two raw 3-bar means — one ta.sma(barRvol, 3), read live and at [3]. Producers
    //      MEASURE, par.advance CLASSIFIES: the thresholds and the degenerate routings live in one
    //      place there rather than two here. The window must be computed in step(), not in
    //      par.advance, because ta.* fills its history buffer per call site on executions that
    //      ACTUALLY HAPPEN — and par.advance is gated on there being a live signal, which would
    //      make "three executions ago" something other than "three bars ago", silently.
    float s2Recent   = na
    float s2Prior    = na
    float adr        = na    // P4
    float dayUsed    = na    // P4 — today's (HOD − LOD) ÷ ADR
    float vwap       = na    // P8
    float vwapSlope  = na    // P8 — na until barsInSess > K
    float dayHi      = na    // forming day's high, as handed to step (entry-location percentile)
    float dayLo      = na    // forming day's low
    bool  live       = false // did the layer run this bar (see step's timeframe gate)
    // ── The at-signal snapshot: every reading as it stood at the END OF THE PREVIOUS BAR ──
    // These exist because par.seed fires from the host's trade-opening block, which is NOT
    // isconfirmed-gated. Reading the live fields there would give a different answer live than on
    // reload — see the copy block at the top of step() for the full derivation — and A1 is latched
    // forever, so the wrong answer would be permanent. Nothing but seed should read these.
    // The naming is a contract, not a style: seed() reads NOTHING off this object that is not a
    // snap* field. Mixing one live value into the snapshot is the failure this whole block exists
    // to prevent, and it has to be checkable by looking rather than by reasoning.
    //
    // lastStepBar seeds to -1, NOT na, and that is load-bearing rather than tidy. bar_index starts
    // at 0, so -1 is an unreachable sentinel — whereas `bar_index != na` evaluates to **na, which is
    // FALSY**. An na seed therefore makes the guard below false on bar 0; lastStepBar is only ever
    // written *inside* that guard, so it stays na, and the snapshot block never runs again for the
    // life of the script. This shipped once (M11-2, step 2D): every signal reported "environment
    // unavailable" and every birth rung came out AUCTIONING, because every snap* field was still at
    // its declared na. Same sentinel idiom as `bkt` above, for exactly the same reason.
    int   lastStepBar  = -1
    float snapCumRvol  = na
    float snapVwap     = na
    float snapSlope    = na
    float snapDayHi    = na
    float snapDayLo    = na
    float snapDayUsed  = na
    float snapAdr      = na
    // ── CONFIGURATION, NOT STATE — the A4 birth-rung thresholds ────────────────────────────
    // Every other field on this type is per-bar state that step() writes and seed() reads. These
    // are the opposite: written ONCE by the host at newState() and never touched again.
    //
    // They ride on ParState because seed() and advance() already receive `p`, so they cost nothing
    // at the ten inlined parSeed call sites — four more parameters on a fifteen-parameter export
    // would have been paid ten times over (CE10295 counts the main body AFTER inlining).
    //
    // The cfg prefix is a contract, in the same way the snap* prefix above is: anything named cfg*
    // is a setting, and step() must never write one. Declared without defaults deliberately —
    // newState() requires them, so there is exactly one place these numbers can enter the object.
    float cfgRvolAdequate
    float cfgRvolStrong
    float cfgDayExtended
    float cfgChaseHigh
    // ── Phase 3 lifetime settings — these three are USER INPUTS, not tuned constants, which is the
    //    one way they differ from the four above. Same route for the same reason: newState() is a
    //    single call site, so routing them here is free, whereas widening advance()'s argument list
    //    would fight the rule that adding a setting must not touch its signature.
    //
    //    ⚠️ cfgTgtName is the DISPLAY TOKEN for the verdict target — "TP1" / "TP2" / "TP3" — and the
    //    price it names is ParticipationState.target, computed host-side at seed. Two facts about
    //    one thing, and they must not drift: the token is what the outcome suffix prints, so a host
    //    that resolves the price from one input and the token from another would print a verdict
    //    naming a target the state never had.
    //
    //    Both durations are in the units the client sees, and the units DIFFER on purpose (hours vs
    //    minutes): the cutoff runs to tens of hours and patience to tens of minutes, so one shared
    //    unit would make one of them unreadable. Neither is a bar count — the conversion to market
    //    time is `bars × timeframe.in_seconds()`, which is why no duration field exists anywhere.
    string cfgTgtName
    int    cfgCutoffHours
    int    cfgPatienceMins      // [P3] read by the ladder's patience rule; unused until then
    // S3's one host-side constant. It separates a +1 from a 0 on a level's FIRST episode and nowhere
    // else, and it can never manufacture negative evidence — which is why it is low-stakes and why
    // the w(E) constants below it stay library-hardcoded while this one does not. It has the A4
    // property: no data exists yet and it will be retuned from observed output, so it must be
    // editable in a host compile rather than a republish plus an import bump.
    float  cfgOiFloor
    // ── The ladder's calibration, all on the same terms as the four A4 thresholds: no data exists
    //    yet, they will be retuned from observed rung distribution, and a retune must be a host-only
    //    compile. ⚠️ THE TRANSPOSITION WARNING GAINS FORCE HERE — the call now carries S2's two
    //    floats side by side and, worse, **two adjacent same-typed ints** in cfgS4Hold / cfgS4Reject,
    //    which start at the SAME value. Positional, a swap compiles clean and is invisible.
    //
    //    Their contracts are per-value rather than comparisons, since H and R are independent:
    //    ⚠️ **H >= 2** — H = 1 promotes almost every signal to DEVELOPING on its own entry bar,
    //    because a breakout entry sits beyond its origin by construction; and **R >= 1**.
    float  cfgS1Band          // ± neutral band on cumDelta/cumVol
    float  cfgS2Building      // recent3/prior3 at or above this is building
    float  cfgS2Fading        // at or below this is fading — multiplicatively symmetric with it
    int    cfgS4Hold          // H — consecutive closes beyond the origin for `holding`
    int    cfgS4Reject        // R — consecutive closes back through it for `rejected`
    int    cfgDecayN          // N — consecutive bars of S1 against + S2 fading that stall a signal
 
// @type Participation-table styling. Every APPEARANCE field is inherited from the host's STATUS
//       table controls — the table deliberately introduces no appearance inputs of its own.
//
//       vertOffset is the exception, and it is layout rather than appearance: the number of
//       ladder units of blank padding above the readings (see parPadRows). The host derives it
//       from its own position/offset inputs and forces it to zero where a top pad cannot move
//       anything; this library only spends what it is handed.
export type ParticipationConfig
    color  txtColor
    color  bgColor
    color  hdrBgColor
    string txtSize
    bool   show
    int    vertOffset = 0
 
// @type One structural level a signal is watching, with its price frozen at signal time.
//
//       wBase is the vote weight the episode engine will apply — the level's base cost normalised
//       against a fixed reference so it lands in (0, 1]. Fixed, not per-watchlist: normalising by
//       the strongest level actually present would promote a weak level to full weight whenever it
//       happened to be the best one there.
//
//       bornSupport is DISPLAY AND ENUMERATION ONLY, and Phase 3 must not read it. The engine's
//       "no stored class flag" rule is about the VOTE, whose sign comes from the side price closes
//       the episode on — that single comparison is what handles all six support/obstacle ×
//       held/broke configurations, break→retest→go included, with no flag and no flip event. This
//       field exists so the tooltip can say "support" or "obstacle" and so the corridor listing can
//       be built; wiring it into the vote would reintroduce exactly the problem the design removed.
//
//       Since 2026-09-03 bornSupport is EXACTLY the [SL, entry] corridor test for every level in
//       the list, the origin included — see the fix at seed() step 3. That equivalence is worth
//       knowing and worth not leaning on: Phase 3's stop-corridor record filter uses the price test
//       directly, because it is one expression over fields already present and stays correct under
//       a future change to how the seed classifies. Not because this field is unreliable — after
//       the fix it is not, and writing that down would invite "simplifying" the filter back.
//
//       Two Phase-3 markers are used throughout this file and they mean different things:
//         [P3]  — declared for Phase 3, neither written nor read here. Free to drop under compile
//                 pressure; deleting one changes nothing today.
//         [→P3] — computed HERE and consumed in Phase 3. Deleting one raises no compile error and
//                 silently produces wrong Phase 3 data. Do not drop.
export type WatchedLevel
    float  price
    float  baseCost
    float  wBase                  // [→P3] vote weight: min(1, baseCost / bcRef)
    string tag
    bool   bornSupport
    // ── [P3] episode state — declared now so the type is never reshaped. Adding a field to a dev
    //    library is free; reshaping one that host code already reads costs a two-file compile.
    bool   testing   = false
    float  oppDelta  = 0.0
    float  volAcc    = 0.0
    float  expVolAcc = 0.0
    // ⚠️ depthMax MUST be reset to 0.0 when an episode OPENS, not merely left at this declared na:
    //    math.max(na, x) is na, so a running max seeded at na stays na for the life of the level —
    //    no error, no tell, and depth silently absent from every vote. Declared na so that a read
    //    before any episode has opened is honestly empty rather than a fabricated zero.
    float  depthMax  = na
    // ⚠️ THESE TWO DELIBERATELY KEEP THEIR na SEEDS, against the direction every other na seed in
    //    this type moved in the same pass. na here MEANS "no comparable prior test", and it is
    //    tested with na(lastOI) — which the sentinel rule permits. What that rule forbids is
    //    `x != na`, which evaluates to na and is falsy; nothing may test these that way.
    //    Load-bearing, not tidy: a dead-volume episode does not write them, so an episode that
    //    proved nothing can never become the yardstick that mutes a later one that proved something.
    float  lastOI    = na
    float  lastDepth = na
    int    tests     = 0
    // [P3] APPROACH CLASS — which side price met this level from on the bar the current episode
    //      opened. **+1 = from above ⇒ "support test" · −1 = from below ⇒ "obstacle test" ·
    //      0 = UNKNOWN.** Display vocabulary ONLY; the vote never consults it, and its sign comes
    //      from the side the episode closes on.
    //
    //      ⚠️ THREE STATES, NOT A BOOL, AND THE THIRD IS NOT DEFENSIVE PADDING. The two tests
    //      (`low[1] > price`, `high[1] < price`) are complementary only for a NON-TOUCH bar. For
    //      every episode after a level's first, bar t−1 is guaranteed non-touch — the previous
    //      episode closed on one — so the pair is exhaustive there. The exception is an episode
    //      opening ON THE ENTRY BAR, where t−1 is the signal bar: pre-signal, never processed by
    //      this engine, and free to have straddled the level. That is common rather than exotic —
    //      a wide breakout bar straddles every watched level inside its range, the origin most of
    //      all — so a bool would have to fold "we cannot tell" into "from below" and print
    //      "obstacle test" for a support test, silently. Same class of error as the fail-open
    //      envKnown, at display scale.
    //
    //      ⚠️ NOT redundant with bornSupport, and the two are right in different contexts: born-
    //      Support answers "where does this level sit relative to entry?" and is fixed for the
    //      signal's life, while this answers "how did price meet the level in THIS test?" and is
    //      rewritten at every open. A level born an obstacle that price cleared and now holds from
    //      above is being tested AS SUPPORT — break→retest→go — and labelling that "obstacle test"
    //      would put the tooltip in contradiction with the chart, the M10 tag-collision failure.
    //
    //      Only knowable at OPEN, which is why it is stored rather than derived. This is the
    //      multiplied structure — N signals × M levels — so it is the expensive kind of field, paid
    //      deliberately; an int costs no more than the bool it replaces.
    int    apprSide = 0
 
// @type One signal's participation state. Created by seed() at the moment the signal fires, then
//       (from Phase 3) advanced every confirmed bar until the trade resolves.
//
//       Independent of the host's TradeState by construction, and that is required rather than
//       tidy: a Friday-blocked signal never builds a TradeState but is still measured in full, and
//       the two lifecycles differ anyway — a trade runs to TP2/TP3/trailing/BE, participation
//       resolves at the chosen verdict target.
//
//       The a1* block is LATCHED and never rewritten. It is the environment as it stood at the
//       signal bar's close; see the snapshot note in step().
//
//       The a2* block is descriptive context that NEVER VOTES. The stop-side scan predicts where
//       fights will occur, and a prediction is not evidence — the episodes that later happen there
//       are, and those are S3's business.
export type ParticipationState
    // ── thesis ──
    bool   bull
    string sigType                // display only; logic uses famIdx (see seed)
    int    famIdx
    int    seedTime
    int    seedBar
    float  entry
    float  stop
    float  target                 // verdict target price — TP1 in M11-2
    float  r                      // |entry − stop|
    float  origin
    string originTag
    // ── A1 — latched environment ──
    float  a1CumRvol
    float  a1DayUsed
    float  a1Adr
    float  a1EntryLoc             // direction-AGNOSTIC (entry − LOD) ÷ (HOD − LOD)
    float  a1Vwap
    float  a1VwapSlope
    // a1Sessions (all three sessions pre-rendered) was REMOVED 2026-08-12 with the tooltip row it
    // served; the readings are host plots now. See the SessSnap note near the top of this file.
    bool   a1EnvKnown
    // ── A2 — stop-side scan ──
    string a2MagnetTag
    float  a2MagnetR
    string a2StrongTag
    float  a2StrongR
    float  a2StrongCost
    string a2SlAdjTag
    float  a2SlAdjR
    float  a2SlAdjCost
    string a2SlAdjWord            // resolved at seed: exposed / protected / thin cover
    int    a2SlAdjSide            // +1 inside the corridor · −1 beyond the stop · +2 ON the stop ·
                                  // 0 none. NOT a sign convention — +2 was added 2026-08-12 and any
                                  // reader treating this as a signed side will mis-handle it.
    string a2Corridor             // pre-rendered "2× ORL, VAL, C-POC"
    string a2Obstacles
    // ── A3 ──
    array<WatchedLevel> levels
    // nSupport / nObstacle were REMOVED 2026-08-12 with the tooltip text that printed them. Unlike
    // the session snapshot they encoded nothing that cannot be recovered: `levels` is retained, and
    // both counts are a walk over it filtering on bornSupport. Derivable ⇒ not stored.
    // ── A4 / ladder ──
    string rung
    string birthRung
    // [→P3] Which other signal families fired during this signal's window. WRITTEN in M11-2 and
    // read only in Phase 3, so it sits outside the dormant block below — the header there would be
    // wrong about it, and a field contradicting its own header is worse than an untagged one.
    int    famMask = 0
    // ── [P3] Phase 3 state, declared now so the type is never reshaped ──
    // Every field below was declared in ONE pass, before any engine code existed, for the reason
    // given on WatchedLevel: adding a field to a dev library is free, while reshaping a type the
    // host already reads costs a two-file compile — so discovering these across three passes would
    // cost three of them.
    // ⚠️ THE BLOCK IS NO LONGER DORMANT — compile 6 filled it; corrected here 2026-09-05. The
    // sentence this replaces said "nothing here is read yet, and only runLow/runHigh are written",
    // which is now false in both halves: the S1/S3/S4 accumulators, the four component statuses,
    // the ladder counters and stamps, the retained records and the resolution fields are all
    // written AND read inside advance(). ✅ The DISPLAY block at the end — lbl / isFollower /
    // leadFam / baseTxt / baseTip — was filled by compile 7 (2026-09-05), which is also where
    // leadFam was added. NOTHING IN THIS BLOCK IS DORMANT ANY MORE.
    //
    // ── S1 — commitment. Advanced PAIRWISE: both, only on bars where barDelta is non-na. Advancing
    //    the denominator alone on a blank-delta bar dilutes the ratio toward zero and reads as a
    //    signal getting LESS committed the longer it is held; and `+= na` is permanently absorbing
    //    and silent, so one such bar would poison the pair for the rest of the signal's life.
    float  cumDelta = 0.0
    float  cumVol   = 0.0
    // Sticky: set the first time a FOLDED bar carried CLV-proxy delta rather than footprint delta.
    // ⚠️ NOT the entry bar's source latched at seed — a signal can begin on footprint delta and
    // meet later bars where the request returns na, and latching would misreport every mixed
    // signal. CLV×volume is a DIFFERENT quantity, not a noisier one, so a cohort that mixes sources
    // silently is exactly the incomparability that keeps thresholds out of the input list.
    bool   proxyDelta = false
    // ── S3 — episodes. Running signed sum of `vote × wBase × w(E)` over the signal's life, NO
    //    decay: the ladder is already the temporal mechanism, and a second one would compete with
    //    it. Unbounded harmlessly — magnitude past the threshold is invisible to the ladder.
    float  s3Tally = 0.0
    // The two retained test records — level tag, approach class, and the three CLOSED values.
    // rec* = the most recent completed measured test at any level; corr* = the same for a level
    // inside the stop corridor, which is the auditability the client asked for on 2026-08-10.
    // They coincide on a trade that never tested anything above entry, so the corr* row renders
    // only when it differs — which makes its presence itself meaningful.
    // recSide / corrSide carry WatchedLevel.apprSide's three states unchanged, 0 included: a record
    // whose approach could not be determined must render without vocabulary, not with the wrong one.
    string recTag   = na
    int    recSide  = 0
    float  recOI    = na
    float  recD     = na
    float  recE     = na
    string corrTag  = na
    int    corrSide = 0
    float  corrOI   = na
    float  corrD    = na
    float  corrE    = na
    // ── SAME-BAR TIE-BREAK STATE for the two records above (§7.10.2). Several episodes can close on
    //    ONE bar — a wide bar touches several levels at once and a later non-touch bar then closes
    //    all of them together — and closeEpisode writes unconditionally, so without these the
    //    surviving record is whichever level came last in `levels`, i.e. buildUniverse's flatten
    //    order. Stable, but arbitrary against anything the reader can see. streamPart already
    //    answers the identical question by wBase (see its header); these let the records answer it
    //    the same way, so one tooltip stops carrying two selection rules for one question.
    // ⚠️ TWO PAIRS, NOT ONE — and one pair is the obvious "simplification". Record 2 is written on a
    //    SUBSET of the closes record 1 sees, so a single shared weight would let a heavy NON-corridor
    //    level block the corridor record from updating at all: a C-POC outside the corridor
    //    (wBase 1.0) and a P-ORH inside it (0.24) closing on one bar need record 1 to take the C-POC
    //    and record 2 to take the P-ORH, which one weight cannot express.
    // ⚠️ SEEDED -1, NEVER na — the sentinel rule, and this is a textbook instance. `recBar !=
    //    bar_index` against an na field evaluates to na, which is FALSY, so the guard would be false
    //    on every bar after the first write and the row would freeze on the signal's first test,
    //    with no error and no tell.
    int    recBar    = -1
    float  recWBase  = 0.0
    int    corrBar   = -1
    float  corrWBase = 0.0
    // ── S4 — acceptance of origin. SIGNED consecutive confirmed closes vs the latched origin, from
    //    the entry bar: positive = beyond, negative = back through, and a close EXACTLY at the
    //    origin holds the run unchanged. ⚠️ No companion `everHeld` bool — the STALLED rule's
    //    "after having held" clause is struck, so nothing needs one.
    int    s4Run = 0
    // ── S5 — the ladder.
    // The four component statuses, RE-CLASSIFIED EVERY CONFIRMED BAR AND STORED. Stored rather than
    // re-derived at display time for one reason that matters: §7.2.6 requires the classification to
    // have exactly ONE site, and the display needs all four (its own rows, and the reason phrase's
    // templates interpolate the status word directly). Deriving them again in the renderer would be
    // a second site, free to drift from this one.
    //
    // ⚠️ THE DEFAULTS ARE `na` BECAUSE PINE REJECTS A CONST AS A FIELD DEFAULT — CE10132, "the
    // default value cannot be a function, variable or calculation", observed 2026-09-05 on the
    // ladder's first paste to TradingView. A `const string` is still a *variable* to the compiler,
    // and the cascade is CE10165 ("no value assigned") at every .new() site.
    // ⚠️ `na` IS NOT A STATUS AND MUST NEVER REACH A READER — reason() concatenates the word into
    // its sentence and the ladder compares it. The real birth values (ST_UNKNOWN ×3 and S3_NONE)
    // are passed at the SINGLE ParticipationState.new() in seed(), which makes these four MANDATORY
    // there rather than optional, exactly as runLow/runHigh are.
    // Hardcoding the words here as literals was the alternative and was REJECTED: it duplicates
    // them somewhere they can drift from the constants, and the drift fails OPEN — a stale birth
    // word satisfies `!= ST_UNKNOWN`, which starts the barsAtRung clock on a signal that cannot be
    // measured, the exact I2 failure advance() carries a standing warning about.
    string s1Stat = na
    string s2Stat = na
    string s3Stat = na           // seeded S3_NONE, not ST_UNKNOWN — S3 has no unknown, see the
                                 // constants block
    string s4Stat = na
    // Is S2 currently good enough for the CONFIRMED conjunct? A FIFTH classification, stored beside
    // the four and written in the same unconditional block, because it is not a status — it is a
    // TWO-BRANCH TEST whose branch selector is the latched entry cumRVOL: enter on decent
    // participation and `steady` suffices, enter on thin participation and only `building` does.
    // ⚠️ IT EXISTS SO THE LADDER AND THE REASON PHRASE CANNOT DISAGREE. reason() has no access to
    // cfgRvolAdequate, so before this field its "but pace is …" clause tested `fading or
    // unreadable` — which MISSES the `steady`-on-a-thin-entry case entirely, and the tooltip then
    // printed a "Developing because …" with NO "but" half at all, asserting that nothing blocked
    // promotion while S2 was blocking it. Silent, and only on signals born into weak environments.
    // Passing the threshold into reason() instead would put the two-branch expression in two places
    // that can drift; §7.2.6's one-site rule is why the four statuses are stored, and it applies
    // here for the same reason.
    bool   s2Ok = false
    // Why this signal stalled, 0 = it has not. Stored because STALLED is absorbing: the ladder stops
    // while the episode engine keeps measuring, so the tally can move afterwards and the reason
    // would no longer be re-derivable from the current statuses.
    int    stallWhy = 0
    // Which disjunct carried the promotion to DEVELOPING — see the DEV_* constants. Latched at the
    // transition for the reason stallWhy is: the disjunction's terms keep moving afterwards.
    int    devWhy = 0
    // Patience multiplier for this signal's type, resolved once at seed from famIdx + the retest
    // flag. Resolved there rather than per bar so the ladder carries no switch.
    float  patMult = 1.0
    int    barsAtRung = 0
    // Consecutive confirmed bars on which S1 reads `against` AND S2 reads `fading`; reset to 0 the
    // moment either fails. ⚠️ Nothing else can serve: the component statuses are derived inside
    // this library and are not Pine series, so [1] and ta.barssince do not apply — and libraries
    // hold no `var`, so the library cannot remember it either.
    int    decayRun = 0
    // Retained ladder history — the bar_index at which each transition happened. Three ints rather
    // than an array because promotions are monotonic and STALLED is absorbing, so a signal makes at
    // most three transitions ever. ⚠️ SEEDED -1, NEVER na: the guard is `>= 0`, and `x != na` is na
    // and therefore falsy. Rendered as "->DEV+3", counting from the ENTRY bar as +0.
    int    devAt   = -1
    int    confAt  = -1
    int    stallAt = -1
    // ── Excursion — per SIGNAL, from entry, and NOT part of S3 (whose depth is per EPISODE and
    //    measured from the level). ⚠️ math.min(na, x) is na, so both are SEEDED TO `entry` in
    //    seed() rather than left at this declared na — which also sidesteps a live/historical
    //    split, since seed() runs on the execution bar's first tick where low/high are partial
    //    while entry is a fixed price.
    float  runLow  = na
    float  runHigh = na
    string outcome = ""           // "" · "TP1" · "stopped" · "expired"
    // ── Display. The label handle is the rewrite key, not the state: two states can share one
    //    handle (a merged inflection), and if each rewrote independently the last write would win
    //    and one signal's readings would vanish. isFollower is set when the handle is ASSIGNED,
    //    from the merge the host has already resolved — never by a scan at render time.
    //
    //    ⚠️ There is NO lastWriteBar dedup field, and that is a decision rather than an omission.
    //    This object lives in a `var` array, so Pine reverts the whole thing on every realtime tick
    //    and the guard would reopen — it can block nothing, ever. Historical bars execute once
    //    anyway. Per-tick rewriting is correct and idempotent, exactly as the status table already
    //    does on bare `islast`. (par.step's lastStepBar is NOT a counter-example: it is a "first
    //    execution of this bar" marker that relies on idempotence, not a dedup.)
    label  lbl = na
    bool   isFollower = false
    // Which family LEADS the handle this state was bound to, **while a partner is still present**;
    // -1 when this label carries one signal, or when the partner has resolved and left. Written by
    // bindLabel on BOTH members of a merged pair — the follower gets the leader's famIdx, the leader
    // gets its own — and it is what makes the partner lookup exact instead of merely usual.
    // ⚠️ IT IS THE LOOKUP'S OWN SHORT-CIRCUIT, which is why the leader carries it too and why
    // render clears it on the survivor at the freeze. Without that, `merged` was doing both jobs and
    // never goes false, so a survivor walked the whole array on every write hunting a partner that
    // had already left. The two fields answer different questions: `merged` is permanent and drives
    // the display prefix, this one is the live link.
    // ⚠️ WITHOUT IT THE LOOKUP MIS-ATTRIBUTES. A follower is found by (isFollower, seedBar, bull),
    // and a Continuation and an AC can fire on the SAME bar in the SAME direction — only one of
    // them takes the merge, but both would match, so the unmerged label would print the
    // inflection's readings too. AC vs AC-Retest cannot collide (host [6793] is an if/else-if
    // chain, so at most one famIdx-1 state exists per bar and direction); Continuation vs AC can.
    // ⚠️ SEEDED -1, NEVER na — `x != na` is na and therefore falsy; the guard is `>= 0`.
    // 📌 CLEARED BACK TO -1 WHEN A FOLLOWER IS PROMOTED (render's freeze), so the field never
    // describes a relationship that no longer exists.
    int    leadFam = -1
    // Does this state's LABEL carry two signals? Set on BOTH of them at bind time, and it stays
    // set for the state's whole life — including after the partner has resolved and been pruned.
    // ⚠️ THIS IS WHY IT IS A FIELD RATHER THAN A SCAN. The prefix used to be derived from "is my
    // partner still in the array", which made a merged label print "[Continuation]" until its
    // partner resolved and then silently stop — worse than either state alone, because the reader
    // cannot tell whether the label ever carried two signals.
    bool   merged = false
    // ⚠️ baseTxt / baseTip ARE NOT PURELY THE CREATION-TIME STRINGS ANY MORE. They start as what
    // label.new was given — arrow, score breakdown, at-signal block — and every rewrite is built
    // as base + live block, because label.set_text REPLACES and cannot append. But when a merged
    // PARTNER resolves, its final block is appended here on its way out of the array (see render),
    // so from that point the base also carries one frozen, permanently-correct signal block. That
    // is what keeps a resolved partner on the label after it stops being a live state.
    string baseTxt = ""
    string baseTip = ""
    bool   resolved = false
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Internal — producers
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// P4 — Average Daily Range over the last _n COMPLETED days, from the host's native daily H/L
// tracker. Zero request.* calls.
// Reads from the END of the arrays because the tracker's depth is max(drawn count, lookback):
// when the user draws more Daily levels than the lookback, the extra ones sit at the front and
// must not dilute the average. The forming day is deliberately excluded — it lives in the
// tracker's curH/curL, not in these arrays.
adrFrom(array<float> _highs, array<float> _lows, int _n) =>
    int   _sz  = array.size(_highs)
    int   _use = math.min(_n, _sz)
    float _sum = 0.0
    if _use > 0
        for _i = 1 to _use
            _sum += array.get(_highs, _sz - _i) - array.get(_lows, _sz - _i)
    _use > 0 ? _sum / _use : na
 
// P1 — fold one completed 30-minute bucket's session volume into that bucket's EMA baseline.
// The EMA seeds on its first observation rather than decaying up from zero, so a bucket's
// baseline is usable from its second session instead of its Nth.
// Buckets that printed no volume are left ALONE, not folded as a zero: a bucket the market
// skipped is a gap in coverage, not evidence that the half-hour is dead.
// _k = −1 ("no bucket yet") is a no-op.
foldBucket(ParState _p, int _k, float _a) =>
    if _k >= 0
        float _today = array.get(_p.bktToday, _k)
        if _today > 0
            float _prev = array.get(_p.bktTypical, _k)
            array.set(_p.bktTypical, _k, na(_prev) ? _today : _a * _today + (1.0 - _a) * _prev)
 
// P5 — advance one session ledger one bar. Mutates _s by reference.
// On entry it captures the open and clears the previous occurrence's efficiency; while inside it
// tracks H/L/close and republishes rng, extension and direction every bar; on exit it computes
// efficiency once and leaves the whole summary frozen until the session next opens. Overlapping
// sessions are independent by construction — London and New York both run through the overlap,
// each on its own ledger.
//
// The live readings are deliberate. Freezing them until the session closed would mean that
// mid-session the fields silently held the PREVIOUS occurrence, which no consumer could detect
// without also reading `active` — a trap. Republishing them makes the object describe one instant.
stepLedger(SessionLedger _s, bool _in, float _adr) =>
    if _in
        if not _s.active
            _s.active := true
            _s.open   := open
            _s.high   := high
            _s.low    := low
            // This occurrence has no efficiency until it closes. Clearing here is what stops the
            // previous session's figure being read as this one's.
            _s.eff    := na
        else
            _s.high := math.max(_s.high, high)
            _s.low  := math.min(_s.low,  low)
        _s.close  := close
        _s.seenAt := time
        // ── Live readings ────────────────────────────────────────────────
        _s.rng    := _s.high - _s.low
        _s.extPct := _s.rng > 0 and not na(_adr) and _adr > 0 ? _s.rng / _adr : na
        _s.dir    := _s.close > _s.open ? 1 : _s.close < _s.open ? -1 : 0
    else if _s.active
        // Exit — detected on the first bar OUTSIDE the session, so rng/extPct/dir already hold
        // the values written on the final in-session bar and need no recomputation. Only
        // efficiency is resolved here, because only now is the close final.
        _s.active := false
        _s.eff    := _s.rng > 0 ? math.abs(_s.close - _s.open) / _s.rng : na
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Exported — state
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// @function  Build an empty producer state. Call once, in a host `var` declaration.
//            bktTypical seeds to na, not 0.0: the EMA takes its first observation as the seed
//            value (see foldBucket), which is the standard warm-up and avoids every bucket
//            spending its first N sessions climbing out of a zero it was never at. bktToday
//            seeds to 0.0 because it is a running sum that is cleared every session anyway.
//            Three ledgers, order-fixed: 0 = Asia, 1 = London, 2 = New York — and three snapshot
//            slots index-aligned with them, allocated once here so the per-bar copy writes into
//            existing objects instead of allocating three every bar.
//
//            EVERY cfg* value is REQUIRED, not defaulted, and that is the point of routing them
//            through here: a default would be a second source of truth that quietly wins whenever a
//            caller forgets one. They are `simple` because they are settings — the qualifier is what
//            makes "config, not state" checkable by the compiler instead of by reading the cfg
//            prefix, since a series argument would be rejected outright. It is also what lets an
//            `input` satisfy them: an input-qualified argument satisfies `simple`.
// @param rvolAdequate  Cumulative RVOL at or above which participation is not obviously absent.
// @param rvolStrong    Cumulative RVOL at or above which the day is genuinely heavier than normal.
//                      MUST be >= rvolAdequate; see the rung comment in seed() for what breaks.
// @param dayExtended   Share of ADR already travelled at which the day counts as extended.
// @param chaseHigh     Direction-adjusted entry location at or above which the entry is chasing.
// @param tgtName       Verdict-target display token — "TP1" / "TP2" / "TP3". ⚠️ The host must derive
//                      the target PRICE it passes to seed() from the same input, or the outcome
//                      suffix names a target the state was never measured against.
// @param cutoffHours   Hours of MARKET time from entry after which tracking ends with no verdict.
// @param patienceMins  Patience base in minutes; multiplied per signal type by the ladder.
// @param oiFloor       Episode opposing-intensity floor: the magnitude of |Σ opposing delta ÷ Σ volume|
//                      a level's FIRST episode must reach for holding it to score +1 rather than 0.
// @param s1Band        Neutral band on the commitment ratio; outside it, S1 is aligned or against.
// @param s2Building    recent3 ÷ prior3 at or above which participation pace is building.
// @param s2Fading      …and at or below which it is fading. Make the pair multiplicatively symmetric
//                      (0.83 ≈ 1/1.20): an arithmetic pair makes fading HARDER to reach, not easier.
// @param s4Hold        H — consecutive closes beyond the origin for `holding`. ⚠️ MUST be >= 2.
// @param s4Reject      R — consecutive closes back through it for `rejected`. ⚠️ MUST be >= 1.
// @param decayN        N — consecutive bars of S1 `against` + S2 `fading` that stall a signal.
// @returns   A fresh `ParState`.
export newState(simple float rvolAdequate, simple float rvolStrong, simple float dayExtended,
     simple float chaseHigh, simple string tgtName, simple int cutoffHours,
     simple int patienceMins, simple float oiFloor, simple float s1Band, simple float s2Building,
     simple float s2Fading, simple int s4Hold, simple int s4Reject, simple int decayN) =>
    ParState.new(
         bktTypical = array.new<float>(BUCKETS, na),
         bktToday   = array.new<float>(BUCKETS, 0.0),
         sess       = array.from(SessionLedger.new(), SessionLedger.new(), SessionLedger.new()),
         cfgRvolAdequate = rvolAdequate,
         cfgRvolStrong   = rvolStrong,
         cfgDayExtended  = dayExtended,
         cfgChaseHigh    = chaseHigh,
         cfgTgtName      = tgtName,
         cfgCutoffHours  = cutoffHours,
         cfgPatienceMins = patienceMins,
         cfgOiFloor      = oiFloor,
         cfgS1Band       = s1Band,
         cfgS2Building   = s2Building,
         cfgS2Fading     = s2Fading,
         cfgS4Hold       = s4Hold,
         cfgS4Reject     = s4Reject,
         cfgDecayN       = decayN)
 
// @function  Advance the whole participation layer one bar. Mutates `p` by reference; returns
//            nothing useful.
//
//            GATED ON timeframe.isintraday, DELIBERATELY NOT ON the host's tfValid. The layer
//            describes the trading DAY, not the OR window, so unlike the rest of the indicator
//            its readings stay meaningful above 15 minutes — and the host's tables render at any
//            timeframe, so a tfValid gate would leave the participation table showing nothing but
//            dashes on a 1H chart. The host's "tfValid gates producers" rule does not bind here:
//            it exists because request.footprint's row count scales with bar range and fed an
//            unbounded var map that replay's rollback snapshots doubled. This layer's state is
//            FIXED size — 2 × 48 floats, 3 small UDTs, a dozen scalars — and allocates nothing
//            per bar, so there is no bar-width-proportional cost to gate away.
//
//            isintraday is the ceiling because that is where the producers actually break, not a
//            round number: at 1D a daily bar sits inside the session on every bar, so a ledger
//            enters and NEVER exits and its high/low accumulate across every day without bound;
//            VWAP re-anchors every bar and collapses to hlc3; and above 1D the daily H/L tracker
//            pushes weekly ranges that ADR would report as daily. Below 1D all of those are
//            sound. P3 has no ceiling at all. P2 has its own, stricter one — see barRvol.
//
//            STATE is never barstate.isconfirmed-gated: `p` is var-held host-side, so Pine reverts
//            those writes on each realtime tick and commits them at close, and gating would hide
//            them from same-bar consumers while buying nothing. The only exception is the two
//            volume RATIOS — barRvol and cumRvol — which are published at close only; the reason
//            is at their write site, and it is about ratios, not about state.
// @param p          Producer state (mutated).
// @param isNewDay   The host's holiday-corrected session boundary — never a raw ta.change.
// @param lookback   Sessions defining "normal": the ADR window and the RVOL EMA weight.
// @param slopeK     Bars back for the VWAP slope.
// @param sAsia      Asia session, in TOKYO time.
// @param sLondon    London session, in LONDON time.
// @param sNY        New York session, in NEW YORK time.
// @param dayHighs   The host daily tracker's completed-day highs.
// @param dayLows    The host daily tracker's completed-day lows.
// @param dayCurH    The forming day's high.
// @param dayCurL    The forming day's low.
export step(ParState p, bool isNewDay, simple int lookback, simple int slopeK,
     simple string sAsia, simple string sLondon, simple string sNY,
     array<float> dayHighs, array<float> dayLows, float dayCurH, float dayCurL) =>
    p.live := timeframe.isintraday
    if timeframe.isintraday
        // ── THE AT-SIGNAL SNAPSHOT (M11-2) — take it FIRST, before anything below moves ────
        //
        // The problem it solves. par.seed is called from the host's score/stop block, which is not
        // isconfirmed-gated, so it runs on the EXECUTION bar. On a historical bar Pine executes
        // that bar exactly once, at its close, so by the time seed runs this function has already
        // written the execution bar's own cumRVOL. Live, seed runs on that bar's FIRST TICK, where
        // the confirmed-only branch below has not run and cumRVOL still holds the previous bar's
        // value. Same signal, two different environment snapshots — and A1 is latched permanently,
        // so the difference never washes out. Phase 1's isconfirmed gate on the two ratios removed
        // the mid-bar dip; it did not remove this.
        //
        // The fix. On the FIRST EXECUTION of any bar — whether that is the only execution
        // (historical) or the first of many (live) — every field below still holds the previous
        // bar's committed value. Copying here therefore produces an identical result in both modes,
        // which is the entire requirement. A1 then describes the SIGNAL bar's close rather than a
        // partially-formed execution bar, which is also the honest reading and matches how
        // scoreEval already takes the signal candle as open[1]/high[1]/low[1]/close[1].
        //
        // Rollback makes this idempotent rather than fragile: on tick 2 Pine reverts the whole var
        // object — lastStepBar included — so the guard opens again and the copy re-runs from the
        // same source values to the same result.
        //
        // The guard is a plain `!=` against a -1 SENTINEL, never against na. See the note on
        // lastStepBar's declaration for what an na seed does to this block: it silences it entirely,
        // on every bar, without any error.
        //
        // dayHi/dayLo are snapped for a sharper reason than the rest. Taken live, the day's range
        // excludes most of the execution bar; taken historically it INCLUDES the whole bar, i.e.
        // price action after the entry. An entry-location percentile measured against a range that
        // already knows what happened next is not a snapshot, it is hindsight.
        //
        // The session ledgers were snapped here too until 2026-08-12, when the tooltip's Sessions row
        // moved to the Data Window. The full design — including why all five readings had to be
        // copied together and why the freshness verdict had to be resolved in this pre-roll frame —
        // is preserved at the SessSnap removal note near the top of this file. Do not reconstruct it
        // from the live ledgers without reading that first.
        if bar_index != p.lastStepBar
            p.snapCumRvol := p.cumRvol
            p.snapVwap    := p.vwap
            p.snapSlope   := p.vwapSlope
            p.snapDayHi   := p.dayHi
            p.snapDayLo   := p.dayLo
            p.snapDayUsed := p.dayUsed
            p.snapAdr     := p.adr
            p.lastStepBar := bar_index
 
        float _alpha = 2.0 / (lookback + 1)
 
        // ── P8 inputs — evaluated FIRST and UNCONDITIONALLY within this block ────
        // Both are ta.* calls, so both must run on every bar the block runs on. The enclosing
        // gate is safe because timeframe.isintraday is constant for the whole run — the calls
        // happen on every bar or on none, never bar-by-bar.
        //
        // ta.change keeps its history buffer PER CALL SITE, filled only on executions that
        // actually happen — so "K bars ago" means "K executions ago". Putting the warm-up test
        // (barsInSess > K) on the call instead of on the result would leave every session's first
        // K bars out of the buffer, and the slope would then silently compare across the anchor.
        // Gate the result, never the call.
        float _vwap    = ta.vwap(hlc3, isNewDay)
        float _vwapChg = ta.change(_vwap, slopeK)
 
        // ── Session roll ────────────────────────────────────────────────────
        // Also fires on the very first bar (sessOpen still na), which is what initialises the
        // bucket anchor. The outgoing session's final bucket never sees an index change, so it
        // is folded here — this is its completion.
        if isNewDay or na(p.sessOpen)
            foldBucket(p, p.bkt, _alpha)
            array.fill(p.bktToday, 0.0)
            p.sessOpen   := time
            p.bkt        := -1
            p.cumVol     := 0.0
            p.cumTyp     := 0.0
            p.barsInSess := 0
            p.sessCount  += 1
            // ADR only changes when a day completes, so it is rolled here rather than recomputed
            // per bar. The host's stepHtf has already pushed the outgoing day, so this includes it.
            p.adr := adrFrom(dayHighs, dayLows, lookback)
            // The two volume ratios are confirmed-only (see below), so without this they would
            // hold the OUTGOING session's final values through the first bar of the new one —
            // yesterday's participation shown at today's open, which is exactly when it is read.
            // One bar of na is honest; one bar of yesterday's number is not.
            p.barRvol := na
            p.cumRvol := na
            // Nothing is done to the session ledgers here. They carry seenAt, so day attribution
            // is the consumer's call — see the SessionLedger doc for why a flag reset on this
            // line could not get the roll/exit collision right.
 
        p.barsInSess += 1
 
        // ── P1 / P2 / P3 — time-of-day volume normalisation ─────────────────
        // Buckets are anchored to the SESSION open, not to midnight, so cumulative RVOL never
        // has to wrap. The clamp parks anything past 24h in the last bucket rather than erroring:
        // the index has no structural ceiling (elapsed time does not wrap the way a clock does),
        // so without it an over-long session indexes past the array and kills the script.
        //
        // int() is NOT optional. Pine's `/` on two ints returns a FLOAT — verified on TradingView
        // 2026-08-01 — and the implicit narrowing on `int _b = …` compiles silently, so without
        // the cast we would be relying on an unknown rounding rule. If it rounded rather than
        // truncated, the index would advance at the 15-minute mark, `_into` below would go
        // negative, and cumRVOL would blink to na for half of every bucket.
        int   _since = time - p.sessOpen
        int   _b     = math.max(0, math.min(BKT_LAST, int(_since / BKT_MS)))
        float _v     = nz(volume)
        if _b > p.bkt
            foldBucket(p, p.bkt, _alpha)
            // Walk every index from the one we were in to the one we have arrived at, adding
            // each bucket's baseline to the running expectation. Incremental here so P3 never
            // pays a per-bar loop over 48 slots.
            //
            // The consequence, which is the interesting part: a bucket the market skipped
            // entirely still contributes its baseline. It added nothing to cumVol, so P3
            // correctly reports that the session is behind. That is deliberately asymmetric
            // with foldBucket, which REFUSES to fold a zero-volume bucket — a coverage gap is
            // not evidence that the half-hour is normally dead. One protects the baseline from
            // today; the other applies the baseline to today.
            //
            // Strict > guards the loop: Pine counts DOWN when a `for` range ends below its
            // start, which here would double-add.
            for _i = p.bkt + 1 to _b
                p.cumTyp += nz(array.get(p.bktTypical, _i))
            p.bkt := _b
        array.set(p.bktToday, _b, array.get(p.bktToday, _b) + _v)
        p.cumVol += _v
 
        // ── P2 / P3 — the two volume RATIOS, and the only gated writes in this layer ──
        //
        // Everything above is state and stays ungated: `p` is var-held host-side, so Pine reverts
        // and re-applies those writes on every realtime tick and commits them at close. Gating an
        // accumulator would buy nothing and hide it from same-bar readers.
        //
        // These two are different in kind. They are ratios whose numerator and denominator FILL AT
        // DIFFERENT RATES: volume accrues gradually through the bar while the expectation it is
        // divided by lands whole. Mid-bar the result is not merely early, it is wrong in a way
        // that does not converge monotonically — cumRVOL dips by roughly (this bar's expectation ÷
        // the session's expectation so far) at every bar open and climbs back by its close, ≈1/N
        // at bar N. Pro-rating the BUCKET, below, cannot touch that: it is a per-BAR effect, and
        // correcting it would need intrabar elapsed time, which exists only on the realtime bar
        // and would make live and historical disagree.
        //
        // So they are published only at bar close. Nothing is lost: every consumer reads confirmed
        // data by design, and one consumer would actively have been harmed — par.seed fires from
        // the host's trade-opening block, which is NOT isconfirmed-gated, so a live cumRVOL would
        // be latched into the at-signal snapshot on the execution bar's FIRST tick, recording a
        // dipped, meaningless participation reading for that signal permanently.
        //
        // Contrast with the fields that stay live because they are self-consistent: vwap is
        // Σ(p·v)/Σv with the same partial bar on both sides; dayUsed and the session extensions
        // are extremal and only grow, so including the forming bar's extremes is correct.
        if barstate.isconfirmed
            // P2 — this bar's volume against what this slice of this bucket normally prints.
            // Scaling the bucket baseline by the bar's share of 30 minutes is what makes the
            // reading chart-TF invariant: 1.0 means typical on 1-min and on 15-min alike.
            //
            // That scaling is only valid while the baseline really does hold 30 minutes of volume.
            // At or below 30 min a bucket collects every bar in its window (6 on 5-min, 2 on
            // 15-min, 1 on 30-min). ABOVE 30 min it collects exactly one bar carrying T minutes,
            // so the baseline is already T minutes' worth and multiplying by T/30 double-scales
            // it — a typical bar would read 30/T (0.5 on 1H, 0.125 on 4H). A constant wrong answer
            // is worse than a noisy one because it looks like a reading, so P2 reports na above
            // its own structural ceiling. This is the ONLY producer with a ceiling below
            // isintraday; cumRVOL does not share it, because P3 never divides by bucket width.
            float _expBar = nz(array.get(p.bktTypical, _b)) * (timeframe.in_seconds() / 60.0) / 30.0
            // [→P3] The expectation is published as well as consumed. Episode RVOL needs the raw
            // denominator, and barRvol is then derived FROM the published field rather than from
            // the local — same arithmetic, but the ratio and the expectation can no longer disagree
            // about which bars carry a usable expectation at all. Deleting this line raises no
            // compile error and silently starves Phase 3's episode admission test.
            p.expVol  := timeframe.in_seconds() <= SECONDS_30MIN and _expBar > 0 ? _expBar : na
            p.barRvol := na(p.expVol) ? na : _v / p.expVol
 
            // [→P3] S2's 3v3 window — the two RAW means, no classification. The producer measures,
            // par.advance classifies, so the thresholds and the degenerate routings have exactly
            // one site rather than two.
            //
            // ⚠️ IT CANNOT LIVE IN par.advance, AND THE FAILURE WOULD BE SILENT. ta.* fills its
            // history buffer per call site, on the executions that ACTUALLY HAPPEN — the rule this
            // file documents at the top of step(). par.advance is gated on there being a live
            // signal, so a ta.sma inside it would mean "three executions in which some signal was
            // open", not "three bars". No error, no tell, and wrong by an amount that varies with
            // how busy the chart was. ⚠️ Reaching for a local and `[3]` instead does NOT escape
            // this — a local's history is indexed by executions of its site too, so it inherits
            // whatever gate it sits under. The gate is the thing that has to be right.
            //
            // ⚠️ Why THIS conditional site is safe, and the exact limit of the precedent: it is
            // inside `if barstate.isconfirmed`, which is true EXACTLY ONCE PER BAR in both modes —
            // once at close on realtime, once per bar on history — so "three executions ago" IS
            // "three bars ago". That is the invariant. A gate that is true on some bars and false
            // on others breaks the buffer silently; do not cite this as licence for one.
            //
            // Placed after barRvol rather than at isintraday level for a reason that outlives S2:
            // barRvol is only assigned inside this block, so a call above it would sample the
            // PREVIOUS bar's value on realtime ticks. The committed series would still be right,
            // but renderParticipation runs on bare `islast` — so the moment a live S2 reading
            // reaches the roll-up row, the higher placement shows a mid-bar artifact and this one
            // cannot.
            //
            // ONE call site feeds both fields. ✅ TradingView-verified 2026-09-03: a local declared
            // inside this block carries history, and `_s2[3]` returns exactly what a second
            // ta.sma(...)[3] would. That is not a coincidence — a local's history and a ta.* buffer
            // are indexed the same way, by EXECUTIONS OF THEIR SITE — so the once-per-bar invariant
            // above is the single thing making both the call and the [3] mean "bars". Two call
            // sites were written first, out of caution about the local; the test removed the doubt
            // and the duplicate.
            // ⚠️ Never nz() these — ta.sma returns na until its window is full of real values, and
            // that na means "no baseline yet", which is a different fact from "a dead market" and
            // is exactly the distinction this whole layer exists to make.
            float _s2  = ta.sma(p.barRvol, 3)
            p.s2Recent := _s2
            p.s2Prior  := _s2[3]
 
            // P3 — the robust read: summing across elapsed buckets averages out the estimation
            // noise that makes any single bucket unreliable. na (not 1.0, not 0.0) until there is
            // a baseline to divide by, so a warm-up value can never be read as a signal.
            //
            // cumTyp counts the CURRENT bucket in full, so the part of it that has not elapsed yet
            // is subtracted back. Without this the expectation jumps a whole bucket the instant we
            // enter one while cumVol has none of it, and cumRVOL sawtooths at every BUCKET
            // boundary — ~100% deep at bucket 0 (a perfectly normal session open would read 0.20
            // on its first 5-min bar), ~17% at bucket 5, ~8% at bucket 12. That is a separate
            // effect from the per-bar one described above, and this is the half that can be fixed.
            // It only exists below 30 min, where several bars share a bucket; at or above 30 min
            // one bar fills a bucket, _frac saturates at 1, and there is correctly nothing to
            // subtract. Pro-rating assumes volume is uniform within a bucket, which it is not —
            // but the error it replaces is the ENTIRE unelapsed remainder, so it is closer in every
            // realistic shape, and exact whenever the bar length divides 30 (1, 2, 3, 5, 6, 10,
            // 15, 30). The bar's own length is included because at close the bar has fully printed.
            //
            // _into is elapsed-within-bucket, derived by subtraction rather than modulo so that a
            // CLAMPED bucket 47 keeps accumulating instead of wrapping: frac saturates at 1 and
            // the over-long bucket counts in full. The denominator is written as a float literal
            // because, as above, Pine's int ÷ int does not do what it looks like it does.
            int   _into = _since - _b * BKT_MS
            float _frac = math.min(1.0, (_into + timeframe.in_seconds() * 1000) / (30.0 * MS_PER_MINUTE))
            float _typ  = p.cumTyp - nz(array.get(p.bktTypical, _b)) * (1.0 - _frac)
            p.cumRvol := _typ > 0 ? p.cumVol / _typ : na
 
        // ── P4 — day range used ─────────────────────────────────────────────
        // dayCurH/dayCurL are the FORMING day, updated by the host's stepHtf earlier this bar.
        // They are also retained on the state, because the at-signal entry-location percentile
        // needs the day's high and low and not just the ratio between them.
        p.dayHi   := dayCurH
        p.dayLo   := dayCurL
        p.dayUsed := not na(p.adr) and p.adr > 0 and not na(dayCurH)
             ? (dayCurH - dayCurL) / p.adr
             : na
 
        // ── P5 — session ledgers, each read in its own clock ────────────────
        // The three time() calls are the heaviest per-bar addition in this layer. Each timezone
        // is a literal, not a parameter: a session defined in one region's clock cannot be named
        // by a fixed string in another region's, because the offset between them is not constant.
        stepLedger(array.get(p.sess, 0), not na(time(timeframe.period, sAsia,   "Asia/Tokyo")),       p.adr)
        stepLedger(array.get(p.sess, 1), not na(time(timeframe.period, sLondon, "Europe/London")),    p.adr)
        stepLedger(array.get(p.sess, 2), not na(time(timeframe.period, sNY,     "America/New_York")), p.adr)
 
        // ── P8 — VWAP ───────────────────────────────────────────────────────
        // Anchored on the host's corrected isNewDay, which folds in newSessionInSameCandle.
        // TradingView's built-in VWAP uses TV's own daily boundary, so on a holiday-merged candle
        // ours re-anchors and the built-in does not, and the two visibly diverge. That is the
        // point of the correction, not a defect.
        //
        // The re-anchor at each session open is deliberate (do not "fix" it by un-anchoring). A
        // slope read spanning that anchor would compare a fresh average against a mature one, so
        // it stays na until the whole K-bar window is inside the session: K+1 bars must have
        // printed. Masked here on the RESULT — see the ta.change note above.
        p.vwap      := _vwap
        p.vwapSlope := p.barsInSess > slopeK ? _vwapChg : na
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Internal — shared value formatting
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Above both consumers, because Pine resolves identifiers top-down: the at-signal session summary
// and the participation table both render the same quantities and must render them identically.
 
// A [0,1]-ish fraction as a percentage to one decimal. extPct legitimately exceeds 100% on a big
// day. The format string does the rounding, rather than math.round + str.tostring, so the decimal
// count is stated explicitly instead of relying on how Pine renders a whole float. One decimal is
// deliberate: these are fractions of ADR, a 20-day mean, so a second decimal would claim precision
// the input does not have — the extra digit lives in the Data Window plots, which carry two.
// ⚠️ THIS ×100 AND sessReading's ARE THE SAME CONVERSION, applied on two paths to the same fields
// (this one for the table, that one for the plots). They must not both be applied to one value, and
// they must not disagree about the unit — that is the whole reason the plots are in percent.
// The integer digit is "0", not "#". In Pine's number formats "#" means "digit, omit if zero", so
// "#.00" renders 0.98 as ".98" and "#.0" renders 0.4% as ".4%" — easy to misread next to a value
// like 25.7%. "0" forces the leading zero.
fmtPct(float _x) =>
    na(_x) ? "—" : str.tostring(_x * 100, "0.0") + "%"
 
fmtRatio(float _x) =>
    na(_x) ? "—" : str.tostring(_x, "0.00")
 
fmtDir(int _d) =>
    _d > 0 ? "▲" : _d < 0 ? "▼" : "–"
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Internal — at-signal snapshot (M11-2)
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// Set one bit of the co-occurrence mask. PINE HAS NO BITWISE OPERATORS — no |, &, ^ or shifts, and
// no math.* equivalents — so a mask has to be maintained arithmetically: each family/direction owns
// a distinct power of two and setting a bit is a guarded add. The guard is what makes it idempotent,
// which matters because realtime rollback re-runs this on every tick of the firing bar.
// int() on the division is mandatory, not cosmetic: Pine's / on two ints returns a FLOAT and the
// narrowing back to int compiles silently, so an uncast version would depend on an unknown
// rounding rule (verified on TradingView, 2026-08-01).
bitSet(int _mask, int _bit) =>
    int(_mask / _bit) % 2 == 1 ? _mask : _mask + _bit
 
// Aggregate one class of watched levels into "2× ORL, VAL, C-POC" — counts per tag, first-seen
// order. Reuses Remaining Room's idiom rather than inventing a second one, so the client reads the
// same shape of listing in the scoring panel and in the participation tooltip. Bounded by the
// number of DISTINCT tags, not by level instances, which is why it needs no "+n more" cap.
aggTags(array<WatchedLevel> _lv, bool _support) =>
    array<string> _tg = array.new<string>()
    array<int>    _ct = array.new<int>()
    int _n = array.size(_lv)
    if _n > 0
        for _i = 0 to _n - 1
            WatchedLevel _w = array.get(_lv, _i)
            if _w.bornSupport == _support
                int _k = -1
                int _m = array.size(_tg)
                if _m > 0
                    for _j = 0 to _m - 1
                        if array.get(_tg, _j) == _w.tag
                            _k := _j
                            break
                if _k >= 0
                    array.set(_ct, _k, array.get(_ct, _k) + 1)
                else
                    array.push(_tg, _w.tag)
                    array.push(_ct, 1)
    string _r = ""
    int _t = array.size(_tg)
    if _t > 0
        for _i = 0 to _t - 1
            int _c = array.get(_ct, _i)
            _r := _r + (_i > 0 ? ", " : "") + (_c > 1 ? str.tostring(_c) + "× " : "") + array.get(_tg, _i)
    _t > 0 ? _r : "—"
 
// Has this session traded within the CURRENT trading day?
//
// THE ONE DEFINITION OF "today", shared by every live consumer — the participation table via
// sessCells() and the host's Data Window plots via sessReading(). It is a function rather than a
// line repeated in both because the ledgers are deliberately NOT reset at the session roll (they
// carry seenAt so day attribution is the consumer's call), which makes this test the only thing
// standing between a reader and yesterday's London extension shown on today's chart. Two copies of
// it would eventually disagree, and the disagreement would be silent.
//
// ⚠️ Both operands are read POST-roll, which is correct for every live consumer and would have been
// wrong for the removed at-signal snapshot — see the SessSnap note near the top of this file.
sessToday(SessionLedger _s, int _sessOpen) =>
    not na(_s.seenAt) and not na(_sessOpen) and _s.seenAt >= _sessOpen
 
// @function     One session's Data-Window readings, freshness-gated: a session that has not traded
//               today returns na on every field rather than its previous occurrence's values.
//
//               ⚠️ ext AND eff COME OUT AS PERCENTAGES (×100); rng stays in points. The stored
//               fields are fractions — the scaling is applied here so that this function and the
//               table's fmtPct agree, because a reader comparing the panel against the Data Window
//               for the same session must not see 45.7% next to 0.457. Two consequences worth
//               stating: the ×100 lives in the library rather than at the host's plot() calls
//               because CE10295 counts the MAIN BODY and six multiplications there are six main-body
//               tokens spent on a unit conversion; and sessCells() does NOT come through here — it
//               scales the raw field through fmtPct — so there is no double scaling today, but a new
//               consumer must pick exactly one of the two paths, never both.
//
//               DIRECTION IS CARRIED BY THE SIGN OF `ext`, which is why this returns a signed value
//               where the table shows an arrow: extPct is a magnitude and never legitimately
//               negative, so the sign is free carriage and saves three plots. ⚠️ The one ambiguity:
//               dir = 0 (a session that closed exactly at its open) renders as positive, so a flat
//               session reads as up. Rare, and the alternative is a third plot per session.
//
//               `rng` is returned alongside so the host's three pre-existing range plots can take
//               the same gate — they were ungated and would show yesterday's range before a session
//               opens today. It is deliberately NOT scaled: points are already the unit a trader
//               reads it in.
// @param s         The live ledger.
// @param sessOpen  Host's parState.sessOpen — the day anchor `seenAt` is compared against.
// @returns         [signed ext %ADR, eff %, rng in points], all na when the session has not traded
//                  today.
export sessReading(SessionLedger s, int sessOpen) =>
    bool  _t   = sessToday(s, sessOpen)
    float _ext = s.dir >= 0 ? s.extPct : -s.extPct
    [_t ? _ext * 100 : na, _t ? s.eff * 100 : na, _t ? s.rng : na]
 
// Append one level to the flat universe. na prices are skipped, so a session with no value area
// simply contributes nothing.
pushLvl(array<float> _p, array<float> _bc, array<string> _lb, float _price, float _cost, string _tag) =>
    if not na(_price)
        array.push(_p,  _price)
        array.push(_bc, _cost)
        array.push(_lb, _tag)
 
pushLvlArr(array<float> _p, array<float> _bc, array<string> _lb, array<float> _src, float _cost, string _tag) =>
    int _n = array.size(_src)
    if _n > 0
        for _i = 0 to _n - 1
            pushLvl(_p, _bc, _lb, array.get(_src, _i), _cost, _tag)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Exported — level universe (M11-2)
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// @function   Build the participation level universe — Room's historical memory, plus the current
//             session's levels, plus the HTF horizontals — as index-aligned
//             [prices, baseCosts, tags]. The corridor scan (A2) and the two-class watchlist (A3)
//             need a wider set than Remaining Room does: Room is historical-only by contract,
//             while participation also has to see what price is trading against right now.
//
//             ⚠️ THE COPY IS LOAD-BEARING. The host shares `histPrice`/`histCost`/`histTag` with
//             Context Score's ScoreInput — one flatten now serves both engines — so appending in
//             place would push the HTF levels into Room and silently change the score. Room's
//             historical-only contract is preserved by copying, not by call ordering, because
//             ordering is the kind of invariant that survives exactly until someone moves a line.
//
//             THIS LIVES IN THE LIBRARY FOR THE MAIN-BODY BUDGET, and the reason generalises:
//             Pine instantiates a host function at EVERY call site, so a fat host body called ten
//             times is counted ten times against CE10295. Library code is exempt from that budget
//             entirely. Host-side this was ~1,550 tokens × 10 firing branches; here it is free, and
//             the host pays only the arguments — once, because the universe is identical for every
//             branch on a given bar.
//
//             Tags are the CHART'S OWN drawing names ("D-SwH", "wk-H", "C-POC"). Not cosmetic: the
//             client asked for this enumeration so he can tell whether an excursion figure came
//             from an OR level, a VAH, a composite or a weekly, so a tooltip must name a level the
//             way the chart labels it.
//
//             Weekly is deliberately absent from the HTF parameters — it arrives inside the hist
//             arrays, because weekly is the one HTF type Context Score already scores.
// @param histPrice  Room's flattened historical levels — price. COPIED, not mutated.
// @param histCost   …base cost, index-aligned.
// @param histTag    …type tag, index-aligned.
// @param bcWeek     The weekly base cost — the calibrated anchor every HTF weight is scaled from.
export buildUniverse(array<float> histPrice, array<float> histCost, array<string> histTag,
     float orh, float orl, float vah, float val, float poc, float cVah, float cVal, float cPoc,
     float bcOr, float bcVa, float bcPoc, float bcCVa, float bcCPoc, float bcWeek,
     array<float> dayHi, array<float> dayLo, array<float> h4Hi,   array<float> h4Lo,
     array<float> dSwHi, array<float> dSwLo, array<float> h4SwHi, array<float> h4SwLo,
     array<float> h1SwHi, array<float> h1SwLo) =>
    array<float>  _p  = array.copy(histPrice)
    array<float>  _bc = array.copy(histCost)
    array<string> _lb = array.copy(histTag)
    // HTF base-cost multipliers. Never free numbers: weekly H/L is the one HTF type Context Score
    // already scores, so it is the calibrated anchor and retuning it moves all five together. At
    // the shipped weekly cost of 20 this gives weekly 20 · D-H/L 15 · D-swing 12 · 4H-H/L 10 ·
    // 4H-swing 8 · 1H-swing 5, interleaving with the scored costs (C-POC 25, POC 20, P-POC 16,
    // C-VA 16, VA 12, P-VA 10, OR 8, P-OR 6). Two orderings are asserted: a longer timeframe
    // outranks a shorter one, and within a timeframe a period extreme outranks an interior 3-bar
    // swing pivot. Provisional defaults, to be validated by backtest — none can block a trade.
    float _bcDay  = 0.75 * bcWeek
    float _bcDsw  = 0.60 * bcWeek
    float _bc4h   = 0.50 * bcWeek
    float _bc4hSw = 0.40 * bcWeek
    float _bc1hSw = 0.25 * bcWeek
    // ── Current session ──
    pushLvl(_p, _bc, _lb, orh,  bcOr,   "ORH")
    pushLvl(_p, _bc, _lb, orl,  bcOr,   "ORL")
    pushLvl(_p, _bc, _lb, vah,  bcVa,   "VAH")
    pushLvl(_p, _bc, _lb, val,  bcVa,   "VAL")
    pushLvl(_p, _bc, _lb, poc,  bcPoc,  "POC")
    pushLvl(_p, _bc, _lb, cVah, bcCVa,  "C-VAH")
    pushLvl(_p, _bc, _lb, cVal, bcCVa,  "C-VAL")
    pushLvl(_p, _bc, _lb, cPoc, bcCPoc, "C-POC")
    // ── HTF horizontals, read from the host's DRAWN sets so watch depth is display depth ──
    pushLvlArr(_p, _bc, _lb, dayHi,  _bcDay,  "D-H")
    pushLvlArr(_p, _bc, _lb, dayLo,  _bcDay,  "D-L")
    pushLvlArr(_p, _bc, _lb, h4Hi,   _bc4h,   "4H-H")
    pushLvlArr(_p, _bc, _lb, h4Lo,   _bc4h,   "4H-L")
    pushLvlArr(_p, _bc, _lb, dSwHi,  _bcDsw,  "D-SwH")
    pushLvlArr(_p, _bc, _lb, dSwLo,  _bcDsw,  "D-SwL")
    pushLvlArr(_p, _bc, _lb, h4SwHi, _bc4hSw, "4H-SwH")
    pushLvlArr(_p, _bc, _lb, h4SwLo, _bc4hSw, "4H-SwL")
    pushLvlArr(_p, _bc, _lb, h1SwHi, _bc1hSw, "1H-SwH")
    pushLvlArr(_p, _bc, _lb, h1SwLo, _bc1hSw, "1H-SwL")
    [_p, _bc, _lb]
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Exported — at-signal seed (M11-2)
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// @function   Latch one signal's at-signal snapshot: A1 environment, A2 stop-side scan, A3
//             two-class watchlist, A4 birth rung. Pushes the new state into `states` and returns
//             nothing useful — the host pays one statement per firing branch.
//
//             CALLED UNCONDITIONALLY per branch, before the host's tradability gate, so a
//             Friday-blocked signal is measured in full. Not isconfirmed-gated either: `states` is
//             a var array host-side, so the push is reverted and re-applied on every realtime tick
//             and committed at close, exactly like the tradeStates push beside it. Gating would
//             hide the state from the label builder, which runs later on the same bar.
//
//             ORDER INSIDE THE BODY IS LOAD-BEARING: the co-occurrence bits are set on the states
//             that already exist BEFORE the new one is pushed. Reversed, a signal would record
//             itself as having co-occurred with itself. Doing both here rather than at the ten host
//             call sites is what makes that structural instead of a rule somebody has to obey.
//
// @param states     The host's var array of live states (mutated).
// @param p          Producer state — read for the A1 snapshot fields only.
// @param bull       Trade direction.
// @param sigType    Signal type string, carried for DISPLAY only.
// @param famIdx     Signal family, 0 = Continuation · 1 = Accepted Continuation · 2 = Inflection ·
//                   3 = Velocity. An int, not a parsed string: the type strings are host constants
//                   and a library that compared them to its own literals would mis-classify in
//                   silence the day one was renamed.
// @param entry      Execution-bar open.
// @param stop       Resolved stop; the whole call is skipped when it cannot be resolved.
// @param target     Verdict target — TP1 today; Phase 3's selectable target changes only the caller.
// @param origin     The level the setup is keyed to (S4 reads it; it joins the support class).
// @param originTag  Its type name, for display.
// @param originCost Its base cost, chosen by the caller because only the firing branch knows which
//                   level type the origin is.
// @param lvlPrice   Flattened level universe — price.
// @param lvlCost    …base cost, index-aligned.
// @param lvlTag     …type tag, index-aligned.
// @param bcRef      Base-cost normaliser for wBase.
// @param isRetest   Is this the RETEST variant within its family? Only Continuation and Accepted
//                   Continuation have one, and it adds the within-family patience step. A bool
//                   rather than a sixth famIdx value on purpose: famIdx is the CLIENT'S four-family
//                   hierarchy and is read by the display filter, so widening it would change what
//                   that filter means. And a bool keeps the type STRINGS out of this library —
//                   comparing them here would mis-classify in silence the day one was renamed.
export seed(array<ParticipationState> states, ParState p, bool bull, string sigType, int famIdx,
     float entry, float stop, float target, float origin, string originTag, float originCost,
     array<float> lvlPrice, array<float> lvlCost, array<string> lvlTag, float bcRef,
     bool isRetest) =>
    float _r = math.abs(entry - stop)
    if not na(entry) and not na(stop) and _r > 0
        // ── 1. [→P3] Co-occurrence — mark what already exists, then push ────
        // Written here and read only in Phase 3's tooltip. It lives in seed because the firing
        // branches are the only place the bits can be set correctly, NOT because it belongs to the
        // at-signal snapshot — do not remove it as dead code.
        int _bit = int(math.pow(2, famIdx * 2 + (bull ? 0 : 1)))
        int _n0  = array.size(states)
        if _n0 > 0
            for _i = 0 to _n0 - 1
                ParticipationState _o = array.get(states, _i)
                _o.famMask := bitSet(_o.famMask, _bit)
 
        // ── 2. A3 watchlist + A2 SL-adjacency, in ONE pass ──────────────────
        // The corridor is [SL, entry] in both directions once min/max are taken. The obstacle range
        // is (entry, target] for a long and [target, entry) for a short — disjoint from the support
        // range at `entry`, which is why a merged pair can never straddle the two classes.
        //
        // The SL-adjacency scan deliberately runs over the WHOLE universe, not the retained
        // watchlist: its worst case — a level just BEYOND the stop, where a genuine retest has to
        // take the stop out first — lies outside the corridor and would be discarded by the class
        // filter. Easy to get wrong, which is why both jobs are done in this one loop.
        float _cLo = math.min(stop, entry)
        float _cHi = math.max(stop, entry)
        float _tol = MERGE_TICKS * syminfo.mintick
 
        array<WatchedLevel> _lv = array.new<WatchedLevel>()
        float  _slD    = na
        string _slTag  = na
        float  _slCost = na
        int    _slSide = 0
 
        int _nU = array.size(lvlPrice)
        if _nU > 0
            for _i = 0 to _nU - 1
                float _L = array.get(lvlPrice, _i)
                if not na(_L)
                    float  _c = array.get(lvlCost, _i)
                    string _t = array.get(lvlTag, _i)
                    // (a) SL adjacency — whole universe
                    float _dS = math.abs(_L - stop)
                    if _dS <= SL_ADJ_FRAC * _r and (na(_slD) or _dS < _slD)
                        _slD    := _dS
                        _slTag  := _t
                        _slCost := _c
                        // +1 = inside the corridor, so the stop sits BEYOND structure.
                        // −1 = beyond the stop, the configuration the client called worst.
                        // +2 = ON the stop — tested FIRST, because the corridor bounds are inclusive
                        //      and would otherwise call it "inside". See AT_STOP_FRAC: a level here
                        //      has no cover either way, and reporting it as +1 produced
                        //      "0.00R inside (protected)", a word contradicting its own number.
                        //      Symmetric by construction, since _dS is an absolute distance: the
                        //      tick-inside and tick-beyond cases were wrong in opposite directions
                        //      and one test absorbs both.
                        // A level ON the stop always wins this scan and that is not luck — _dS = 0
                        // is minimal, so the strict < tie-break can never displace it.
                        _slSide := _dS <= AT_STOP_FRAC * _r ? 2
                             : _L >= _cLo and _L <= _cHi ? 1 : -1
                    // (b) classify into the watchlist
                    bool _sup = _L >= _cLo and _L <= _cHi
                    bool _obs = not na(target) and (bull ? _L > entry and _L <= target
                         : _L < entry and _L >= target)
                    if _sup or _obs
                        // De-duplicate within one mintick, strongest cost winning outright — the
                        // same merge ContextScore's obstruction() performs.
                        int _k = -1
                        int _m = array.size(_lv)
                        if _m > 0
                            for _j = 0 to _m - 1
                                // Bound to a local rather than array.get(...).price inline: there is
                                // no local compiler, so an avoidable parser question costs a whole
                                // round trip to answer.
                                WatchedLevel _q = array.get(_lv, _j)
                                if math.abs(_L - _q.price) <= _tol and _q.bornSupport == _sup
                                    _k := _j
                                    break
                        if _k >= 0
                            WatchedLevel _e = array.get(_lv, _k)
                            if _c > _e.baseCost
                                _e.price    := _L
                                _e.baseCost := _c
                                _e.tag      := _t
                                _e.wBase    := bcRef > 0 ? math.min(1.0, _c / bcRef) : 1.0
                        else
                            array.push(_lv, WatchedLevel.new(
                                 price       = _L,
                                 baseCost    = _c,
                                 wBase       = bcRef > 0 ? math.min(1.0, _c / bcRef) : 1.0,
                                 tag         = _t,
                                 bornSupport = _sup))
 
        // ── 3. The origin joins the support class — WHEN IT IS IN THE CORRIDOR ──
        // Pushed only when it did not merge into a level already present; where it did, the merge
        // above kept the stronger cost, so the two can never disagree about the same price.
        //
        // ⚠️ THE CORRIDOR TEST IS A FIX (2026-09-03), and it is the SAME expression (b) applies to
        // every other level: up there `bornSupport` IS the corridor test, and the origin was the
        // sole exception — pushed with bornSupport = true and no test at all. A tight or fixed-
        // points stop puts the origin outside [SL, entry] (entry 2050, stop 2049, VAH origin 2048),
        // and it was then classified as a corridor level when it is not one. Both consequences are
        // client-facing: a2Corridor is presented to him as "the full [SL, entry] corridor grouped
        // by tag", so it was naming a level outside the corridor — the same class of defect as the
        // tag collision he reported; and the first magnet, displayed as `Min. expected AE`, is the
        // nearest support-class level to entry, so an origin beyond the stop could WIN that scan
        // when price would take the stop out before ever reaching it.
        //
        // Dropping an out-of-corridor origin from the watchlist costs nothing: a level beyond the
        // stop is unreachable, because the state resolves at SL first. S4 is unaffected — it reads
        // state.origin, a separate scalar, and never this list. a2SlAdjSide is unaffected because
        // (a) above deliberately scans the WHOLE universe, ahead of any classification.
        if not na(origin) and origin >= _cLo and origin <= _cHi
            bool _have = false
            int  _m    = array.size(_lv)
            if _m > 0
                for _j = 0 to _m - 1
                    WatchedLevel _q = array.get(_lv, _j)
                    if math.abs(origin - _q.price) <= _tol and _q.bornSupport
                        _have := true
                        break
            if not _have
                array.push(_lv, WatchedLevel.new(
                     price       = origin,
                     baseCost    = originCost,
                     wBase       = bcRef > 0 ? math.min(1.0, originCost / bcRef) : 1.0,
                     tag         = originTag,
                     bornSupport = true))
 
        // ── 4. A2 descriptors, over the MERGED support set ──────────────────
        // Computed after the merge so a duplicated price cannot win "strongest" twice or distort
        // the counts. Stored rather than recomputed at read time: a label's text is frozen at
        // label.new, so anything that has to appear on a historical label must exist before then.
        string _magT = na
        float  _magD = na
        string _strT = na
        float  _strD = na
        float  _strC = na
        int    _nL   = array.size(_lv)
        if _nL > 0
            for _i = 0 to _nL - 1
                WatchedLevel _w = array.get(_lv, _i)
                if _w.bornSupport
                    float _dE = math.abs(_w.price - entry)
                    if na(_magD) or _dE < _magD
                        _magD := _dE
                        _magT := _w.tag
                    if na(_strC) or _w.baseCost > _strC
                        _strC := _w.baseCost
                        _strD := _dE
                        _strT := _w.tag
 
        // The client's three configurations collapse to THREE geometries plus a strength test, so
        // the verdict is resolved here rather than left to the renderer. `beyond` is the case he
        // called worst — a genuine retest has to take the stop out first. A level INSIDE the
        // corridor means the stop sits past structure: real cover when the level is strong, thin
        // cover when it is not. Resolved at seed because bcRef is in scope here and nowhere
        // downstream.
        //
        // ⚠️ THE AT-STOP BRANCH USES A DIFFERENT VOCABULARY ON PURPOSE. "protected" and "thin cover"
        // describe how much cover the level gives the stop, and at zero distance it gives none — so
        // the same strength test is reported as a property of the LEVEL instead. It still matters:
        // a stop resting on a major level is far less likely to be swept than one resting on a
        // minor one, which is exactly the judgment the client's adverse-excursion audit is for.
        string _slWord = _slSide == 0 ? ""
             : _slSide == 2 ? (bcRef > 0 and _slCost >= PROTECTED_FRAC * bcRef ? "strong level"
                  : "weak level")
             : _slSide < 0 ? "exposed"
             : (bcRef > 0 and _slCost >= PROTECTED_FRAC * bcRef ? "protected" : "thin cover")
 
        // ── 5. A1 — the latched environment ─────────────────────────────────
        // Every value comes from the snapshot, never from the live field; see step().
        float _span = p.snapDayHi - p.snapDayLo
        float _loc  = _span > 0 ? (entry - p.snapDayLo) / _span : na
        // ── 6. A4 — the birth rung ──────────────────────────────────────────
        // Categorical, never a numeric score: "not another scoring component" is a standing client
        // constraint. A2 is absent from every clause on purpose — it predicts where fights will
        // occur, and predictions are not evidence.
        //
        // envKnown covers ALL THREE A1 readings the rung consumes, snapDayUsed included — it means
        // "the snapshot is complete", not "the volume readings arrived". Folded in here rather than
        // guarded at the CONFIRMED clause for two reasons. The tooltip's "no volume feed, or first
        // session of history" message stays literally true, because ADR is unavailable in exactly
        // that window and no longer: adrFrom takes math.min(n, size), so it returns after ONE
        // completed day, not after `lookback` of them. And envKnown already gates all three rungs,
        // so a future clause cannot forget the guard — structural rather than a rule to obey.
        //
        // a1EnvKnown is stored on the state and Phase 3 will bucket outcomes on it, so its meaning
        // is now ALL A1 readings present. Do not narrow it back to the two volume fields.
        bool _envKnown = not na(p.snapCumRvol) and not na(p.snapVwap) and not na(p.snapDayUsed)
        bool _adequate = not na(p.snapCumRvol) and p.snapCumRvol >= p.cfgRvolAdequate
        bool _strong   = not na(p.snapCumRvol) and p.snapCumRvol >= p.cfgRvolStrong
        // entry, not close: close on a forming execution bar is the same live/historical trap the
        // snapshot exists to close, while entry is that bar's open and is fixed from the first tick.
        // A na slope does NOT disqualify. It is structurally unavailable for a session's first K
        // bars — which is exactly when the OR completes and signals fire — so requiring it would
        // systematically deny promotion at the open. The side test still has to pass on its own.
        bool _aligned = not na(p.snapVwap) and (bull
             ? entry > p.snapVwap and (na(p.snapSlope) or p.snapSlope >= 0)
             : entry < p.snapVwap and (na(p.snapSlope) or p.snapSlope <= 0))
        float _chase    = bull ? _loc : 1.0 - _loc
        bool  _chasing  = not na(_chase) and _chase >= p.cfgChaseHigh
        // The na guard is redundant while envKnown requires snapDayUsed, and is kept anyway: it
        // costs nothing and keeps this line correct on its own terms rather than by depending on a
        // condition three lines above it.
        bool  _extended = not na(p.snapDayUsed) and p.snapDayUsed >= p.cfgDayExtended
        // THE TWO ARE READ TOGETHER, AND THE PARENTHESES ARE THE ENTIRE POINT.
        //
        // A high entry location is not adverse by itself. A breakout entry sits at the top of the
        // day's range BY CONSTRUCTION — the signal bar is the bar that made the day's high, and
        // entry is the next bar's open — so `chasing` alone is very nearly a tautology for the
        // continuation, accepted-continuation and velocity families and denied them CONFIRMED no
        // matter how good the environment was. `extended` was no better as an independent veto:
        // heavy participation produces wide-range days, so requiring it alongside `strong` demanded
        // two conditions that are anti-correlated by construction. Measured: across two symbols and
        // four months, on every signal type, not one signal was ever born CONFIRMED.
        //
        // What IS adverse is entering at the far end of a day that has already travelled its normal
        // range. Location says where in the day the entry is; dayUsed says how much of the day is
        // left; only the conjunction says "chasing". The class this opens up is a new high, on
        // heavy volume, early enough that the day still has runway — which is the client's
        // "immediate execution" case stated precisely.
        //
        // ⚠️ DO NOT "SIMPLIFY" THIS BACK TO `not _chasing and not _extended`. The two forms differ
        // by one paren and De Morgan does not bridge them: ¬A ∧ ¬B is ¬(A ∨ B), NOT ¬(A ∧ B). The
        // wrong form raises no compile error and no runtime error. It silently makes CONFIRMED
        // unreachable again — the exact state this replaced, which took four months of observation
        // to notice.
        bool _exhausted = _chasing and _extended
        // Born CONFIRMED is the client's "immediate execution" case and is deliberately hard to
        // reach: heavy participation, price already on the right side of the average transaction
        // price with it moving the right way, and the day not spent.
        // Never born STALLED — that is a decay state, and at birth nothing has had time to decay.
        // An unknown environment lands on AUCTIONING and says so, rather than reading a na cumRVOL
        // as "not participating", which would be a wrong answer dressed as a real one.
        //
        // AUCTIONING STILL DEPENDS ON EXACTLY THREE FLAGS — envKnown, aligned, adequate. That
        // survives because `strong` implies `adequate`, which keeps CONFIRMED a strict subset of
        // DEVELOPING's condition and makes this three-way ternary safe. It is now a HOST-SIDE
        // CONTRACT rather than a property of two literals in this file: cfgRvolStrong must be >=
        // cfgRvolAdequate. Inverted, a signal too thin for DEVELOPING is promoted straight past it,
        // silently, because CONFIRMED is tested first.
        //
        // What DID change: DEVELOPING now covers TWO situations, not the four the plan's §6.4.5
        // enumerates — merely-adequate participation, or a chasing entry on an extended day.
        // Chasing alone and extended alone no longer demote.
        string _rung = _envKnown and _aligned and _strong and not _exhausted
             ? RUNG_CONFIRMED
             : _envKnown and _aligned and _adequate ? RUNG_DEVELOPING : RUNG_AUCTIONING
 
        // ── 7. Push, then cap ───────────────────────────────────────────────
        // [→P3] runLow / runHigh are seeded to ENTRY here, not left at their declared na:
        // math.min(na, x) is na, so an na seed would make MAE/MFE absent for the signal's whole
        // life, with no error and no tell. entry rather than this bar's low/high also keeps live
        // and historical identical — seed() runs on the execution bar's FIRST tick, where low and
        // high are still partial, while entry is fixed from that tick onward.
        //
        // [→P3] The four component statuses are set here for a DIFFERENT reason: Pine rejects a
        // const as a field default (CE10132), so the type declares them `na` and this is the site
        // where they become real. ⚠️ THEY ARE MANDATORY HERE, NOT OPTIONAL — `na` is not a status
        // word, and a second ParticipationState.new() that omitted them would fail SILENTLY, with
        // reason() concatenating na into its sentence. This is the only such site in the library
        // and the host cannot build a state, so today the guarantee holds by construction.
        array.push(states, ParticipationState.new(
             bull = bull, sigType = sigType, famIdx = famIdx,
             seedTime = time, seedBar = bar_index,
             entry = entry, stop = stop, target = target, r = _r,
             origin = origin, originTag = originTag,
             a1CumRvol = p.snapCumRvol, a1DayUsed = p.snapDayUsed, a1Adr = p.snapAdr,
             a1EntryLoc = _loc, a1Vwap = p.snapVwap, a1VwapSlope = p.snapSlope,
             a1EnvKnown = _envKnown,
             a2MagnetTag = _magT, a2MagnetR = na(_magD) ? na : _magD / _r,
             a2StrongTag = _strT, a2StrongR = na(_strD) ? na : _strD / _r, a2StrongCost = _strC,
             a2SlAdjTag  = _slTag, a2SlAdjR = na(_slD) ? na : _slD / _r, a2SlAdjCost = _slCost,
             a2SlAdjSide = _slSide, a2SlAdjWord = _slWord,
             a2Corridor  = aggTags(_lv, true), a2Obstacles = aggTags(_lv, false),
             levels = _lv,
             rung = _rung, birthRung = _rung,
             s1Stat = ST_UNKNOWN, s2Stat = ST_UNKNOWN,
             s3Stat = S3_NONE, s4Stat = ST_UNKNOWN,
             patMult = (famIdx == 3 ? PAT_VEL : famIdx == 2 ? PAT_INFL
                  : famIdx == 1 ? PAT_AC : PAT_CONT)
                  + (isRetest and famIdx <= 1 ? PAT_RETEST : 0.0),
             runLow = entry, runHigh = entry))
        // ⚠️ THE MAX_STATES CAP USED TO BE ENFORCED HERE, WITH A BARE array.shift — REMOVED
        // 2026-09-05. Deleting the oldest state in place dropped it with no resolution, no outcome
        // and no final label write; and if it happened to be a merged label's LEADER, its follower
        // stayed flagged `isFollower` for ever, which render's write gate skips — so that label was
        // never written again at all. Enforcement now lives at the top of render(), where an evicted
        // state resolves as OUTCOME_CAP and takes the same path as any other resolution. It could
        // not be done here: the display builders are all defined below this function.
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Internal — S3, the episode engine (M11-3)
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// Close one episode: derive its three measurements, cast the vote, fold the contribution into the
// signal's tally, and update the level's pairwise baseline and the signal's retained records.
//
// A FUNCTION rather than inline code because there are TWO close paths — the ordinary first
// non-touch bar, and the SL force-close — and they must not drift. The only thing that differs
// between them is `_fav`, which is why it is the parameter.
//
// ⚠️ THE TERMINATING BAR IS NOT PART OF THE EPISODE. It supplies the side and nothing else: no
// volume, no delta, no depth. It is the verdict, not evidence. The accumulators are already final
// when this runs, which is what makes that true by construction rather than by discipline.
//
// ⚠️ OI IS ACCUMULATED AS A MAGNITUDE, AND THAT IS A CORRECTION, NOT A SIMPLIFICATION. SCOPE
// defines opposing intensity signed by thesis — "for a long, each bar contributes min(delta, 0)" —
// so a long's raw OI is negative. But every consumer asks about SIZE: `|OI| >= OI_FLOOR`, and the
// pairwise rule's "OI growing". Stored signed, `_OI > lastOI` on a long would mean *less negative*,
// i.e. pressure SHRINKING — the exact opposite of the condition the rule names, muting the vote
// precisely when the level is holding better. Silent, and only on longs. Storing the magnitude
// makes the comparison mean what it reads as, in both directions.
//
// @param _s        The signal state — its tally and retained records are written.
// @param _w        The level whose episode is closing. Mutated: baseline, tests, testing.
// @param _oiFloor  ParState.cfgOiFloor.
// @param _fav      Did the episode end on the thesis's side? The SL force-close passes false.
closeEpisode(ParticipationState _s, WatchedLevel _w, float _oiFloor, bool _fav) =>
    _w.testing := false
    // E is na when NO bar was admitted — the episode was never measurable. That is a full no-op:
    // no vote, no tally movement, no test counted, no baseline written. Distinct from a measured
    // episode that happens to vote 0, which counts and does update the baseline.
    float _E = _w.expVolAcc > 0 ? _w.volAcc / _w.expVolAcc : na
    if not na(_E)
        float _OI = _w.volAcc > 0 ? _w.oppDelta / _w.volAcc : na
        // w(E) — the size weight, and the ONLY place the dead-volume threshold appears. SCOPE
        // states 0.5 twice, as vote-function step 1 and as this function's zero region, but they
        // are one rule; writing it twice puts the constant in two places that can drift. Every
        // other "is this episode measured?" test below reads `_wE > 0` for the same reason.
        // Library-hardcoded on purpose (unlike _oiFloor): pure RVOL ratios, the shape of a weight
        // function, and SCOPE committed them.
        float _wE = _E < 0.5 ? 0.0
             : _E <= 1.0 ? (_E - 0.5) / 0.5
             : math.min(_E, 1.5)
        int _vote = 0
        if not _fav
            // A break or rejection is negative regardless of trends. No double-punishing runs the
            // other way: a deteriorating-but-HOLDING test is muted to 0 below, never −1, because if
            // the level does break, that break is its own terminating episode and casts its own −1.
            _vote := -1
        else if na(_w.lastOI)
            // First measured episode at this level: absolutes decide. ⚠️ THE FLOOR IS A FLOOR — the
            // natural reading is backwards. +1 requires that real pressure ARRIVED and the level
            // held anyway; thin evidence is the low-pressure case and is already the 0. ⚠️ This
            // reads as inverted against the pairwise rule below and is not: within one episode,
            // heavy pressure absorbed means the defenders are strong, while across episodes
            // declining pressure means the attackers are giving up. Both are supply exhausting.
            // Adjacent in code, opposite in direction — someone will eventually "fix" one of them.
            //
            // ⚠️ The routing test is na(lastOI), NOT `tests == 0`, and the two now mean different
            // things cleanly: a dead-volume episode counts as a test but writes no baseline, so it
            // can never become the yardstick that mutes a later episode which proved something.
            // This is the one place the na-sentinel rule does not apply — it forbids `x != na`,
            // not `na(x)`.
            _vote := _OI >= _oiFloor ? 1 : 0
        else if not na(_OI)
            // Pairwise against the immediately previous episode AT THIS LEVEL — lastOI/lastDepth
            // are single floats, so nothing else is possible. ⚠️ Muted to 0 IFF BOTH deteriorated;
            // the residual is +1. SCOPE's original form left "OI unchanged and D unchanged"
            // undefined, and an undefined branch in a vote function is not a thing to leave to
            // float equality.
            //
            // ⚠️ The guard is on the BRANCH, not inside the comparison, and that is the fail-closed
            // half of it: with no current reading there is nothing to compare, no branch fires, and
            // the vote keeps the 0 it was declared with. Inside the comparison, `na > x` would be
            // na — falsy — collapsing the `and` and handing back the residual +1, i.e. reading
            // "cannot compare" as "improving".
            _vote := _OI > _w.lastOI and _w.depthMax > _w.lastDepth ? 0 : 1
        _w.tests += 1
        // ⚠️ Votes are NEVER summed per level. Each episode casts its own; the pairwise rule
        // compares MEASUREMENTS to decide the current one. Accumulation happens here, once, at
        // signal scale. No decay — the ladder is already the temporal mechanism.
        _s.s3Tally += _vote * _w.wBase * _wE
        if _wE > 0
            _w.lastOI    := _OI
            _w.lastDepth := _w.depthMax
            // Record 1 — the most recent completed measured test at ANY level, with the same-bar
            // tie-break streamPart already uses: on a bar closing several episodes the HEAVIEST
            // level wins, instead of whichever came last in `levels`. Why it exists and why there
            // are two pairs: the recBar/recWBase field comments.
            // ⚠️ `>=`, NOT `>`. Every same-bar tie went to the last writer before this guard, so
            // `>=` leaves the equal-weight case exactly as it was and the ONLY behavior that changes
            // is a heavier level displacing a lighter one. Equal wBase is common — two levels of one
            // type share it — so this is not a corner.
            // ⚠️ wBase is NOT tested against zero, deliberately. A level whose base cost is 0 has
            // wBase 0, contributes nothing to the tally, and STILL writes a record — correct, the
            // test happened and is worth showing. The 0.0 seed with `>=` preserves that exactly;
            // `>` would silently stop such a level from ever claiming the row.
            if _s.recBar != bar_index or _w.wBase >= _s.recWBase
                _s.recBar   := bar_index
                _s.recWBase := _w.wBase
                _s.recTag   := _w.tag
                _s.recSide  := _w.apprSide
                _s.recOI    := _OI
                _s.recD     := _w.depthMax
                _s.recE     := _E
            // Record 2 — the dedicated stop-corridor slot, the auditability the client asked for.
            // ⚠️ The test is on PRICE, and the reason is drift-proofing rather than correctness:
            // after the origin fix in seed(), bornSupport is exactly equivalent for this filter. It
            // is written this way because it is one expression over fields already present, provable
            // at the point of use, and immune to a future change in how the seed classifies.
            // ⚠️ ITS OWN BAR/WEIGHT PAIR, not record 1's — see the field comments. Folded into this
            // condition rather than nested inside it: the corridor test and the tie-break are both
            // admission tests for this write, and one `if` keeps the assignments at one indent.
            if _w.price >= math.min(_s.stop, _s.entry) and _w.price <= math.max(_s.stop, _s.entry)
                 and (_s.corrBar != bar_index or _w.wBase >= _s.corrWBase)
                _s.corrBar   := bar_index
                _s.corrWBase := _w.wBase
                _s.corrTag   := _w.tag
                _s.corrSide  := _w.apprSide
                _s.corrOI    := _OI
                _s.corrD     := _w.depthMax
                _s.corrE     := _E
    true
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Internal — S5, component classification (M11-3)
// ═══════════════════════════════════════════════════════════════════════════════════════════
// FOUR FUNCTIONS, ONE CALL SITE EACH, all in advance(). The producers measure and the engine
// classifies — that separation is what keeps every threshold and every degenerate routing in one
// place instead of two.
//
// ⚠️ EVERY STATUS IS A POSITIVE ENUMERATION, never "not X". `unknown` must make its own clause
// false, and `status != FADING` would be TRUE for an unreadable component — the fail-open shape.
// The consumers below therefore ask "is it building or steady?", not "is it not fading?".
 
// S1 — commitment. The delta ratio ALONE; ⚠️ VWAP does NOT vote here, and its removal is what
// resolves the session-re-anchor discontinuity SCOPE had accepted. Direction-aware: `aligned` means
// the imbalance runs WITH the thesis, so the test flips on shorts.
//
// `unknown` ⟺ cumVol == 0, one test covering two honest situations — nothing folded yet, and
// everything folded was zero-volume — and guarding the division. ⚠️ Ratio == 0 is MEASURED (real
// bars, no net commitment) and must never be confused with ratio == na, which is unmeasurable.
//
// ⚠️⚠️ THIS TEST IS SUFFICIENT ONLY BECAUSE THE HOST POPULATES barDelta ON EVERY CONFIRMED BAR.
// It is a CUMULATIVE test, so it says nothing about whether THIS bar was measurable — and that is
// safe only while the two coincide. They coincide because, after the delta window was deleted (dev
// plan §7.8), the sole remaining na-delta path is `volume` itself being na, which is a PERMANENT
// property of the instrument (index, forex spot) and therefore also holds cumVol at 0 for ever. So
// "cumVol == 0" and "this signal's commitment is unmeasurable" became exactly equivalent.
// ⚠️ RE-NARROW THE HOST'S DELTA WINDOW AND THAT EQUIVALENCE BREAKS SILENTLY: a signal that folded
// bars before the gap would carry a FROZEN status across it, satisfying the CONFIRMED conjunct,
// advancing decayRun and running the patience clock on a reading that could not change. That is
// exactly what §7.8 fixed, and it produced no error of any kind for three milestones.
// 📌 A per-bar `na(barDelta)` gate was considered as belt-and-braces and REJECTED — it is dead code
// while the window is whole, and it would punish a transient one-bar data gap as if the instrument
// had no volume. The window is the guarantee; this test relies on it.
s1Of(ParticipationState _s, float _band) =>
    string _r = ST_UNKNOWN
    if _s.cumVol > 0
        float _ratio = _s.cumDelta / _s.cumVol
        _r := (_s.bull ? _ratio >= _band : _ratio <= -_band) ? S1_ALIGNED
             : (_s.bull ? _ratio <= -_band : _ratio >= _band) ? S1_AGAINST
             : S1_NEUTRAL
    _r
 
// S2 — participation slope, as a RATIO not a difference: a difference treats 0.5→0.8 and 2.0→2.3 as
// the same event, and "building or fading" is proportional.
//
// 📌 THE THREE NAMES FOR THIS COMPONENT, AND THIS IS THE ONLY PLACE THEY ARE LINKED. SCOPE calls it
// the **participation slope**; it RENDERS as **`Pace:`** on the tooltip and the verbose label; and
// reason() speaks of it in prose as **"pace"**. The row read `Participation:` until C18
// (2026-09-07), where it collided with the block's own `── Participation:` header — which names the
// whole ENGINE and deliberately did not change, that separation being the entire point of renaming
// the component rather than the header. ⚠️ If the row is ever renamed again, update it HERE; nothing
// else in the file connects the concept to what a reader sees.
//
// ⚠️ NO DEAD FLOOR ON prior3 — designed and rejected, do not add one. Borrowing w(E)'s `E < 0.5 ⇒ 0`
// looks like consistency but would mute the strongest build the engine can see: prior3 → 0 with a
// normal recent3 is a genuine ramp out of a dead market. w(E) gates evidence WEIGHT, which is a
// different job from reading a slope. The unbounded ratio is harmless because S2's output is a
// CATEGORY: 20× and 2× land on the same side of the threshold.
//
// The only real hazard is the exact-zero denominator, which is reachable on three consecutive
// zero-volume bars, so it is routed structurally and the division never happens in that case.
s2Of(ParState _p, float _build, float _fade) =>
    string _r = ST_UNKNOWN
    if not na(_p.s2Recent) and not na(_p.s2Prior)
        if _p.s2Prior == 0
            // Unambiguous either way: something out of nothing is building, nothing out of nothing
            // is a dead market, which is not building.
            _r := _p.s2Recent > 0 ? S2_BUILDING : S2_STEADY
        else
            float _ratio = _p.s2Recent / _p.s2Prior
            _r := _ratio >= _build ? S2_BUILDING : _ratio <= _fade ? S2_FADING : S2_STEADY
    _r
 
// S3 — level tests. Reads the TALLY, never individual votes. ⚠️ Three statuses, no `unknown`: the
// tally is realized evidence, so "nothing banked" is genuinely `none`, and the constants block
// carries the proof that this cannot fail open.
s3Of(float _tally) =>
    _tally >= TALLY_POS ? S3_POSITIVE : _tally <= TALLY_NEG ? S3_NEGATIVE : S3_NONE
 
// S4 — acceptance of the origin. `rotating` is the RESIDUAL and is functionally complete: the ladder
// only ever acts on `holding` (promote) and `rejected` (decay), so the middle correctly means "no S4
// evidence either way". H and R are independent — there is no reason acceptance and rejection should
// need the same number of closes, and forcing symmetry would be a decision taken by accident.
s4Of(ParticipationState _s, int _h, int _rej) =>
    na(_s.origin) ? ST_UNKNOWN
     : _s.s4Run >= _h ? S4_HOLDING
     : _s.s4Run <= -_rej ? S4_REJECTED
     : S4_ROTATING
 
// @function  Advance every live participation state one CONFIRMED bar: resolve the ones that end on
//            this bar, writing each one's outcome and removing it in the same pass. Mutates `states`
//            and its members by reference; the return value carries nothing and exists only to give
//            the export a defined type — see the note at the bottom of the body.
//
//            ⚠️ NAMED advance, NOT step. `par.step` is already taken — it is the M11-1 PRODUCER step
//            and takes a `ParState`, while this takes the array of per-signal states. Whether Pine
//            v6 resolves user-defined library overloads by parameter type is not stated anywhere in
//            the v6 reference set, and there is no local compiler to settle it cheaply, so the two
//            deliberately never share a name.
//
//            THE HOST GATE IS `array.size(parStates) > 0 and barstate.isconfirmed`, and BOTH terms
//            diverge from par.step's own gate on purpose. ⚠️ Do not harmonise them:
//
//              • tfValid — which par.step explicitly REJECTS (see its own doc comment) — does bind
//                here. Post-signal state is array<ParticipationState>, each holding its own
//                array<WatchedLevel>, so it scales with signal count × level count: exactly the
//                bar-range-proportional shape the host's "tfValid gates producers" rule was written
//                for, and not the fixed-size producer state that rule does not reach.
//                It is delivered by the EMPTINESS TEST rather than spelled out, because the explicit
//                term is provably dead: par.seed is reachable only from inside the host's
//                `if i_tmEnabled and orComplete and tfValid` block, so `states` cannot gain a member
//                while tfValid is false, and changing the chart timeframe recalculates the script
//                from bar 1, so no populated array can survive into a timeframe above the ceiling.
//                ⚠️ THAT REASONING DIES IF A SEED PATH IS EVER ADDED OUTSIDE THAT BLOCK — the term
//                would then have to be written out. This note is why the missing test is not read
//                as an oversight and "fixed" with main-body tokens that can never do anything.
//
//              • barstate.isconfirmed binds here and does NOT gate par.step's state writes. Two
//                independent reasons, either sufficient: S3's vote sign rests on a non-touch bar's
//                range being STRICTLY one side of the level, which is not true of a forming bar (a
//                bar that is non-touch at tick 3 can be a touch bar at tick 40, so episodes would
//                open and un-open through the bar and correctness would rest on rollback rather
//                than on the stated invariant); and barDelta is na on every non-confirmed tick, so
//                an ungated engine would accumulate na into cumDelta, which is permanently
//                absorbing.
//
//            ⚠️ THE DISPLAY WRITES ARE NOT ON THIS GATE. Resolution writes fire from inside here,
//            but the live refresh is `barstate.islast` and must never gain isconfirmed.
//
//            ⚠️ CALL-SITE RULE, AND IT IS A RULE RATHER THAN A LINE NUMBER: **below every signal
//            `label.new`, above every display read.** Three independent things pin it there.
//
//              1. INVARIANT — THE ENGINE ADVANCES A STATE ON THE SAME BAR THAT SEEDED IT, AND NEVER
//                 BEFORE. Being below all ten seed sites and below the footprint block means a state
//                 seeded this bar is advanced on its own entry bar with that bar's true delta,
//                 identically live and on reload. Move the call above the firing block and cumDelta
//                 starts a bar late, and a signal stopped out on its own entry bar is first tested
//                 on bar N+1 against N+1's low — bar N's stop-out is never seen at all, which is
//                 invisible rather than merely late.
//              2. ⚠️ THE RESOLUTION WRITE NEEDS A LABEL THAT EXISTS. The host's pending-signal
//                 renderers create the handles far below the trade-opening block — and VELOCITY's
//                 renderer is ~1,100 lines below the others, so "under the main label block" is not
//                 far enough and would leave one family broken while looking fixed. Called any
//                 earlier, a signal resolving on its own entry bar hits its only history-surviving
//                 write with a na handle and keeps its birth text, with no outcome suffix, for ever.
//              3. ⚠️ THE PRUNE WOULD OUTRUN THE AT-SIGNAL RENDERERS. atSignalText/atSignalTip find
//                 their states by `seedBar == bar_index` (renders()), so removing a state on the bar
//                 it resolved — above those renderers — would strip the participation block off that
//                 signal's label entirely. Below them, the removal is free and immediate.
//
//            Everything between the trade-opening block and here is safe to skip past: nothing else
//            reads this array, barDelta is a host global fixed for the bar, and the trailing engine
//            touches only tradeStates and drawings, while a participation stop is latched at seed
//            and never trailed.
//            ⚠️ THE BAR'S OHLCV IS READ FROM THE BUILT-INS, NOT PASSED — and that reverses the
//            plan's §7.2.2 signature on evidence it did not have. Two reasons, the first decisive:
//
//              • **Pine rejects an unused argument outright (CE10237)**, so a signature CANNOT be
//                declared ahead of its consumers. §7.2.2's `(states, p, high, low, close, volume,
//                barDelta)` was written to be declared once and never touched again; that is not a
//                thing Pine allows, and the choice became "grow it in three steps" versus "don't
//                need it". Cost of being wrong here is one host line plus a republish, which is
//                free during development.
//              • It is this file's own idiom. `stepLedger` reads open/high/low/close/time directly
//                and the exported `step` reads `volume` directly — a library function evaluates in
//                the caller's bar context, so these are the host chart's values. Passing them also
//                meant FIVE same-typed float parameters at one call site, where a transposition
//                compiles clean and is invisible on the chart — the hazard the A4 thresholds carry
//                a standing warning about.
//
//            `barDelta` IS the one bar input that is not a built-in — the host computes it from the
//            footprint or the CLV proxy — which is why it, alone, is a parameter. Producer readings
//            never join the signature at all: they ride `p`, which is what §7.2.2's surviving
//            argument was actually about.
// @param states    The host's `var` array of per-signal states. Mutated: resolved, then pruned.
// @param p         The producer state — read for its cfg* settings and its per-bar readings.
// @param barDelta  This confirmed bar's signed volume delta, or na where it could not be measured.
// @param deltaSrc  Which source produced it — 1 footprint, 2 CLV proxy. The second host-computed
//                  bar input, and the only reason it is passed: S1 records, per signal, whether any
//                  folded bar used the proxy.
export advance(array<ParticipationState> states, ParState p, float barDelta, float deltaSrc) =>
    int _i = 0
    while _i < array.size(states)
        ParticipationState _s = array.get(states, _i)
        // ── Running excursion — PER SIGNAL, from entry, and NOT part of S3 ───────────────
        // ⚠️ Two quantities that are easy to conflate: this measures how far price moved FROM
        // ENTRY since entry, while an episode's depth measures how far the opposing side pushed
        // price FROM THE LEVEL. Different scopes, different anchors. Both seeded safely — these
        // two hold `entry`, not na, or math.min/max would return na for the signal's whole life.
        _s.runLow  := math.min(_s.runLow,  low)
        _s.runHigh := math.max(_s.runHigh, high)
 
        // ── S1 — commitment. The two halves advance PAIRWISE, only on bars the numerator can
        //    see. Advancing the denominator alone on a blank-delta bar would dilute the ratio
        //    toward zero and read as a signal getting LESS committed the longer it is held; and
        //    `+= na` is permanently absorbing and silent, so one such bar would poison the pair for
        //    the rest of the signal's life. What that really guards is index and forex-spot
        //    symbols, where `volume` is na and therefore `barDelta` is too: unusable must look like
        //    `unknown`, not like a number that never comes back.
        //
        // ⚠️ A zero-VOLUME bar is a different case and IS folded — the proxy branch yields a
        //    non-na 0.0 delta for it, so it contributes 0 to both sides. That is why S1's
        //    `unknown` test is `cumVol == 0` rather than a bar count: it covers "nothing folded
        //    yet" and "everything folded was empty" with one expression, and guards the division.
        if not na(barDelta)
            _s.cumDelta += barDelta
            _s.cumVol   += nz(volume)
            // Sticky, and set from a FOLDED bar rather than latched at seed: a signal can begin on
            // footprint delta and meet later bars where the request returns na, and latching the
            // entry bar's source would misreport every mixed signal. CLV×volume is a DIFFERENT
            // quantity, not a noisier one — it infers side from where the close sits in the range —
            // so a cohort that mixes sources silently is the same incomparability that keeps
            // thresholds out of the input list. The equality is exact: deltaSrc is assigned the
            // literal 2 at its one write site, never computed.
            // 📌 RENDERED AS "(mixed)", not "(proxy)" — the field name and the display word differ
            // on purpose; the reasoning is at the liveTip site. ⚠️ This write's position INSIDE the
            // fold guard is what keeps the flag describing the same bar set as the ratio it
            // annotates. Do not lift it out.
            if deltaSrc == 2
                _s.proxyDelta := true
 
        // ── S4 — acceptance of the origin. One SIGNED run of consecutive confirmed closes,
        //    starting with the entry bar, which this call folds.
        //
        // ⚠️ BOTH TESTS ARE STRICT AND A CLOSE EXACTLY AT THE ORIGIN HOLDS THE RUN, unchanged.
        //    That is a deliberate no-op, not an oversight, and the case is NOT rare: origins are
        //    real levels sitting on the mintick grid (VAH is literally down_price() + mintick), so
        //    a "not beyond ⇒ through" reading would let one tick-exact close reset an acceptance
        //    run. The codebase already leaves an exactly-at case in neither bucket on purpose —
        //    the Path/Room seam, where a level exactly at entry is scored by neither engine.
        //
        // ⚠️ The origin NEVER MOVES. It is latched at seed, so a continuation running into the
        //    next session keeps the VAH it was keyed to even after that session's VAH changes.
        //    Correct — the thesis was about THAT level. "Refreshing" it would look like a bug fix
        //    and would silently change what S4 measures.
        //
        // No separate time measure: `s4Run × timeframe.in_seconds()` IS the time held, so a bar-age
        // field beside it would be a second name for one quantity.
        if not na(_s.origin)
            bool _beyond  = _s.bull ? close > _s.origin : close < _s.origin
            bool _through = _s.bull ? close < _s.origin : close > _s.origin
            if _beyond
                _s.s4Run := _s.s4Run > 0 ? _s.s4Run + 1 : 1
            else if _through
                _s.s4Run := _s.s4Run < 0 ? _s.s4Run - 1 : -1
 
        // ── Terminal tests. Priority: SL · target · cutoff ──────────────────────────────
        // ⚠️ SL WINS A TIE, and the tie is real: a bar that touches both the stop and the target
        // traversed (1 + n)R and Pine cannot know the order within it. The optimistic reading
        // would post CONFIRMED(TP1) on ambiguous evidence and inflate the very cohort this
        // milestone exists to measure — the client buckets outcomes by birth rung, so a bias here
        // corrupts the headline comparison rather than one label. The pessimistic reading costs
        // at most a verdict that was never provable. It also matches the host's own SL monitor,
        // which latches on `low <= stop` with no target arbitration at all.
        bool _slHit  = _s.bull ? low  <= _s.stop   : high >= _s.stop
        bool _tgtHit = _s.bull ? high >= _s.target : low  <= _s.target
        // MARKET time, not wall-clock, and it needs no new field: bar_index does not advance
        // across weekends, holidays or overnight closures, so the gaps cost nothing and seedBar
        // already ships. Wall-clock would gut exactly the signals the client asked to have
        // measured — a Friday 15:00 signal would expire on a Saturday where no bar exists, having
        // tracked one extra hour, and would never see Monday. All-integer, so there is no
        // int-division question here.
        //
        // ⚠️ THE `+ 1` IS NOT AN OFF-BY-ONE GUESS — IT IS THE FIX FOR ONE. Entry is the entry
        // bar's OPEN and this test runs at the entry bar's CLOSE, so one bar of market time has
        // already elapsed at the first evaluation. Without the term the count is the number of
        // bars STARTED since entry rather than elapsed, and expiry fires exactly one bar late at
        // every setting — not merely at a boundary. Read it as "bars elapsed INCLUSIVE of the
        // entry bar". ⚠️ Deliberately the OPPOSITE convention to the retained ladder history's
        // "+N", where the entry bar is +0: that one is a navigation offset you count off on the
        // chart, this one is a duration. Do not harmonise them.
        bool _expired = (bar_index - _s.seedBar + 1) * timeframe.in_seconds()
             >= p.cfgCutoffHours * 3600
        bool _term = _slHit or _tgtHit or _expired
 
        // ── S3 — N independent episode state machines, one per watched level ────────────
        // The watchlist is fixed at seed and never grows, shrinks or re-prices. `testing`, the
        // accumulators and the pairwise baseline all live on WatchedLevel, so a wide bar can open
        // several episodes at once and the open set can mix support and obstacle classes with no
        // shared state to collide.
        //
        // ⚠️ ADMISSION GOVERNS MEASUREMENT, NEVER BOUNDARIES. A bar is admitted only if barDelta
        // and expVol are both non-na; admitted bars advance every accumulator together, so each
        // derived ratio is over the same bar set by construction and nothing can absorb an na. But
        // the touch test and the terminating side test are PRICE-ONLY, so a non-admitted bar opens,
        // extends and terminates episodes exactly as normal. Folding admission into the touch logic
        // instead would silently MERGE episodes across a warm-up gap.
        bool _adm = not na(barDelta) and not na(p.expVol)
        int  _nL  = array.size(_s.levels)
        if _nL > 0
            for _j = 0 to _nL - 1
                WatchedLevel _w = array.get(_s.levels, _j)
                // Strict touch, zero knobs. Crossing bars always register as touches.
                bool _touch = low <= _w.price and high >= _w.price
                if _touch
                    if not _w.testing
                        // ── OPEN. Reset here, not at close: this is where "a new episode begins"
                        // belongs, and between episodes the stale values are unread because
                        // `testing` is false. ⚠️ depthMax MUST be zeroed — math.max(na, x) is na,
                        // so a running max left at its declared na stays na for the level's whole
                        // life and depth vanishes from every vote with no error and no tell.
                        _w.testing   := true
                        _w.oppDelta  := 0.0
                        _w.volAcc    := 0.0
                        _w.expVolAcc := 0.0
                        _w.depthMax  := 0.0
                        // Approach class — DISPLAY VOCABULARY ONLY, and only knowable now. It is
                        // not redundant with bornSupport: that says where the level sits relative
                        // to entry and is fixed for the signal's life, this says how price met the
                        // level in THIS test. A level born an obstacle, cleared, and now held from
                        // above is being tested AS SUPPORT. ⚠️ The vote never reads it.
                        //
                        // ⚠️ BOTH SIDES ARE TESTED EXPLICITLY; the residual 0 means UNKNOWN and is
                        // reachable. The two conditions are complementary only for a NON-TOUCH bar,
                        // which t−1 is for every episode after a level's first — but an episode
                        // opening on the ENTRY BAR has the signal bar behind it, pre-signal and
                        // never processed here, and a breakout bar straddles every watched level in
                        // its range. Writing this as one test and its negation would print
                        // "obstacle test" for those, silently and most often on the origin.
                        _w.apprSide := low[1] > _w.price ? 1 : high[1] < _w.price ? -1 : 0
                    if _adm
                        // OI's numerator, as a MAGNITUDE — see the note on closeEpisode for why
                        // signed storage would invert the pairwise test on longs.
                        _w.oppDelta  += math.abs(_s.bull ? math.min(barDelta, 0.0)
                             : math.max(barDelta, 0.0))
                        _w.volAcc    += nz(volume)
                        _w.expVolAcc += p.expVol
                        // Depth is THESIS-relative — how far the opposing side pushed price, from
                        // the level, in R. ⚠️ It must NOT be derived from the approach class: this
                        // one expression reads correctly for both classes (at a support, how far
                        // below the sellers drove it; at an obstacle, how far back down they pushed
                        // it), which is why the vote needs no class branch. Clamped at 0 because a
                        // touching bar that never traded through the level has no penetration.
                        _w.depthMax := math.max(_w.depthMax,
                             math.max((_s.bull ? _w.price - low : high - _w.price) / _s.r, 0.0))
                    if _term
                        // A terminal event caught this episode still open — `testing` is necessarily
                        // true here, since this branch either just opened it or found it open — so
                        // the touch rule will never get to end it. There is no bar after this one:
                        // the state resolves and is removed below.
                        // ⚠️ THE THREE TERMINALS ARE NOT SYMMETRIC, and that is deliberate: an SL
                        // hit is an EVENT that resolves the test — unfavorable by definition, so it
                        // force-closes and casts its −1, recorded for the dataset even though the
                        // ladder has stopped. A target hit or a cutoff is the TRADE ending on a
                        // test that never resolved itself, so it casts no vote.
                        //
                        // ⚠️ DISCARDING IS THE ABSENCE OF closeEpisode, NOT A FLAG — corrected
                        // 2026-09-05. This used to clear `testing` in an else branch, which was
                        // worse than redundant: NOTHING IN THE ENGINE EVER READS THAT FLAG AGAIN,
                        // because the state resolves on this bar and render() prunes it in the same
                        // pass. Its only remaining reader was streamPart, so its only effect was
                        // deleting the open test from the one write that survives on history — and
                        // the accumulators directly above have just been advanced on this very bar,
                        // so it measured the episode in full and then hid the measurement. No vote,
                        // no tally, no test count and no baseline all follow from not calling
                        // closeEpisode, which is where they belong.
                        if _slHit
                            closeEpisode(_s, _w, p.cfgOiFloor, false)
                else if _w.testing
                    // ── CLOSE on the first non-touch bar. A non-touch bar's whole range is
                    // strictly one side of the level, so this single comparison sets the vote sign
                    // and replaces a stored class flag — it handles all six support/obstacle ×
                    // held/broke configurations, break→retest→go included.
                    closeEpisode(_s, _w, p.cfgOiFloor,
                         _s.bull ? low > _w.price : high < _w.price)
 
        // ── S5 — classify, then walk the ladder ─────────────────────────────────────────
        // Classification is UNCONDITIONAL, even on a terminal bar: these four are display rows in
        // their own right, so a resolved signal must freeze holding its last real readings rather
        // than whatever it had a bar earlier.
        _s.s1Stat := s1Of(_s, p.cfgS1Band)
        _s.s2Stat := s2Of(p, p.cfgS2Building, p.cfgS2Fading)
        _s.s3Stat := s3Of(_s.s3Tally)
        _s.s4Stat := s4Of(_s, p.cfgS4Hold, p.cfgS4Reject)
        // ⚠️ "S2 ADEQUATE" IS A TWO-PART GATE AND THE LATCHED ENTRY cumRVOL IS A BRANCH SELECTOR,
        // NOT A CONJUNCT. As a conjunct the entry environment would permanently CAP a post-entry
        // verdict, contradicting the ladder's whole premise that it measures evolution. Enter into
        // decent participation and you only need it not to deteriorate; enter into thin
        // participation and you have to actively build. An unreadable a1CumRvol fails the `>=` and
        // routes to the strict branch, which is the right default: if we cannot tell what the entry
        // environment was, demand more.
        // ⚠️ COMPUTED HERE, WITH THE FOUR STATUSES, AND NOT INSIDE THE LADDER. It has to be fresh on
        // a terminal bar — where the ladder does not run — because the reason phrase reads it, and
        // it has to have exactly one site because both the ladder and that phrase depend on it.
        _s.s2Ok := _s.a1CumRvol >= p.cfgRvolAdequate
             ? (_s.s2Stat == S2_BUILDING or _s.s2Stat == S2_STEADY)
             : _s.s2Stat == S2_BUILDING
 
        // ⚠️ THE LADDER DOES NOT RUN ON A TERMINAL BAR, and that is SCOPE's rule rather than an
        // optimisation: an SL force-close records its −1 "for the dataset only, since the ladder
        // stops", so letting that vote drive a STALLED transition on the way out would manufacture
        // a verdict out of the exit itself.
        // ✅ AND SINCE 2026-09-05 THE RULE HAS NO EXCEPTION. All three terminals leave the rung
        // untouched — the resolution block below stopped writing CONFIRMED on a target hit, see the
        // note there. So the rung has exactly ONE writer, this ladder, which is what makes "the
        // rung is what the engine concluded" true without a carve-out.
        //
        // ⚠️ STALLED IS ABSORBING. Once stalled the ladder stops evaluating for good and the signal
        // runs to resolution carrying it. SCOPE supported both readings and settled neither; decided
        // absorbing on its own "off-ramp" wording plus a research argument — a recoverable STALLED
        // makes "did this signal stall?" unanswerable, and bucketing outcomes by state is the whole
        // point of the phase.
        if not _term and _s.rung != RUNG_STALLED
            // The one decay path with no existing state behind it, and the only one that fires with
            // NO level interaction at all: price drifting against the thesis on fading participation
            // pace — the phrase this writes says "as pace faded" — never touching a watched level
            // and never closing back through the origin. S3 and S4 are both blind to that.
            if _s.s1Stat == S1_AGAINST and _s.s2Stat == S2_FADING
                _s.decayRun += 1
            else
                _s.decayRun := 0
 
            // I2's guard, and it costs one condition on an increment that already existed:
            // ⚠️ THE CLOCK ONLY RUNS ON BARS WHERE THE NEXT PROMOTION IS NOT BLOCKED BY AN
            // UNREADABLE COMPONENT. Unguarded, a signal on a chart we cannot measure sits at its
            // birth rung, fails to promote for want of data, and then decays to STALLED — which the
            // client reads as "confirmation never arrived" when the truth is "confirmation was never
            // measurable". A false negative presented as a verdict, at instrument scale.
            // ⚠️ PAUSING, not suspending: a suspended clock would fire the instant measurability
            // returned, stalling a signal that never had a measurable chance. Paused, the counter
            // means "time spent waiting WITH THE ABILITY TO SEE".
            // ⚠️ This is warmup protection FIRST and no-volume protection second — the first ~N
            // sessions of any fresh chart have an unwarmed RVOL baseline, so S2 is unreadable there
            // on a perfectly ordinary instrument.
            bool _canSee = _s.s1Stat != ST_UNKNOWN and _s.s4Stat != ST_UNKNOWN
                 and (_s.rung != RUNG_DEVELOPING or _s.s2Stat != ST_UNKNOWN)
            if _canSee
                _s.barsAtRung += 1
 
            // ── Decay first. ⚠️ THIS ORDERING IS A BUILD-TIME DECISION THE PLAN DID NOT TAKE.
            // Two conflicts are reachable — S4 holding with a negative tally, and S3 positive with
            // the origin rejected — and STALLED being absorbing makes the order permanent. Decided
            // for decay-first: both decay conditions are REALIZED negative evidence about the
            // thesis's own structure, and suppressing one because a sibling still looks good would
            // make "did this signal stall?" depend on evaluation order and hide the negative half.
            // 📌 The third conflict is already impossible: the decay path needs S1 `against`, which
            // the promotion veto rejects anyway.
            bool _stall = false
            int  _why   = 0
            if _s.s3Stat == S3_NEGATIVE
                _stall := true
                _why   := STALL_TALLY
            else if _s.s4Stat == S4_REJECTED
                _stall := true
                _why   := STALL_REJECTED
            else if _s.decayRun >= p.cfgDecayN
                _stall := true
                _why   := STALL_DECAY
            else if _s.rung == _s.birthRung and _s.birthRung != RUNG_CONFIRMED
                 and _s.barsAtRung * timeframe.in_seconds() >= _s.patMult * p.cfgPatienceMins * 60
                // ⚠️ PATIENCE DOES NOT APPLY TO A SIGNAL BORN CONFIRMED — a gap in SCOPE's wording.
                // "Still on its birth rung" is the natural implementation and it is wrong: A4 can
                // birth CONFIRMED, so read literally a signal born CONFIRMED and still CONFIRMED
                // would decay to STALLED on the clock. Patience means "confirmation never arrived",
                // and it already has.
                // 📌 Promoting off the birth rung therefore DISABLES patience entirely, which is why
                // H is the highest-leverage constant in the block: set too low it does not merely
                // make DEVELOPING uninformative, it hands most signals a free pass out of the fourth
                // transition the client specifically asked for.
                _stall := true
                _why   := STALL_PATIENCE
 
            if _stall
                _s.rung     := RUNG_STALLED
                _s.stallWhy := _why
                _s.stallAt  := bar_index
            else if _s.rung == RUNG_DEVELOPING
                // CONFIRMED — a four-way conjunction, so any unreadable component blocks it.
                // The S2 conjunct is the stored `s2Ok`, classified above with the four statuses —
                // see its field comment for why it is a field and not an expression written here.
                // ⚠️ The S3 conjunct is unreachable-false here — a negative tally stalled above —
                // and is kept anyway so this line states the whole rule on its own terms.
                if _s.s4Stat == S4_HOLDING and _s.s1Stat == S1_ALIGNED and _s.s2Ok
                     and _s.s3Stat != S3_NEGATIVE
                    _s.rung       := RUNG_CONFIRMED
                    _s.confAt     := bar_index
                    _s.barsAtRung := 0
            else if _s.rung == RUNG_AUCTIONING
                // DEVELOPING — a DISJUNCTION of evidence under a VETO.
                // ⚠️ THE VETO IS STRICT: `S1 known AND not against`, never `S1 != against`. The
                // permissive form is the fail-open shape, and this project decided the identical
                // question once already, against it — A4's envKnown, where an unmeasurable day made
                // CONFIRMED easier. An unreadable commitment reading cannot be CLEARED, only left
                // unevaluated. ⚠️ Consequence, recorded so it is not a surprise: on a genuinely
                // volume-less instrument S1 is permanently unreadable, so every signal sits at
                // AUCTIONING for its whole life — and the clock above is paused, so patience never
                // fires either. That is the honest output of a participation engine with no
                // participation data, and the reason phrase is what makes it legible.
                if _s.s1Stat != ST_UNKNOWN and _s.s1Stat != S1_AGAINST
                     and (_s.s4Stat == S4_HOLDING or _s.s3Stat == S3_POSITIVE)
                    _s.rung       := RUNG_DEVELOPING
                    _s.devAt      := bar_index
                    _s.barsAtRung := 0
                    // ⚠️ LATCH WHICH DISJUNCT CARRIED IT. Both terms keep moving after the
                    // promotion, so the reason phrase cannot re-derive this — see the DEV_*
                    // constants. S4 first, the same declaration order the "but" clauses use, so
                    // that a promotion satisfying both is attributed consistently rather than by
                    // whichever test happens to be written first.
                    _s.devWhy     := _s.s4Stat == S4_HOLDING ? DEV_ORIGIN : DEV_TESTS
 
        if _term
            if _slHit
                _s.outcome := OUTCOME_SL
            else if _tgtHit
                // Named from the setting so the suffix says TP2 when the user tracks to TP2.
                //
                // ⚠️ THE RUNG IS NOT TOUCHED HERE, AND IT USED TO BE. `_s.rung := RUNG_CONFIRMED`
                // was removed 2026-09-05: it contradicted §7.6.7's own rule — "the rung VALUE is
                // never adjusted at resolution" — and it did three separate things wrong.
                //   • It made STALLED NON-ABSORBING in exactly the direction §7.5.5 exists to
                //     prevent, erasing the stall from the rung rather than merely allowing
                //     recovery from it.
                //   • It CONTAMINATED THE RESEARCH. With every target-hitting signal relabelled
                //     CONFIRMED, "does promotion to CONFIRMED predict reaching the target?" becomes
                //     circular — the predictor is overwritten by the outcome. (birthRung stayed
                //     clean, so the born-CONFIRMED question survived; the evolution question, which
                //     is what the ladder was built for, did not.)
                //   • It made reason() print a REACHABLE FALSEHOOD. That function branches on the
                //     rung alone, so an AUCTIONING signal reading commitment `against` that touched
                //     the target printed CONFIRMED's phrase — "on acceptance, commitment and pace"
                //     — a conjunction the ladder had explicitly refused. (It read "Confirmed on
                //     acceptance, commitment and participation together" when this was written:
                //     C17 made reason() a subjectless fragment, C18 renamed the component.)
                // The rung says what the LADDER concluded; `outcome` says what the TRADE did. All
                // twelve combinations are reachable and each means something: DEVELOPING(TP1) is a
                // trade that worked without participation ever confirming it.
                _s.outcome := p.cfgTgtName
            else
                _s.outcome := OUTCOME_EX
            _s.resolved := true
        // ⚠️ THE RESOLUTION DISPLAY WRITE AND THE PRUNE BOTH MOVED TO render() — compile 7,
        // 2026-09-05, and this is a DEVIATION from §7.6.6a, which put them here.
        //
        // The reason is Pine's, not a design preference: identifiers resolve TOP-DOWN, and the
        // final text a resolving signal must be left holding is built from reason() and the block
        // builders, every one of which is defined BELOW this function. The alternatives were to
        // hoist ~100 lines of shipped, densely commented display code above the engine purely to
        // satisfy the compiler, or to move the two lines that have to travel together. The pair
        // travels.
        //
        // ⚠️ WHAT §7.6.6a ACTUALLY REQUIRES IS PRESERVED: the write still happens in the same pass
        // as the removal, still before it, and still while the label handle is alive — render()
        // runs immediately after this function, on the same bar, from the same host block. What
        // changed is only WHICH function holds the pair.
        // ⚠️ CONSEQUENCE, and it is the thing to check if a state ever renders after resolving:
        // this function no longer prunes, so **`par.render` is not optional** — without it resolved
        // states accumulate to MAX_STATES and never write their final text.
        _i += 1
    // An explicit trailing value, so the export's return type is this and not the branch values of
    // the loop's trailing if/else — both arms are now `+=`, but an int-valued if/else in the value
    // position of an exported function is exactly what this guards against, and there is no local
    // compiler to find out cheaply. One token settles it. Same shape as the host's
    // renderStatusTable(), which ends in a bare `true` and is called as a statement.
    true
 
// @function  The one-sentence reason for a signal's current rung. Two halves: **why it is where it
//            is** ("because") and **what blocks the next rung** ("but").
//
//            TEMPLATES, NOT FIXED STRINGS, and that is not a style preference. A conjunct can be
//            unmet for meaningfully different reasons and whether that matters differs per
//            component: S1 can be `neutral` OR `against` at DEVELOPING — and `against` alone does
//            not decay, that needs the sustained conjunction — while S2 can be `steady` or `fading`.
//            Interpolating the component's own status word carries every distinction at one string
//            each, and the same templates absorb the unreadable cases for free, which is why the
//            word is "unreadable" rather than "unknown".
//
//            ⚠️ ONE BLOCKER IS NAMED, NOT ALL, and completeness is delivered elsewhere: the four
//            component statuses have their own display rows, always visible, so a reader already
//            sees that S4 is rotating AND S2 fading AND S1 against. This row's job is the headline;
//            naming four blockers in prose would duplicate those rows and re-inflate a tooltip that
//            was deliberately cut from 23 rows to 14.
//
//            ⚠️ DECLARATION ORDER IS USER-VISIBLE BEHAVIOUR. "First unmet conjunct in declaration
//            order" is deterministic and free; the alternative is a priority heuristic ranking four
//            blockers, a judgment with no evidence behind it and a second thing to maintain. But
//            whichever conjunct is written first gets named most often, so **S4 is declared first**
//            deliberately — acceptance of the origin is the most legible blocker to a trader — not
//            by falling out of typing order.
//
//            ⚠️ Why the DISJUNCTION needs only one phrase: for a conjunction, failure means CHOOSING
//            which conjunct to name, since several can be false at once. For a disjunction, failure
//            means EVERY branch is false, so there is nothing to choose. The veto is a separate
//            conjunct, hence its own phrase.
//            ⚠️ THE RULE THAT DECIDES WHETHER A CLAUSE MAY READ A LIVE FIELD, and both halves of
//            this function were wrong about it once:
//            ⚠️ AND IT SPEAKS ONLY ABOUT LADDER EVOLUTION — silent where none has happened.
//            AUCTIONING, DEVELOPING and CONFIRMED are ALL reachable at BIRTH, from A4's entry
//            environment, which the ladder never evaluated; a phrase describing a transition that
//            did not occur is simply false. The birth justification is not lost by the silence: the
//            at-signal block already carries `Birth:<rung>` and the whole `Env:` line, which IS
//            A4's rule in its own terms, so a birth phrase would restate a reading already on
//            screen — the duplication §7.5.7 rejects for the blocker list.
//            📌 AUCTIONING IS THE DELIBERATE EXCEPTION and must NOT be silenced by that rule.
//            Nothing ever transitions INTO it, so a strict reading would delete its phrase
//            entirely — but that phrase is a BLOCKER statement wearing "because" clothing, and at
//            the birth rung the blocker is the whole story.
//
//              • **A "because" clause about a TRANSITION is PAST tense and must be LATCHED.** The
//                statuses keep being re-classified after a transition (STALLED freezes the rung,
//                not the components), so re-deriving the cause at display time produces a sentence
//                about a different bar. `stallWhy` and `devWhy` exist for this, and where the cause
//                pins the status word the clause states the CONSTANT. ⚠️ The tense is load-bearing,
//                not cosmetic: present tense beside a live "but" clause about the same component
//                produces a sentence that contradicts itself in a reachable, ordinary state.
//                📌 AUCTIONING's "because" is the exception and is correctly PRESENT — it is the
//                birth rung, so it describes an ongoing absence rather than a transition.
//              • **"but" describes what blocks the NEXT rung — PRESENT tense, so it must be LIVE**,
//                and each clause must be the exact negation of its conjunct.
//            Both defects that came from getting this backwards were reachable and silent, and both
//            are described at the clauses below.
// @param s   The signal state, already classified by advance() this bar.
// @returns   A FRAGMENT, not a sentence — no subject, no leading capital, no trailing stop, and ""
//            where there is nothing to say. It names the rung's CAUSE and its blocker only, because
//            liveTip appends it directly after `State:<rung>,` which supplies the subject. That is
//            an amendment to §7.5.7, whose table is written in full sentences: the rung word and
//            "because" were pure duplication of an item two characters to the left, and this phrase
//            was ~30% of the whole per-signal block.
//            ⚠️ IT IS THEREFORE POSITION-DEPENDENT. Rendered anywhere but immediately after the
//            rung it loses its subject, and the born-DEVELOPING case — which returns a bare
//            "but …" — becomes ungrammatical rather than merely terse.
export reason(ParticipationState s) =>
    string _out = ""
    if s.rung == RUNG_STALLED
        // ⚠️ THE STALLED CLAUSES INTERPOLATE NOTHING LIVE, AND S4's ONE USED TO — fixed 2026-09-05.
        // It read `+ s.s4Stat`, but STALLED freezes the RUNG and not the statuses: classification
        // runs unconditionally above the ladder's guard, so a stalled signal whose origin is later
        // reclaimed printed "Stalled because the origin was holding beyond" — a sentence stating
        // its own contradiction. `S4_REJECTED` is the value the field HELD when it stalled, and the
        // branch condition is already the proof of that, since STALL_REJECTED is written only on
        // `s4Stat == S4_REJECTED`. The constant, not a literal, so the word stays single-sourced.
        // 📌 THIS IS NOT A RETREAT FROM §7.5.7's "templates, not fixed strings". That rule is about
        // the DEVELOPING "but" clauses, where the component is live and neutral-vs-against is a
        // real present-tense distinction. A STALLED "because" clause describes a LATCHED past
        // event, so interpolating a live field there is not a template — it is a stale read.
        _out := s.stallWhy == STALL_TALLY ? "level tests turned negative"
             : s.stallWhy == STALL_REJECTED ? "the origin was " + S4_REJECTED
             : s.stallWhy == STALL_DECAY
                  ? "commitment stayed against as pace faded"
             : "confirmation never arrived in time"
    else if s.rung == RUNG_CONFIRMED
        // ⚠️ GATED ON confAt, BECAUSE CONFIRMED IS ALSO A BIRTH RUNG. A4 can birth a signal
        // CONFIRMED from the entry environment — the client's "immediate execution" case — and that
        // has nothing to do with the ladder's four-way conjunction: at birth all four statuses are
        // still `unreadable`. Ungated, this phrase asserted acceptance, commitment and pace for a
        // signal where none of the three had ever been measured.
        // 📌 An earlier comment here claimed CONFIRMED was "reachable only through the ladder"
        // once the target override was removed. That was wrong — birth is the other route.
        // Silent when born: the at-signal block two items to the left already carries
        // `Birth:CONFIRMED` and the whole `Env:` line, which IS A4's rule in its own terms, so a
        // birth phrase would be prose restating a reading already on screen.
        _out := s.confAt >= 0 ? "on acceptance, commitment and pace" : ""
    else if s.rung == RUNG_DEVELOPING
        // because — the disjunct that actually carried it, read from the LATCH (`devWhy`, written
        // once at the transition) and stated with the constants. Two defects are fixed here, both
        // 2026-09-05 and both silent:
        //   • It used to test the live s4Stat and interpolate the live s3Stat, attributing the
        //     promotion to whichever disjunct happened to be true NOW — and in the ordinary state
        //     where S4 has loosened to `rotating` and the tally is `none`, neither is, so it read
        //     "Developing because level tests are none": developing because of an absence.
        //   • ⚠️ DEVELOPING IS ALSO A BIRTH RUNG, and the common one — A4's middle branch births it
        //     on adequate participation, or on a chasing entry into an extended day. Those carry
        //     devWhy == 0, and a two-way ternary falls through to the S3 arm, so EVERY born-
        //     DEVELOPING signal printed "…level tests turned positive" against a tally of zero.
        // ⚠️ PAST TENSE ON BOTH ARMS, AND NOT AS A STYLE CHOICE. Present tense put a flat
        // contradiction inside one sentence in the ordinary post-promotion state: with S4 loosened
        // to `rotating` it read "…because the origin IS holding beyond, but the origin IS rotating
        // around". The wording also mirrors the STALLED clauses, which are all past.
        string _bec = s.devWhy == DEV_ORIGIN ? "the origin was " + S4_HOLDING
             : s.devWhy == DEV_TESTS ? "level tests turned " + S3_POSITIVE
             : ""
        // but — the first unmet CONFIRMED conjunct, S4 first per the declaration-order note. This
        // half is PRESENT tense and survives regardless of how the rung was reached: "what blocks
        // CONFIRMED right now" is the most useful thing on the row for a born-DEVELOPING signal,
        // which is why the birth case suppresses the because and not the whole phrase.
        // ⚠️ THE S2 CLAUSE READS THE STORED `s2Ok`, NOT A STATUS COMPARISON. It used to test
        // `fading or unreadable`, which is not the conjunct: on a signal born into thin
        // participation the conjunct demands `building`, so `steady` blocks CONFIRMED while that
        // test passed it — and the whole "but" half then fell through to "", asserting that nothing
        // blocked promotion. Every clause here must be the negation of its conjunct exactly.
        string _but = s.s4Stat != S4_HOLDING ? "the origin is " + s.s4Stat
             : s.s1Stat != S1_ALIGNED ? "commitment is " + s.s1Stat
             : not s.s2Ok ? "pace is " + s.s2Stat
             : s.s3Stat == S3_NEGATIVE ? "level tests are " + s.s3Stat
             : ""
        _out := _bec
        if _but != ""
            // ⚠️ A BARE "but …" IS CORRECT HERE AND ONLY BECAUSE OF WHERE THIS LANDS. liveTip
            // appends the phrase immediately after `State:<rung>,` — so on a born-DEVELOPING signal
            // with no cause to state, `but` attaches to the rung itself and reads
            // "State:DEV, but pace is steady". Move this phrase away from the rung
            // and that sentence loses its subject.
            _out := (_out == "" ? "but " : _out + ", but ") + _but
    else
        // AUCTIONING. The veto is its own phrase because it is a separate conjunct from the
        // disjunction — and it is the one case where naming the blocker changes what the reader
        // should do, so it is tested first.
        // ⚠️ THIS BRANCH IS THE DELIBERATE EXCEPTION TO "SPEAK ONLY ABOUT EVOLUTION", AND MUST NOT
        // BE SILENCED THE WAY THE OTHER TWO BIRTH CASES WERE. Nothing ever transitions INTO
        // AUCTIONING — it is only ever a birth rung — so applying that rule literally would delete
        // the phrase outright. It survives because it is not a transition explanation: it is a
        // BLOCKER statement wearing "because" wording, present tense and true of the state now,
        // and at the birth rung the blocker is the whole story.
        // The two veto arms produced an identical string and are merged — the veto is still tested
        // first, which is the only thing the ordering was carrying.
        _out := s.s1Stat == ST_UNKNOWN or s.s1Stat == S1_AGAINST
             ? "commitment is " + s.s1Stat
             : "no confirming evidence yet"
    _out
 
// ══════════════════════════════════════════════════════════════════════════════════════════
// Exported — at-signal display (M11-2, step 2D)
// ══════════════════════════════════════════════════════════════════════════════════════════
//
// Both renderers walk the state array and emit the states seeded on `bar`, in direction `bull`,
// whose FAMILY the calling label actually carries — see renders().
//
// ⚠️ THIS USED TO MATCH ON BAR AND DIRECTION ALONE, on the reasoning that the inflection MERGE case
// would then fall out with no special-casing: two states share one bar and one direction, both
// render onto the single label, and the host never has to work out which state belongs to which
// label. The merge case did work. Everything else did not, and it shipped broken:
//
//   • Velocity NEVER merges — it has its own renderer and its own labels — so a velocity signal and
//     a continuation firing the same bar in the same direction produced TWO labels, each showing
//     BOTH signals' readings.
//   • An inflection whose merge target is hidden (its `i_show*` toggle off) takes its own label too,
//     which is the same shape.
//   • par.seed is gated on i_tmEnabled, NOT on the label toggles — correctly, because a hidden
//     signal must still be measured for Phase 3 — so a signal the user switched OFF still seeded a
//     state, and its readings still appeared on whatever label was visible.
//
// The fix is the family filter, and the merge case now says so explicitly rather than relying on an
// indiscriminate match: the six merge sites pass famAlso = 2 (Inflection). Note they pass a SECOND
// FAMILY and not "render everything" — velocity can be on that bar too, and "everything" would put
// it back on the merged label.
//
// Ordering is what makes the shared/per-signal split work: par.seed runs in the host's score/stop
// block, which precedes the label block, so every state for the bar exists before any label is
// built. It is also why the TOOLTIP needs help from the host that the TEXT does not — a merge
// rewrites the label's text at the merge site, where the second family is known, but the tooltip
// was frozen at label.new before the merge was decided, so the merge sites re-set it.
//
// Both return "" when nothing matches, so the host concatenates unconditionally.
//
// Nothing here is rewritten after the signal bar, and that is correct rather than lazy: a label's
// text and tooltip are frozen at label.new, and at-signal data never changes. The resolution and
// barstate.islast write triggers belong to Phase 3, when the readings start evolving.
 
fmtRmult(float _x) =>
    na(_x) ? "—" : str.tostring(_x, "0.00") + "R"
 
// One descriptor of the A2 line — ", label:TAG(inner)", empty when the descriptor does not exist.
//
// The caller assembles `_inner` rather than this function composing it from parts, because the three
// descriptors do not share a shape: first magnet and strongest are a bare R multiple, while
// SL-adjacent carries a geometry word and a strength word — and in the at-stop case DROPS the R
// entirely, since AT_STOP_FRAC is the display's rounding boundary so the value is provably "0.00R"
// and says nothing. Composing here would need a flag per combination.
//
// Existence is tested on the TAG, not on the R multiple, precisely so the at-stop case can omit R.
a2Item(string _label, string _tag, string _inner) =>
    na(_tag) ? "" : ", " + _label + ":" + _tag + "(" + _inner + ")"
 
// Display name for a signal family. Keyed on famIdx — an int this library owns the meaning of (see
// seed's @param) — and NEVER on sigType. Matching sigType against this library's own copies of the
// host's TM_SIG_* literals would mis-classify in silence the day one was renamed, which is the same
// reason famIdx exists at all. It also spares the tooltip the raw identifiers: "ac_retest" is an
// internal token, not something to put in front of the client.
//
// ⚠️ ABBREVIATED 2026-09-05, AND THE WORDS ARE THE CHART'S OWN. AC / INFL / VEL are literally what
// the signal labels print; CONT is the one that needed choosing, because continuation is unmarked
// on the label — the alerts call it CONTINUATION, so CONT is its established short form.
// 📌 The saving is not in the co-occurrence row, it is in the MERGE PREFIX. `[Accepted Cont.] ` is
// 17 characters and appears on all three of liveRows' lines for BOTH merged states, plus once per
// state in each tooltip builder — 60-100 characters on a merged verbose label, which is the single
// most cluttered surface in the product and the one the 2026-08-08 commitment exists to protect.
// ⚠️ This changes SHIPPED M11-2 text: atSignalText and atSignalTip print the same prefix. It is a
// compaction in the direction of the client's standing complaint rather than a reworded reading,
// but it is visible, so it carries a changelog line.
famName(int _f) =>
    _f == 0 ? "CONT" : _f == 1 ? "AC" : _f == 2 ? "INFL" : _f == 3 ? "VEL" : "?"
 
// Does this state belong on the label being rendered?
//
// `fam` is the family the label was created for; `famAlso` is a SECOND family the same label
// carries, which happens only on an inflection MERGE — the host folds an inflection into an
// existing Continuation / AC / AC-Retest label and leaves the inflection's own label na. Every
// other caller passes famAlso = -1.
//
// -1 rather than na as the "no second family" sentinel, for the reason this file has already paid
// for once: `x == na` evaluates to na, which is falsy, so an na sentinel would appear to work here
// and would break silently the moment the test were inverted. Same idiom as bkt and lastStepBar.
//
// THE BAR AND DIRECTION TESTS ARE NOT SUFFICIENT ON THEIR OWN, and that is what this function
// exists to make structural. Several signals can fire on one bar in one direction and land on
// SEPARATE labels — velocity never merges, and an inflection whose merge target is hidden takes its
// own label — so matching on bar+direction alone put every co-firing signal's readings on every one
// of their labels. Both renderers go through here so they cannot drift apart on that.
renders(ParticipationState _s, int _bar, bool _bull, int _fam, int _famAlso) =>
    _s.seedBar == _bar and _s.bull == _bull and (_s.famIdx == _fam or _s.famIdx == _famAlso)
 
// @function   The at-signal block for the VERBOSE label — two lines, and deliberately only two.
//             §537's verbose defaults are the state, the birth state (identical at birth) and the
//             first magnet flagged as the minimum expected adverse excursion; everything else is
//             tooltip-only by nature. THE COMPACT LABEL GETS NOTHING — that is the standing
//             commitment made to the client on 2026-08-08, and it is why this is a separate
//             function rather than a verbosity flag on atSignalTip.
//             The magnet names the level's TYPE, per his 2026-08-10 auditability request.
//
//             ON A MERGED LABEL THE RUNG IS EMITTED ONCE, and that is provable rather than merely
//             usual: every signal firing on one bar takes the SAME entry (the host resolves one
//             `_entry` local for the whole trade-opening block) and every A1 reading is bar-level,
//             so all five rung clauses evaluate identically for every state on the bar. ⚠️ If entry
//             ever becomes per-branch, this has to go back to one rung line per signal.
//             What is NOT shared is the min-AE row: it comes from the stop-side scan, and the stop
//             differs per signal type. So one rung, N magnets.
// @param bar  The bar whose signals to render — the host passes bar_index.
// @param bull Direction to render; a bull label must not pick up a bear state fired on the same bar.
// @param fam      Family this label was created for; see renders().
// @param famAlso  Second family the label carries (merge only). Defaults to -1 — "this label carries
//                 one family" is the overwhelmingly common case, so only the host's merge targets
//                 pass it. Verified on TradingView 2026-08-12 that an export takes a parameter
//                 default; it is not something to rediscover.
export atSignalText(array<ParticipationState> states, int bar, bool bull, int fam, int famAlso = -1) =>
    string _r    = ""
    bool   _rung = false
    int    _n    = array.size(states)
    if _n > 0
        for _i = 0 to _n - 1
            ParticipationState _s = array.get(states, _i)
            if renders(_s, bar, bull, fam, famAlso)
                if not _rung
                    _r    := _r + "\nParticipation: " + _s.rung
                    _rung := true
                if not na(_s.a2MagnetR)
                    // Attributed only on a merged label, where two magnets would otherwise be
                    // indistinguishable. A single-signal label already names its own signal in the
                    // base text above this block, so the tag would be noise on the surface whose
                    // clutter the client is complaining about.
                    string _tag = famAlso >= 0 ? "[" + famName(_s.famIdx) + "] " : ""
                    _r := _r + "\nMin. expected AE: " + _tag + _s.a2MagnetTag + " " +
                         fmtRmult(_s.a2MagnetR)
    _r
 
// @function   The at-signal block for the TOOLTIP — the full A1 / A2 / A3 readout.
//             Everything past the label's two lines lives here because the label is on-chart and
//             chart clutter is the client's open complaint, while a tooltip is invisible until
//             hovered. The corridor enumeration is his 2026-08-10 request and names level types
//             for the same auditability reason.
//
//             An unknown environment SAYS SO. Reading a na cumRVOL as "not participating" would be
//             a wrong answer dressed as a real one — it means a volume-less symbol or the first
//             session of loaded history, not a quiet market.
//
//             THE BODY IS SPLIT INTO SHARED AND PER-SIGNAL HALVES, because a merged label carries
//             more than one signal and most of this block is identical across them:
//               SHARED (emitted once)     — the rung, the whole A1 environment line, the sessions
//                                           line. All of it is bar-level or derives from the entry,
//                                           and every signal on one bar shares one entry (see
//                                           atSignalText for why that is structural, not incidental).
//               PER-SIGNAL (emitted N×)   — origin, the corridor enumeration and every A2 descriptor.
//                                           All of these hang off the STOP, which differs per signal
//                                           type, so they are the only things that can disagree.
//             ⚠️ `origin` belongs to the per-signal half and used to share the "Birth:" line with
//             the rung, which does not. Splitting that line is the whole point; do not rejoin them.
// @param fam      Family this label was created for; see renders().
// @param famAlso  Second family the label carries (merge only); defaults to -1. See atSignalText.
export atSignalTip(array<ParticipationState> states, int bar, bool bull, int fam, int famAlso = -1) =>
    string _r     = ""
    bool   _first = false
    int    _n     = array.size(states)
    if _n > 0
        for _i = 0 to _n - 1
            ParticipationState _s = array.get(states, _i)
            if renders(_s, bar, bull, fam, famAlso)
                // ── shared ──
                if not _first
                    _first := true
                    _r := _r + "\n── Participation: Birth:" + _s.rung
                    if not _s.a1EnvKnown
                        _r := _r + " · Env:unavailable (no volume feed, or first session of history)"
                    else
                        string _side = _s.entry > _s.a1Vwap ? "above" : _s.entry < _s.a1Vwap ? "below" : "at"
                        string _tr   = na(_s.a1VwapSlope) ? "—" :
                             _s.a1VwapSlope > 0 ? "rising" : _s.a1VwapSlope < 0 ? "falling" : "flat"
                        _r := _r + " · Env:cRVOL " + fmtRatio(_s.a1CumRvol) +
                             ", day " + fmtPct(_s.a1DayUsed) + " ADR" +
                             ", entry loc " + fmtPct(_s.a1EntryLoc) +
                             ", VWAP " + _side + "/" + _tr
                // ── per-signal ──
                // Prefixed only on a merged label; a single-signal tooltip hangs off a label that
                // already names its signal, so the tag would say nothing.
                string _pfx = famAlso >= 0 ? "[" + famName(_s.famIdx) + "] " : ""
                _r := _r + " · " + _pfx + "Origin:" + _s.originTag
                _r := _r + " · SL corridor:[" + _s.a2Corridor + "]"
                // ⚠️ C18: WHEN THE NEAREST CORRIDOR LEVEL IS ALSO THE HEAVIEST, THE TWO DESCRIPTORS
                // ARE ONE LEVEL NAMED TWICE — the ordinary case on a single-level corridor, and the
                // largest single saving in that pass (−18 characters).
                // 📌 COLLAPSED, NOT SUPPRESSED. Dropping `strongest` outright was rejected: its
                // absence would be ambiguous with "never computed", and "the nearest level in the
                // corridor is also the heaviest" is a real reading worth its six characters.
                // ⚠️ `=` was chosen over the natural "1st magnet(strongest)" — a2Item's shape is
                // `label:TAG(inner)`, so that spelling would put two parentheticals eight characters
                // apart carrying different meanings. `=` appears nowhere else on this surface.
                // ✅ THE FLOAT `==` IS EXACT HERE, AND THAT IS STRUCTURAL RATHER THAN LUCKY: seed()
                // picks both in ONE loop over the same array — magnet takes min |L−entry|, strongest
                // takes max baseCost — and BOTH store that same `_dE`, divided by the same `_r`. So
                // when one level wins both scans the two fields come from an identical float.
                // Rounding happens in fmtRmult at display and cannot merge two distinct levels: same
                // tag at a different price gives a different `_dE`, same price under different tags
                // gives different tags.
                // ⚠️ GUARDED ON THE TAG FIRST, and the failure direction is chosen to match
                // sameRec(): `na == na` is na, which is falsy, so an unwritten pair falls through to
                // rendering both. A false "different" costs one duplicate item; a false "same"
                // hides a level.
                bool _magIsStr = not na(_s.a2MagnetTag) and _s.a2MagnetTag == _s.a2StrongTag and
                     _s.a2MagnetR == _s.a2StrongR
                _r := _r + a2Item(_magIsStr ? "1st magnet=strongest" : "1st magnet",
                     _s.a2MagnetTag, fmtRmult(_s.a2MagnetR))
                if not _magIsStr
                    _r := _r + a2Item("strongest", _s.a2StrongTag, fmtRmult(_s.a2StrongR))
                string _slIn = (_s.a2SlAdjSide == 2 ? "" : fmtRmult(_s.a2SlAdjR) + ", ") +
                     (_s.a2SlAdjSide == 2 ? "at stop"
                      : _s.a2SlAdjSide < 0 ? "beyond stop" : "inside") + ", " + _s.a2SlAdjWord
                _r := _r + a2Item("SL-adj", _s.a2SlAdjTag, _slIn)
                _r := _r + " · Obstacles:[" + _s.a2Obstacles + "]"
    _r
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Internal — Phase 3 live display (M11-3, compile 7)
// ═══════════════════════════════════════════════════════════════════════════════════════════
//
// Everything below builds the block that is RE-WRITTEN onto a signal's label as the signal
// evolves, as opposed to the at-signal block above, which is frozen at label.new and never
// touched again. The two are appended, never merged: `baseTxt` / `baseTip` hold the whole
// creation-time string — arrow, score breakdown and at-signal block — because label.set_text
// REPLACES and cannot append.
//
// ⚠️ THE VERBOSE LABEL AND THE TOOLTIP ARE SEPARATE BUILDERS, and that is the 2026-08-08
// commitment expressed as code rather than as a rule: the label gets §7.6.4's Y rows and nothing
// else, the tooltip gets everything. A single builder with a verbosity flag would put the whole
// block one edit away from the surface the client complained about.
 
// The rung with §7.6.7's outcome suffix — CONFIRMED(TP1) · DEVELOPING(SL) · AUCTIONING(EX), and
// "(—)" while the signal is still running. ⚠️ The rung VALUE is never adjusted at resolution: a
// signal stopped out while Developing IS Developing, and the suffix is what separates it from a
// live one. Without the suffix a resolved and a live signal both read CONFIRMED.
// ⚠️ AN UNRESOLVED SIGNAL GETS NO SUFFIX AT ALL — it used to render "(—)". §7.6.7 argues for having
// a suffix because "without it a resolved and a live signal both read CONFIRMED", and the PRESENCE
// of the parenthetical carries that distinction on its own; a placeholder inside it adds nothing.
// Nor does it have an audience: the only write that survives on history is the resolution write, so
// "(—)" could appear only on a signal still open at the chart's right edge — where being open is
// already evident — while costing characters on the verbose label, the surface the 2026-08-08
// clutter commitment exists to protect.
rungTxt(ParticipationState _s) =>
    _s.rung + (_s.resolved ? "(" + _s.outcome + ")" : "")
 
// The retained ladder history (§7.7.4) — WHEN each transition happened, as a bar offset from the
// entry bar. On history this is the only thing on the label that says when anything changed: the
// surviving write happens at resolution, so every other reading is a resolution-bar value.
//
// ⚠️ ZERO-BASED, AND THAT IS NAVIGATION SEMANTICS RATHER THAN AN INDEXING HABIT. `+N` is the raw
// bar_index difference, so the number IS how many candles to move right from the entry label —
// which is the workflow §7.7.4 built this for: jump to the two or three bars where something
// actually changed and read the full state there, instead of stepping forward forty. One-based
// would put a −1 into exactly that workflow, and would read WORSE as elapsed time: a transition on
// the candle after entry is "+1 bars later", not "bar 2". 📌 It is explained once in the changelog.
// 📌 `+0` is unreachable at the default numbers — every transition needs at least two bars of
// evidence (H=3 closes, R=3 closes, N=3 decay bars, and an episode needs a non-touch bar to close)
// — but that is a property of the settings, not a proof: set H=1 and a +0 DEVELOPING is reachable
// on the entry bar.
//
// Arrow and ARRIVAL state only; the departure state is already on the Birth: row. Conditional at no
// cost — a signal still on its birth rung has all three stamps at -1 and emits nothing at all.
// ⚠️ "bars" IS DROPPED AND THE `+` IS ATTACHED — `->DEV+3`, not `→DEV +3 bars`. The unit is the
// convention, stated once in the changelog rather than five characters on every stamp of every
// signal, and attaching the sign matches the same rule that attaches `VAH(0.40R)`.
//
// ⚠️ ASCII `->`, NOT `→`, SINCE C18 — AND IT COSTS A CHARACTER RATHER THAN SAVING ONE, SO DO NOT
// "OPTIMISE" IT BACK. `→` is ALREADY TAKEN on this rendered surface: ContextScore builds its zone
// detail as `POC→VAH`, meaning *the span between two levels*, and that renders inside the `Comp:` /
// `Prev:` / `Curr:` brackets of the same wrapped line. One glyph would then carry "the span
// between" and "transitioned to" in one tooltip. `->` only ever appears as raw->weighted in the
// score breakdown, which is unambiguous. 📌 The inverse fix — moving ContextScore's six `->` onto
// `→` — SAVES six characters and was still rejected: it walks into the `POC→VAH` collision and
// rewrites shipped M11-2 text to do it.
ladderHist(ParticipationState _s) =>
    (_s.devAt   >= 0 ? " · ->DEV+"   + str.tostring(_s.devAt   - _s.seedBar) : "") +
     (_s.confAt  >= 0 ? " · ->CONF+"  + str.tostring(_s.confAt  - _s.seedBar) : "") +
     (_s.stallAt >= 0 ? " · ->STALL+" + str.tostring(_s.stallAt - _s.seedBar) : "")
 
// A signed magnitude — the leading "+" is what makes a tally or a delta ratio readable as a
// direction rather than as a size. Negative values carry their own sign.
fmtSigned(float _x) =>
    na(_x) ? "—" : (_x > 0 ? "+" : "") + str.tostring(_x, "0.00")
 
// S4's counter, direction-aware, per §7.3.5: the ACTIVE run only, never both, with the origin's
// tag so the row is verifiable against the chart by eye.
//
// ⚠️ THE DENOMINATOR FOLLOWS FAVORABLE/UNFAVORABLE, NOT ABOVE/BELOW. `s4Run` is signed against
// the THESIS — positive is beyond the origin, negative is back through it — so the hold threshold
// pairs with the positive run and the reject threshold with the negative one, in both directions.
// The side WORD is the part that flips: beyond the origin means above it on a long and below it
// on a short. Hardcoding "above" to the hold case is correct on every long and silently wrong on
// every short, which is the family of the direction-blind "Historical resistance ahead" literal
// that shipped in M10 and cost a client bug report.
// `_s.bull == (_r > 0)` is that table in one expression: bull+beyond and bear+through are the two
// "above" cases, and they are exactly the two where the operands agree.
//
// ⚠️ THE NUMERATOR IS CLAMPED TO THE THRESHOLD (C18) — `127/3` now reads `3/3`, with NO `+` or `≥`
// marker by decision. `s4Run` is unbounded, so on a long-lived trade it grew to three and four
// digits on the surface that clips, and "127 out of 3" reads as a defect. §7.3.5's stated job for
// this counter is making the verdict countable against the chart by eye, which `3/3` preserves
// exactly; the `rotating` case (|run| < threshold) is untouched by a min and still renders `1/3`
// or `2/3`.
// ⚠️ WHAT THE CLAMP DELETES, AND HOW S4 MUST NOW BE VERIFIED. The DURATION of acceptance is gone —
// `3/3` reads identically at bar 3 and at bar 127, and that figure is retained nowhere else
// (accepted; recoverable later with a marker if the client asks). More importantly it removes an
// accidental diagnostic: a `s4Run` that failed to reset used to announce itself as an implausible
// number. **It still shows up as a WRONG STATUS WORD** — `holding` on a chart that visibly rotates
// — because the clamp is display-only and s4Of reads the raw field. So verify S4 on the status word
// and on the unclamped middle; `3/3` alone is now unfalsifiable and proves only that the threshold
// was reached at some point.
s4Phrase(ParticipationState _s, ParState _p) =>
    int _r   = _s.s4Run
    // Evaluated on the _r == 0 branch too, where it is unused — the branch returns before it.
    int _thr = _r > 0 ? _p.cfgS4Hold : _p.cfgS4Reject
    _r == 0 ? "at " + _s.originTag
     : str.tostring(int(math.min(math.abs(_r), _thr))) + "/" + str.tostring(_thr) + " " +
       (_s.bull == (_r > 0) ? "above " : "below ") + _s.originTag
 
// Total completed tests across every watched level — the tally's denominator. Derived rather than
// stored, for the reason nSupport/nObstacle were removed in M11-2: it is a walk over an array the
// state already retains, so storing it would be a second copy free to drift from the first.
nTests(ParticipationState _s) =>
    int _t = 0
    int _n = array.size(_s.levels)
    if _n > 0
        for _i = 0 to _n - 1
            WatchedLevel _w = array.get(_s.levels, _i)
            _t += _w.tests
    _t
 
// The approach class as display vocabulary. ⚠️ THE UNKNOWN STATE RENDERS NOTHING, deliberately:
// apprSide 0 means the engine could not tell which side price met the level from — reachable on
// any episode that opens on the entry bar, whose t−1 is the unprocessed signal bar — and a record
// whose approach could not be determined must render without vocabulary, not with the wrong one.
// ⚠️ ATTACHED AND ABBREVIATED. The leading space is gone because the shipped `a2Item` attaches its
// parenthetical the same way — `first magnet:VAH(0.40R)` — and SCOPE's "support test" / "obstacle
// test" is the READING a user gets, not a string that has to be spelled out on a surface whose
// vertical cost is characters ÷ ~53.
apprWord(int _side) =>
    _side > 0 ? "(sup)" : _side < 0 ? "(obs)" : ""
 
// One retained-record row. Existence is tested on the TAG, exactly as a2Item does, so a record
// that was never written costs nothing.
recPart(string _label, string _tag, int _side, float _oi, float _d, float _e) =>
    na(_tag) ? "" : " · " + _label + ":" + _tag + apprWord(_side) + " OI " + fmtRatio(_oi) +
         ", depth " + fmtRmult(_d) + ", E " + fmtRatio(_e)
 
// Do the two retained records describe the SAME episode? They coincide on a trade that never
// tested anything outside its stop corridor, which is the common case, and SCOPE asks for the
// duplicate to be suppressed so that the stop-side row's PRESENCE is itself meaningful.
//
// ⚠️ COMPARED FIELD BY FIELD RATHER THAN BY A STORED MARKER, and the failure direction is chosen:
// any disagreement renders BOTH rows. A false "different" costs one duplicate row; a false "same"
// silently hides the stop-corridor record the client asked for on 2026-08-10.
// ⚠️ nz(x, -1) on the three floats is not decoration — a bare `==` between two na floats is na,
// which is falsy, so an all-na comparison would report "different" and print an empty second row.
sameRec(ParticipationState _s) =>
    _s.corrTag == _s.recTag and _s.corrSide == _s.recSide and
     nz(_s.corrOI, -1) == nz(_s.recOI, -1) and nz(_s.corrD, -1) == nz(_s.recD, -1) and
     nz(_s.corrE, -1) == nz(_s.recE, -1)
 
// The one OPEN episode, streamed. Measured on every level, rendered for one — rendering every open
// episode would be a fifth unbounded set on a tooltip that was deliberately compacted from 23 rows
// to 14.
//
// ⚠️ THE CHOICE IS THE HIGHEST-wBase episode THAT HAS BEEN MEASURED, and both halves were decided.
// "Closest to close" was considered and rejected: every open episode is touched by the current bar
// — an episode closes on the first non-touch bar — so all of them sit inside one bar's [low, high]
// and proximity discriminates on a few ticks of noise, flickering the shown narrative between bars
// with no underlying event. wBase is stable, free, and discriminates on the level's actual weight.
//
// ⚠️ THE `expVolAcc > 0` TERM IS NOT AN OPTIMISATION — it is what stops this row making a claim it
// cannot support. An episode with no admitted bar has volAcc and expVolAcc at zero, so OI and E
// render as "—" and, worse, `depthMax` renders as a NUMBER: `depth 0.00R` reads as "price barely
// penetrated the level" when the truth is "no bar was ever measured". Depth advances on admitted
// bars only. 📌 C14 is the governing precedent, same class of defect: it suppressed
// `Acceptance:unreadable, at —` as a position claim about a level that does not exist.
// ⚠️ THE TEST IS `expVolAcc > 0` SPECIFICALLY, because that is the exact expression closeEpisode
// uses to decide whether an episode was measurable at all. One definition of "measured", two
// consumers — do not substitute `volAcc > 0` or a bar count, which can disagree with it.
// ⚠️ Consequence, accepted: ABSENCE OF THIS ROW IS NOW AMBIGUOUS — it means either "no level is
// being tested" or "one is, but nothing about it is measurable yet". The information given up is
// the level's tag and its (prev …) baseline. Suppression won over rendering it honestly because
// this surface had just been compacted and C14 points this way.
// 📌 STILL NEEDED AFTER §7.8 CLOSED THE DELTA-WINDOW GAP, so this is not redundant with it: expVol
// is na during RVOL baseline warm-up and above 30-min, so an unmeasured open episode stays
// reachable on a fresh chart.
//
// The priors appear only when they exist, and that is self-enforcing rather than a wording rule:
// a dead-volume episode never writes lastOI/lastDepth, so na means "no comparable prior test" and
// the row falls back to absolutes. E never has a prior at all, which is exactly SCOPE's "OI and
// depth only, not E" constraint arriving for free.
streamPart(ParticipationState _s) =>
    string _out  = ""
    float  _best = -1.0
    int    _bi   = -1
    int    _n    = array.size(_s.levels)
    if _n > 0
        for _i = 0 to _n - 1
            WatchedLevel _w = array.get(_s.levels, _i)
            if _w.testing and _w.expVolAcc > 0 and _w.wBase > _best
                _best := _w.wBase
                _bi   := _i
    if _bi >= 0
        // Named apart from the scan's `_w` on purpose — sibling blocks, but a second declaration
        // of one name inside a single function is not worth finding out about on TradingView.
        WatchedLevel _wb = array.get(_s.levels, _bi)
        // oppDelta is accumulated as a MAGNITUDE (see closeEpisode), so this needs no abs and no
        // direction branch — the same expression the vote uses.
        float _oi = _wb.volAcc > 0 ? _wb.oppDelta / _wb.volAcc : na
        float _e  = _wb.expVolAcc > 0 ? _wb.volAcc / _wb.expVolAcc : na
        // ⚠️ THE LABEL NAMES ITS OWN ASYMMETRY. On a RESOLVED signal an episode can still be open,
        // because only an SL force-closes one: an SL is an event that resolves the test — price
        // came to the level and carried through it to the stop — while a target hit or a cutoff is
        // the TRADE ending on a test that never resolved itself, so it casts no vote and closes
        // nothing. Consequence, and it is in the NUMBERS as well as the wording: a stopped signal
        // carries that episode's −1 in its tally and shows it under "Last test", while a
        // target/cutoff signal carries nothing from it and shows it here. Saying "Open test" on a
        // finished signal would read as a bug; "Unresolved test" says what actually happened.
        _out := " · " + (_s.resolved ? "Unresolved test:" : "Open test:") + _wb.tag + apprWord(_wb.apprSide) +
             " OI " + fmtRatio(_oi) +
             (na(_wb.lastOI) ? "" : "(prev " + fmtRatio(_wb.lastOI) + ")") +
             ", depth " + fmtRmult(_wb.depthMax) +
             (na(_wb.lastDepth) ? "" : "(prev " + fmtRmult(_wb.lastDepth) + ")") +
             ", E " + fmtRatio(_e)
    _out
 
// Decode the co-occurrence bitmask. The layout is seed()'s: family f owns 2^(2f) bull and
// 2^(2f+1) bear, and Pine has no bitwise operators, so the test is the same guarded arithmetic
// bitSet uses — int() on the division is mandatory, since Pine's / on two ints returns a float.
//
// ⚠️ THE DIRECTION OF THIS ROW IS THE OPPOSITE OF THE INTUITIVE READING: seed() sets the bit on
// the states that ALREADY EXIST when a new signal fires, so this lists the families that fired
// AFTER this signal, not the ones already running when it did.
famMaskTxt(int _m) =>
    string _o = ""
    for _f = 0 to 3
        for _d = 0 to 1
            int _bit = int(math.pow(2, _f * 2 + _d))
            if int(_m / _bit) % 2 == 1
                // No leading space on the first item — the caller's "Also fired:" already ends in a
                // colon, and the shipped convention puts no space after one.
                _o := _o + (_o == "" ? "" : ", ") + famName(_f) + (_d == 0 ? "▲" : "▼")
    _o
 
// The VERBOSE LABEL block — §7.6.4's Y rows only, and the ○ extras stay in the tooltip until the
// client asks for them. Rows 2 (birth state) and 18 (first magnet) already ship inside the frozen
// at-signal block above, so what is added here is row 1 (the live state) and rows 4/8/11/15 (the
// four component statuses).
//
// ⚠️ THE FOUR STATUSES ARE PAIRED TWO TO A LINE, not one row each. Taken literally the map would
// add five lines to a surface whose clutter is the client's standing complaint; pairing costs
// three. The label is the surface the whole 2026-08-08 commitment exists to protect.
//
// "State now:" rather than "State:" because the frozen block two lines above already reads
// "Participation: <birth rung>" — approved client-facing text whose LABEL is not being reworded
// (⚠️ C18 does abbreviate the rung WORD it interpolates, `DEVELOPING`→`DEV`; the row prefix is what
// stays) — and
// two unqualified rung lines on one label would be ambiguous about which is which.
liveRows(ParticipationState _s, string _pfx) =>
    "\n" + _pfx + "State now: " + rungTxt(_s) +
     "\n" + _pfx + "Commitment: " + _s.s1Stat + " · Pace: " + _s.s2Stat +
     "\n" + _pfx + "Retests: " + _s.s3Stat + " · Acceptance: " + _s.s4Stat
 
// The TOOLTIP block — everything, appended as " · " items onto the single line the at-signal
// tooltip already is. ⚠️ THE VERTICAL COST IS CHARACTERS ÷ ~53, not rows: this whole surface
// contains exactly one "\n", at the at-signal block's opening, and force-wraps from there. So a
// repeated LABEL costs as much as a value, and "putting two things on one line" saves nothing.
//
// Ordering per §7.6.2: live state and the reason first, then the four components each carrying its
// own evidence adjacent, then the excursions, the retained records and the open test.
//
// ⚠️ THE COMPONENTS RENDER STATUS + EVIDENCE, NOT THE MAP'S RAW READINGS. Two of the map's Phase 3
// rows already ship in the shared `Env:` block — latched cumRVOL and the VWAP side/slope — so
// neither is repeated here, which is also consistent with block B removing VWAP from S1's status.
liveTip(ParticipationState _s, ParState _p, string _pfx) =>
    // ⚠️ THE REASON SITS IMMEDIATELY AFTER THE RUNG, INSIDE THE SAME ITEM — an amendment to
    // §7.7.4, which put the ladder stamps between them. It is not a preference: the phrase no
    // longer names its own subject (it dropped the rung word and "because", which `State:` already
    // carries two characters earlier), so a fragment separated from the rung by a " · " item would
    // be orphaned. Adjacency is also what makes the born case grammatical — see reason().
    // The comma costs one character and buys the reading. ⚠️ ITS ORIGINAL JUSTIFICATION IS WEAKENED
    // BY C18, so do not re-derive it from the current strings and conclude the comma is free to go:
    // the case was that "DEVELOPING the origin was holding beyond" garden-paths as "developing the
    // origin", and the abbreviated "DEV" no longer does that. The comma stays on the weaker but
    // sufficient ground that it separates a label from a fragment carrying no subject of its own.
    // The stamps follow, so the line now reads: what state + why · how it got there · on what
    // evidence. ⚠️ Guarded on empty — a born-CONFIRMED signal has no phrase, and an unguarded join
    // would leave a dangling ", " before the next item.
    string _rsn = reason(_s)
    string _o = " · " + _pfx + "State:" + rungTxt(_s) +
         (_rsn == "" ? "" : ", " + _rsn) + ladderHist(_s)
    // S1 — the ratio is per SIGNAL, and cumVol > 0 is the same test that makes the status
    // readable, so the evidence appears exactly when the status is not "unreadable".
    // The source note is sticky and surfaces when ANY folded bar used the CLV proxy: CLV×volume
    // is a different quantity, not a noisier one, so a mixed-source signal has to say so.
    // ⚠️ THE WORD IS "(mixed)" AND THE FIELD IS `proxyDelta` — the mismatch is deliberate. The
    // TRIGGER is "at least one folded bar was proxy", which describes a MIXED-SOURCE ratio, and
    // "(proxy)" overstated that: it read as "this number is the proxy" on a signal that was 95%
    // footprint. The flag is one bit and cannot express a proportion, so the word has to match the
    // trigger rather than the worst case. ⚠️ Known imprecision, accepted: with the emergency valve
    // ON every bar is proxy, so nothing is actually mixed and this reads as understatement rather
    // than overstatement. That is the rarer case, it only occurs by the user's own deliberate
    // action, and the input's own tooltip already says footprint delta is unavailable.
    // 📌 If this ever needs to be exact, the fix is a PROPORTION, not a different bit — accumulate
    // proxy-sourced volume alongside cumVol and render the share. Do not reach for a second bool.
    // "since entry" is dropped: cumDelta accumulates from the entry bar by construction, so every
    // reading on this row is since entry and the words carried no information.
    _o := _o + " · Commitment:" + _s.s1Stat +
         (_s.cumVol > 0 ? ", " + fmtSigned(_s.cumDelta / _s.cumVol) : "") +
         (_s.proxyDelta ? "(mixed)" : "")
    // S2 — BAR-LEVEL, off ParState, not off the signal. Every live signal on the chart shares this
    // reading; it is the market's participation slope, not the trade's.
    // 📌 Rendered `Pace:` since C18, NOT `Participation:` — that collided with the `── Participation:`
    // header naming the whole engine. The three names for this component are mapped at s2Of.
    // 📌 "vs prior" DROPPED (§7.10.1) — the status word and the ratio already say what the number
    // is, and §4.3 of the changelog states the two windows. ⚠️ Not a lever against the tooltip
    // clipping: C18's conclusion stands, that wording cannot fix it. ⚠️ The `(prev …)` parentheticals
    // on the test rows are a DIFFERENT convention and stay — there the prior value is actually
    // printed, so the word is doing work.
    _o := _o + " · Pace:" + _s.s2Stat +
         (nz(_p.s2Prior) > 0 ? ", " + fmtRatio(_p.s2Recent / _p.s2Prior) : "")
    // S3 — the NUMBER only. The word is already the status; repeating it would duplicate the row.
    // ⚠️ THE COUNT IS PARENTHESISED, NOT SLASHED, and §7.6.2's own `+1.8/3 tests` example is what
    // this corrects. The ACCEPTANCE row one item away already uses "/" as PART-OF-WHOLE —
    // `3/3 above VAH` — while here the two numbers are unrelated quantities, so the same glyph
    // would carry two meanings in adjacent items. A dash is worse: the tally is SIGNED, so
    // `-1.50-3 tests` reads as subtraction. The parenthetical is the shipped attach convention,
    // the one `VAH(0.40R)` uses, and costs one character over the slash.
    // ⚠️ `n=` RATHER THAN A BARE `(16)` — C18, and the bare form was considered first. Every other
    // parenthetical on this surface is LABELLED (`(prev 0.05)`, `(0.32R)`, `(obs)`), so a bare
    // integer sitting against a signed float would be the one unlabelled aside in the block and
    // would lean entirely on the `Retests:` label two words to its left. `n=` gives back −4 instead
    // of −6 and keeps the convention intact.
    _o := _o + " · Retests:" + _s.s3Stat + ", " + fmtSigned(_s.s3Tally) +
         "(n=" + str.tostring(nTests(_s)) + ")"
    // ⚠️ NO COUNTER WHEN S4 IS UNREADABLE. s4Stat is `unreadable` exactly when the signal has no
    // origin, and then s4Run never advances (the whole S4 block is guarded on it) while originTag
    // is the "—" placeholder — so the phrase rendered "at —", a position claim about a level that
    // does not exist. An unmeasurable component states that it is unmeasurable and stops.
    _o := _o + " · Acceptance:" + _s.s4Stat +
         (_s.s4Stat == ST_UNKNOWN ? "" : ", " + s4Phrase(_s, _p))
    // Both extremes, in R. Both are shown because "both extremes since entry are held, in R" was
    // said to the client in writing, and both fields are maintained regardless — displaying only
    // the adverse one would mean holding a value we told him we keep and not showing it.
    _o := _o + " · MAE:" + fmtRmult((_s.bull ? _s.entry - _s.runLow : _s.runHigh - _s.entry) / _s.r) +
         " · MFE:" + fmtRmult((_s.bull ? _s.runHigh - _s.entry : _s.entry - _s.runLow) / _s.r)
    _o := _o + recPart("Last test", _s.recTag, _s.recSide, _s.recOI, _s.recD, _s.recE)
    if not na(_s.corrTag) and not sameRec(_s)
        _o := _o + recPart("Stop-side", _s.corrTag, _s.corrSide, _s.corrOI, _s.corrD, _s.corrE)
    _o := _o + streamPart(_s)
    if _s.famMask != 0
        _o := _o + " · Also fired:" + famMaskTxt(_s.famMask)
    _o
 
// The OTHER state sharing this one's label — the follower when `_s` leads, the leader when `_s`
// follows — or na when nothing does: never merged, or the partner has already resolved and left.
//
// ⚠️ ONE PREDICATE READ IN BOTH DIRECTIONS, and it was briefly two: the follower lookup inline in
// writeOne and a `leaderOf` of its own. Splitting them is how the removal path came to implement
// only one direction, which left a merged signal whose LEADER resolved first reading "(—)" — still
// running — for ever. One relation, one function, both directions or neither.
//
// ⚠️ IT NEEDS leadFam, not just (isFollower, seedBar, bull): a Continuation and an AC can fire on
// the same bar in the same direction and only one of them takes the merge, so the unmerged label
// would otherwise claim the inflection too. ✅ AC vs AC-Retest cannot collide — host [6793] is an
// if/else-if chain, so at most one famIdx-1 state exists per bar and direction.
// ⚠️ `leadFam >= 0` SHORT-CIRCUITS THE SCAN, AND IT IS THE RIGHT FIELD RATHER THAN `merged`. Both
// are true for a single-signal label's whole life, so either would skip the walk there — but only
// leadFam goes false when a partner RESOLVES AND LEAVES, and `merged` must not, because it drives
// the display prefix and that has to survive the partner. Using `merged` here left every survivor
// walking the array on every write for something that was no longer in it.
partnerOf(array<ParticipationState> _states, ParticipationState _s) =>
    ParticipationState _out = na
    int _n = array.size(_states)
    if _s.leadFam >= 0 and _n > 0
        for _j = 0 to _n - 1
            ParticipationState _o = array.get(_states, _j)
            bool _match = _s.isFollower ? (not _o.isFollower and _o.famIdx == _s.leadFam)
                 : (_o.isFollower and _o.leadFam == _s.famIdx)
            if _match and _o.seedBar == _s.seedBar and _o.bull == _s.bull
                _out := _o
                break
    _out
 
// Write one LABEL — its leader's block, then its merged follower's if it has one.
//
// ⚠️ KEYED ON THE LABEL, NOT ON THE STATE, and that is the whole reason isFollower exists. Two
// states can share one handle (an inflection merged into a Continuation/AC label); if each wrote
// independently, label.set_text REPLACES rather than appends, so the last write would win and one
// signal's readings would vanish silently.
//
// ⚠️ WITH VERBOSE LABELS OFF — THE DEFAULT — THE TEXT IS NEVER REWRITTEN. §7.6.1 keeps the compact
// label untouched "including the rung", and the outcome suffix attaches to the rung, which the
// compact label does not carry. The natural implementation rewrites both unconditionally and would
// silently start putting rung text on the compact label, which is exactly what the 2026-08-08
// commitment forbids. The tooltip is rewritten either way: it is invisible until hovered, so it
// cannot contribute to the clutter that produced the commitment.
// ⚠️ CALLED ONLY ON A LEADER — render's write gate excludes followers — so partnerOf returns this
// label's follower, if it still has one.
writeOne(array<ParticipationState> _states, ParticipationState _s, ParState _p, bool _verbose) =>
    // Prefixed for the label's whole life when it carries two signals; `merged` is a property of
    // the LABEL, not of what the array currently holds. See the field's comment for why that
    // distinction is the fix and not a refinement.
    string _pfx = _s.merged ? "[" + famName(_s.famIdx) + "] " : ""
    ParticipationState _of = partnerOf(_states, _s)
    // ── Tooltip — always. Invisible until hovered, so it cannot contribute to the clutter.
    string _pf2 = ""
    string _tip = _s.baseTip + liveTip(_s, _p, _pfx)
    if not na(_of)
        _pf2 := "[" + famName(_of.famIdx) + "] "
        _tip := _tip + liveTip(_of, _p, _pf2)
    label.set_tooltip(_s.lbl, _tip)
    // ── Label text — ONLY when verbose, and the rows are not even BUILT otherwise.
    // ⚠️ THE GATE WRAPS THE CONSTRUCTION, NOT JUST THE WRITE. `i_sigVerboseLabels` defaults to
    // false, so building the text and discarding it would be the DEFAULT path, on every islast tick
    // of every live signal. Wrapping the write alone also reads as though the string might be
    // wanted, when §7.6.6f's rule is that under the default the label text is never rewritten at
    // all. ⚠️ The ternary form is deliberately avoided: Pine may evaluate both branches of `?:`,
    // and liveRows on an na partner would be a field access on an undefined object.
    if _verbose
        string _txt = _s.baseTxt + liveRows(_s, _pfx)
        if not na(_of)
            _txt := _txt + liveRows(_of, _pf2)
        label.set_text(_s.lbl, _txt)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Exported — Phase 3 label binding and the live write pass (M11-3, compile 7)
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// @function   Bind a freshly created signal label to the state(s) it renders, and latch the base
//             strings the live rewrite appends to.
//
//             ⚠️ THIS CANNOT BE DONE ANYWHERE ELSE, and the two obvious places both fail. The
//             handle does not exist until label.new RETURNS, so sigLabelText/sigTooltip cannot do
//             it; and by the time par.advance runs, the host's finalisation blocks have already
//             pushed each pending handle into its history array and nulled the pending variable.
//             So binding happens between creation and finalisation, at the ten label sites.
//
//             ⚠️ THE BASE STRINGS ARE PASSED, NOT READ BACK. Pine has label.get_text but no
//             label.get_tooltip, so the tooltip half could not be recovered from the handle even
//             if the text half could. The host holds both in locals it already computed for
//             label.new, so this costs no extra work — only the argument.
//
//             ⚠️ RE-BINDING EVERY TICK IS CORRECT, NOT WASTE. The pending renderers are
//             deliberately not isconfirmed-gated: on a realtime bar rollback deletes the label and
//             the block creates a fresh one each tick, so the handle churns. It is harmless
//             because parStates is a var array and the handle is rolled back and re-bound in the
//             same pass — but a "first tick only" guard would leave the state pointing at a
//             deleted label for the rest of the bar.
//
//             A na handle is a no-op, so a bar with no signal costs nothing.
// @param bar      The bar whose states to bind — the host passes bar_index.
// @param bull     Direction; a bull label must not bind a bear state fired on the same bar.
// @param fam      Family this label was created for; see renders().
// @param famAlso  Second family the same label carries — the inflection MERGE, and the only case
//                 where this call binds two states. -1 elsewhere.
// @param lbl      The handle label.new just returned.
// @param baseTxt  The label's creation-time text — arrow, score, at-signal block.
// @param baseTip  The label's creation-time tooltip. label.set_text REPLACES, so the rewrite is
//                 always base + block and both halves have to be kept.
export bindLabel(array<ParticipationState> states, int bar, bool bull, int fam, int famAlso,
     label lbl, string baseTxt, string baseTip) =>
    if not na(lbl)
        int _n = array.size(states)
        if _n > 0
            // The FIRST match leads and every later one follows. Which state that is depends on
            // the host's seed order, and it does not matter: each block carries its own family
            // prefix, so the order only decides which of the two prints first.
            // ⚠️ THE FOLLOWER RECORDS THE LEADER'S ACTUAL famIdx, NOT `fam`. Writing `fam` here
            // would be right only if the target's state always sorted first, and the inflection
            // being seeded first is a host ordering detail this library must not depend on —
            // wrong, every partnerOf lookup would miss and a merged label would silently render
            // one signal.
            // ⚠️ `merged` IS SET ON BOTH, AND THE LEADER IS MARKED WHEN THE SECOND MATCH APPEARS
            // — its index is still in hand, so this needs no second pass. Every field is written
            // unconditionally on each bind, because this re-runs on every realtime tick of the
            // entry bar and a stale flag from a previous tick would outlive its reason.
            int _leadIdx = -1
            int _leadFam = -1
            for _i = 0 to _n - 1
                ParticipationState _s = array.get(states, _i)
                if renders(_s, bar, bull, fam, famAlso)
                    _s.lbl     := lbl
                    _s.baseTxt := baseTxt
                    _s.baseTip := baseTip
                    if _leadFam < 0
                        _s.isFollower := false
                        _s.leadFam    := -1
                        _s.merged     := false
                        _leadIdx      := _i
                        _leadFam      := _s.famIdx
                    else
                        _s.isFollower := true
                        _s.leadFam    := _leadFam
                        _s.merged     := true
                        // The leader is marked here, when the second match proves the label carries
                        // two — its index is still in hand, so this needs no second pass. It takes
                        // its OWN famIdx as leadFam: the field means "the family leading this
                        // handle", and for the leader that is itself.
                        ParticipationState _ld = array.get(states, _leadIdx)
                        _ld.merged  := true
                        _ld.leadFam := _leadFam
    true
 
// Has this state outlived the label it renders on? ONE DEFINITION, two call sites in render() — the
// eviction and the write gate — because those two ask the same question and a second copy of the
// expression is exactly how the OR/velocity divergence survived compile 7 unnoticed.
//
// ⚠️ THE THRESHOLD IS PER FAMILY. The host prunes OR-keyed signal labels against orBarIndices but
// VELOCITY labels against velZoneIdx, governed by i_velZoneRetention (default 20) versus i_pastORs
// (default 0) — so at the shipped defaults a velocity label outlives the oldest retained OR by many
// sessions. A single threshold is wrong in both directions and silent in both: it stops rendering a
// velocity signal whose label is VISIBLE (which then never receives its outcome suffix), or lets a
// write reach a DELETED velocity label.
//
// 📌 `famIdx` is assigned HOST-SIDE at the ten parSeed call sites (0 cont · 1 AC · 2 infl · 3 vel),
// so the literal 3 is bound to those and to famName's own 3. A library const would NOT single-source
// it — the host's literals are the source — so it is a comment rather than a constant.
//
// ⚠️ seedBar, not the handle: a deleted label is NOT na, and there is no "is this drawing alive"
// test in Pine. A signal label's x IS its entry bar, so this is bit for bit the host's own prune
// test, as an integer comparison that never touches a possibly-dead drawing.
agedOut(ParticipationState _s, int _oldestOR, int _oldestVel) =>
    _s.famIdx == 3 ? _s.seedBar < _oldestVel : _s.seedBar < _oldestOR
 
// @function   The live write pass, and the prune. Rewrites every rendered signal's label text and
//             tooltip from current state, then removes the states that have resolved.
//
//             ⚠️ THREE TRIGGERS, AND ONLY ONE OF THEM SURVIVES ON HISTORY. `barstate.islast` fires
//             on a single bar, so a signal that resolved earlier is never revisited by it — the
//             RESOLUTION write is the only one that leaves a permanent record.
//
//             ⚠️ `barstate.islastconfirmedhistory` IS THE THIRD, AND IT EXISTS TO PAY FOR THE HOST'S
//             `isconfirmed` GATE. Every value this function renders is either latched at seed or
//             written on a confirmed bar — `advance` for all of it, `par.step` for S2's window,
//             inside its own isconfirmed block — so NOTHING here can change within a bar, and
//             running per tick reproduces identical strings. The host therefore calls this once per
//             bar. But `islast` on a live chart is the FORMING bar, so an isconfirmed gate alone
//             would leave a live signal with no live block until that bar closed — and since every
//             input change forces a full recalculation, that is not a rare "fresh load" case, it is
//             every settings tweak. This trigger fires on the last SETTLED bar (the one before the
//             realtime bar when the market is open, the dataset's last when closed), which the
//             historical pass always reaches, so the block is present the moment a recalculation
//             finishes, carrying the same confirmed-bar content the per-tick writes used to.
//             ⚠️ `barstate.isnew` was considered and rejected: the reference defines it as the first
//             update of a *newly generated* real-time bar, which a mid-bar recalculation's existing
//             bar is not — so it would probably not fire in the one case that matters, silently.
//
//             ⚠️ NO PER-BAR DEDUP GUARD, and that is a decision rather than an omission. SCOPE
//             specifies a `lastWriteBar` int; rollback defeats it. These states live in a var
//             array, so Pine reverts the field on every realtime tick and the guard reopens — it
//             can block nothing, ever. Historical bars execute once anyway, and the writes are
//             idempotent, exactly as the status table's per-tick render already is.
//
//             ⚠️ `na(s.lbl)` DOES NOT CATCH A DELETED LABEL, and states routinely outlive their
//             labels. Signal labels are pruned when their x falls behind a retention threshold, and
//             `i_pastORs` defaults to 0 — so every session deletes the previous session's OR-keyed
//             signal labels, while the tracking cutoff defaults to 24 market hours. A live state
//             whose label is gone is the NORMAL case, and a deleted handle is NOT na. The test is
//             therefore on `seedBar`: bit for bit the host's own prune test, since a signal label's
//             x IS its entry bar, but as an integer comparison that never touches a possibly-dead
//             drawing.
//
//             ⚠️⚠️ THE THRESHOLD IS PER FAMILY, AND A SINGLE ONE IS A REACHABLE SILENT DEFECT.
//             `oldestORIdx` prunes six label arrays (continuation, AC, inflection × 2 directions),
//             but VELOCITY LABELS HAVE THEIR OWN RETENTION RULE — host [7958-7974], keyed on
//             `velZoneIdx` and governed by `i_velZoneRetention`, DEFAULT 20, against `i_pastORs`
//             DEFAULT 0. So `seedBar < oldestOR` does not mean "this state has no label"; it means
//             that for eight of the ten bind sites and is false for the two velocity ones, at the
//             shipped defaults, by many sessions. Both directions of getting this wrong are silent:
//             a live velocity signal whose label is VISIBLE stops updating and never receives its
//             outcome suffix, or — with the retentions set the other way — a write reaches a DELETED
//             velocity label, which is the one thing the integer comparison exists to avoid.
//             📌 `famIdx` is assigned by the HOST at the ten parSeed sites (0 cont · 1 AC · 2 infl ·
//             3 vel), so the literal 3 below is bound to those and to famName's own 3. A library
//             const would not single-source it — the host's literals are the source.
//
//             ⚠️ THE STATE IS NOW EVICTED, NOT MERELY LEFT UNRENDERED — this reverses the earlier
//             rule ("the state keeps being MEASURED; only rendering stops"). Nothing can observe a
//             state whose label is gone: the write pass skips it, `renders()` keys on
//             `seedBar == bar_index` and so can never reach one, and there is no telemetry, alert or
//             retained result array — the LABEL IS THE RECORD. Its only remaining consumer was
//             rollUp's `Live` count, which it inflated with entries the user cannot inspect
//             anywhere. So it is resolved as OUTCOME_GONE and pruned, and the per-bar engine cost it
//             was paying — the whole episode state machine over its `levels` array — stops.
//             ⚠️ IF TELEMETRY IS EVER BUILT, revisit: at that point the outcome becomes readable.
//
//             ⚠️ EVICTION MARKS, IT DOES NOT REMOVE — so the write gate STILL CARRIES THE AGE TEST,
//             and dropping it as "now dead code" is a mistake this function was one review away from
//             shipping. The eviction block sets `resolved` and hands the state to the loop, exactly
//             as C10's single-eviction-path design requires; removal happens in that loop, AFTER the
//             write. An aged state therefore reaches the gate with `resolved` true and a non-na but
//             DELETED handle. Both sites call `agedOut` so there is one definition of the question.
//
//             ⚠️ ON A MERGED LABEL ONLY THE LEADER WRITES, so whichever of the pair resolves
//             first would take its final readings out of the array before any write could show
//             them — and every later write of that label would then omit it. **The departing state
//             is frozen into the SURVIVOR's base on its way out**, in whichever direction it goes:
//             the base is what every rewrite is built on, so a resolved partner's last state
//             becomes permanent exactly as its at-signal block already is, while the survivor goes
//             on evolving beside it.
//             ⚠️ AND WHEN THE DEPARTING STATE IS THE LEADER, THE SURVIVOR IS PROMOTED. Freezing
//             alone is not enough there: the write gate skips followers, so an un-promoted
//             survivor would keep being measured while nothing rendered it, and its own resolution
//             would never reach the chart — it would read "(—)", still running, for ever. ⚠️ THAT
//             IS EXACTLY WHAT AN EARLIER VERSION OF THIS FUNCTION DID, because it implemented the
//             follower→leader freeze and not its mirror. Both directions or neither.
//             📌 One cosmetic consequence, deliberately not chased: the frozen block always
//             precedes the survivor's live one, so the two swap order when it is the follower that
//             leaves. Order carries no meaning — seed order already decides which of the pair
//             leads — and both blocks stay prefixed with their own family for the label's life.
// @param states     The host's var array. Mutated: resolved states are removed here.
// @param p          Producer state — S2's ratio and the S4 thresholds are read from it.
// @param oldestOR   Oldest retained OR bar index — the label-retention threshold for every family
//                   EXCEPT velocity. -1 when none is registered, which disables the test by
//                   construction: seedBar is a bar_index and therefore >= 0, so `seedBar < -1` is
//                   always false and nothing is evicted on age. Correct, because with no OR
//                   registered no label has been pruned. ⚠️ -1 and NOT na — `seedBar < na` is na,
//                   which is falsy, so an na sentinel would appear to work for the wrong reason.
// @param oldestVel  The same, for VELOCITY signals only — host `velZoneIdx`, governed by
//                   i_velZoneRetention. Same -1 semantics.
//                   ⚠️ EITHER THRESHOLD MAY LAG, AND LAGGING IS SAFE IN ONE DIRECTION ONLY. Each
//                   stands in for "which labels have actually been deleted"; if it ever disagrees it
//                   must disagree toward an OLDER (smaller) bar index, never a newer one. Too old
//                   means a ghost survives one extra bar — harmless. TOO NEW WOULD EVICT A STATE
//                   WHOSE LABEL IS STILL ALIVE. ✅ Both are exact rather than merely safe today,
//                   because each host prune shifts its index array and deletes its labels in one
//                   block, and both blocks run above this call under the same isconfirmed gate. The
//                   velocity block additionally sits under `velReady and velEngineOn`, so with the
//                   engine off it never fires and the threshold stays at its oldest registered zone
//                   or at -1 — the permissive value, and correct, since no velocity labels are being
//                   deleted either. ⚠️ Do not delete this note on the grounds that the values are
//                   currently exact; it is the guarantee if that adjacency is ever broken.
// @param verbose    i_sigVerboseLabels. False — the default — makes this tooltip-only.
export render(array<ParticipationState> states, ParState p, int oldestOR, int oldestVel,
     bool verbose) =>
    // ── Eviction — the UNION of two prefix rules, enforced as RESOLUTION rather than deletion ───
    // ⚠️ MARKING, NOT SHIFTING, AND THAT IS THE WHOLE FIX. seed() used to drop the oldest state
    // with a bare array.shift, which lost its final write, its outcome and — when it was a merged
    // label's leader — left the follower permanently flagged, so that label was never written
    // again. Marking it resolved hands it to the loop below, which writes its last state, freezes
    // it into its partner, promotes a surviving follower and prunes it, exactly as a stop or a
    // cutoff would. ONE eviction path, and it is the path that already works — do not fork it.
    //
    // TWO rules, and they are unioned rather than compared: MAX_STATES is a COUNT and the age
    // thresholds are BAR INDICES, so there is no smaller-of-the-two to take. What they share is
    // that each evicts a PREFIX — the array is append-ordered by seed and array.remove preserves
    // order, so seedBar is non-decreasing and both predicates are monotone across the front. One
    // forward scan with a break therefore covers both, which is the shape the host's own label
    // prunes use, and neither bound has to be computed.
    // 📌 `_capped` is the cap rule stated positionally: `_n0 - _k` is how many states remain from
    // here to the end, so it reads "there are still more than MAX_STATES behind me". Identical set
    // to the old `size - MAX_STATES` prefix, and exact at every index.
    //
    // ⚠️ NO EARLY `break`, AND THE HOST'S PRUNE LOOPS ARE NOT THE PRECEDENT HERE. Theirs break
    // because each walks ONE label array under ONE threshold, so their predicate is monotone. This
    // one interleaves families under TWO thresholds, so it is NOT: a velocity state at the front
    // that is still inside its own retention would stop the scan and strand an older-thresholded
    // continuation state behind it. Under-eviction is the conservative direction — nothing is ever
    // wrongly evicted — but it would persist for as long as the blocker sits at the front. The full
    // scan is at most MAX_STATES comparisons on a loop that already walks the whole array below.
    //
    // ⚠️ `not _old.resolved` IS REQUIRED, not tidiness. advance() runs immediately before this and
    // may have just resolved this state on its stop or its target; overwriting that with GONE would
    // replace a real outcome with a fabricated one — the same objection that keeps GONE and CAP
    // apart, one step further along.
    int _n0 = array.size(states)
    if _n0 > 0
        for _k = 0 to _n0 - 1
            ParticipationState _old = array.get(states, _k)
            bool _capped = (_n0 - _k) > MAX_STATES
            bool _aged   = agedOut(_old, oldestOR, oldestVel)
            if (_capped or _aged) and not _old.resolved
                _old.resolved := true
                // Age wins the tie, and the distinction is for the code rather than the screen: an
                // age-evicted state has no label, so GONE can never render. Reporting it as CAP
                // would put a false reason — "the engine ran out of slots" — in a field the next
                // reader will trust.
                _old.outcome := _aged ? OUTCOME_GONE : OUTCOME_CAP
    int _i = 0
    while _i < array.size(states)
        ParticipationState _s = array.get(states, _i)
        // ⚠️ THE agedOut TERM IS LOAD-BEARING AND MUST NOT BE READ AS DEAD CODE. The eviction above
        // MARKS an aged state resolved; it does not remove it — removal happens in this loop, AFTER
        // the write. So without this term an age-evicted state arrives here with `resolved` true and
        // a non-na (but DELETED) handle, and writeOne would fire on it. The eviction and this gate
        // are the same question asked at two moments in one pass, which is why both call agedOut
        // rather than restating the comparison.
        // 📌 `not na(_s.lbl)` is a DIFFERENT case and is not a substitute for it: seed() is gated on
        // i_tmEnabled and never on the display toggles, so a signal whose label type is switched off
        // has a state and no handle at all. Never-had-a-handle and handle-since-deleted are two
        // problems and each needs its own test.
        if (_s.resolved or barstate.islast or barstate.islastconfirmedhistory)
             and not _s.isFollower and not na(_s.lbl) and not agedOut(_s, oldestOR, oldestVel)
            writeOne(states, _s, p, verbose)
        if _s.resolved
            // FREEZE INTO THE SURVIVOR, IN WHICHEVER DIRECTION APPLIES. Both are needed and the
            // symmetry is the whole point — see the function comment.
            ParticipationState _pt = partnerOf(states, _s)
            if not na(_pt)
                string _pfx = "[" + famName(_s.famIdx) + "] "
                _pt.baseTxt := _pt.baseTxt + liveRows(_s, _pfx)
                _pt.baseTip := _pt.baseTip + liveTip(_s, p, _pfx)
                // ⚠️ CLEAR THE SURVIVOR'S LINK IN BOTH DIRECTIONS. leadFam means "the family
                // leading this handle WHILE A PARTNER IS PRESENT", and one has just stopped being
                // present — so this is what closes partnerOf's short-circuit and stops the survivor
                // walking the array on every write for a partner that has left. `merged` is NOT
                // cleared with it: that answers a different question, "did this label ever carry
                // two signals", and the prefix has to stay for the label's whole life.
                _pt.leadFam := -1
                // PROMOTE when the state leaving was the LEADER. Without this the survivor stays
                // flagged as a follower, and render's write gate skips followers — so it would go
                // on being measured while nothing ever rendered it again, and its own resolution
                // would never reach the chart.
                if not _s.isFollower
                    _pt.isFollower := false
            array.remove(states, _i)
            // Do NOT increment — the element that shifted down into _i needs checking next. That
            // is also what lets a just-promoted survivor be written in this same pass when it
            // shifted down into this slot.
        else
            _i += 1
    true
 
// Live-signal roll-up for the participation table's row 8 — the count plus the rung breakdown.
// ⚠️ NEVER PER-SIGNAL DETAIL. The panel is a singleton surface, so an older unresolved signal
// would silently vanish the moment a newer one fired; per-signal readings belong on the labels,
// which are one per signal by construction.
rollUp(array<ParticipationState> _states) =>
    int _n = array.size(_states)
    string _o = str.tostring(_n) + " live"
    if _n > 0
        int _a = 0
        int _d = 0
        int _c = 0
        int _t = 0
        for _i = 0 to _n - 1
            ParticipationState _s = array.get(_states, _i)
            _a += _s.rung == RUNG_AUCTIONING ? 1 : 0
            _d += _s.rung == RUNG_DEVELOPING ? 1 : 0
            _c += _s.rung == RUNG_CONFIRMED  ? 1 : 0
            _t += _s.rung == RUNG_STALLED    ? 1 : 0
        // ⚠️ THE RUNG WORDS ARE READ FROM THE CONSTANTS, NOT RESTATED — changed at C18. This row
        // carried its own literal "AUCT"/"DEV"/"CONF"/"STALL" copies, which was harmless only while
        // RUNG_* still spelled the words out in full; the moment lever 5 abbreviated them to these
        // same four strings, two independent sources for one vocabulary became live drift risk.
        // (A library function may read the library's own `const` globals — the comparisons above
        // already do.)
        _o := _o + (_a > 0 ? " · " + str.tostring(_a) + " " + RUNG_AUCTIONING : "") +
             (_d > 0 ? " · " + str.tostring(_d) + " " + RUNG_DEVELOPING : "") +
             (_c > 0 ? " · " + str.tostring(_c) + " " + RUNG_CONFIRMED  : "") +
             (_t > 0 ? " · " + str.tostring(_t) + " " + RUNG_STALLED    : "")
    _o
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Internal — table formatting
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// Write a full four-column row. EVERY cell is written, including the ones whose text is empty, and
// every row in this renderer goes through here — the spacer included.
//
// The reason is that a cell which is never written renders as NOTHING: no text, no background, no
// border. It is absent, not transparent. Leaving column 3 untouched on the rows that do not use it
// therefore punched a see-through notch out of the top right of the panel rather than producing a
// tidy ragged edge (observed on chart, 2026-08-01).
//
// Note what is NOT available as a third option: a cell whose border is suppressed. table.cell()
// takes no border arguments — border_color and border_width belong to table.new and apply to every
// cell — so "written but invisible" does not exist. A written cell always draws its border. Every
// row here is therefore a visible panel row, the spacer included.
writeRow(table _t, int _r, string _l1, string _l2, string _l3, string _l4,
     color _tc, color _bg, string _ts) =>
    table.cell(_t, 0, _r, _l1, text_color = _tc, bgcolor = _bg, text_size = _ts, text_halign = text.align_left)
    table.cell(_t, 1, _r, _l2, text_color = _tc, bgcolor = _bg, text_size = _ts)
    table.cell(_t, 2, _r, _l3, text_color = _tc, bgcolor = _bg, text_size = _ts)
    table.cell(_t, 3, _r, _l4, text_color = _tc, bgcolor = _bg, text_size = _ts)
 
// One session's two cells: extension and efficiency. A ledger counts as today's when its last
// in-session bar is at or after the current session's open — the seenAt test that replaced the old
// boolean flag. A session that has not traded yet today reads as dashes rather than showing the
// previous occurrence's numbers. `●` marks the one open right now; its extension is live, and its
// efficiency is still na by design until it closes.
sessCells(SessionLedger _s, int _sessOpen) =>
    bool   _today = sessToday(_s, _sessOpen)
    string _ext   = not _today ? "—" : (_s.active ? "● " : "") + fmtPct(_s.extPct) + " " + fmtDir(_s.dir)
    string _eff   = not _today ? "—" : fmtPct(_s.eff)
    [_ext, _eff]
 
// ═══════════════════════════════════════════════════════════════════════════════════════════
// Exported — table
// ═══════════════════════════════════════════════════════════════════════════════════════════
 
// Table dimensions. Exported so the host can feed them to table.new without hard-coding numbers
// that would then have to be kept in sync with the renderer below. Six CONTENT rows, fixed by
// construction — the readings do not grow with trades — plus however many rows the vertical
// offset costs.
//
// THE OFFSET LADDER. Pine tables snap to nine fixed anchors and take no pixel offset, so the only
// way to push a table down is to give it blank rows above the content. A blank cell's height still
// scales with its text_size (verified on TradingView, 2026-08-06), which means one row buys five
// distinct heights, not one. `units` therefore spends a single integer across BOTH dimensions:
//
//   1 = tiny · 2 = small · 3 = normal · 4 = large · 5 = huge · 6 = huge + tiny · 10 = huge + huge …
//
// i.e. int(units / 5) rows at size.huge, plus one row at size[units % 5] when there is a
// remainder — which is exactly ceil(units / 5) rows, written without a float so the int-division
// rule stays out of it. Filling one row to `huge` before opening a second is deliberate: every pad
// row draws its own borders (see writeRow), so the fewest rows means the fewest seams through the
// blank block. One `huge` row is visually cleaner than three `normal` ones of the same height.
//
// Two things the ladder is NOT: linear, and free. Row height is font height PLUS fixed cell
// padding, so two tiny rows are taller than one small row and every fifth step — the one that
// opens a new row — jumps further than the four before it. It is strictly monotonic, which is all
// a knob needs. And the offset makes the panel TALLER; it does not slide the panel down.
// parPadRows stays INTERNAL: the host only ever needs the total, and parTableRows is that total.
// ⚠️ SIX CONTENT ROWS BECAME EIGHT IN M11-3 (compile 7) — the live-signal roll-up and the
// engine-configuration row. Still fixed by construction, which is the property a top anchor
// depends on: neither new row grows with the number of trades.
parPadRows(int units)          => int(units / 5) + (units % 5 > 0 ? 1 : 0)
export parTableRows(int units) => 8 + parPadRows(units)
export parTableCols()          => 4
 
// The ladder's size rung. Called with units % 5, so 0 never reaches it — the `=>` default covers
// the whole-row case for free.
padSize(int _u) =>
    switch _u
        1 => size.tiny
        2 => size.small
        3 => size.normal
        4 => size.large
        =>   size.huge
 
// Write the blank offset block at the top of the table and return the number of rows it took, so
// the caller can use it as the content-row origin. `_wide` picks the four-column panel row used by
// the live table over the single centred cell the not-live message uses, so the pad matches
// whichever body follows it.
//
// The `_n > 0` guard is load-bearing: Pine's `for` counts DOWN when `to` is below `from`, so an
// unguarded `for _i = 0 to _n - 1` at _n = 0 would run twice rather than not at all.
writePad(table _t, ParticipationConfig _c, bool _wide) =>
    int _n   = parPadRows(_c.vertOffset)
    int _rem = _c.vertOffset % 5
    if _n > 0
        for _i = 0 to _n - 1
            string _sz = _rem > 0 and _i == 0 ? padSize(_rem) : size.huge
            if _wide
                writeRow(_t, _i, "", "", "", "", _c.txtColor, _c.bgColor, _sz)
            else
                table.cell(_t, 0, _i, "", text_color = _c.txtColor, bgcolor = _c.bgColor,
                     text_size = _sz, text_halign = text.align_center)
    _n
 
// @function   Render the participation table: the always-on environment block.
//             Fixed content height by construction — the readings do not grow with trades — which
//             is what makes a top anchor viable at all.
//
//             Layout, 4 columns × (pad + 8) rows:
//               (blank offset rows — c.vertOffset, see parPadRows)
//               Cum RVOL   | 0.98        |
//               Day range  | 25.7% ADR   | ADR 91.50
//               VWAP       | above       | falling
//                          | Asia        | London      | New York   ← header
//               Rng % ADR  | 23.5% ▲     | ● 15.6% ▼   | —
//               Efficiency | 53.5%       | —           | —
//               Live       | 3 live · 1 AUCT · 2 DEV
//               Tracking   | to TP1      | 24h cutoff              ← M11-3
//
//             THE PAD ROWS ARE NOT CONTENT. They clear TradingView's symbol/OHLC legend, which
//             runs along the top of the pane at exactly the height a top anchor would otherwise
//             occupy — and the table draws OVER it, so without them the legend text is unreadable.
//             The fix has to be vertical: the legend's width changes with the symbol name, so
//             narrowing the table would only postpone the collision to a longer ticker.
//
//             The block was a single unconditional row until M11-1 feedback. It is now sized by
//             the host (M11-1 patch, 2026-08-06), because how much has to be cleared is not
//             knowable from inside Pine: the legend's height depends on the user's chart font, on
//             how many indicators share the pane, and on Chart Settings → Status Line → Indicator
//             Inputs. The symbol/OHLC line cannot be hidden at all, so at a top anchor an offset
//             of zero WILL sit under it — that is a reachable state by choice, not an oversight.
//
//             The sessions own COLUMNS rather than rows, which is what buys back the row the
//             spacer costs and puts them side by side for the question that block answers — who
//             spent the day's range. The three rows above them use only columns 0–2 and leave
//             column 3 unwritten, so they end ragged instead of trailing empty boxes.
//
//             On a symbol with no volume feed the Cum RVOL and VWAP value cells read
//             "No volume data available" instead. The other rows are pure price and keep working,
//             which is why this does NOT blank the whole table the way the debug table's
//             noVolData branch does.
//
//             The two standalone rows use words rather than symbols ("above", "falling") so they
//             describe themselves without needing headers of their own — an arrow next to VWAP
//             would be ambiguous between "price above VWAP" and "VWAP rising".
//
//             The host gates the call on its show toggle, a non-na table and barstate.islast;
//             the internal guard is kept as defence. islast, not isconfirmed: this is a live
//             environment read and immediacy is the point, matching the status table.
//             THE TWO M11-3 ROWS ARE NOT MEASUREMENTS OF THIS BAR, and each is here for its own
//             reason. The roll-up is a fleet view — how many signals are live and at which rungs —
//             which is the one participation question no per-signal label can answer. The
//             tracking row is CONFIGURATION: the verdict target and the cutoff are inputs,
//             identical on every signal, and changing either recalculates the whole script, so no
//             signal can diverge from what this row shows. Repeating them on every signal's
//             tooltip would cost characters on the surface §7.6.2 is trying to keep short.
// @param t      The participation table (host-owned; created via table.new).
// @param c      Styling, inherited from the host's status-table controls.
// @param p      The producer state this library filled in.
// @param states The live signal states, for the roll-up row. Read only — the prune belongs to
//               render(), which the host calls above this.
export renderParticipation(table t, ParticipationConfig c, ParState p,
     array<ParticipationState> states) =>
    if c.show and not na(t) and barstate.islast
        // The pad rows carry the panel background rather than a transparent one, which was the
        // first attempt. table.cell() has NO border parameters — border_color and border_width are
        // set once on table.new and applied to every cell — so a transparent background does not
        // produce an invisible row, it produces four empty bordered boxes floating above the
        // panel. There is no per-cell override, so the choice is between that and blank rows that
        // match the rest of the table. The blank rows win: they read as padding inside the panel,
        // and the cost is only that the strip covers the chart legend behind it instead of letting
        // it show through. The legend's TEXT is what had to be cleared, and it is.
        //
        // Written per branch rather than once above them, because the not-live message is a single
        // centred column and a four-column pad above it would advertise columns that never fill.
        // writePad returns its row count, which is the content origin for everything below.
        if not p.live
            table.clear(t, 0, 0, parTableCols() - 1, parTableRows(c.vertOffset) - 1)
            int _r0 = writePad(t, c, false)
            table.cell(t, 0, _r0, "Participation needs an intraday timeframe.", text_color = c.txtColor,
                 bgcolor = c.bgColor, text_size = c.txtSize, text_halign = text.align_center)
        else
            int _r0 = writePad(t, c, true)
            // ta.vwap returns NaN on a symbol with no volume feed rather than raising (verified on
            // TradingView 2026-08-01), so na here means exactly one thing at the live edge and the
            // row can say so. Same for cumRVOL: it is na when no bucket ever accumulated volume.
            //
            // Known limitation, accepted: cumRVOL is ALSO na during the first session of loaded
            // history, so scrubbing replay to the very start — or loading a freshly listed symbol
            // — will show this message on an instrument that does have volume. Not worth a second
            // message, because the table renders on barstate.islast and the live edge is hundreds
            // of sessions past warm-up on any normal chart.
            string _vwapSide  = na(p.vwap) ? NO_VOL_MSG : close > p.vwap ? "above" : close < p.vwap ? "below" : "at"
            string _vwapTrend = na(p.vwap) ? "" : na(p.vwapSlope) ? "—" :
                 p.vwapSlope > 0 ? "rising" : p.vwapSlope < 0 ? "falling" : "flat"
            string _cumRvolTxt = na(p.cumRvol) ? NO_VOL_MSG : fmtRatio(p.cumRvol)
            string _adrTxt     = na(p.adr) ? "—" : "ADR " + str.tostring(p.adr, format.mintick)
 
            [_extA, _effA] = sessCells(array.get(p.sess, 0), p.sessOpen)
            [_extL, _effL] = sessCells(array.get(p.sess, 1), p.sessOpen)
            [_extN, _effN] = sessCells(array.get(p.sess, 2), p.sessOpen)
 
            // The first three content rows use only three columns; the fourth is written empty so
            // the panel stays a rectangle (see writeRow). Rows are relative to _r0, the pad's
            // height — they are NOT fixed indices any more.
            writeRow(t, _r0,     "Cum RVOL",   _cumRvolTxt,                "",         "",         c.txtColor, c.bgColor,    c.txtSize)
            writeRow(t, _r0 + 1, "Day range",  fmtPct(p.dayUsed) + " ADR", _adrTxt,    "",         c.txtColor, c.bgColor,    c.txtSize)
            writeRow(t, _r0 + 2, "VWAP",       _vwapSide,                  _vwapTrend, "",         c.txtColor, c.bgColor,    c.txtSize)
            // Session block — one column per session, so the three read side by side.
            writeRow(t, _r0 + 3, "",           "Asia",                     "London",   "New York", c.txtColor, c.hdrBgColor, c.txtSize)
            writeRow(t, _r0 + 4, "Rng % ADR",  _extA,                      _extL,      _extN,      c.txtColor, c.bgColor,    c.txtSize)
            writeRow(t, _r0 + 5, "Efficiency", _effA,                      _effL,      _effN,      c.txtColor, c.bgColor,    c.txtSize)
            // ── M11-3: the engine's own two rows. Both follow the first three rows' shape —
            // label in column 0, value(s) after it, the unused columns written EMPTY rather than
            // left untouched, because an unwritten cell renders as nothing at all (see writeRow).
            writeRow(t, _r0 + 6, "Live",       rollUp(states),             "",         "",         c.txtColor, c.bgColor,    c.txtSize)
            writeRow(t, _r0 + 7, "Tracking",   "to " + p.cfgTgtName,
                 str.tostring(p.cfgCutoffHours) + "h cutoff", "", c.txtColor, c.bgColor, c.txtSize)

← 返回列表