From 807e461b349b07a1ea7bc0c6114e08f63745efd5 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:45:56 -0500 Subject: [PATCH 01/61] refactor(quality): runQualityDelta in named phases, one row model for XML and JSON GE-RUNQD (#4 on the 5df5a26be tangle census, S 19.2): split computing the --quality-delta answer from rendering it, byte-identical output. - QdJudged + judgeQualityDelta: the scope partition and the ack ratchet. - runQualityAckWrite: the --quality-ack arm as named steps (ackOnlySelects, discloseAckBackfill, acceptFinding, refuseUnmatchedAckOnly, writeAcceptedAcks) instead of a lambda and loop nested five deep. - QdReport + qdReportOf: every count and root disclosure, computed once, in the order their stderr lines have always printed; exitCode() names the exit decision that was written at four return sites. - QdRowModel: each row's shape, display symbol, gating, facet name and origin decided once; emitQdXmlRow and emitQdJsonRow render it, and the in-scope and out-of-scope halves share one row loop per format. - emitQualityDeltaJson / emitQualityDeltaXml (+ emitQdXmlDocument, emitQdVerdict, qdStaleCollapse, qdNothingElseToDisclose) render it. Co-Authored-By: Claude Opus 5.5 --- src/verbs_quality.h | 1588 +++++++++++++++++++++++-------------------- 1 file changed, 864 insertions(+), 724 deletions(-) diff --git a/src/verbs_quality.h b/src/verbs_quality.h index d0b6186af..c730c16e4 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -2584,749 +2584,889 @@ inline std::string presentXmlAttr( std::string_view name, const std::string& v, return v.empty() ? std::string() : " " + std::string( name ) + "=\"" + esc( v ) + "\""; } -std::optional runQualityDelta( const MainDispatch& d ) +// ── --quality-delta, in three phases: JUDGE (scope partition + ack ratchet), then either WRITE ACKS or REPORT ────────── +// GE-RUNQD: runQualityDelta used to compute the answer and render it in one 744-line body, with the JSON and XML row +// emitters written twice inside it. The phases are now named functions over two small state structs — QdJudged (the +// comparison after the partition and the ratchet) and QdReport (everything a rendering reads) — and one row model +// (QdRowModel) decides each row's printed facts once for both formats. + +// The comparison once the scope partition and the ack ratchet ran: what the --quality-ack writer and the report both read. +// `refs` owns both materialized trees' teardown and must outlive every read of basis.regs (DeltaBasis's header states that +// rule, and why every path and symbol downstream is spelled against basis.deltaRoot rather than against `root`). +struct QdJudged +{ + const rw::Config& cfg; + const std::string& root; + RefPairDelta& refs; + DeltaBasis& basis; + const bool refPair; + const rw::IngestResult& judged; // the JUDGED tree's index: tree B in the ref-pair form, else the working tree + const rw::Graph& workingGraph; // the working tree's graph: the bare form's stale-ack snapshot reads it + rw::quality::Scope scope; + std::vector outOfScope; + std::vector foreignAcks; + std::size_t diffFileCount = 0; // P1.2: 0 = the reserved diff token was not used + std::size_t scopedOutGating = 0; + std::size_t ackedCount = 0; +}; + +// JUDGE — the scope partition, then the per-finding ack ratchet, over the delta resolveDeltaBasis computed. Returns the +// refusal's exit code when the scope cannot be used. +std::optional judgeQualityDelta( QdJudged& j ) { using namespace rw; - const Config& cfg = d.cfg; - const IngestResult& ing = d.ing; - const Graph& g = d.g; - const std::string& root = d.root; - - // --quality-baseline / --quality-delta (the convergence-loop oracle): snapshot ccx + clone groups + dead - // candidates to .ripwire_quality_baseline; then report ONLY what a change made WORSE vs it. The "delta not - // absolute" discipline — a refine loop targets the regression it introduced, not absolute numbers (the - // defense against metric-gaming). exit 2 if any new debt, like --arch. - if( cfg.qualityBaseline || cfg.qualityDelta ) - { - // D1 fix (HIGH): resolve BOTH sidecars against the analyzed ROOT, not the process CWD — - // see quality::rootQualifiedSidecar's comment for why a bare relative filename is unsafe here - // (a foreign cwd's sidecar could be silently rewritten, or even deleted by the stale-baseline - // self-heal below). Computed once; every read/write/remove site in this block uses it. - const std::string baselineFile = quality::baselinePath( root ); - const std::string acksFile = quality::acksPath( root ); - - if( cfg.qualityBaseline ) - { - return runQualityBaselinePin( d, baselineFile, acksFile ); - } + std::vector& regs = j.basis.regs; + // ── P1 SCOPE — the OWNERSHIP partition for a working tree with several writers in it ───────────── + j.scope = quality::parseScope( j.cfg.qualityScope ); + if( const std::optional refused = expandScopeDiff( j.scope, j.refPair, j.judged, j.root, j.basis.deltaRoot, j.diffFileCount ) ) + { + return refused; + } + if( const std::optional refused = refuseUnusableScope( j.cfg, j.scope, j.judged, j.basis.deltaRoot, j.refs.scopeFiles() ) ) + { + return refused; + } + + // Signal-to-noise round — the per-finding ACK RATCHET. Suppress findings already accepted (with a + // reason) in .ripwire_quality_acks, honestly (acked="N"); a finding that WORSENED past its acked + // magnitude survives the filter and reappears. --quality-ack merges the currently-VISIBLE findings + // into that file instead of printing the report (accepting what previous acks already hid would be + // a silent blanket ack — only what the agent can see right now is what it can accept). + // R1 IDENTITY: the ledger was read and HEALED inside resolveDeltaBasis (it had to be — the baseline + // half of the same healing has to precede computeDelta), so this arm takes the already-current map + // rather than re-reading the file and undoing it. + gtl::btree_map& acks = j.basis.acks; + quality::countAckRescues( regs, acks, j.basis.healing.ackRemap, j.basis.healing.ackedByRename, j.basis.healing.ackedByContent ); + // P1.4 PROVENANCE — the foreign-ack sweep reads the PRE-ratchet list on purpose (computeForeignAcks' + // header states why: the question is about acks that are suppressing something right now). + j.foreignAcks = quality::computeForeignAcks( regs, acks ); + // P1 — the partition runs BEFORE the ratchet so acked="N" counts THIS scope's suppressions rather + // than the whole tree's (partitionByScope owns the rest of the rule). + j.scopedOutGating = partitionByScope( j.scope, regs, j.outOfScope, acks ); + j.ackedCount = quality::applyAckRatchet( regs, acks ); + return std::nullopt; +} - // Precedence for the baseline: (1) an explicit `.ripwire_quality_baseline` sidecar (from - // --quality-baseline) wins whenever it is pinned at the CURRENT HEAD — the mid-task convergence loop - // (baseline once, edit, re-check) is unchanged; (2) else — no sidecar, or a STALE one (see R3 below) — - // if the root is a git repo with a HEAD tree, auto-baseline against HEAD so the "before I push" loop - // works with no start-of-task ritual (T0.1); (3) else degrade to the exit-1 "run --quality-baseline - // first" guidance (non-git / unborn / detached-no-tree — unchanged). - // - // STALENESS + the self-heal now live in ONE place, quality::selectBaseline — R3 owner ruling - // (2026-07-29): a sidecar whose pinned sha != the CURRENT HEAD sha is STALE, full stop. The B10.1b - // "reachable ancestor is a deliberately-pinned floor" carve-out this arm used to apply (gitIsAncestor) - // is REVOKED: a parallel session's sidecar pinned at a commit that merely happened to be an ancestor of - // this session's HEAD made THIS arm report 31 phantom regressions while the MCP quality_delta verb — - // same binary, same repo, same second — correctly reported zero. That divergence was only possible - // because each arm carried its own copy of the test; there is now exactly one, in quality.h. - // - // What remains this arm's own POLICY is the `removeStaleFile=true` argument: the stale sidecar is - // silently UNLINKED (best-effort) so the NEXT run sees no file at all rather than rediscovering the - // same dead pin, and the ONLY record is the `baseline=` XML attribute ("git-HEAD (stale sidecar - // removed)") — no stderr spam, which is the B10.1b noise fix that survives the ruling intact. The - // read-only MCP arm passes false and reports "…ignored" instead. When the unlink FAILS (read-only - // parent dir) this arm degrades to the read-only story — marker "…ignored", one DISCLOSE - // from the seam — because the pin is still on disk; `baseSel.isStaleFileOnDisk()` is the fact, and the - // fatal message below words itself from it rather than from the intent. - // `refs` is declared HERE because it owns both materialized trees' teardown and they must outlive - // every read of `regs` (DeltaBasis's header states that rule, and why the emitters below spell every - // path and symbol against basis.deltaRoot rather than against `root`). - // F-04 (round-4 audit) — SERIALIZE THE ACK LEDGER'S READ-MODIFY-WRITE, cross-process. - // - // --quality-ack reads the whole ledger (inside resolveDeltaBasis just below — the heal has to happen - // before computeDelta), folds this run's accepted findings into that map, then rewrites the file from - // it. Nothing serialized that. Three sessions acking DISJOINT rows in one shared checkout — the exact - // scenario --scope exists for — lost two of the three acks on 8 of 8 measured runs, because whichever - // process rewrote last overwrote a map the other two had already published into. - // - // The lock therefore has to span the READ as well as the write, which is why it is taken HERE and not - // inside writeAckRecords: a lock held only around the final rewrite still lets two processes read the - // same stale map first and then take turns clobbering. Engaged ONLY under --quality-ack — a read-only - // --quality-delta never waits, never creates the lockfile, and is byte-for-byte the run it always was. - // RAII: released when this function returns, on every path including the refusals below. quality.h's - // SidecarWriteLock has the lockfile's location (per-user cache dir, never a repo-tree sidecar), the - // wait budget, and the honest limits. - std::optional ackLock; - if( cfg.qualityAck ) +// --ack-only=SUBSTR[,SUBSTR]: ack a SUBSET instead of everything on screen. Without it, the only way to accept one +// deliberate contract change was to accept the whole report — which is how a ratchet quietly becomes a rubber stamp. A +// finding matches if a pattern occurs in its kind, its canonical id or its FACET (so "api-surface", "src/quality.h", one +// exact id, or "format-arity" all work). The facet is what makes this precise enough to be honest: "api-surface" also +// covers the never-gating new-symbol rows, so acking by kind would sweep in 59 findings to accept 8; +// --ack-only=contract-change accepts exactly the deliberate ones. The pseudo-token "gating" selects whatever would +// actually exit 2. +// P1: `inScope` is a parameter because the predicate is asked about BOTH halves of the partition — once to choose what to +// write, once to detect an ack selection that NAMES a row belonging to someone else. It is also what keeps `gating` honest +// under a scope: an out-of-scope row does not gate, so `gating` must not select it. +bool ackOnlySelects( std::string_view ackOnly, const rw::quality::Regression& r, bool inScope ) +{ + if( ackOnly.empty() ) + { + return true; + } + const bool gates = rw::quality::rowGates( r ) && inScope; + const auto patternSelects = [ & ]( std::string_view pat ) + { + return !pat.empty() && ( r.kind.find( pat ) != std::string::npos || r.sym.find( pat ) != std::string::npos + || ( !r.facet.empty() && r.facet.find( pat ) != std::string::npos ) || ( pat == "gating" && gates ) ); + }; + for( std::string_view rest = ackOnly; !rest.empty(); ) + { + const std::size_t comma = rest.find( ',' ); + if( patternSelects( rest.substr( 0, comma ) ) ) { - ackLock.emplace( acksFile ); + return true; } + rest = comma == std::string_view::npos ? std::string_view() : rest.substr( comma + 1 ); + } + return false; +} - const bool refPair = !cfg.qualityDeltaRange.empty(); - RefPairDelta refs; - DeltaBasis basis; - if( const std::optional refused = applyKindSelector( cfg, refs ) ) - { - return refused; - } - if( const std::optional refused = resolveDeltaBasis( d, baselineFile, refs, basis ) ) - { - return refused; - } - const quality::BaselineSelection& baseSel = basis.baseSel; - const std::string& deltaRoot = basis.deltaRoot; - std::vector& regs = basis.regs; - - // ── P1 SCOPE — the OWNERSHIP partition for a working tree with several writers in it ───────────── - quality::Scope scope = quality::parseScope( cfg.qualityScope ); - std::vector outOfScope; - std::size_t diffFileCount = 0; // P1.2: 0 = the reserved diff token was not used - const IngestResult& judged = refPair ? refs.target().ing : ing; - if( const std::optional refused = expandScopeDiff( scope, refPair, judged, root, deltaRoot, diffFileCount ) ) - { - return refused; - } - if( const std::optional refused = refuseUnusableScope( cfg, scope, judged, deltaRoot, refs.scopeFiles() ) ) - { - return refused; - } +// THE LEGACY-ACK BACKFILL's disclosure. A reconstructed row is a weaker claim than a measured one, so a reader is told how +// many rows just changed confidence class and how many could not be healed at all. The unresolved count is a FLOOR on +// what is missing, not a total of what is wrong: a member set that no longer clones in THIS tree is unanswerable here, +// not proven gone. Silent when the backfill touched nothing. +void discloseAckBackfill( const rw::quality::AckBackfill& backfilled ) +{ + if( backfilled.resolved == 0 && backfilled.refreshed == 0 && backfilled.unverified == 0 && backfilled.unresolved == 0 ) + { + return; + } + rw::emitTo( stderr, "ripwire: ack provenance backfill — {} clone row(s) reconstructed from the current tree, {} re-derived, {} left UNVERIFIED (their group was not found here — a floor, not proof it is gone), " + "{} left legacy (member set not found cloning here — a floor, not proof it is gone), {} ineligible (no current-tree fact answers their kind), {} already measured (left alone). " + "prov=recon is what the idiom is NOW, as of the last run that could check it — not what was measured when the row was accepted.\n", + backfilled.resolved, backfilled.refreshed, backfilled.unverified, backfilled.unresolved, backfilled.ineligible, backfilled.measured ); +} - // Signal-to-noise round — the per-finding ACK RATCHET. Suppress findings already accepted (with a - // reason) in .ripwire_quality_acks, honestly (acked="N"); a finding that WORSENED past its acked - // magnitude survives the filter and reappears. --quality-ack merges the currently-VISIBLE findings - // into that file instead of printing the report (accepting what previous acks already hid would be - // a silent blanket ack — only what the agent can see right now is what it can accept). - // R1 IDENTITY: the ledger was read and HEALED inside resolveDeltaBasis (it had to be — the baseline - // half of the same healing has to precede computeDelta), so this arm takes the already-current map - // rather than re-reading the file and undoing it. - gtl::btree_map& acks = basis.acks; - quality::countAckRescues( regs, acks, basis.healing.ackRemap, - basis.healing.ackedByRename, basis.healing.ackedByContent ); - // P1.4 PROVENANCE — the foreign-ack sweep reads the PRE-ratchet list on purpose (computeForeignAcks' - // header states why: the question is about acks that are suppressing something right now). - const std::vector foreignAcks = quality::computeForeignAcks( regs, acks ); - // P1 — the partition runs BEFORE the ratchet so acked="N" counts THIS scope's suppressions rather - // than the whole tree's (partitionByScope owns the rest of the rule). - const std::size_t scopedOutGating = partitionByScope( scope, regs, outOfScope, acks ); - const std::size_t ackedCount = quality::applyAckRatchet( regs, acks ); - if( cfg.qualityAck ) - { - // --ack-only=SUBSTR[,SUBSTR]: ack a SUBSET instead of everything on screen. Without it, the only - // way to accept one deliberate contract change was to accept the whole report — which is how a - // ratchet quietly becomes a rubber stamp. A finding matches if a substring occurs in its kind or - // in its canonical id (so "api-surface", "src/quality.h", or one exact id all work). - // P1: `inScope` is a parameter rather than a capture because this predicate is asked about BOTH - // halves of the partition — once to choose what to write, once to detect an ack selection that - // NAMES a row belonging to someone else. It is also what keeps the `gating` pseudo-token honest - // under a scope: an out-of-scope row does not gate, so `gating` must not select it. - const auto ackSelected = [ & ]( const quality::Regression& r, bool inScope ) -> bool - { - if( cfg.qualityAckOnly.empty() ) - { - return true; - } - std::string_view rest = cfg.qualityAckOnly; - while( !rest.empty() ) - { - const std::size_t comma = rest.find( ',' ); - const std::string_view pat = rest.substr( 0, comma ); - // kind, canonical id, or FACET. The facet is what makes this precise enough to be honest: - // "api-surface" also covers the never-gating new-symbol rows, so acking by kind would - // sweep in 59 findings to accept 8. --ack-only=contract-change accepts exactly the - // deliberate ones. The pseudo-token "gating" selects whatever would actually exit 2. - const bool gates = quality::rowGates( r ) && inScope; - if( !pat.empty() && ( r.kind.find( pat ) != std::string::npos || r.sym.find( pat ) != std::string::npos || ( !r.facet.empty() && r.facet.find( pat ) != std::string::npos ) || ( pat == "gating" && gates ) ) ) - { - return true; - } - if( comma == std::string_view::npos ) - { - break; - } - rest = rest.substr( comma + 1 ); - } - return false; - }; +// Fold ONE accepted finding into the ack ledger `j.basis.acks`, then prove the re-score formula agrees with the live one. +void acceptFinding( QdJudged& j, const rw::quality::Regression& r ) +{ + using namespace rw; + // P0.3: the ack IDENTITY is ackKindToken, not the bare kind — a zero-magnitude finding + // (was==now==0: dead-code, api-surface tier A) acks per ORIGIN, so acking the never-gating + // new-symbol row can no longer blank-check the gating contract-change row on the same symbol. + const std::string ackKind = quality::ackKindToken( r ); + quality::AckRecord& rec = j.basis.acks[ quality::ackMapKey( ackKind, r.key ) ]; + // R1 IDENTITY: stamp the finding's SCRUBBED CONTENT ID alongside the key, so this ack can + // still be found after a move git records no rename for. Absent (0) for the two clone kinds — + // their key is a member-SET hash with no single body behind it — and the row is then written + // exactly as it is today. A REFRESH, not a preserve: re-acking a finding re-reads the body, so + // the stored cid always describes the code as accepted, never as it was two edits ago. + const auto cidIt = j.basis.healing.cids.cidByKey.find( r.key ); + const std::uint64_t cid = ( cidIt == j.basis.healing.cids.cidByKey.end() ) ? 0u : cidIt->second; + // P1.4 PROVENANCE: `by` follows the SAME rule the reason does one line down — set from this + // run when this run supplies one, PRESERVED otherwise. A later scope-less re-ack therefore + // refreshes the magnitude without erasing the record of who accepted the row originally, + // which is the only reading under which the foreign-ack sweep means anything. + // REASON CLOBBER FIX (round 2026-08-29): a re-ack that supplies a DIFFERENT reason no longer + // overwrites the row's existing one outright — composeAckReason folds it in as + // " | prior: " (capped at one hop; a no-op when the reason is unchanged), so a + // shared row re-acked by unrelated sessions keeps both justifications instead of the last + // writer silently erasing the one before it. See quality.h's composeAckReason for the rule. + // RE-SCORE PROVENANCE: was/now/facet/path/line are a REFRESH, not a preserve, same posture as + // cid= above — a re-ack re-reads the finding, so the stored triple always describes the row AS + // JUST ACCEPTED, never as it was some earlier run. See AckRecord's doc comment for what each + // one is and why a later run can re-score from them alone. + rec = quality::AckRecord{ ackKind, r.key, std::max( rec.ackNow, r.now ), cid, + j.scope.active() ? j.scope.spec : rec.by, + r.was, r.now, r.facet, r.path, r.line, quality::AckProvenance::Measured, + j.cfg.qualityAckReason.empty() ? rec.reason + : quality::composeAckReason( rec.reason, std::string( j.cfg.qualityAckReason ) ) }; + // SELF-CHECK, not a one-off test: every magnitude-bearing ack proves that the TABLE-DRIVEN + // re-score formula agrees with the LIVE one on the row it just built. NOT a full round trip — + // rescoreAckRecord runs here on the in-memory `rec` directly; it never goes through + // renderAckRecords/readAckRecords, so this does not exercise the ledger's text grammar (order- + // tolerant token parsing, splitAckLocator, the takeAckNamedToken family) at all — that half of + // the contract is what qackconcurrencycheck.sh's grammar arm (2) and byte-identity arm (7) pin + // instead, over the actual file. What THIS catches: rescoreNumericMajor's kMaterialityBars + // lookup (by kind name) silently drifting from the kMaterialityBars row perSymbolKind is handed + // by index (computeDelta; the static_assert beside the table pins the order) — two ways + // to reach the same constants that a future edit could break in only one place. A drift there means the live + // formula (numericRegressionIsMajor, via perSymbolKind) and the re-score formula + // (rescoreNumericMajor) have silently diverged — see quality.h's MaterialityBar table, the one + // place both are meant to agree. ENSURES, not ASSUME: this is this function's OWN postcondition + // on the row it just built, not a fact something else already guarantees. + const std::optional rescored = quality::rescoreAckRecord( rec ); + const bool rescoreAgrees = !rescored.has_value() || *rescored == !r.isMinor; // plain bool, so the promise below is a bare accessor-free read + ENSURES( rescoreAgrees, + "ack provenance re-score (in-memory, not a ledger round trip) must reproduce the just-computed severity" ); +} - // P1 — THE RUBBER-STAMP GUARD (refuseForeignAckSelection owns the rule and the message). - if( const std::optional refused = refuseForeignAckSelection( cfg, scope, outOfScope, deltaRoot, ackSelected ) ) - { - return refused; - } +// An --ack-only that matched NO finding: refused with exit 1, and nothing accepted. +// M1 FOLLOW-UP (round train-18, rv-ack-provenance-backfill.md): this refusal used to discard the backfill unconditionally — +// `backfillCloneAckProvenance` already mutated `acks` in memory, but returning without ever calling writeAckRecords threw +// that healing away, so a rubber-stamp-guarded --ack-only that (correctly) refused to accept anything ALSO silently un-did +// an otherwise-independent repair to the ledger's provenance. Same canonical-bytes rule H10's ackNothingToAccept applies +// when there is nothing to accept at all: a ledger already equal to its own canonical bytes is left untouched (no spurious +// diff); a non-canonical one — including one this run's backfill just healed — is rewritten and the run says so. This +// never accepts a finding and the refusal's exit code is unchanged. +int refuseUnmatchedAckOnly( std::string_view ackOnly, const std::string& acksFile, + const gtl::btree_map& acks, std::size_t findingCount ) +{ + using namespace rw; + const bool nonCanonical = !acks.empty() + && quality::renderAckRecords( acks ) != docparse::detail::readRegularFile( "the quality-acks ledger", acksFile ).value_or( std::string() ); + if( !nonCanonical ) + { + rw::emitTo( stderr, "ripwire: --ack-only={} matched none of the {} finding(s) — nothing written\n", ackOnly, findingCount ); + return 1; + } + // A failed heal is said, not folded into "nothing written" (CodeRabbit on #331): the same "could not write" + // ackNothingToAccept prints for the same failure. writeAckRecords has already DISCLOSEd on its answerRefused sink; the + // exit code is 1 either way. + if( !quality::writeAckRecords( acksFile, acks ) ) + { + rw::emitTo( stderr, "ripwire: --ack-only={} matched none of the {} finding(s) — nothing accepted; could not write {} " + "(it was not in canonical form, and re-serialising it failed)\n", + ackOnly, findingCount, acksFile.c_str() ); + return 1; + } + rw::emitTo( stderr, "ripwire: --ack-only={} matched none of the {} finding(s) — nothing accepted, but {} was not in canonical form " + "(ack provenance backfill / legacy rows) and has been re-serialised\n", + ackOnly, findingCount, acksFile.c_str() ); + return 1; +} - // THE LEGACY-ACK BACKFILL, run on the map this process already holds the write lock over and - // BEFORE this run's own acks are folded in, so a row healed here can still be overwritten by a - // live measurement of the same finding in the loop below — measured always beats reconstructed, - // and ordering is what guarantees it rather than a check. It runs even when this run accepts - // NOTHING: healing the ledger's provenance is the same class of forward repair the identity - // remap already performs on every ack, and H10's ackNothingToAccept re-renders and notices. - // quality::backfillCloneAckProvenance owns the rule, what it refuses to touch, and why. - const quality::AckBackfill backfilled = quality::backfillCloneAckProvenance( acks, basis.cloneIdioms ); - // DISCLOSED, never silent: a reconstructed row is a weaker claim than a measured one, so a reader - // is told how many rows just changed confidence class and how many could not be healed at all. - // The unresolved count is a FLOOR on what is missing, not a total of what is wrong: a member set - // that no longer clones in THIS tree is unanswerable here, not proven gone. - if( backfilled.resolved > 0 || backfilled.refreshed > 0 || backfilled.unverified > 0 || backfilled.unresolved > 0 ) - { - rw::emitTo( stderr, "ripwire: ack provenance backfill — {} clone row(s) reconstructed from the current tree, {} re-derived, {} left UNVERIFIED (their group was not found here — a floor, not proof it is gone), " - "{} left legacy (member set not found cloning here — a floor, not proof it is gone), {} ineligible (no current-tree fact answers their kind), {} already measured (left alone). " - "prov=recon is what the idiom is NOW, as of the last run that could check it — not what was measured when the row was accepted.\n", - backfilled.resolved, backfilled.refreshed, backfilled.unverified, backfilled.unresolved, backfilled.ineligible, backfilled.measured ); - } +// Rewrite the ledger with this run's accepted findings and say what was written. Returns the exit code. +int writeAcceptedAcks( const QdJudged& j, const std::string& acksFile, std::size_t ackWritten, std::size_t ackSkipped ) +{ + using namespace rw; + const std::size_t findingCount = j.basis.regs.size(); + const bool wroteAcks = quality::writeAckRecords( acksFile, j.basis.acks ); + if( !wroteAcks ) + { + rw::emitTo( stderr, "ripwire: could not write {}\n", acksFile.c_str() ); + return 1; + } + if( !j.cfg.qualityAckOnly.empty() ) + { + rw::emitTo( stderr, "ripwire: acknowledged {} of {} finding(s) ({} left UNACKED by --ack-only, {} already acked) → {}\n", + ackWritten, findingCount, ackSkipped, j.ackedCount, acksFile.c_str() ); + } + else + { + rw::emitTo( stderr, "ripwire: acknowledged {} finding(s) ({} already acked) → {}\n", findingCount, j.ackedCount, acksFile.c_str() ); + } + // P1 — the skip is DISCLOSED, never silent: the count of rows this ack deliberately did not + // touch is the whole reason the caller passed a scope, and a quiet success would leave them + // believing the ledger now covers the report they were looking at. + if( j.scope.active() && !j.outOfScope.empty() ) + { + rw::emitTo( stderr, "ripwire: {} finding(s) OUT OF SCOPE for --scope={} were left unacked — not yours to accept " + "(they are still in the report, under the out-of-scope element)\n", + j.outOfScope.size(), j.scope.spec.c_str() ); + } + return 0; +} - std::size_t ackWritten = 0, ackSkipped = 0; - for( const quality::Regression& r : regs ) - { - if( !ackSelected( r, /*inScope=*/true ) ) { ++ackSkipped; continue; } - ++ackWritten; - // P0.3: the ack IDENTITY is ackKindToken, not the bare kind — a zero-magnitude finding - // (was==now==0: dead-code, api-surface tier A) acks per ORIGIN, so acking the never-gating - // new-symbol row can no longer blank-check the gating contract-change row on the same symbol. - const std::string ackKind = quality::ackKindToken( r ); - quality::AckRecord& rec = acks[ quality::ackMapKey( ackKind, r.key ) ]; - // R1 IDENTITY: stamp the finding's SCRUBBED CONTENT ID alongside the key, so this ack can - // still be found after a move git records no rename for. Absent (0) for the two clone kinds — - // their key is a member-SET hash with no single body behind it — and the row is then written - // exactly as it is today. A REFRESH, not a preserve: re-acking a finding re-reads the body, so - // the stored cid always describes the code as accepted, never as it was two edits ago. - const auto cidIt = basis.healing.cids.cidByKey.find( r.key ); - const std::uint64_t cid = ( cidIt == basis.healing.cids.cidByKey.end() ) ? 0u : cidIt->second; - // P1.4 PROVENANCE: `by` follows the SAME rule the reason does one line down — set from this - // run when this run supplies one, PRESERVED otherwise. A later scope-less re-ack therefore - // refreshes the magnitude without erasing the record of who accepted the row originally, - // which is the only reading under which the foreign-ack sweep means anything. - // REASON CLOBBER FIX (round 2026-08-29): a re-ack that supplies a DIFFERENT reason no longer - // overwrites the row's existing one outright — composeAckReason folds it in as - // " | prior: " (capped at one hop; a no-op when the reason is unchanged), so a - // shared row re-acked by unrelated sessions keeps both justifications instead of the last - // writer silently erasing the one before it. See quality.h's composeAckReason for the rule. - // RE-SCORE PROVENANCE: was/now/facet/path/line are a REFRESH, not a preserve, same posture as - // cid= above — a re-ack re-reads the finding, so the stored triple always describes the row AS - // JUST ACCEPTED, never as it was some earlier run. See AckRecord's doc comment for what each - // one is and why a later run can re-score from them alone. - rec = quality::AckRecord{ ackKind, r.key, std::max( rec.ackNow, r.now ), cid, - scope.active() ? scope.spec : rec.by, - r.was, r.now, r.facet, r.path, r.line, quality::AckProvenance::Measured, - cfg.qualityAckReason.empty() ? rec.reason - : quality::composeAckReason( rec.reason, std::string( cfg.qualityAckReason ) ) }; - // SELF-CHECK, not a one-off test: every magnitude-bearing ack proves that the TABLE-DRIVEN - // re-score formula agrees with the LIVE one on the row it just built. NOT a full round trip — - // rescoreAckRecord runs here on the in-memory `rec` directly; it never goes through - // renderAckRecords/readAckRecords, so this does not exercise the ledger's text grammar (order- - // tolerant token parsing, splitAckLocator, the takeAckNamedToken family) at all — that half of - // the contract is what qackconcurrencycheck.sh's grammar arm (2) and byte-identity arm (7) pin - // instead, over the actual file. What THIS catches: rescoreNumericMajor's kMaterialityBars - // lookup (by kind name) silently drifting from the kMaterialityBars row perSymbolKind is handed - // by index (computeDelta, above; the static_assert beside the table pins the order) — two ways - // to reach the same constants that a future edit could break in only one place. A drift there means the live - // formula (numericRegressionIsMajor, via perSymbolKind) and the re-score formula - // (rescoreNumericMajor) have silently diverged — see quality.h's MaterialityBar table, the one - // place both are meant to agree. ENSURES, not ASSUME: this is this function's OWN postcondition - // on the row it just built, not a fact something else already guarantees. - const std::optional rescored = quality::rescoreAckRecord( rec ); - const bool rescoreAgrees = !rescored.has_value() || *rescored == !r.isMinor; // plain bool, so the promise below is a bare accessor-free read - ENSURES( rescoreAgrees, - "ack provenance re-score (in-memory, not a ledger round trip) must reproduce the just-computed severity" ); - } - if( ackWritten == 0 && !cfg.qualityAckOnly.empty() ) - { - // M1 FOLLOW-UP (round train-18, rv-ack-provenance-backfill.md): this refusal used to discard - // the backfill above unconditionally — `backfillCloneAckProvenance` already mutated `acks` in - // memory, but returning here without ever calling writeAckRecords threw that healing away, - // so a rubber-stamp-guarded --ack-only that (correctly) refused to accept anything ALSO - // silently un-did an otherwise-independent repair to the ledger's provenance. Same - // canonical-bytes rule H10's ackNothingToAccept applies when there is nothing to accept at - // all: a ledger already equal to its own canonical bytes is left untouched (no spurious - // diff); a non-canonical one — including one this run's backfill just healed — is rewritten - // and the run says so. This never accepts a finding and the refusal's exit code is unchanged. - const bool nonCanonical = !acks.empty() - && quality::renderAckRecords( acks ) != docparse::detail::readRegularFile( "the quality-acks ledger", acksFile ).value_or( std::string() ); - if( nonCanonical ) - { - // A failed heal is said, not folded into "nothing written" (CodeRabbit on #331): the same - // "could not write" ackNothingToAccept prints for the same failure. writeAckRecords has already - // DISCLOSEd on its answerRefused sink; the exit code is 1 either way. - if( !quality::writeAckRecords( acksFile, acks ) ) - { - rw::emitTo( stderr, "ripwire: --ack-only={} matched none of the {} finding(s) — nothing accepted; could not write {} " - "(it was not in canonical form, and re-serialising it failed)\n", - std::string_view( cfg.qualityAckOnly.data(), cfg.qualityAckOnly.size() ), regs.size(), acksFile.c_str() ); - return 1; - } - rw::emitTo( stderr, "ripwire: --ack-only={} matched none of the {} finding(s) — nothing accepted, but {} was not in canonical form " - "(ack provenance backfill / legacy rows) and has been re-serialised\n", - std::string_view( cfg.qualityAckOnly.data(), cfg.qualityAckOnly.size() ), regs.size(), acksFile.c_str() ); - return 1; - } - rw::emitTo( stderr, "ripwire: --ack-only={} matched none of the {} finding(s) — nothing written\n", std::string_view( cfg.qualityAckOnly.data(), cfg.qualityAckOnly.size() ), regs.size() ); - return 1; - } - // H10: nothing to accept — leave a canonical ledger alone, heal a non-canonical one (ackNothingToAccept) - if( regs.empty() ) - { - return ackNothingToAccept( acksFile, acks, scope, outOfScope.size() ); - } - const bool wroteAcks = quality::writeAckRecords( acksFile, acks ); - if( wroteAcks && !cfg.qualityAckOnly.empty() ) - { - rw::emitTo( stderr, "ripwire: acknowledged {} of {} finding(s) ({} left UNACKED by --ack-only, {} already acked) → {}\n", - ackWritten, regs.size(), ackSkipped, ackedCount, acksFile.c_str() ); - } - else if( wroteAcks ) - { - rw::emitTo( stderr, "ripwire: acknowledged {} finding(s) ({} already acked) → {}\n", - regs.size(), ackedCount, acksFile.c_str() ); - } - else - { - rw::emitTo( stderr, "ripwire: could not write {}\n", acksFile.c_str() ); - } - // P1 — the skip is DISCLOSED, never silent: the count of rows this ack deliberately did not - // touch is the whole reason the caller passed a scope, and a quiet success would leave them - // believing the ledger now covers the report they were looking at. - if( wroteAcks && scope.active() && !outOfScope.empty() ) - { - rw::emitTo( stderr, "ripwire: {} finding(s) OUT OF SCOPE for --scope={} were left unacked — not yours to accept " - "(they are still in the report, under the out-of-scope element)\n", - outOfScope.size(), scope.spec.c_str() ); - } - return wroteAcks ? 0 : 1; - } +// WRITE ACKS — the --quality-ack arm: fold the VISIBLE findings --ack-only selects into the ledger instead of printing the +// report. Returns the exit code. +int runQualityAckWrite( QdJudged& j, const std::string& acksFile ) +{ + using namespace rw; + const std::string_view ackOnly = j.cfg.qualityAckOnly; + const auto selected = [ & ]( const quality::Regression& r, bool inScope ) { return ackOnlySelects( ackOnly, r, inScope ); }; - // L2 — stale-ack disclosure (rationale: quality.h's computeStaleAcks). Checked against the CURRENT - // tree, not the baseline above, so it costs one more computeSnapshot; skipped when the ledger is - // empty. Reported, never gated — the exit code below reads `regs` alone. - // R-I: "the CURRENT tree" is the JUDGED tree, which in the ref-pair form is tree B — checking the - // ledger against the working tree there would report acks as stale because of edits that have nothing - // to do with the comparison being made. - // qd-memory-degrade: refPairStaleAcks owns the two range-form departures (a changed-files answer judges none; a - // kind selection judges its own kinds' acks only). - const std::vector staleAcks = acks.empty() ? std::vector{} - : refPair ? refPairStaleAcks( acks, refs ) - : quality::computeStaleAcks( acks, quality::computeSnapshot( ing, g, cfg.rootPath, nullptr, {}, &basis.passes ) ); - if( std::getenv( "RIPWIRE_STATS" ) ) // QD-ENVOY-TIME cost bound: Type-3 passes this call ran (test/qdtype3oncecheck.sh) - { - rw::emitTo( stderr, "ripwire: quality-passes type3_runs={} type3_pairs={}\n", gType3PassRuns.load( std::memory_order_relaxed ), - gType3PassPairs.load( std::memory_order_relaxed ) ); - } + // P1 — THE RUBBER-STAMP GUARD (refuseForeignAckSelection owns the rule and the message). + if( const std::optional refused = refuseForeignAckSelection( j.cfg, j.scope, j.outOfScope, j.basis.deltaRoot, selected ) ) + { + return *refused; + } - // P1.4 — the family now carries THREE whys, and the third is counted SEPARATELY: stale= means - // "this ack no longer applies", and a foreign ack applies fine — it is the SESSION that was wrong, - // not the target. Merging the rows into one list keeps the two emitters from growing a second loop - // each; keeping the COUNTS apart keeps stale= meaning what it has always meant. - std::vector saRows = staleAcks; - saRows.insert( saRows.end(), foreignAcks.begin(), foreignAcks.end() ); - // M21(a): name the rows the tree can still name, against the SAME tree computeStaleAcks judged - // (tree B in the ref-pair form) — naming a stale ack after the working tree would print an identity - // the verdict was never computed from. Costs one walk over ing.symbols, and only when there are rows. - quality::stampStaleAckIdentity( saRows, refPair ? refs.target().ing : ing, - refPair ? std::string_view( refs.target().root ) : std::string_view( cfg.rootPath ) ); - - // r26 ORIGIN SPLIT — three counts over the VISIBLE (post-ack) findings, one pass: - // minorCount — the materiality tier (unchanged axis). - // newSymbolCount — findings that exist only because the code is NEW (quality.h's origin axis). - // gatingCount — the EXIT PREDICATE (quality::rowGates): major AND preexisting-worse, or a defect-shape - // format-arity row of any origin. Emitted as gating= so the header alone tells you - // the exit code (it used to be "regressions > minor"). - // preexisting-worse = regressions − new-symbol by construction (the axis is a partition), so the two - // header counters always sum to regressions= — an invariant the gate asserts. - std::size_t minorCount = 0, newSymbolCount = 0, gatingCount = 0; - for( const quality::Regression& r : regs ) - { - if( r.isMinor ) - { - ++minorCount; - } - if( r.isNewSymbol ) - { - ++newSymbolCount; - } - if( quality::rowGates( r ) ) - { - ++gatingCount; - } - } - const std::size_t preexistingCount = regs.size() - newSymbolCount; - // H11 — the absorbed-debt stamp on the honored sidecar, or 0. Read ONLY when the sidecar is the floor - // in force: on the git-HEAD and ref-pair floors there is no pin whose contents could have absorbed - // anything, and printing a 0 there would define an attribute about a file this run did not use. - const std::size_t baselineAbsorbed = ( baseSel.marker == std::string_view( "sidecar" ) ) - ? quality::readBaselineAbsorbed( baselineFile ) : 0; - const std::string baselineAbsorbedAttr = baselineAbsorbed == 0 ? std::string() - : " baseline_absorbed=\"" + std::to_string( baselineAbsorbed ) + "\""; - - // R1 IDENTITY — the disclosure, built ONCE for both emitters (quality::identityDisclosure). An ack - // that follows a rename is a claim about identity, and a claim is only honest if the reader can see - // what it rested on; building the XML and JSON halves in one place is what keeps the two surfaces - // from disclosing different things about the same run. - const auto [ identityAttrs, identityJson ] = quality::identityDisclosure( basis.healing ); - // hwh-fix4 (N1): the history a gating kind could not read, one builder for every emitter (absent when all was read) - const auto [ historyAttrs, historyJson ] = quality::historyUnreadDisclosure( basis.historyUnread ); - if( gatingCount == 0 && basis.historyUnread.any() ) - { - rw::emitTo( stderr, "ripwire: --quality-delta: not a clean pass - git history a gating kind needs could not be read ({}; a partial clone " - "does not download it), so a gating row may be missing: exit 6\n", historyAttrs.substr( 1 ).c_str() ); - } + // THE LEGACY-ACK BACKFILL, run on the map this process already holds the write lock over and + // BEFORE this run's own acks are folded in, so a row healed here can still be overwritten by a + // live measurement of the same finding in the loop below — measured always beats reconstructed, + // and ordering is what guarantees it rather than a check. It runs even when this run accepts + // NOTHING: healing the ledger's provenance is the same class of forward repair the identity + // remap already performs on every ack, and H10's ackNothingToAccept re-renders and notices. + // quality::backfillCloneAckProvenance owns the rule, what it refuses to touch, and why. + discloseAckBackfill( quality::backfillCloneAckProvenance( j.basis.acks, j.basis.cloneIdioms ) ); - // P1/P1.4 — the scope disclosure, built once for both emitters (quality::scopeDisclosure). - const auto [ scopeAttrs, scopeJson ] = quality::scopeDisclosure( scope, outOfScope.size(), scopedOutGating, foreignAcks.size(), diffFileCount ); - - // F-13 — the .ripwire_config disclosure, built once for both emitters (see the header comment on - // registerMacroConfigWarningAttr just above runQualityViews for why the stderr wording lives there). - // #387: the inert-name test reads the JUDGED tree's index, which in the ref-pair form is tree B — the working tree - // is not indexed there at all (runQualityDeltaRangeBeforeIngest). - // qd-memory-degrade: not over a changed-files index, which cannot tell an inert name from one the tree defines (also_skipped=) - const rw::quality::RegisterMacroConfigDiagnostics configDiag = refs.degraded ? rw::quality::RegisterMacroConfigDiagnostics{} - : rw::quality::diagnoseRegisterMacroConfig( judged, root ); - const std::string configWarnAttr = registerMacroConfigWarningAttr( configDiag ); - // qd-memory-degrade: the kinds this answer did not run, why, and the replay — plus the peak, read once now that the - // comparison is done (kindsDisclosure). Their stderr lines come first: an answer that is partial, or that ran past - // the limit, says so on the channel a human reads before anything else. - const KindsDisclosure kd = kindsDisclosure( cfg, refs, basis, refPair ); - emitMemoryLines( kd, refs ); - const bool deadRan = !refPair || quality::kindSelected( refs.kinds, "dead-code" ); // dead-code's side counts exist only when it ran - - // P2.5 — one stderr line NAMING the gating finding, in --token-budget's style ("ripwire: --token-budget - // exceeded: est_tokens=… > budget=…"). stdout is the machine artifact and a caller that only checks - // `$?` gets a number with no subject; this puts the WHICH on the channel a human reads, without - // touching the XML contract. Names the first gating row in the already-sorted list (deterministic). - // - // §A4 (minor): emitted BEFORE the format fork, not after the XML tail — under --json the fork returned - // first, so exactly the caller most likely to be a script reading `$?` got the bare exit=2 with no - // subject. The line is about the EXIT CODE, which both formats share, so it belongs to neither. - emitQdGatingLine( regs, gatingCount, deltaRoot ); - - // L2: --json — same regressions, keys mirror the XML attr names (kind/sym/members/tokens/was/now/ - // sev/churn/surface). jsonUnsupportedVerb already refused --quality-baseline/--quality-ack, so - // reaching here with cfg.json means the plain --quality-delta report. - if( cfg.json ) + std::size_t ackWritten = 0, ackSkipped = 0; + for( const quality::Regression& r : j.basis.regs ) + { + if( !selected( r, /*inScope=*/true ) ) { - const char* baseMarkerJ = baseSel.marker; // R3: the one spelling table lives in quality::selectBaseline — the XML/JSON twins cannot drift apart - // The JSON sibling of the XML at= anchor — "at":null (never a fake sha) on a non-git root, and - // null in the ref-pair form too: the list was not computed "at" any working-tree state, and the - // two refs below ARE its anchor. - const std::string atValJ = refPair ? std::string{} : gitstamp::stampAt( root ); - const std::string atJsonJ = atValJ.empty() ? std::string( "null" ) : ( "\"" + atValJ + "\"" ); - // R-I: the same two shas + the same unmeasurable-kind disclosure the XML root carries, spelled in - // JSON. Empty for the bare form, so that object stays byte-identical to before. - // F-13: config-warnings is the JSON sibling of the XML config-warnings= attribute — omitted - // (never 0) when .ripwire_config carried nothing to disclose, same "absent means never happened, - // 0 means checked and clean" rule scopeJson/identityJson already follow. - const std::string configWarnJson = configDiag.total() == 0 ? std::string() - : ",\"config-warnings\":" + std::to_string( configDiag.total() ); - // H11: the JSON twin of baseline_absorbed=, under the same absent-means-none rule as the XML half. - const std::string absorbedJson = baselineAbsorbed == 0 ? std::string() - : ",\"baseline_absorbed\":" + std::to_string( baselineAbsorbed ); - // #228: the JSON twin of head_basis=, under the same absent-means-the-ordinary-archived-tree rule. - const std::string headBasisJson = ( basis.headBasis == nullptr ? std::string() - : std::string( ",\"head_basis\":\"" ) + basis.headBasis + "\"" ) - + ( basis.declinedCallExcluded == 0 ? std::string() // the XML twin's declined-call-excluded=, absent at zero - : ",\"declined-call-excluded\":" + std::to_string( basis.declinedCallExcluded ) ) - + rw::countFieldOrEmpty( "value-ref-excluded", basis.valueRefExcluded, /*json=*/true ); - // qd-memory-degrade: stale and register-macro-excluded are absent (never 0) when their pass did not run - const std::string staleJ = refs.degraded ? std::string() : ",\"stale\":" + std::to_string( staleAcks.size() ); - const std::string rmeJ = deadRan ? ",\"register-macro-excluded\":" + std::to_string( basis.registerMacroExcluded ) : std::string(); - rw::emitTo( stdout, "{{\"baseline\":\"{}\",\"regressions\":{},\"minor\":{},\"acked\":{}{}," - "\"preexisting-worse\":{},\"new-symbol\":{},\"gating\":{}{},\"api-new-surface\":{},\"at\":{}{}{}{}{}{}{}{},\"r\":[", - jsonStr( baseMarkerJ ).c_str(), regs.size(), minorCount, ackedCount, staleJ, - preexistingCount, newSymbolCount, gatingCount, rmeJ, basis.apiNewSurface, atJsonJ.c_str(), refs.jsonAttrs.c_str(), - identityJson.c_str(), scopeJson.c_str(), configWarnJson.c_str(), absorbedJson.c_str(), headBasisJson.c_str(), kd.json + historyJson + quality::ratchetAttrsJson( basis.extras ) ); - // P1: one row emitter, called for both halves of the scope partition — the disclosed rows carry - // the identical key set, so nothing about a row changes by being someone else's. `gatingAllowed` - // is the ONE difference: an out-of-scope row is not what the exit code fires on, so claiming - // gating on it would contradict the exit code in the same document. - const auto emitJsonRow = [ & ]( const quality::Regression& r, bool gatingAllowed ) - { - rw::emitTo( stdout, "{{\"kind\":\"{}\"", jsonStr( r.kind ).c_str() ); - if( r.kind == "duplication" ) - { - rw::emitTo( stdout, ",\"members\":\"{}\",\"tokens\":{}", jsonStr( quality::displaySym( r.sym, deltaRoot ) ).c_str(), r.now ); - } - else - { - rw::emitTo( stdout, ",\"sym\":\"{}\"", jsonStr( quality::displaySym( r.sym, deltaRoot ) ).c_str() ); - if( !( r.kind == "dead-code" ) && !( r.kind == "api-surface" && r.was == r.now ) ) - { - rw::emitTo( stdout, ",\"was\":{},\"now\":{}", quality::rowValueText( r, r.was ), quality::rowValueText( r, r.now ) ); - } - } - if( !r.path.empty() ) - { - rw::emitTo( stdout, ",\"p\":\"{}:{}\"", jsonStr( r.path ).c_str(), r.line ); // P2.5 locator - } - if( gatingAllowed && quality::rowGates( r ) ) - { - rw::emitRaw( stdout, ",\"gating\":true" ); // P2.5 — the exit predicate, stated per row - } - if( r.isMinor ) - { - rw::emitRaw( stdout, ",\"sev\":\"minor\"" ); - } - if( !r.facet.empty() ) - { - const char* facetName = quality::facetAttrName( r.kind ); // ONE kind→name table (quality.h) - if( facetName ) - { - rw::emitTo( stdout, ",\"{}\":\"{}\"", facetName, jsonStr( r.facet ).c_str() ); - } - } - if( const char* origin = quality::originValue( r ) ) - { - rw::emitTo( stdout, ",\"origin\":\"{}\"", origin ); // absent = preexisting-worse (mirrors the XML) - } - if( r.ceiling != 0 ) - { - rw::emitTo( stdout, ",\"ceiling\":{}", r.ceiling ); // QD-ENTRY-CEILING (mirrors the XML) - } - rw::emitRaw( stdout, presentJsonMember( "call", r.call ).c_str() ); // QD-UNCHECKED-STATUS (mirrors the XML) - std::fputs( quality::tangleRowAttrs( r, /*json=*/true, []( std::string_view s ) { return jsonStr( s ); } ).c_str(), stdout ); // QD-TANGLE (mirrors the XML) - rw::emitRaw( stdout, "}" ); - }; - bool firstR = true; - for( const quality::Regression& r : regs ) - { - if( !firstR ) - { - rw::emitRaw( stdout, "," ); - } - firstR = false; - emitJsonRow( r, /*gatingAllowed=*/true ); - } - rw::emitRaw( stdout, "]," ); - if( scope.active() ) - { - // The JSON sibling of the XML out-of-scope element: a SEPARATE array, never a flag on a row - // in "r", so a consumer that reads "r" and checks "gating" cannot accidentally count someone - // else's debt as this run's. Emitted (possibly empty) whenever a scope was given, so its - // absence means "no scope", never "no disclosed rows". - rw::emitRaw( stdout, "\"oos\":[" ); - bool firstO = true; - for( const quality::Regression& r : outOfScope ) - { - if( !firstO ) - { - rw::emitRaw( stdout, "," ); - } - firstO = false; - emitJsonRow( r, /*gatingAllowed=*/false ); - } - rw::emitRaw( stdout, "]," ); - } - std::fputs( quality::staleAcksJsonArray( saRows ).c_str(), stdout ); // L2 — "sa":[...], same taxonomy as the XML sa= rows below - std::fputs( quality::improvedJson( basis.extras.improved, deltaRoot ).c_str(), stdout ); // QD-CREDIT-ROW (absent when none) - rw::emitRaw( stdout, "}" ); - return qualityDeltaExit( gatingCount, refs.degraded || basis.historyUnread.any() ); + ++ackSkipped; + continue; } + ++ackWritten; + acceptFinding( j, r ); + } + if( ackWritten == 0 && !ackOnly.empty() ) + { + return refuseUnmatchedAckOnly( ackOnly, acksFile, j.basis.acks, j.basis.regs.size() ); + } + // H10: nothing to accept — leave a canonical ledger alone, heal a non-canonical one (ackNothingToAccept) + if( j.basis.regs.empty() ) + { + return ackNothingToAccept( acksFile, j.basis.acks, j.scope, j.outOfScope.size() ); + } + return writeAcceptedAcks( j, acksFile, ackWritten, ackSkipped ); +} - std::vector esc; - const auto ex = [ & ]( std::string_view s ) -> std::string { return std::string( escapeXml( s, esc ) ); }; - // §B7.1 (CA4) — the heading used to open "only what changed for the WORSE vs - // .ripwire_quality_baseline", which is FALSE in every state but one: three of the five floors this - // verb can use are not that file, and in one of them the file was judged stale and DELETED from the - // user's tree during this very run. The floor actually used is named by baseline= on the element - // below, so the heading points at that attribute instead of asserting a floor. - // - // 2026-09-02 (lane B): the marker states are still defined on the first screen — the only place a - // reader meets them — but ONE state per run, the one in force, rather than all five on every call. - // emitQualityDeltaLegend above holds the section table and the reasoning; it is passed the same - // values the root element below prints, so "the legend defines what the header emits" is read off - // one set of values rather than restated as a second condition that could drift from it. - // idea #11 — THE CLEAN-TREE PAYLOAD. A regression-free answer collapses its stale-ack rows to counts (stale= and - // stale_by_kind=), and stale_next= is the call that prints them; on a tree that IS its HEAD (head_basis="identity": - // the floor is this tree's own snapshot) with nothing else to disclose, the verdict is the whole answer. Foreign- - // scope rows are never collapsed: they are about findings suppressed RIGHT NOW. --show-stale restores today's - // document byte for byte, so every collapsed row and attribute is one flag away (PROCESS rule 5). - const bool collapseStale = regs.empty() && outOfScope.empty() && !cfg.showStale && !staleAcks.empty(); - std::string staleCollapseAttrs; - if( collapseStale ) - { - const std::string kinds = quality::staleByKindValue( staleAcks ); // shared with the MCP twin (lane lean2b) - std::string replay = cfg.qualityDeltaRange.empty() ? std::string( "--quality-delta" ) : rw::nextFlag( "--quality-delta=", cfg.qualityDeltaRange ); - if( scope.active() ) - { - replay += " " + rw::nextFlag( "--scope=", cfg.qualityScope ); - } - staleCollapseAttrs = " stale_by_kind=\"" + ex( kinds ) + "\"" + rw::nextAttrXml( replay + " --show-stale", "stale_next" ); - } - const bool verdictOnly = collapseStale && !refPair && basis.headBasis != nullptr && std::string_view( basis.headBasis ) == "identity" - && !scope.active() && foreignAcks.empty() && ackedCount == 0 && configDiag.total() == 0 && baselineAbsorbed == 0 - && basis.apiNewSurface == 0 && baseSel.sidecarBadLines == 0 && basis.acksBadLines == 0; - // P1: ONE row emitter for both halves of the scope partition — a disclosed row carries the identical - // attribute set, because nothing about a finding changes by belonging to someone else. `gatingAllowed` - // is the one difference: an out-of-scope row is not what the exit code fires on, and a gating - // attribute on it would contradict the header's own gating counter inside the same document. - const auto emitRow = [ & ]( std::FILE* out, const quality::Regression& r, bool gatingAllowed ) - { - // duplication carries a member LIST (members=) + token count; the per-symbol was/now kinds - // (complexity/verbosity/nesting/params) carry was/now; api-surface + dead-code are sym-only. - // sev="minor" marks a below-materiality delta (never gates); absent = major. - const char* sev = r.isMinor ? " sev=\"minor\"" : ""; - // B10.2 — the optional classification facet: attribute NAME is chosen by kind (churn= - // short-horizon-churn's self/ambient split; surface= api-surface's new-symbol/contract-change - // tier; idiom= the duplication kind's recognized clone-body shape); r.facet carries only the - // VALUE, and quality::facetAttrName is the ONE table that maps kind → attribute name for all - // three emitters (this one, the --json twin above, and the MCP one). - std::string facetAttr; - if( !r.facet.empty() ) - { - const char* facetName = quality::facetAttrName( r.kind ); - if( facetName ) - { - facetAttr = std::string( " " ) + facetName + "=\"" + ex( r.facet ) + "\""; // escaped: a ratchet facet is a tag name - } - } - // r26 — the ORIGIN axis, emitted LAST so the existing attribute order is untouched. Present only - // on new-symbol rows (absent = preexisting-worse), the same "mark the exception" convention sev= - // uses. api-surface's own surface="new-symbol" facet is the same fact narrowed to that kind; it - // stays for shape compatibility, and origin= is what the exit gate reads. - const char* origin = !r.isNewSymbol ? "" : r.isMoved ? " origin=\"moved\"" : " origin=\"new-symbol\""; // quality::originValue - // P2.5 — the two attributes that make a row ACTIONABLE, appended last so every pre-r27 attribute - // keeps its position: - // p="path:line" — sym= is a canonical id whose display tail is often a bare one-letter local - // (`sym="cc"`), i.e. ungreppable. Omitted, never faked, when no locator was resolvable. - // gating="1" — marks exactly the rows the header's gating= counts and the exit code fires on. - // Until now a gating row was identifiable ONLY by the ABSENCE of sev="minor" (and of - // origin="new-symbol") — absence-as-signal is the least machine-friendly encoding available. - std::string locAttr; - if( !r.path.empty() ) - { - locAttr = " p=\"" + ex( r.path ) + ":" + std::to_string( r.line ) + "\""; - } - const char* gatingAttr = ( gatingAllowed && quality::rowGates( r ) ) ? " gating=\"1\"" : ""; - // QD-ENTRY-CEILING: the ceiling a NEW function reached, beside the gating= it causes (present-only) - const std::string ceilingAttr = r.ceiling != 0 ? " ceiling=\"" + std::to_string( r.ceiling ) + "\"" : std::string(); - // QD-UNCHECKED-STATUS: the call whose status a defect-shape unchecked-status row drops (present-only) - const std::string callAttr = presentXmlAttr( "call", r.call, ex ); - // P8 (L7): the threshold beside the number it judges — bar= on the four numeric kinds (quality.h's - // kCcxBar/kLocBar/kNestBar/kParamBar), so was=/now= read without the legend. - const char* barAttr = qdBarAttrOf( r.kind ); - const std::string tangleAttrs = quality::tangleRowAttrs( r, /*json=*/false, ex ); // QD-TANGLE: why= / fix= / locals= - // P3 (L7, nextverb.h): a GATING row hands the agent the body to fix — --expand=FILE:NAME (the file-qualified - // selector, so a same-named symbol elsewhere cannot answer). The name is the sym key's last :: segment; - // duplication rows name a SET (members=) and carry no single body to open, nor does a FILE-anchored - // defect-shape row (top-level code: sym= is the path, and --expand=FILE:FILE matches no symbol). - std::string nextAttr; - if( *gatingAttr && !r.path.empty() && r.kind != "duplication" && !( r.kind == "defect-shape" && r.sym == r.path ) ) - { - const std::size_t sep = r.sym.rfind( "::" ); - const std::string bare = sep == std::string::npos ? r.sym : r.sym.substr( sep + 2 ); - nextAttr = rw::nextAttrXml( rw::nextFlag( "--expand=", r.path + ":" + bare ) ); - } - if( r.kind == "duplication" ) - { - rw::emitTo( out, "", ex( quality::displaySym( r.sym, deltaRoot ) ).c_str(), r.now, sev, facetAttr.c_str(), origin, locAttr.c_str(), gatingAttr, - tangleAttrs ); // QD-IDIOM-ELEMTYPE: why= when the operand path demoted it - } - else if( r.kind == "dead-code" ) - { - rw::emitTo( out, "", r.kind.c_str(), ex( quality::displaySym( r.sym, deltaRoot ) ).c_str(), sev, facetAttr.c_str(), origin, locAttr.c_str(), gatingAttr, nextAttr.c_str() ); - // B10.2e: api-surface now carries two shapes — a brand-new/newly-public symbol (was=now=0, no - // param comparison to show) and a param-count contract-change (was/now = the real counts). Print - // was/now whenever they differ from each other so the contract-change case's was=/now= is visible - // while the new-symbol case's meaningless was="0" now="0" is omitted, matching its old sym-only shape. - } - else if( r.kind == "api-surface" && r.was == r.now ) - { - rw::emitTo( out, "", r.kind.c_str(), ex( quality::displaySym( r.sym, deltaRoot ) ).c_str(), sev, facetAttr.c_str(), origin, locAttr.c_str(), gatingAttr, nextAttr.c_str() ); - } - else - { - rw::emitTo( out, "", r.kind.c_str(), ex( quality::displaySym( r.sym, deltaRoot ) ).c_str(), - quality::rowValueText( r, r.was ), quality::rowValueText( r, r.now ), barAttr, sev, facetAttr.c_str(), origin, locAttr.c_str(), gatingAttr, - ceilingAttr.c_str(), callAttr.c_str(), nextAttr.c_str(), tangleAttrs ); - } - }; - // Fix round 1 (rv-lean-trio item 5, owner ruling 5): a fold ships only when it PAYS (compactlegend.h foldPays: shorter - // by its margin, as written AND as the compact layer delivers it). The whole XML document is one renderer over a FILE*, - // so both candidates are rendered and measured, and the full document wins a fold that does not pay or a failed render - // (fx, dirty tree, one stale ack: 1512 B folded vs 1481 B full). - // `collapse` picks the stale rows' form: true serves only the foreign-scope rows and the stale_by_kind=/stale_next= counts. - // R-I: at= is OMITTED for the ref-pair form (see the root below). Read ONCE: both candidates print the same stamp. - const std::string atAttrs = refPair ? std::string() : gitstamp::atAttr( root ); - const auto emitDocument = [ & ]( std::FILE* out, bool collapse ) - { - const std::vector& served = collapse ? foreignAcks : saRows; - emitQualityDeltaLegend( { baseSel.marker, refPair, identityAttrs, !served.empty(), ackedCount > 0, - basis.registerMacroExcluded > 0, configDiag.total() > 0, regs, outOfScope, - scope.active() || !foreignAcks.empty(), !foreignAcks.empty(), baselineAbsorbed, - basis.headBasis, basis.declinedCallExcluded > 0, basis.valueRefExcluded > 0, collapse, - refs.kinds != quality::kAllKinds, refs.degraded, !refs.memoryStop.empty(), kd.peakOver != 0, - kd.memorySkipped != 0 && refs.selected != quality::kAllKinds, basis.historyUnread.any(), - basis.rustTestExcluded, refs.staleTree, !basis.extras.ratchetRef.empty(), !basis.extras.improved.empty() }, out ); - const char* baseMarker = baseSel.marker; // R3: ditto — one seam decides staleness AND names it - // 2026-09-06: what the sidecar readers skipped, on the root (absent means none) — see kQdBaseHeadUnreadable - std::string sidecarHealthAttrs; - if( baseSel.sidecarBadLines > 0 ) { sidecarHealthAttrs += " baseline_bad_lines=\"" + std::to_string( baseSel.sidecarBadLines ) + "\""; } - if( basis.acksBadLines > 0 ) { sidecarHealthAttrs += " acks_bad_lines=\"" + std::to_string( basis.acksBadLines ) + "\""; } - // #228: present-only, and its absence is the ordinary archived HEAD tree — the floor every git-HEAD - // marker named on its own before this attribute existed. - if( basis.headBasis != nullptr ) { sidecarHealthAttrs += std::string( " head_basis=\"" ) + basis.headBasis + "\""; } - if( basis.declinedCallExcluded > 0 ) { sidecarHealthAttrs += " declined-call-excluded=\"" + std::to_string( basis.declinedCallExcluded ) + "\""; } - sidecarHealthAttrs += rw::countAttrXmlOrEmpty( "value-ref-excluded", basis.valueRefExcluded ); // absent at zero, beside its sibling - // at= anchors this regression list to the commit (+dirty state) it was computed against. - // qd-memory-degrade: stale= and register-macro-excluded= are absent (never 0) when their pass did not run - const std::string staleX = refs.degraded ? std::string() : " stale=\"" + std::to_string( staleAcks.size() ) + "\""; - const std::string rmeX = deadRan ? " register-macro-excluded=\"" + std::to_string( basis.registerMacroExcluded ) + "\"" : std::string(); - rw::emitTo( out, "", - baseMarker, regs.size(), minorCount, ackedCount, staleX, preexistingCount, newSymbolCount, gatingCount, rmeX, basis.apiNewSurface, - // R-I: at= is OMITTED for the ref-pair form rather than stamped with the working tree's - // sha, which would anchor the list to a commit it was not computed from. base_ref= and - // target_ref= are the anchor there, and they carry FULL shas because a wave measurement - // gets quoted into handoffs where a 9-char prefix is one collision from unverifiable. - atAttrs.c_str(), refs.attrs.c_str(), identityAttrs.c_str(), - scopeAttrs.c_str(), configWarnAttr.c_str(), baselineAbsorbedAttr.c_str(), ( sidecarHealthAttrs + ( collapse ? staleCollapseAttrs : std::string() ) + kd.xml + historyAttrs + quality::ratchetAttrsXml( basis.extras, ex ) ).c_str() ); - for( const quality::Regression& r : regs ) - { - emitRow( out, r, /*gatingAllowed=*/true ); - } - std::fputs( quality::improvedXml( basis.extras.improved, deltaRoot, ex ).c_str(), out ); // QD-CREDIT-ROW: never a row, never gating - if( scope.active() ) - { - // P1 — the DISCLOSURE half. Dropping these rows would make a scoped report a quieter lie than - // the unscoped one it replaces: the debt is real, it is in the same tree, and it will be in - // someone's report. So they are printed, in their own element, marked non-gating, with the one - // sentence a reader needs written where they meet it. Emitted even when EMPTY — an absent - // element then means "no scope was given", never "nobody else has anything open". - rw::emitTo( out, "", - outOfScope.size(), scopedOutGating ); - for( const quality::Regression& r : outOfScope ) - { - emitRow( out, r, /*gatingAllowed=*/false ); - } - rw::emitRaw( out, "" ); - } - { // L2 — one row per stale ack (quality::staleAcksXml). M21(a): the escaper is passed in - // because sym= carries a canonical id (corpus text), unlike the closed-vocabulary kind=/why=. - std::vector saEsc; - std::fputs( quality::staleAcksXml( served, [ & ]( std::string_view t ) { return std::string( escapeXml( t, saEsc ) ); } ).c_str(), out ); - } - rw::emitRaw( out, "" ); - }; - // the identity-tree VERDICT (verdictOnly above): the root line alone - const auto emitVerdict = [ & ]( std::FILE* out ) - { - rw::emitTo( out, "" - "", - baseSel.marker, staleAcks.size(), atAttrs, staleCollapseAttrs ); - }; - if( !collapseStale ) - { - emitDocument( stdout, /*collapse=*/false ); - return qualityDeltaExit( gatingCount, refs.degraded || basis.historyUnread.any() ); - } - const Rendered full = renderToString( [ & ]( std::FILE* f ) { emitDocument( f, /*collapse=*/false ); } ); - const Rendered folded = renderToString( [ & ]( std::FILE* f ) { if( verdictOnly ) { emitVerdict( f ); } else { emitDocument( f, /*collapse=*/true ); } } ); - if( !full.ok || !folded.ok ) +// r26 ORIGIN SPLIT — three counts over the VISIBLE (post-ack) findings, one pass: +// minor — the materiality tier (unchanged axis). +// newSymbol — findings that exist only because the code is NEW (quality.h's origin axis). +// gating — the EXIT PREDICATE (quality::rowGates): major AND preexisting-worse, or a defect-shape +// format-arity row of any origin. Emitted as gating= so the header alone tells you +// the exit code (it used to be "regressions > minor"). +// preexisting-worse = regressions − new-symbol by construction (the axis is a partition), so the two +// header counters always sum to regressions= — an invariant the gate asserts. +struct QdCounts +{ + std::size_t minor = 0, newSymbol = 0, gating = 0, preexisting = 0; +}; +QdCounts countQdRows( const std::vector& regs ) +{ + QdCounts c; + for( const rw::quality::Regression& r : regs ) + { + c.minor += r.isMinor ? 1 : 0; + c.newSymbol += r.isNewSymbol ? 1 : 0; + c.gating += rw::quality::rowGates( r ) ? 1 : 0; + } + c.preexisting = regs.size() - c.newSymbol; + return c; +} + +// Everything one --quality-delta answer renders, computed before the format is chosen: the JSON and XML emitters read only +// this (plus the judged comparison it points at), so the two formats cannot disagree about a fact. +struct QdReport +{ + const QdJudged& j; + std::vector staleAcks; + std::vector saRows; // stale + foreign acks: the one / "sa" list + QdCounts counts; + std::size_t baselineAbsorbed = 0; + std::pair identity, history, scope; // (XML attrs, JSON members), built once for both + rw::quality::RegisterMacroConfigDiagnostics configDiag; + std::string configWarnAttr; + KindsDisclosure kd; + bool deadRan = false; // dead-code's side counts exist only when it ran + + const rw::quality::BaselineSelection& baseSel() const noexcept { return j.basis.baseSel; } + const std::vector& regs() const noexcept { return j.basis.regs; } + const std::string& deltaRoot() const noexcept { return j.basis.deltaRoot; } + // The exit code every rendering returns (qualityDeltaExit): r26 — only a PREEXISTING-worse AND major regression gates (== gating=). + int exitCode() const noexcept { return qualityDeltaExit( counts.gating, j.refs.degraded || j.basis.historyUnread.any() ); } +}; + +// REPORT (compute half) — the stale-ack verdicts, the counts and every root disclosure, in the order their stderr lines +// have always printed. +QdReport qdReportOf( const QdJudged& j, const std::string& baselineFile ) +{ + using namespace rw; + QdReport rep{ .j = j }; + const gtl::btree_map& acks = j.basis.acks; + // L2 — stale-ack disclosure (rationale: quality.h's computeStaleAcks). Checked against the CURRENT + // tree, not the baseline above, so it costs one more computeSnapshot; skipped when the ledger is + // empty. Reported, never gated — the exit code reads `regs` alone. + // R-I: "the CURRENT tree" is the JUDGED tree, which in the ref-pair form is tree B — checking the + // ledger against the working tree there would report acks as stale because of edits that have nothing + // to do with the comparison being made. + // qd-memory-degrade: refPairStaleAcks owns the two range-form departures (a changed-files answer judges none; a + // kind selection judges its own kinds' acks only). + rep.staleAcks = acks.empty() ? std::vector{} + : j.refPair ? refPairStaleAcks( acks, j.refs ) + : quality::computeStaleAcks( acks, quality::computeSnapshot( j.judged, j.workingGraph, j.cfg.rootPath, nullptr, {}, &j.basis.passes ) ); + if( std::getenv( "RIPWIRE_STATS" ) ) // QD-ENVOY-TIME cost bound: Type-3 passes this call ran (test/qdtype3oncecheck.sh) + { + rw::emitTo( stderr, "ripwire: quality-passes type3_runs={} type3_pairs={}\n", gType3PassRuns.load( std::memory_order_relaxed ), + gType3PassPairs.load( std::memory_order_relaxed ) ); + } + + // P1.4 — the family now carries THREE whys, and the third is counted SEPARATELY: stale= means + // "this ack no longer applies", and a foreign ack applies fine — it is the SESSION that was wrong, + // not the target. Merging the rows into one list keeps the two emitters from growing a second loop + // each; keeping the COUNTS apart keeps stale= meaning what it has always meant. + rep.saRows = rep.staleAcks; + rep.saRows.insert( rep.saRows.end(), j.foreignAcks.begin(), j.foreignAcks.end() ); + // M21(a): name the rows the tree can still name, against the SAME tree computeStaleAcks judged + // (tree B in the ref-pair form) — naming a stale ack after the working tree would print an identity + // the verdict was never computed from. Costs one walk over the judged symbols, and only when there are rows. + quality::stampStaleAckIdentity( rep.saRows, j.judged, j.refPair ? std::string_view( j.refs.target().root ) : std::string_view( j.cfg.rootPath ) ); + + rep.counts = countQdRows( j.basis.regs ); + // H11 — the absorbed-debt stamp on the honored sidecar, or 0. Read ONLY when the sidecar is the floor + // in force: on the git-HEAD and ref-pair floors there is no pin whose contents could have absorbed + // anything, and printing a 0 there would define an attribute about a file this run did not use. + rep.baselineAbsorbed = ( rep.baseSel().marker == std::string_view( "sidecar" ) ) ? quality::readBaselineAbsorbed( baselineFile ) : 0; + + // R1 IDENTITY — the disclosure, built ONCE for both emitters (quality::identityDisclosure). An ack + // that follows a rename is a claim about identity, and a claim is only honest if the reader can see + // what it rested on; building the XML and JSON halves in one place is what keeps the two surfaces + // from disclosing different things about the same run. + rep.identity = quality::identityDisclosure( j.basis.healing ); + // hwh-fix4 (N1): the history a gating kind could not read, one builder for every emitter (absent when all was read) + rep.history = quality::historyUnreadDisclosure( j.basis.historyUnread ); + if( rep.counts.gating == 0 && j.basis.historyUnread.any() ) + { + rw::emitTo( stderr, "ripwire: --quality-delta: not a clean pass - git history a gating kind needs could not be read ({}; a partial clone " + "does not download it), so a gating row may be missing: exit 6\n", rep.history.first.substr( 1 ).c_str() ); + } + + // P1/P1.4 — the scope disclosure, built once for both emitters (quality::scopeDisclosure). + rep.scope = quality::scopeDisclosure( j.scope, j.outOfScope.size(), j.scopedOutGating, j.foreignAcks.size(), j.diffFileCount ); + + // F-13 — the .ripwire_config disclosure, built once for both emitters (see the header comment on + // registerMacroConfigWarningAttr just above runQualityViews for why the stderr wording lives there). + // #387: the inert-name test reads the JUDGED tree's index, which in the ref-pair form is tree B — the working tree + // is not indexed there at all (runQualityDeltaRangeBeforeIngest). + // qd-memory-degrade: not over a changed-files index, which cannot tell an inert name from one the tree defines (also_skipped=) + rep.configDiag = j.refs.degraded ? quality::RegisterMacroConfigDiagnostics{} : quality::diagnoseRegisterMacroConfig( j.judged, j.root ); + rep.configWarnAttr = registerMacroConfigWarningAttr( rep.configDiag ); + // qd-memory-degrade: the kinds this answer did not run, why, and the replay — plus the peak, read once now that the + // comparison is done (kindsDisclosure). Its stderr lines are the caller's to print, first. + rep.kd = kindsDisclosure( j.cfg, j.refs, j.basis, j.refPair ); + rep.deadRan = !j.refPair || quality::kindSelected( j.refs.kinds, "dead-code" ); + return rep; +} + +// ── the ROW MODEL: one --quality-delta row's printed facts, decided once for the XML and JSON emitters ───────────────── +// P1: both formats print the in-scope rows and the disclosed out-of-scope rows with this one model — a disclosed row +// carries the identical attribute set, because nothing about a finding changes by belonging to someone else. `gating` is +// the one difference: an out-of-scope row is not what the exit code fires on, and claiming gating on it would contradict +// the header's own gating counter inside the same document. +struct QdRowModel +{ + // duplication carries a member LIST (members=) + token count; dead-code and an api-surface row whose counts did not + // change are sym-only; every other kind carries was/now. + // B10.2e: api-surface carries two shapes — a brand-new/newly-public symbol (was=now=0, no param comparison to show) + // and a param-count contract-change (was/now = the real counts). was/now print whenever they differ from each other, + // so the contract-change case's was=/now= is visible while the new-symbol case's meaningless was="0" now="0" is + // omitted, matching its old sym-only shape. + enum class Shape : std::uint8_t { Members, SymOnly, WasNow }; + Shape shape = Shape::WasNow; + std::string sym; // quality::displaySym, unescaped: members= for Members, sym= otherwise + bool gating = false; // P2.5: the exit predicate (quality::rowGates), stated per row; never on a disclosed row + // B10.2 — the optional classification facet: its attribute NAME is chosen by kind (quality::facetAttrName, the ONE + // kind→name table for every emitter, MCP included); r.facet carries only the VALUE. nullptr = no facet attribute. + const char* facetName = nullptr; + // r26 — the ORIGIN axis (quality::originValue): present only on new-symbol rows (absent = preexisting-worse), the same + // "mark the exception" convention sev= uses. origin= is what the exit gate reads. + const char* origin = nullptr; +}; +QdRowModel qdRowModel( const rw::quality::Regression& r, bool gatingAllowed, std::string_view deltaRoot ) +{ + using namespace rw; + QdRowModel m; + m.shape = r.kind == "duplication" ? QdRowModel::Shape::Members + : ( r.kind == "dead-code" || ( r.kind == "api-surface" && r.was == r.now ) ) ? QdRowModel::Shape::SymOnly + : QdRowModel::Shape::WasNow; + m.sym = quality::displaySym( r.sym, deltaRoot ); + m.gating = gatingAllowed && quality::rowGates( r ); + m.facetName = r.facet.empty() ? nullptr : quality::facetAttrName( r.kind ); + m.origin = quality::originValue( r ); + return m; +} + +// P3 (L7, nextverb.h): a GATING row hands the agent the body to fix — --expand=FILE:NAME (the file-qualified selector, so +// a same-named symbol elsewhere cannot answer). The name is the sym key's last :: segment; duplication rows name a SET +// (members=) and carry no single body to open, nor does a FILE-anchored defect-shape row (top-level code: sym= is the +// path, and --expand=FILE:FILE matches no symbol). Empty when the row offers no body. +std::string qdExpandNextAttr( const rw::quality::Regression& r, const QdRowModel& m ) +{ + if( !m.gating || r.path.empty() || r.kind == "duplication" || ( r.kind == "defect-shape" && r.sym == r.path ) ) + { + return std::string(); + } + const std::size_t sep = r.sym.rfind( "::" ); + const std::string bare = sep == std::string::npos ? r.sym : r.sym.substr( sep + 2 ); + return rw::nextAttrXml( rw::nextFlag( "--expand=", r.path + ":" + bare ) ); +} + +// One XML row. The attribute order is the contract every gate reads: kind/sym (or members/tokens), was/now with bar=, +// then sev= facet= origin= and the P2.5 pair p= gating= (appended after every pre-r27 attribute), then the per-kind tail. +// `ex` is the document's XML escaper. +template +void emitQdXmlRow( std::FILE* out, const rw::quality::Regression& r, const QdRowModel& m, const Escape& ex ) +{ + using namespace rw; + // sev="minor" marks a below-materiality delta (never gates); absent = major. + std::string common = r.isMinor ? " sev=\"minor\"" : ""; + if( m.facetName != nullptr ) + { + common += std::string( " " ) + m.facetName + "=\"" + ex( r.facet ) + "\""; // escaped: a ratchet facet is a tag name + } + if( m.origin != nullptr ) + { + common += std::string( " origin=\"" ) + m.origin + "\""; + } + // P2.5 — p="path:line": sym= is a canonical id whose display tail is often a bare one-letter local (`sym="cc"`), i.e. + // ungreppable. Omitted, never faked, when no locator was resolvable. gating="1" marks exactly the rows the header's + // gating= counts — until r27 a gating row was identifiable only by the ABSENCE of sev="minor" and origin=. + if( !r.path.empty() ) + { + common += " p=\"" + ex( r.path ) + ":" + std::to_string( r.line ) + "\""; + } + common += m.gating ? " gating=\"1\"" : ""; + switch( m.shape ) + { + case QdRowModel::Shape::Members: + rw::emitTo( out, "", ex( m.sym ), r.now, common, + quality::tangleRowAttrs( r, /*json=*/false, ex ) ); // QD-IDIOM-ELEMTYPE: why= when the operand path demoted it + return; + case QdRowModel::Shape::SymOnly: + rw::emitTo( out, "", r.kind, ex( m.sym ), common, qdExpandNextAttr( r, m ) ); + return; + case QdRowModel::Shape::WasNow: + // P8 (L7): bar= is the threshold beside the number it judges, on the four numeric kinds (quality.h's + // kCcxBar/kLocBar/kNestBar/kParamBar), so was=/now= read without the legend. QD-ENTRY-CEILING: ceiling= is the + // ceiling a NEW function reached, beside the gating= it causes; QD-UNCHECKED-STATUS: call= is the call whose + // status a defect-shape unchecked-status row drops; QD-TANGLE: why= / fix= / locals=. All present-only. + rw::emitTo( out, "", r.kind, ex( m.sym ), + quality::rowValueText( r, r.was ), quality::rowValueText( r, r.now ), qdBarAttrOf( r.kind ), common, + r.ceiling != 0 ? " ceiling=\"" + std::to_string( r.ceiling ) + "\"" : std::string(), presentXmlAttr( "call", r.call, ex ), + qdExpandNextAttr( r, m ), quality::tangleRowAttrs( r, /*json=*/false, ex ) ); + return; + } +} + +// One JSON row object: the keys mirror the XML attribute names, in the order the --json contract has always used. +void emitQdJsonRow( std::FILE* out, const rw::quality::Regression& r, const QdRowModel& m ) +{ + using namespace rw; + rw::emitTo( out, "{{\"kind\":\"{}\"", jsonStr( r.kind ) ); + if( m.shape == QdRowModel::Shape::Members ) + { + rw::emitTo( out, ",\"members\":\"{}\",\"tokens\":{}", jsonStr( m.sym ), r.now ); + } + else + { + rw::emitTo( out, ",\"sym\":\"{}\"", jsonStr( m.sym ) ); + } + if( m.shape == QdRowModel::Shape::WasNow ) + { + rw::emitTo( out, ",\"was\":{},\"now\":{}", quality::rowValueText( r, r.was ), quality::rowValueText( r, r.now ) ); + } + if( !r.path.empty() ) + { + rw::emitTo( out, ",\"p\":\"{}:{}\"", jsonStr( r.path ), r.line ); // P2.5 locator + } + rw::emitRaw( out, m.gating ? ",\"gating\":true" : "" ); // P2.5 — the exit predicate, stated per row + rw::emitRaw( out, r.isMinor ? ",\"sev\":\"minor\"" : "" ); + if( m.facetName != nullptr ) + { + rw::emitTo( out, ",\"{}\":\"{}\"", m.facetName, jsonStr( r.facet ) ); + } + if( m.origin != nullptr ) + { + rw::emitTo( out, ",\"origin\":\"{}\"", m.origin ); // absent = preexisting-worse (mirrors the XML) + } + if( r.ceiling != 0 ) + { + rw::emitTo( out, ",\"ceiling\":{}", r.ceiling ); // QD-ENTRY-CEILING (mirrors the XML) + } + rw::emitRaw( out, presentJsonMember( "call", r.call ).c_str() ); // QD-UNCHECKED-STATUS (mirrors the XML) + std::fputs( quality::tangleRowAttrs( r, /*json=*/true, []( std::string_view s ) { return jsonStr( s ); } ).c_str(), out ); // QD-TANGLE (mirrors the XML) + rw::emitRaw( out, "}" ); +} + +// A comma-separated run of JSON rows (the "r" array's body, or "oos"'s). +void emitQdJsonRows( std::FILE* out, const std::vector& rows, bool gatingAllowed, std::string_view deltaRoot ) +{ + bool first = true; + for( const rw::quality::Regression& r : rows ) + { + rw::emitRaw( out, first ? "" : "," ); + first = false; + emitQdJsonRow( out, r, qdRowModel( r, gatingAllowed, deltaRoot ) ); + } +} + +// REPORT (render half), --json — same regressions, keys mirror the XML attr names (kind/sym/members/tokens/was/now/ +// sev/churn/surface). jsonUnsupportedVerb already refused --quality-baseline/--quality-ack, so reaching here with cfg.json +// means the plain --quality-delta report. Every optional root member follows the XML twin's absent-means-never-happened rule. +void emitQualityDeltaJson( const QdReport& rep ) +{ + using namespace rw; + const QdJudged& j = rep.j; + const DeltaBasis& basis = j.basis; + // The JSON sibling of the XML at= anchor — "at":null (never a fake sha) on a non-git root, and + // null in the ref-pair form too: the list was not computed "at" any working-tree state, and the + // two refs ARE its anchor. + const std::string atVal = j.refPair ? std::string{} : gitstamp::stampAt( j.root ); + const std::string atJson = atVal.empty() ? std::string( "null" ) : ( "\"" + atVal + "\"" ); + // F-13: config-warnings is the JSON sibling of the XML config-warnings= attribute — omitted + // (never 0) when .ripwire_config carried nothing to disclose. + const std::string configWarnJson = rep.configDiag.total() == 0 ? std::string() : ",\"config-warnings\":" + std::to_string( rep.configDiag.total() ); + // H11: the JSON twin of baseline_absorbed=. + const std::string absorbedJson = rep.baselineAbsorbed == 0 ? std::string() : ",\"baseline_absorbed\":" + std::to_string( rep.baselineAbsorbed ); + // #228: the JSON twin of head_basis=, under the same absent-means-the-ordinary-archived-tree rule. + const std::string headBasisJson = ( basis.headBasis == nullptr ? std::string() : std::string( ",\"head_basis\":\"" ) + basis.headBasis + "\"" ) + + ( basis.declinedCallExcluded == 0 ? std::string() // the XML twin's declined-call-excluded=, absent at zero + : ",\"declined-call-excluded\":" + std::to_string( basis.declinedCallExcluded ) ) + + rw::countFieldOrEmpty( "value-ref-excluded", basis.valueRefExcluded, /*json=*/true ); + // qd-memory-degrade: stale and register-macro-excluded are absent (never 0) when their pass did not run + const std::string staleJ = j.refs.degraded ? std::string() : ",\"stale\":" + std::to_string( rep.staleAcks.size() ); + const std::string rmeJ = rep.deadRan ? ",\"register-macro-excluded\":" + std::to_string( basis.registerMacroExcluded ) : std::string(); + // R-I: refs.jsonAttrs carries the same two shas + unmeasurable-kind disclosure the XML root carries (empty for the bare form). + rw::emitTo( stdout, "{{\"baseline\":\"{}\",\"regressions\":{},\"minor\":{},\"acked\":{}{}," + "\"preexisting-worse\":{},\"new-symbol\":{},\"gating\":{}{},\"api-new-surface\":{},\"at\":{}{}{}{}{}{}{}{},\"r\":[", + jsonStr( rep.baseSel().marker ), rep.regs().size(), rep.counts.minor, j.ackedCount, staleJ, + rep.counts.preexisting, rep.counts.newSymbol, rep.counts.gating, rmeJ, basis.apiNewSurface, atJson, j.refs.jsonAttrs, + rep.identity.second, rep.scope.second, configWarnJson, absorbedJson, headBasisJson, + rep.kd.json + rep.history.second + quality::ratchetAttrsJson( basis.extras ) ); + emitQdJsonRows( stdout, rep.regs(), /*gatingAllowed=*/true, rep.deltaRoot() ); + rw::emitRaw( stdout, "]," ); + if( j.scope.active() ) + { + // The JSON sibling of the XML out-of-scope element: a SEPARATE array, never a flag on a row + // in "r", so a consumer that reads "r" and checks "gating" cannot accidentally count someone + // else's debt as this run's. Emitted (possibly empty) whenever a scope was given, so its + // absence means "no scope", never "no disclosed rows". + rw::emitRaw( stdout, "\"oos\":[" ); + emitQdJsonRows( stdout, j.outOfScope, /*gatingAllowed=*/false, rep.deltaRoot() ); + rw::emitRaw( stdout, "]," ); + } + std::fputs( quality::staleAcksJsonArray( rep.saRows ).c_str(), stdout ); // L2 — "sa":[...], same taxonomy as the XML sa= rows + std::fputs( quality::improvedJson( basis.extras.improved, rep.deltaRoot() ).c_str(), stdout ); // QD-CREDIT-ROW (absent when none) + rw::emitRaw( stdout, "}" ); +} + +// 2026-09-06: what the sidecar readers skipped, on the root (absent means none) — see kQdBaseHeadUnreadable — plus the +// #228 head_basis= (present-only: its absence is the ordinary archived HEAD tree) and the dead-code exemption counts. +std::string qdSidecarHealthAttrs( const DeltaBasis& basis ) +{ + std::string out; + if( basis.baseSel.sidecarBadLines > 0 ) { out += " baseline_bad_lines=\"" + std::to_string( basis.baseSel.sidecarBadLines ) + "\""; } + if( basis.acksBadLines > 0 ) { out += " acks_bad_lines=\"" + std::to_string( basis.acksBadLines ) + "\""; } + if( basis.headBasis != nullptr ) { out += std::string( " head_basis=\"" ) + basis.headBasis + "\""; } + if( basis.declinedCallExcluded > 0 ) { out += " declined-call-excluded=\"" + std::to_string( basis.declinedCallExcluded ) + "\""; } + out += rw::countAttrXmlOrEmpty( "value-ref-excluded", basis.valueRefExcluded ); // absent at zero, beside its sibling + return out; +} + +// idea #11 — THE CLEAN-TREE PAYLOAD. A regression-free answer collapses its stale-ack rows to counts (stale= and +// stale_by_kind=), and stale_next= is the call that prints them; on a tree that IS its HEAD (head_basis="identity": the +// floor is this tree's own snapshot) with nothing else to disclose, the verdict is the whole answer. Foreign-scope rows are +// never collapsed: they are about findings suppressed RIGHT NOW. --show-stale restores today's document byte for byte, so +// every collapsed row and attribute is one flag away (PROCESS rule 5). `attrs` is empty when the answer does not collapse. +struct QdStaleCollapse +{ + bool collapse = false; + bool verdictOnly = false; // the identity-tree VERDICT: the root line alone + std::string attrs; // stale_by_kind= + stale_next= +}; +// The identity-tree verdict's precondition: a working-tree answer whose floor is this tree's own snapshot +// (head_basis="identity") with no scope, foreign or accepted ack, config warning, absorbed debt, new public surface or +// unreadable sidecar line to disclose — so the root line alone loses nothing. +bool qdNothingElseToDisclose( const QdReport& rep ) +{ + const QdJudged& j = rep.j; + const DeltaBasis& basis = j.basis; + return !j.refPair && basis.headBasis != nullptr && std::string_view( basis.headBasis ) == "identity" + && !j.scope.active() && j.foreignAcks.empty() && j.ackedCount == 0 && rep.configDiag.total() == 0 && rep.baselineAbsorbed == 0 + && basis.apiNewSurface == 0 && rep.baseSel().sidecarBadLines == 0 && basis.acksBadLines == 0; +} + +template +QdStaleCollapse qdStaleCollapse( const QdReport& rep, const Escape& ex ) +{ + using namespace rw; + const QdJudged& j = rep.j; + QdStaleCollapse c; + c.collapse = rep.regs().empty() && j.outOfScope.empty() && !j.cfg.showStale && !rep.staleAcks.empty(); + if( !c.collapse ) + { + return c; + } + const std::string kinds = quality::staleByKindValue( rep.staleAcks ); // shared with the MCP twin (lane lean2b) + std::string replay = j.cfg.qualityDeltaRange.empty() ? std::string( "--quality-delta" ) : rw::nextFlag( "--quality-delta=", j.cfg.qualityDeltaRange ); + if( j.scope.active() ) + { + replay += " " + rw::nextFlag( "--scope=", j.cfg.qualityScope ); + } + c.attrs = " stale_by_kind=\"" + ex( kinds ) + "\"" + rw::nextAttrXml( replay + " --show-stale", "stale_next" ); + c.verdictOnly = qdNothingElseToDisclose( rep ); + return c; +} + +// The whole XML document over one FILE*: legend, root, rows, improvements, the out-of-scope disclosure and the rows. +// `collapse` picks the stale rows' form: true serves only the foreign-scope rows and the stale_by_kind=/stale_next= counts. +void emitQdXmlDocument( std::FILE* out, const QdReport& rep, const QdStaleCollapse& stale, const std::string& atAttrs, bool collapse ) +{ + using namespace rw; + const QdJudged& j = rep.j; + const DeltaBasis& basis = j.basis; + const RefPairDelta& refs = j.refs; + std::vector esc; + const auto ex = [ & ]( std::string_view s ) -> std::string { return std::string( escapeXml( s, esc ) ); }; + const std::vector& served = collapse ? j.foreignAcks : rep.saRows; + // the legend is passed the same values the root element below prints, so "the legend defines what the header emits" is + // read off one set of values rather than restated as a second condition that could drift from it + emitQualityDeltaLegend( { rep.baseSel().marker, j.refPair, rep.identity.first, !served.empty(), j.ackedCount > 0, + basis.registerMacroExcluded > 0, rep.configDiag.total() > 0, rep.regs(), j.outOfScope, + j.scope.active() || !j.foreignAcks.empty(), !j.foreignAcks.empty(), rep.baselineAbsorbed, + basis.headBasis, basis.declinedCallExcluded > 0, basis.valueRefExcluded > 0, collapse, + refs.kinds != quality::kAllKinds, refs.degraded, !refs.memoryStop.empty(), rep.kd.peakOver != 0, + rep.kd.memorySkipped != 0 && refs.selected != quality::kAllKinds, basis.historyUnread.any(), + basis.rustTestExcluded, refs.staleTree, !basis.extras.ratchetRef.empty(), !basis.extras.improved.empty() }, out ); + // qd-memory-degrade: stale= and register-macro-excluded= are absent (never 0) when their pass did not run + const std::string staleX = refs.degraded ? std::string() : " stale=\"" + std::to_string( rep.staleAcks.size() ) + "\""; + const std::string rmeX = rep.deadRan ? " register-macro-excluded=\"" + std::to_string( basis.registerMacroExcluded ) + "\"" : std::string(); + rw::emitTo( out, "", + rep.baseSel().marker, rep.regs().size(), rep.counts.minor, j.ackedCount, staleX, rep.counts.preexisting, rep.counts.newSymbol, rep.counts.gating, + rmeX, basis.apiNewSurface, + // at= anchors this regression list to the commit (+dirty state) it was computed against. R-I: it is + // OMITTED for the ref-pair form rather than stamped with the working tree's sha, which would anchor the + // list to a commit it was not computed from. base_ref= and target_ref= are the anchor there, and they + // carry FULL shas because a wave measurement gets quoted into handoffs where a 9-char prefix is one + // collision from unverifiable. + atAttrs, refs.attrs, rep.identity.first, rep.scope.first, rep.configWarnAttr, rep.baselineAbsorbed == 0 ? std::string() : " baseline_absorbed=\"" + std::to_string( rep.baselineAbsorbed ) + "\"", + qdSidecarHealthAttrs( basis ) + ( collapse ? stale.attrs : std::string() ) + rep.kd.xml + rep.history.first + quality::ratchetAttrsXml( basis.extras, ex ) ); + for( const quality::Regression& r : rep.regs() ) + { + emitQdXmlRow( out, r, qdRowModel( r, /*gatingAllowed=*/true, rep.deltaRoot() ), ex ); + } + std::fputs( quality::improvedXml( basis.extras.improved, rep.deltaRoot(), ex ).c_str(), out ); // QD-CREDIT-ROW: never a row, never gating + if( j.scope.active() ) + { + // P1 — the DISCLOSURE half. Dropping these rows would make a scoped report a quieter lie than + // the unscoped one it replaces: the debt is real, it is in the same tree, and it will be in + // someone's report. So they are printed, in their own element, marked non-gating, with the one + // sentence a reader needs written where they meet it. Emitted even when EMPTY — an absent + // element then means "no scope was given", never "nobody else has anything open". + rw::emitTo( out, "", + j.outOfScope.size(), j.scopedOutGating ); + for( const quality::Regression& r : j.outOfScope ) { - // renderToString DISCLOSEd the failed buffer; the full document is the superset, written straight to stdout - emitDocument( stdout, /*collapse=*/false ); - return qualityDeltaExit( gatingCount, refs.degraded || basis.historyUnread.any() ); + emitQdXmlRow( out, r, qdRowModel( r, /*gatingAllowed=*/false, rep.deltaRoot() ), ex ); } - const std::string& chosen = foldPays( folded.text, full.text ) ? folded.text : full.text; // compactlegend.h: the margin and why - std::fwrite( chosen.data(), 1, chosen.size(), stdout ); - return qualityDeltaExit( gatingCount, refs.degraded || basis.historyUnread.any() ); // r26: only a PREEXISTING-worse AND major regression gates (== gating=) + rw::emitRaw( out, "" ); } - return std::nullopt; + // L2 — one row per stale ack (quality::staleAcksXml). M21(a): the escaper is passed in because sym= carries a + // canonical id (corpus text), unlike the closed-vocabulary kind=/why=. + std::vector saEsc; + std::fputs( quality::staleAcksXml( served, [ & ]( std::string_view t ) { return std::string( escapeXml( t, saEsc ) ); } ).c_str(), out ); + rw::emitRaw( out, "" ); +} + +// The identity-tree VERDICT (QdStaleCollapse::verdictOnly): the root line alone. +void emitQdVerdict( std::FILE* out, const QdReport& rep, const QdStaleCollapse& stale, const std::string& atAttrs ) +{ + rw::emitTo( out, "" + "", + rep.baseSel().marker, rep.staleAcks.size(), atAttrs, stale.attrs ); +} + +// REPORT (render half), XML. +// §B7.1 (CA4) — the heading used to open "only what changed for the WORSE vs .ripwire_quality_baseline", which is FALSE in +// every state but one: three of the five floors this verb can use are not that file, and in one of them the file was judged +// stale and DELETED from the user's tree during this very run. The floor actually used is named by baseline= on the root, +// so the heading points at that attribute instead of asserting a floor. +// 2026-09-02 (lane B): the marker states are still defined on the first screen — the only place a reader meets them — but +// ONE state per run, the one in force, rather than all five on every call (emitQualityDeltaLegend). +// Fix round 1 (rv-lean-trio item 5, owner ruling 5): a fold ships only when it PAYS (compactlegend.h foldPays: shorter +// by its margin, as written AND as the compact layer delivers it). The whole XML document is one renderer over a FILE*, +// so both candidates are rendered and measured, and the full document wins a fold that does not pay or a failed render +// (fx, dirty tree, one stale ack: 1512 B folded vs 1481 B full). +void emitQualityDeltaXml( const QdReport& rep ) +{ + using namespace rw; + std::vector esc; + const QdStaleCollapse stale = qdStaleCollapse( rep, [ & ]( std::string_view s ) -> std::string { return std::string( escapeXml( s, esc ) ); } ); + // R-I: at= is OMITTED for the ref-pair form (see the root). Read ONCE: both candidates print the same stamp. + const std::string atAttrs = rep.j.refPair ? std::string() : gitstamp::atAttr( rep.j.root ); + if( !stale.collapse ) + { + emitQdXmlDocument( stdout, rep, stale, atAttrs, /*collapse=*/false ); + return; + } + const Rendered full = renderToString( [ & ]( std::FILE* f ) { emitQdXmlDocument( f, rep, stale, atAttrs, /*collapse=*/false ); } ); + const Rendered folded = renderToString( [ & ]( std::FILE* f ) + { + if( stale.verdictOnly ) { emitQdVerdict( f, rep, stale, atAttrs ); } + else { emitQdXmlDocument( f, rep, stale, atAttrs, /*collapse=*/true ); } + } ); + if( !full.ok || !folded.ok ) + { + // renderToString DISCLOSEd the failed buffer; the full document is the superset, written straight to stdout + emitQdXmlDocument( stdout, rep, stale, atAttrs, /*collapse=*/false ); + return; + } + const std::string& chosen = foldPays( folded.text, full.text ) ? folded.text : full.text; // compactlegend.h: the margin and why + std::fwrite( chosen.data(), 1, chosen.size(), stdout ); +} + +// --quality-baseline / --quality-delta (the convergence-loop oracle): snapshot ccx + clone groups + dead candidates to +// .ripwire_quality_baseline; then report ONLY what a change made WORSE vs it. The "delta not absolute" discipline — a refine +// loop targets the regression it introduced, not absolute numbers (the defense against metric-gaming). exit 2 if any new +// debt, like --arch. The phases: resolve the floor and the delta (resolveDeltaBasis), JUDGE (judgeQualityDelta), then +// either WRITE ACKS (runQualityAckWrite) or REPORT (qdReportOf, then the JSON or XML rendering). +std::optional runQualityDelta( const MainDispatch& d ) +{ + using namespace rw; + const Config& cfg = d.cfg; + if( !cfg.qualityBaseline && !cfg.qualityDelta ) + { + return std::nullopt; + } + // D1 fix (HIGH): resolve BOTH sidecars against the analyzed ROOT, not the process CWD — + // see quality::rootQualifiedSidecar's comment for why a bare relative filename is unsafe here + // (a foreign cwd's sidecar could be silently rewritten, or even deleted by the stale-baseline + // self-heal). Computed once; every read/write/remove site downstream uses it. + const std::string baselineFile = quality::baselinePath( d.root ); + const std::string acksFile = quality::acksPath( d.root ); + if( cfg.qualityBaseline ) + { + return runQualityBaselinePin( d, baselineFile, acksFile ); + } + + // Precedence for the baseline: (1) an explicit `.ripwire_quality_baseline` sidecar (from + // --quality-baseline) wins whenever it is pinned at the CURRENT HEAD — the mid-task convergence loop + // (baseline once, edit, re-check) is unchanged; (2) else — no sidecar, or a STALE one (see R3 below) — + // if the root is a git repo with a HEAD tree, auto-baseline against HEAD so the "before I push" loop + // works with no start-of-task ritual (T0.1); (3) else degrade to the exit-1 "run --quality-baseline + // first" guidance (non-git / unborn / detached-no-tree — unchanged). + // + // STALENESS + the self-heal now live in ONE place, quality::selectBaseline — R3 owner ruling + // (2026-07-29): a sidecar whose pinned sha != the CURRENT HEAD sha is STALE, full stop. The B10.1b + // "reachable ancestor is a deliberately-pinned floor" carve-out this arm used to apply (gitIsAncestor) + // is REVOKED: a parallel session's sidecar pinned at a commit that merely happened to be an ancestor of + // this session's HEAD made THIS arm report 31 phantom regressions while the MCP quality_delta verb — + // same binary, same repo, same second — correctly reported zero. That divergence was only possible + // because each arm carried its own copy of the test; there is now exactly one, in quality.h. + // + // What remains this arm's own POLICY is the `removeStaleFile=true` argument: the stale sidecar is + // silently UNLINKED (best-effort) so the NEXT run sees no file at all rather than rediscovering the + // same dead pin, and the ONLY record is the `baseline=` XML attribute ("git-HEAD (stale sidecar + // removed)") — no stderr spam, which is the B10.1b noise fix that survives the ruling intact. The + // read-only MCP arm passes false and reports "…ignored" instead. When the unlink FAILS (read-only + // parent dir) this arm degrades to the read-only story — marker "…ignored", one DISCLOSE + // from the seam — because the pin is still on disk; `baseSel.isStaleFileOnDisk()` is the fact, and the + // fatal message words itself from it rather than from the intent. + // + // F-04 (round-4 audit) — SERIALIZE THE ACK LEDGER'S READ-MODIFY-WRITE, cross-process. + // + // --quality-ack reads the whole ledger (inside resolveDeltaBasis just below — the heal has to happen + // before computeDelta), folds this run's accepted findings into that map, then rewrites the file from + // it. Nothing serialized that. Three sessions acking DISJOINT rows in one shared checkout — the exact + // scenario --scope exists for — lost two of the three acks on 8 of 8 measured runs, because whichever + // process rewrote last overwrote a map the other two had already published into. + // + // The lock therefore has to span the READ as well as the write, which is why it is taken HERE and not + // inside writeAckRecords: a lock held only around the final rewrite still lets two processes read the + // same stale map first and then take turns clobbering. Engaged ONLY under --quality-ack — a read-only + // --quality-delta never waits, never creates the lockfile, and is byte-for-byte the run it always was. + // RAII: released when this function returns, on every path including the refusals below. quality.h's + // SidecarWriteLock has the lockfile's location (per-user cache dir, never a repo-tree sidecar), the + // wait budget, and the honest limits. + std::optional ackLock; + if( cfg.qualityAck ) + { + ackLock.emplace( acksFile ); + } + + // `refs` is declared HERE because it owns both materialized trees' teardown and they must outlive every read of the + // delta (QdJudged's header). + RefPairDelta refs; + DeltaBasis basis; + if( const std::optional refused = applyKindSelector( cfg, refs ) ) + { + return refused; + } + if( const std::optional refused = resolveDeltaBasis( d, baselineFile, refs, basis ) ) + { + return refused; + } + const bool refPair = !cfg.qualityDeltaRange.empty(); + QdJudged judged{ .cfg = cfg, .root = d.root, .refs = refs, .basis = basis, .refPair = refPair, .judged = refPair ? refs.target().ing : d.ing, + .workingGraph = d.g }; + if( const std::optional refused = judgeQualityDelta( judged ) ) + { + return refused; + } + if( cfg.qualityAck ) + { + return runQualityAckWrite( judged, acksFile ); + } + + const QdReport report = qdReportOf( judged, baselineFile ); + // the stderr lines of a partial or over-the-limit answer come first: it says so on the channel a human reads before + // anything else + emitMemoryLines( report.kd, refs ); + // P2.5 — one stderr line NAMING the gating finding, in --token-budget's style ("ripwire: --token-budget + // exceeded: est_tokens=… > budget=…"). stdout is the machine artifact and a caller that only checks + // `$?` gets a number with no subject; this puts the WHICH on the channel a human reads, without + // touching the XML contract. Names the first gating row in the already-sorted list (deterministic). + // §A4 (minor): emitted BEFORE the format fork — the line is about the EXIT CODE, which both formats share, so it + // belongs to neither (under --json the fork used to return first, and a script reading `$?` got no subject). + emitQdGatingLine( report.regs(), report.counts.gating, report.deltaRoot() ); + if( cfg.json ) + { + emitQualityDeltaJson( report ); + } + else + { + emitQualityDeltaXml( report ); + } + return report.exitCode(); } // #387: the range form compares two COMMITTED trees, each materialized and indexed by loadRefPairDelta, and reads the From 1deff0fc4ec8ca71987e584e0c0b1f507f60fe66 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:45:23 -0500 Subject: [PATCH 02/61] refactor(quality): --quality-delta computes silently, decides each root attribute once GE-RUNQD round 2, from the blind review of 38c9aac7d; output byte-identical. - computeQdReport (was qdReportOf) prints nothing: the RIPWIRE_STATS, unread-history, .ripwire_config, memory and gating lines all print from emitQdStderrLines, in their old order. registerMacroConfigWarningAttr's stderr half is now emitRegisterMacroConfigWarnings (--dead-code keeps the combined call). - Each optional root attribute is one QdRootField {xml, json} built once in qdRootFieldsOf (stale, register-macro-excluded, at, the range refs, identity, scope, config-warnings, baseline_absorbed, the bad-line counts, head_basis, the two exclusion counts, kinds, history, ratchet); qdRootTail renders the tail in one order for both formats. This replaces the .first/.second pairs and the per-format presence tests. - The context structs are gone: applyScopeAndAcks returns a QdPartition; the ack arm takes the config, scope, partition and basis it uses; acceptFinding takes the ledger map, the cid index, the scope spec and the reason. The report reads a read-only QdComparison built once. - The bare form's stale-ack snapshot is computed in runQualityDelta from d.ing and d.g, with its write to basis.passes visible there. - The stale fold is one optional QdStaleFold (no second collapse bool), and qdExpandNextAttr drops its unreachable duplication test. Co-Authored-By: Claude Opus 5.5 --- src/verbs_quality.h | 676 ++++++++++++++++++++++++-------------------- 1 file changed, 374 insertions(+), 302 deletions(-) diff --git a/src/verbs_quality.h b/src/verbs_quality.h index c730c16e4..102f96b39 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -2166,15 +2166,12 @@ inline void emitQualityDeltaLegend( const QualityDeltaLegendParts& p, std::FILE* // F-13 — the one place both --dead-code and --quality-delta turn a RegisterMacroConfigDiagnostics into // output: the specific keys/names on stderr (never guessed at in the XML — a hand-edited config's tokens -// are not free text an attribute repeats), and the shared `config-warnings="N"` attribute string, present -// only when non-zero (this file's standing convention for every optional root attribute). One function so -// the two verbs cannot report the same misconfiguration two different ways. -inline std::string registerMacroConfigWarningAttr( const rw::quality::RegisterMacroConfigDiagnostics& diag ) +// are not free text an attribute repeats; emitRegisterMacroConfigWarnings), and the shared `config-warnings="N"` +// attribute, present only when non-zero (this file's standing convention for every optional root attribute; +// --quality-delta spells it as a QdRootField). One pair of functions so the two verbs cannot report the same +// misconfiguration two different ways. +inline void emitRegisterMacroConfigWarnings( const rw::quality::RegisterMacroConfigDiagnostics& diag ) { - if( diag.total() == 0 ) - { - return std::string(); - } const auto joined = [] ( const std::vector& v ) -> std::string { std::string out; @@ -2195,7 +2192,13 @@ inline std::string registerMacroConfigWarningAttr( const rw::quality::RegisterMa rw::emitTo( stderr, "ripwire: .ripwire_config's register_macros= names a macro matching no indexed symbol (typo, or unused): {}\n", joined( diag.inertNames ).c_str() ); } - return " config-warnings=\"" + std::to_string( diag.total() ) + "\""; +} + +// --dead-code's half of F-13: the stderr lines, then the attribute. +inline std::string registerMacroConfigWarningAttr( const rw::quality::RegisterMacroConfigDiagnostics& diag ) +{ + emitRegisterMacroConfigWarnings( diag ); + return diag.total() == 0 ? std::string() : " config-warnings=\"" + std::to_string( diag.total() ) + "\""; } // H10 (capture-audit 2026-09-04): the --quality-ack run that has NOTHING to accept. It used to re-serialise @@ -2584,67 +2587,48 @@ inline std::string presentXmlAttr( std::string_view name, const std::string& v, return v.empty() ? std::string() : " " + std::string( name ) + "=\"" + esc( v ) + "\""; } -// ── --quality-delta, in three phases: JUDGE (scope partition + ack ratchet), then either WRITE ACKS or REPORT ────────── +// ── --quality-delta, in phases: SCOPE + RATCHET, then either WRITE ACKS or COMPUTE the report and RENDER it ────────────── // GE-RUNQD: runQualityDelta used to compute the answer and render it in one 744-line body, with the JSON and XML row -// emitters written twice inside it. The phases are now named functions over two small state structs — QdJudged (the -// comparison after the partition and the ratchet) and QdReport (everything a rendering reads) — and one row model -// (QdRowModel) decides each row's printed facts once for both formats. - -// The comparison once the scope partition and the ack ratchet ran: what the --quality-ack writer and the report both read. -// `refs` owns both materialized trees' teardown and must outlive every read of basis.regs (DeltaBasis's header states that -// rule, and why every path and symbol downstream is spelled against basis.deltaRoot rather than against `root`). -struct QdJudged +// emitters written twice inside it. The phases are now named functions: applyScopeAndAcks returns what the partition and +// the ratchet decided (QdPartition); runQualityAckWrite is the --quality-ack arm; computeQdReport builds every count and +// root disclosure once, silently (QdReport, with each root attribute a QdRootField spelled for both formats); the stderr +// lines print from emitQdStderrLines; one row model (QdRowModel) decides each row's printed facts for both formats. + +// What the scope partition and the ack ratchet decided over basis.regs (applyScopeAndAcks): the rows that belong to someone +// else, the acks suppressing a finding in a session other than the one that wrote them, and the two counts they feed. +struct QdPartition { - const rw::Config& cfg; - const std::string& root; - RefPairDelta& refs; - DeltaBasis& basis; - const bool refPair; - const rw::IngestResult& judged; // the JUDGED tree's index: tree B in the ref-pair form, else the working tree - const rw::Graph& workingGraph; // the working tree's graph: the bare form's stale-ack snapshot reads it - rw::quality::Scope scope; std::vector outOfScope; std::vector foreignAcks; - std::size_t diffFileCount = 0; // P1.2: 0 = the reserved diff token was not used - std::size_t scopedOutGating = 0; - std::size_t ackedCount = 0; + std::size_t scopedOutGating = 0; // out-of-scope rows that would have gated (would-gate=) + std::size_t ackedCount = 0; // in-scope rows the ack ledger suppressed (acked=) }; -// JUDGE — the scope partition, then the per-finding ack ratchet, over the delta resolveDeltaBasis computed. Returns the -// refusal's exit code when the scope cannot be used. -std::optional judgeQualityDelta( QdJudged& j ) +// SCOPE + RATCHET — split basis.regs by --scope, then suppress what the ack ledger already accepted. basis.regs keeps only +// the in-scope, unsuppressed rows. +// Signal-to-noise round — the per-finding ACK RATCHET. Suppress findings already accepted (with a +// reason) in .ripwire_quality_acks, honestly (acked="N"); a finding that WORSENED past its acked +// magnitude survives the filter and reappears. --quality-ack merges the currently-VISIBLE findings +// into that file instead of printing the report (accepting what previous acks already hid would be +// a silent blanket ack — only what the agent can see right now is what it can accept). +// R1 IDENTITY: the ledger was read and HEALED inside resolveDeltaBasis (it had to be — the baseline +// half of the same healing has to precede computeDelta), so this step takes the already-current map +// rather than re-reading the file and undoing it. +QdPartition applyScopeAndAcks( const rw::quality::Scope& scope, DeltaBasis& basis ) { using namespace rw; - std::vector& regs = j.basis.regs; - // ── P1 SCOPE — the OWNERSHIP partition for a working tree with several writers in it ───────────── - j.scope = quality::parseScope( j.cfg.qualityScope ); - if( const std::optional refused = expandScopeDiff( j.scope, j.refPair, j.judged, j.root, j.basis.deltaRoot, j.diffFileCount ) ) - { - return refused; - } - if( const std::optional refused = refuseUnusableScope( j.cfg, j.scope, j.judged, j.basis.deltaRoot, j.refs.scopeFiles() ) ) - { - return refused; - } - - // Signal-to-noise round — the per-finding ACK RATCHET. Suppress findings already accepted (with a - // reason) in .ripwire_quality_acks, honestly (acked="N"); a finding that WORSENED past its acked - // magnitude survives the filter and reappears. --quality-ack merges the currently-VISIBLE findings - // into that file instead of printing the report (accepting what previous acks already hid would be - // a silent blanket ack — only what the agent can see right now is what it can accept). - // R1 IDENTITY: the ledger was read and HEALED inside resolveDeltaBasis (it had to be — the baseline - // half of the same healing has to precede computeDelta), so this arm takes the already-current map - // rather than re-reading the file and undoing it. - gtl::btree_map& acks = j.basis.acks; - quality::countAckRescues( regs, acks, j.basis.healing.ackRemap, j.basis.healing.ackedByRename, j.basis.healing.ackedByContent ); + std::vector& regs = basis.regs; + const gtl::btree_map& acks = basis.acks; + QdPartition out; + quality::countAckRescues( regs, acks, basis.healing.ackRemap, basis.healing.ackedByRename, basis.healing.ackedByContent ); // P1.4 PROVENANCE — the foreign-ack sweep reads the PRE-ratchet list on purpose (computeForeignAcks' // header states why: the question is about acks that are suppressing something right now). - j.foreignAcks = quality::computeForeignAcks( regs, acks ); + out.foreignAcks = quality::computeForeignAcks( regs, acks ); // P1 — the partition runs BEFORE the ratchet so acked="N" counts THIS scope's suppressions rather // than the whole tree's (partitionByScope owns the rest of the rule). - j.scopedOutGating = partitionByScope( j.scope, regs, j.outOfScope, acks ); - j.ackedCount = quality::applyAckRatchet( regs, acks ); - return std::nullopt; + out.scopedOutGating = partitionByScope( scope, regs, out.outOfScope, acks ); + out.ackedCount = quality::applyAckRatchet( regs, acks ); + return out; } // --ack-only=SUBSTR[,SUBSTR]: ack a SUBSET instead of everything on screen. Without it, the only way to accept one @@ -2697,22 +2681,25 @@ void discloseAckBackfill( const rw::quality::AckBackfill& backfilled ) backfilled.resolved, backfilled.refreshed, backfilled.unverified, backfilled.unresolved, backfilled.ineligible, backfilled.measured ); } -// Fold ONE accepted finding into the ack ledger `j.basis.acks`, then prove the re-score formula agrees with the live one. -void acceptFinding( QdJudged& j, const rw::quality::Regression& r ) +// Fold ONE accepted finding into the ack ledger `acks`, then prove the re-score formula agrees with the live one. `cidByKey` +// is the healing pre-pass's content-id index; `scopeSpec` is the --scope this run names (nullptr: none, so an existing row +// keeps its `by`); `reason` is --quality-ack's text (empty: an existing row keeps its reason). +void acceptFinding( gtl::btree_map& acks, const gtl::btree_map& cidByKey, + const rw::quality::Regression& r, const std::string* scopeSpec, std::string_view reason ) { using namespace rw; // P0.3: the ack IDENTITY is ackKindToken, not the bare kind — a zero-magnitude finding // (was==now==0: dead-code, api-surface tier A) acks per ORIGIN, so acking the never-gating // new-symbol row can no longer blank-check the gating contract-change row on the same symbol. const std::string ackKind = quality::ackKindToken( r ); - quality::AckRecord& rec = j.basis.acks[ quality::ackMapKey( ackKind, r.key ) ]; + quality::AckRecord& rec = acks[ quality::ackMapKey( ackKind, r.key ) ]; // R1 IDENTITY: stamp the finding's SCRUBBED CONTENT ID alongside the key, so this ack can // still be found after a move git records no rename for. Absent (0) for the two clone kinds — // their key is a member-SET hash with no single body behind it — and the row is then written // exactly as it is today. A REFRESH, not a preserve: re-acking a finding re-reads the body, so // the stored cid always describes the code as accepted, never as it was two edits ago. - const auto cidIt = j.basis.healing.cids.cidByKey.find( r.key ); - const std::uint64_t cid = ( cidIt == j.basis.healing.cids.cidByKey.end() ) ? 0u : cidIt->second; + const auto cidIt = cidByKey.find( r.key ); + const std::uint64_t cid = ( cidIt == cidByKey.end() ) ? 0u : cidIt->second; // P1.4 PROVENANCE: `by` follows the SAME rule the reason does one line down — set from this // run when this run supplies one, PRESERVED otherwise. A later scope-less re-ack therefore // refreshes the magnitude without erasing the record of who accepted the row originally, @@ -2727,10 +2714,9 @@ void acceptFinding( QdJudged& j, const rw::quality::Regression& r ) // JUST ACCEPTED, never as it was some earlier run. See AckRecord's doc comment for what each // one is and why a later run can re-score from them alone. rec = quality::AckRecord{ ackKind, r.key, std::max( rec.ackNow, r.now ), cid, - j.scope.active() ? j.scope.spec : rec.by, + scopeSpec != nullptr ? *scopeSpec : rec.by, r.was, r.now, r.facet, r.path, r.line, quality::AckProvenance::Measured, - j.cfg.qualityAckReason.empty() ? rec.reason - : quality::composeAckReason( rec.reason, std::string( j.cfg.qualityAckReason ) ) }; + reason.empty() ? rec.reason : quality::composeAckReason( rec.reason, std::string( reason ) ) }; // SELF-CHECK, not a one-off test: every magnitude-bearing ack proves that the TABLE-DRIVEN // re-score formula agrees with the LIVE one on the row it just built. NOT a full round trip — // rescoreAckRecord runs here on the in-memory `rec` directly; it never goes through @@ -2786,48 +2772,58 @@ int refuseUnmatchedAckOnly( std::string_view ackOnly, const std::string& acksFil return 1; } +// What one --quality-ack run counted, for writeAcceptedAcks's report. +struct QdAckTally +{ + std::size_t findings = 0; // visible findings this run could accept + std::size_t alreadyAcked = 0; // suppressed by an earlier ack (acked=) + std::size_t accepted = 0; + std::size_t skipped = 0; // visible but not selected by --ack-only + bool narrowed = false; // --ack-only was given +}; + // Rewrite the ledger with this run's accepted findings and say what was written. Returns the exit code. -int writeAcceptedAcks( const QdJudged& j, const std::string& acksFile, std::size_t ackWritten, std::size_t ackSkipped ) +int writeAcceptedAcks( const std::string& acksFile, const gtl::btree_map& acks, const QdAckTally& tally, + const rw::quality::Scope& scope, std::size_t outOfScopeCount ) { using namespace rw; - const std::size_t findingCount = j.basis.regs.size(); - const bool wroteAcks = quality::writeAckRecords( acksFile, j.basis.acks ); - if( !wroteAcks ) + if( !quality::writeAckRecords( acksFile, acks ) ) { rw::emitTo( stderr, "ripwire: could not write {}\n", acksFile.c_str() ); return 1; } - if( !j.cfg.qualityAckOnly.empty() ) + if( tally.narrowed ) { rw::emitTo( stderr, "ripwire: acknowledged {} of {} finding(s) ({} left UNACKED by --ack-only, {} already acked) → {}\n", - ackWritten, findingCount, ackSkipped, j.ackedCount, acksFile.c_str() ); + tally.accepted, tally.findings, tally.skipped, tally.alreadyAcked, acksFile.c_str() ); } else { - rw::emitTo( stderr, "ripwire: acknowledged {} finding(s) ({} already acked) → {}\n", findingCount, j.ackedCount, acksFile.c_str() ); + rw::emitTo( stderr, "ripwire: acknowledged {} finding(s) ({} already acked) → {}\n", tally.findings, tally.alreadyAcked, acksFile.c_str() ); } // P1 — the skip is DISCLOSED, never silent: the count of rows this ack deliberately did not // touch is the whole reason the caller passed a scope, and a quiet success would leave them // believing the ledger now covers the report they were looking at. - if( j.scope.active() && !j.outOfScope.empty() ) + if( scope.active() && outOfScopeCount != 0 ) { rw::emitTo( stderr, "ripwire: {} finding(s) OUT OF SCOPE for --scope={} were left unacked — not yours to accept " "(they are still in the report, under the out-of-scope element)\n", - j.outOfScope.size(), j.scope.spec.c_str() ); + outOfScopeCount, scope.spec.c_str() ); } return 0; } -// WRITE ACKS — the --quality-ack arm: fold the VISIBLE findings --ack-only selects into the ledger instead of printing the -// report. Returns the exit code. -int runQualityAckWrite( QdJudged& j, const std::string& acksFile ) +// WRITE ACKS — the --quality-ack arm: fold the VISIBLE findings --ack-only selects into the ledger (basis.acks, then the +// file) instead of printing the report. Returns the exit code. +int runQualityAckWrite( const rw::Config& cfg, const rw::quality::Scope& scope, const QdPartition& part, DeltaBasis& basis, + const std::string& acksFile ) { using namespace rw; - const std::string_view ackOnly = j.cfg.qualityAckOnly; + const std::string_view ackOnly = cfg.qualityAckOnly; const auto selected = [ & ]( const quality::Regression& r, bool inScope ) { return ackOnlySelects( ackOnly, r, inScope ); }; // P1 — THE RUBBER-STAMP GUARD (refuseForeignAckSelection owns the rule and the message). - if( const std::optional refused = refuseForeignAckSelection( j.cfg, j.scope, j.outOfScope, j.basis.deltaRoot, selected ) ) + if( const std::optional refused = refuseForeignAckSelection( cfg, scope, part.outOfScope, basis.deltaRoot, selected ) ) { return *refused; } @@ -2839,29 +2835,30 @@ int runQualityAckWrite( QdJudged& j, const std::string& acksFile ) // NOTHING: healing the ledger's provenance is the same class of forward repair the identity // remap already performs on every ack, and H10's ackNothingToAccept re-renders and notices. // quality::backfillCloneAckProvenance owns the rule, what it refuses to touch, and why. - discloseAckBackfill( quality::backfillCloneAckProvenance( j.basis.acks, j.basis.cloneIdioms ) ); + discloseAckBackfill( quality::backfillCloneAckProvenance( basis.acks, basis.cloneIdioms ) ); - std::size_t ackWritten = 0, ackSkipped = 0; - for( const quality::Regression& r : j.basis.regs ) + const std::string* const scopeSpec = scope.active() ? &scope.spec : nullptr; + QdAckTally tally{ .findings = basis.regs.size(), .alreadyAcked = part.ackedCount, .narrowed = !ackOnly.empty() }; + for( const quality::Regression& r : basis.regs ) { if( !selected( r, /*inScope=*/true ) ) { - ++ackSkipped; + ++tally.skipped; continue; } - ++ackWritten; - acceptFinding( j, r ); + ++tally.accepted; + acceptFinding( basis.acks, basis.healing.cids.cidByKey, r, scopeSpec, cfg.qualityAckReason ); } - if( ackWritten == 0 && !ackOnly.empty() ) + if( tally.accepted == 0 && tally.narrowed ) { - return refuseUnmatchedAckOnly( ackOnly, acksFile, j.basis.acks, j.basis.regs.size() ); + return refuseUnmatchedAckOnly( ackOnly, acksFile, basis.acks, tally.findings ); } // H10: nothing to accept — leave a canonical ledger alone, heal a non-canonical one (ackNothingToAccept) - if( j.basis.regs.empty() ) + if( basis.regs.empty() ) { - return ackNothingToAccept( acksFile, j.basis.acks, j.scope, j.outOfScope.size() ); + return ackNothingToAccept( acksFile, basis.acks, scope, part.outOfScope.size() ); } - return writeAcceptedAcks( j, acksFile, ackWritten, ackSkipped ); + return writeAcceptedAcks( acksFile, basis.acks, tally, scope, part.outOfScope.size() ); } // r26 ORIGIN SPLIT — three counts over the VISIBLE (post-ack) findings, one pass: @@ -2889,97 +2886,202 @@ QdCounts countQdRows( const std::vector& regs ) return c; } -// Everything one --quality-delta answer renders, computed before the format is chosen: the JSON and XML emitters read only -// this (plus the judged comparison it points at), so the two formats cannot disagree about a fact. -struct QdReport +// The finished comparison every report step reads, READ-ONLY: the floor and the delta (basis), the range form's trees +// (refs), the scope and what the partition and the ratchet decided. Built once, after the last write to any of them. +// Every path and symbol downstream is spelled against basis.deltaRoot rather than against `root` (DeltaBasis's header). +struct QdComparison { - const QdJudged& j; - std::vector staleAcks; - std::vector saRows; // stale + foreign acks: the one / "sa" list - QdCounts counts; - std::size_t baselineAbsorbed = 0; - std::pair identity, history, scope; // (XML attrs, JSON members), built once for both - rw::quality::RegisterMacroConfigDiagnostics configDiag; - std::string configWarnAttr; - KindsDisclosure kd; - bool deadRan = false; // dead-code's side counts exist only when it ran - - const rw::quality::BaselineSelection& baseSel() const noexcept { return j.basis.baseSel; } - const std::vector& regs() const noexcept { return j.basis.regs; } - const std::string& deltaRoot() const noexcept { return j.basis.deltaRoot; } - // The exit code every rendering returns (qualityDeltaExit): r26 — only a PREEXISTING-worse AND major regression gates (== gating=). - int exitCode() const noexcept { return qualityDeltaExit( counts.gating, j.refs.degraded || j.basis.historyUnread.any() ); } + const rw::Config& cfg; + const std::string& root; + const RefPairDelta& refs; + const DeltaBasis& basis; + const rw::quality::Scope& scope; + const QdPartition& part; + const rw::IngestResult& judgedIndex; // the JUDGED tree's index: tree B in the range form, else the working tree + bool refPair; // the range form (--quality-delta=A..B) + std::size_t diffFileCount; // P1.2: files the reserved diff token expanded to (0 = not used) }; -// REPORT (compute half) — the stale-ack verdicts, the counts and every root disclosure, in the order their stderr lines -// have always printed. -QdReport qdReportOf( const QdJudged& j, const std::string& baselineFile ) +// Which spelling of a root disclosure an emitter wants. +enum class QdFormat : std::uint8_t { - using namespace rw; - QdReport rep{ .j = j }; - const gtl::btree_map& acks = j.basis.acks; - // L2 — stale-ack disclosure (rationale: quality.h's computeStaleAcks). Checked against the CURRENT - // tree, not the baseline above, so it costs one more computeSnapshot; skipped when the ledger is - // empty. Reported, never gated — the exit code reads `regs` alone. - // R-I: "the CURRENT tree" is the JUDGED tree, which in the ref-pair form is tree B — checking the - // ledger against the working tree there would report acks as stale because of edits that have nothing - // to do with the comparison being made. - // qd-memory-degrade: refPairStaleAcks owns the two range-form departures (a changed-files answer judges none; a - // kind selection judges its own kinds' acks only). - rep.staleAcks = acks.empty() ? std::vector{} - : j.refPair ? refPairStaleAcks( acks, j.refs ) - : quality::computeStaleAcks( acks, quality::computeSnapshot( j.judged, j.workingGraph, j.cfg.rootPath, nullptr, {}, &j.basis.passes ) ); - if( std::getenv( "RIPWIRE_STATS" ) ) // QD-ENVOY-TIME cost bound: Type-3 passes this call ran (test/qdtype3oncecheck.sh) + Xml, + Json +}; + +// One optional root disclosure of the --quality-delta answer, decided ONCE and spelled for both formats: `xml` is spliced +// into the root element, `json` into the top-level object. Both are empty when the fact is absent — absent means "never +// happened" or "not run", never 0. A field the JSON object has never carried keeps `json` empty. +struct QdRootField +{ + std::string xml, json; + + const std::string& in( QdFormat format ) const noexcept { return format == QdFormat::Xml ? xml : json; } +}; + +// A count as a root disclosure: ` name="N"` / `,"name":N` when `present`, else absent. +QdRootField qdCountField( std::string_view name, std::size_t count, bool present ) +{ + if( !present ) { - rw::emitTo( stderr, "ripwire: quality-passes type3_runs={} type3_pairs={}\n", gType3PassRuns.load( std::memory_order_relaxed ), - gType3PassPairs.load( std::memory_order_relaxed ) ); + return {}; + } + const std::string n = std::to_string( count ); + return { " " + std::string( name ) + "=\"" + n + "\"", ",\"" + std::string( name ) + "\":" + n }; +} + +// Every root disclosure, each built once (qdRootFieldsOf). `stale` and `registerMacroExcluded` sit between the fixed +// counts; the rest form the root's tail in qdRootTail's order. +struct QdRootFields +{ + // qd-memory-degrade: stale= and register-macro-excluded= are absent (never 0) when their pass did not run + QdRootField stale, registerMacroExcluded; + QdRootField at; // at=: commit+dirty state; the range form omits it in XML and says null in JSON + QdRootField rangeRefs; // R-I: base_ref= target_ref= churn= (RefPairDelta::attrs / jsonAttrs) + QdRootField identity; // R1 IDENTITY: renames and acks re-filed by rename or content (quality::identityDisclosure) + QdRootField scopeDisclosure; // P1/P1.4: --scope, out-of-scope and foreign-ack counts (quality::scopeDisclosure) + QdRootField configWarnings; // F-13: .ripwire_config keys/names that did nothing + QdRootField baselineAbsorbed; // H11: debt the honored sidecar absorbed + QdRootField baselineBadLines, acksBadLines; // 2026-09-06: unparseable sidecar lines skipped (XML only, as always) + QdRootField headBasis; // #228: which basis produced a git-HEAD floor (absent = the archived HEAD tree) + QdRootField declinedCallExcluded, valueRefExcluded; // dead-code exemptions, absent at zero + QdRootField kinds; // qd-memory-degrade: kinds not run, why, the replay, the peak (kindsDisclosure) + QdRootField history; // hwh-fix4 (N1): history a gating kind could not read (unread_history=) + QdRootField ratchet; // D4: the ratchet's reference point and what it could not read +}; + +// The root's tail in one order for both formats. `foldAttrs` (XML only) is the stale fold's stale_by_kind=/stale_next=, +// which sits between the exclusion counts and the kinds disclosure. +std::string qdRootTail( const QdRootFields& f, QdFormat format, std::string_view foldAttrs ) +{ + std::string out; + for( const QdRootField* field : { &f.at, &f.rangeRefs, &f.identity, &f.scopeDisclosure, &f.configWarnings, &f.baselineAbsorbed, + &f.baselineBadLines, &f.acksBadLines, &f.headBasis, &f.declinedCallExcluded, &f.valueRefExcluded } ) + { + out += field->in( format ); + } + out += foldAttrs; + for( const QdRootField* field : { &f.kinds, &f.history, &f.ratchet } ) + { + out += field->in( format ); } + return out; +} + +// Everything one --quality-delta answer renders, computed before the format is chosen (computeQdReport): the JSON and XML +// emitters read only this and the comparison it points at, so the two formats cannot disagree about a fact. +struct QdReport +{ + const QdComparison& c; + std::vector staleAcks; + std::vector saRows; // stale + foreign acks: the one / "sa" list + QdCounts counts; + std::size_t baselineAbsorbed = 0; + rw::quality::RegisterMacroConfigDiagnostics configDiag; // its stderr lines are emitQdStderrLines' + KindsDisclosure kd; + QdRootFields root; + + // The exit code every rendering returns (qualityDeltaExit): r26 — only a PREEXISTING-worse AND major regression gates + // (== gating=); a changed-files answer, or one whose gating history could not be read, is partial. + int exitCode() const noexcept { return qualityDeltaExit( counts.gating, c.refs.degraded || c.basis.historyUnread.any() ); } +}; +// Every root disclosure of `rep`, each decided here once for both formats. +QdRootFields qdRootFieldsOf( const QdReport& rep ) +{ + using namespace rw; + const QdComparison& c = rep.c; + const DeltaBasis& basis = c.basis; + const bool deadRan = !c.refPair || quality::kindSelected( c.refs.kinds, "dead-code" ); // dead-code's side counts exist only when it ran + const auto fromPair = []( std::pair p ) { return QdRootField{ std::move( p.first ), std::move( p.second ) }; }; + std::vector esc; + QdRootFields f; + f.stale = qdCountField( "stale", rep.staleAcks.size(), !c.refs.degraded ); + f.registerMacroExcluded = qdCountField( "register-macro-excluded", basis.registerMacroExcluded, deadRan ); + // R-I: the range form's list was not computed "at" any working-tree state — base_ref= and target_ref= are its anchor, so + // XML omits at= and JSON says null (never a fake sha); a non-git root is null too. + const std::string atValue = c.refPair ? std::string() : gitstamp::stampAt( c.root ); + f.at = { atValue.empty() ? std::string() : " at=\"" + atValue + "\"", + ",\"at\":" + ( atValue.empty() ? std::string( "null" ) : "\"" + atValue + "\"" ) }; + f.rangeRefs = { c.refs.attrs, c.refs.jsonAttrs }; + f.identity = fromPair( quality::identityDisclosure( basis.healing ) ); + f.scopeDisclosure = fromPair( quality::scopeDisclosure( c.scope, c.part.outOfScope.size(), c.part.scopedOutGating, c.part.foreignAcks.size(), c.diffFileCount ) ); + f.configWarnings = qdCountField( "config-warnings", rep.configDiag.total(), rep.configDiag.total() != 0 ); + f.baselineAbsorbed = qdCountField( "baseline_absorbed", rep.baselineAbsorbed, rep.baselineAbsorbed != 0 ); + f.baselineBadLines = { qdCountField( "baseline_bad_lines", basis.baseSel.sidecarBadLines, basis.baseSel.sidecarBadLines != 0 ).xml, {} }; + f.acksBadLines = { qdCountField( "acks_bad_lines", basis.acksBadLines, basis.acksBadLines != 0 ).xml, {} }; + if( basis.headBasis != nullptr ) + { + f.headBasis = { std::string( " head_basis=\"" ) + basis.headBasis + "\"", std::string( ",\"head_basis\":\"" ) + basis.headBasis + "\"" }; + } + f.declinedCallExcluded = qdCountField( "declined-call-excluded", basis.declinedCallExcluded, basis.declinedCallExcluded != 0 ); + f.valueRefExcluded = qdCountField( "value-ref-excluded", basis.valueRefExcluded, basis.valueRefExcluded != 0 ); + f.kinds = { rep.kd.xml, rep.kd.json }; + f.history = fromPair( quality::historyUnreadDisclosure( basis.historyUnread ) ); + f.ratchet = { quality::ratchetAttrsXml( basis.extras, [ & ]( std::string_view s ) { return std::string( escapeXml( s, esc ) ); } ), + quality::ratchetAttrsJson( basis.extras ) }; + return f; +} + +// COMPUTE — the counts, the rows and every root disclosure of one answer. Prints nothing: its stderr lines are +// emitQdStderrLines'. `staleAcks` are the ledger rows the judged tree no longer supports (the caller computes them, since +// the bare form's snapshot writes the shared tree passes). +QdReport computeQdReport( const QdComparison& c, std::vector staleAcks, const std::string& baselineFile ) +{ + using namespace rw; + QdReport rep{ .c = c, .staleAcks = std::move( staleAcks ) }; // P1.4 — the family now carries THREE whys, and the third is counted SEPARATELY: stale= means // "this ack no longer applies", and a foreign ack applies fine — it is the SESSION that was wrong, // not the target. Merging the rows into one list keeps the two emitters from growing a second loop // each; keeping the COUNTS apart keeps stale= meaning what it has always meant. rep.saRows = rep.staleAcks; - rep.saRows.insert( rep.saRows.end(), j.foreignAcks.begin(), j.foreignAcks.end() ); + rep.saRows.insert( rep.saRows.end(), c.part.foreignAcks.begin(), c.part.foreignAcks.end() ); // M21(a): name the rows the tree can still name, against the SAME tree computeStaleAcks judged // (tree B in the ref-pair form) — naming a stale ack after the working tree would print an identity // the verdict was never computed from. Costs one walk over the judged symbols, and only when there are rows. - quality::stampStaleAckIdentity( rep.saRows, j.judged, j.refPair ? std::string_view( j.refs.target().root ) : std::string_view( j.cfg.rootPath ) ); + quality::stampStaleAckIdentity( rep.saRows, c.judgedIndex, c.refPair ? std::string_view( c.refs.target().root ) : std::string_view( c.cfg.rootPath ) ); - rep.counts = countQdRows( j.basis.regs ); + rep.counts = countQdRows( c.basis.regs ); // H11 — the absorbed-debt stamp on the honored sidecar, or 0. Read ONLY when the sidecar is the floor // in force: on the git-HEAD and ref-pair floors there is no pin whose contents could have absorbed // anything, and printing a 0 there would define an attribute about a file this run did not use. - rep.baselineAbsorbed = ( rep.baseSel().marker == std::string_view( "sidecar" ) ) ? quality::readBaselineAbsorbed( baselineFile ) : 0; + rep.baselineAbsorbed = ( c.basis.baseSel.marker == std::string_view( "sidecar" ) ) ? quality::readBaselineAbsorbed( baselineFile ) : 0; + // F-13 — the .ripwire_config diagnosis. #387: the inert-name test reads the JUDGED tree's index, which in the ref-pair + // form is tree B — the working tree is not indexed there at all (runQualityDeltaRangeBeforeIngest). + // qd-memory-degrade: not over a changed-files index, which cannot tell an inert name from one the tree defines (also_skipped=) + rep.configDiag = c.refs.degraded ? quality::RegisterMacroConfigDiagnostics{} : quality::diagnoseRegisterMacroConfig( c.judgedIndex, c.root ); + // qd-memory-degrade: the kinds this answer did not run, why, and the replay — plus the peak, read once now that the + // comparison is done (kindsDisclosure). + rep.kd = kindsDisclosure( c.cfg, c.refs, c.basis, c.refPair ); + rep.root = qdRootFieldsOf( rep ); + return rep; +} - // R1 IDENTITY — the disclosure, built ONCE for both emitters (quality::identityDisclosure). An ack - // that follows a rename is a claim about identity, and a claim is only honest if the reader can see - // what it rested on; building the XML and JSON halves in one place is what keeps the two surfaces - // from disclosing different things about the same run. - rep.identity = quality::identityDisclosure( j.basis.healing ); - // hwh-fix4 (N1): the history a gating kind could not read, one builder for every emitter (absent when all was read) - rep.history = quality::historyUnreadDisclosure( j.basis.historyUnread ); - if( rep.counts.gating == 0 && j.basis.historyUnread.any() ) +// The human channel's lines of one answer, in the order they have always printed, before stdout is written: a stdout +// answer that is partial, ran past the memory limit or gates says so first on the channel a human reads. +void emitQdStderrLines( const QdReport& rep ) +{ + using namespace rw; + const QdComparison& c = rep.c; + if( std::getenv( "RIPWIRE_STATS" ) ) // QD-ENVOY-TIME cost bound: Type-3 passes this call ran (test/qdtype3oncecheck.sh) + { + rw::emitTo( stderr, "ripwire: quality-passes type3_runs={} type3_pairs={}\n", gType3PassRuns.load( std::memory_order_relaxed ), + gType3PassPairs.load( std::memory_order_relaxed ) ); + } + if( rep.counts.gating == 0 && c.basis.historyUnread.any() ) { rw::emitTo( stderr, "ripwire: --quality-delta: not a clean pass - git history a gating kind needs could not be read ({}; a partial clone " - "does not download it), so a gating row may be missing: exit 6\n", rep.history.first.substr( 1 ).c_str() ); + "does not download it), so a gating row may be missing: exit 6\n", rep.root.history.xml.substr( 1 ).c_str() ); } - - // P1/P1.4 — the scope disclosure, built once for both emitters (quality::scopeDisclosure). - rep.scope = quality::scopeDisclosure( j.scope, j.outOfScope.size(), j.scopedOutGating, j.foreignAcks.size(), j.diffFileCount ); - - // F-13 — the .ripwire_config disclosure, built once for both emitters (see the header comment on - // registerMacroConfigWarningAttr just above runQualityViews for why the stderr wording lives there). - // #387: the inert-name test reads the JUDGED tree's index, which in the ref-pair form is tree B — the working tree - // is not indexed there at all (runQualityDeltaRangeBeforeIngest). - // qd-memory-degrade: not over a changed-files index, which cannot tell an inert name from one the tree defines (also_skipped=) - rep.configDiag = j.refs.degraded ? quality::RegisterMacroConfigDiagnostics{} : quality::diagnoseRegisterMacroConfig( j.judged, j.root ); - rep.configWarnAttr = registerMacroConfigWarningAttr( rep.configDiag ); - // qd-memory-degrade: the kinds this answer did not run, why, and the replay — plus the peak, read once now that the - // comparison is done (kindsDisclosure). Its stderr lines are the caller's to print, first. - rep.kd = kindsDisclosure( j.cfg, j.refs, j.basis, j.refPair ); - rep.deadRan = !j.refPair || quality::kindSelected( j.refs.kinds, "dead-code" ); - return rep; + emitRegisterMacroConfigWarnings( rep.configDiag ); // F-13: the specific keys and names, never guessed at in the attribute + emitMemoryLines( rep.kd, c.refs ); + // P2.5 — one stderr line NAMING the gating finding, in --token-budget's style ("ripwire: --token-budget + // exceeded: est_tokens=… > budget=…"). stdout is the machine artifact and a caller that only checks + // `$?` gets a number with no subject; this puts the WHICH on the channel a human reads, without + // touching the XML contract. Names the first gating row in the already-sorted list (deterministic). + // §A4 (minor): emitted BEFORE the format fork — the line is about the EXIT CODE, which both formats share, so it + // belongs to neither (under --json the fork used to return first, and a script reading `$?` got no subject). + emitQdGatingLine( c.basis.regs, rep.counts.gating, c.basis.deltaRoot ); } // ── the ROW MODEL: one --quality-delta row's printed facts, decided once for the XML and JSON emitters ───────────────── @@ -3021,12 +3123,12 @@ QdRowModel qdRowModel( const rw::quality::Regression& r, bool gatingAllowed, std } // P3 (L7, nextverb.h): a GATING row hands the agent the body to fix — --expand=FILE:NAME (the file-qualified selector, so -// a same-named symbol elsewhere cannot answer). The name is the sym key's last :: segment; duplication rows name a SET -// (members=) and carry no single body to open, nor does a FILE-anchored defect-shape row (top-level code: sym= is the -// path, and --expand=FILE:FILE matches no symbol). Empty when the row offers no body. +// a same-named symbol elsewhere cannot answer). The name is the sym key's last :: segment. Only the sym-carrying shapes ask: +// a Members row (duplication) names a SET and has no single body to open. Nor does a FILE-anchored defect-shape row +// (top-level code: sym= is the path, and --expand=FILE:FILE matches no symbol). Empty when the row offers no body. std::string qdExpandNextAttr( const rw::quality::Regression& r, const QdRowModel& m ) { - if( !m.gating || r.path.empty() || r.kind == "duplication" || ( r.kind == "defect-shape" && r.sym == r.path ) ) + if( !m.gating || r.path.empty() || ( r.kind == "defect-shape" && r.sym == r.path ) ) { return std::string(); } @@ -3134,153 +3236,113 @@ void emitQdJsonRows( std::FILE* out, const std::vector& } } -// REPORT (render half), --json — same regressions, keys mirror the XML attr names (kind/sym/members/tokens/was/now/ -// sev/churn/surface). jsonUnsupportedVerb already refused --quality-baseline/--quality-ack, so reaching here with cfg.json -// means the plain --quality-delta report. Every optional root member follows the XML twin's absent-means-never-happened rule. +// RENDER, --json — same regressions, keys mirror the XML attr names (kind/sym/members/tokens/was/now/sev/churn/surface). +// jsonUnsupportedVerb already refused --quality-baseline/--quality-ack, so reaching here with cfg.json means the plain +// --quality-delta report. Every optional root member is the JSON spelling of a QdRootField. void emitQualityDeltaJson( const QdReport& rep ) { using namespace rw; - const QdJudged& j = rep.j; - const DeltaBasis& basis = j.basis; - // The JSON sibling of the XML at= anchor — "at":null (never a fake sha) on a non-git root, and - // null in the ref-pair form too: the list was not computed "at" any working-tree state, and the - // two refs ARE its anchor. - const std::string atVal = j.refPair ? std::string{} : gitstamp::stampAt( j.root ); - const std::string atJson = atVal.empty() ? std::string( "null" ) : ( "\"" + atVal + "\"" ); - // F-13: config-warnings is the JSON sibling of the XML config-warnings= attribute — omitted - // (never 0) when .ripwire_config carried nothing to disclose. - const std::string configWarnJson = rep.configDiag.total() == 0 ? std::string() : ",\"config-warnings\":" + std::to_string( rep.configDiag.total() ); - // H11: the JSON twin of baseline_absorbed=. - const std::string absorbedJson = rep.baselineAbsorbed == 0 ? std::string() : ",\"baseline_absorbed\":" + std::to_string( rep.baselineAbsorbed ); - // #228: the JSON twin of head_basis=, under the same absent-means-the-ordinary-archived-tree rule. - const std::string headBasisJson = ( basis.headBasis == nullptr ? std::string() : std::string( ",\"head_basis\":\"" ) + basis.headBasis + "\"" ) - + ( basis.declinedCallExcluded == 0 ? std::string() // the XML twin's declined-call-excluded=, absent at zero - : ",\"declined-call-excluded\":" + std::to_string( basis.declinedCallExcluded ) ) - + rw::countFieldOrEmpty( "value-ref-excluded", basis.valueRefExcluded, /*json=*/true ); - // qd-memory-degrade: stale and register-macro-excluded are absent (never 0) when their pass did not run - const std::string staleJ = j.refs.degraded ? std::string() : ",\"stale\":" + std::to_string( rep.staleAcks.size() ); - const std::string rmeJ = rep.deadRan ? ",\"register-macro-excluded\":" + std::to_string( basis.registerMacroExcluded ) : std::string(); - // R-I: refs.jsonAttrs carries the same two shas + unmeasurable-kind disclosure the XML root carries (empty for the bare form). + const QdComparison& c = rep.c; + const DeltaBasis& basis = c.basis; rw::emitTo( stdout, "{{\"baseline\":\"{}\",\"regressions\":{},\"minor\":{},\"acked\":{}{}," - "\"preexisting-worse\":{},\"new-symbol\":{},\"gating\":{}{},\"api-new-surface\":{},\"at\":{}{}{}{}{}{}{}{},\"r\":[", - jsonStr( rep.baseSel().marker ), rep.regs().size(), rep.counts.minor, j.ackedCount, staleJ, - rep.counts.preexisting, rep.counts.newSymbol, rep.counts.gating, rmeJ, basis.apiNewSurface, atJson, j.refs.jsonAttrs, - rep.identity.second, rep.scope.second, configWarnJson, absorbedJson, headBasisJson, - rep.kd.json + rep.history.second + quality::ratchetAttrsJson( basis.extras ) ); - emitQdJsonRows( stdout, rep.regs(), /*gatingAllowed=*/true, rep.deltaRoot() ); + "\"preexisting-worse\":{},\"new-symbol\":{},\"gating\":{}{},\"api-new-surface\":{}{},\"r\":[", + jsonStr( basis.baseSel.marker ), basis.regs.size(), rep.counts.minor, c.part.ackedCount, rep.root.stale.json, + rep.counts.preexisting, rep.counts.newSymbol, rep.counts.gating, rep.root.registerMacroExcluded.json, basis.apiNewSurface, + qdRootTail( rep.root, QdFormat::Json, {} ) ); + emitQdJsonRows( stdout, basis.regs, /*gatingAllowed=*/true, basis.deltaRoot ); rw::emitRaw( stdout, "]," ); - if( j.scope.active() ) + if( c.scope.active() ) { // The JSON sibling of the XML out-of-scope element: a SEPARATE array, never a flag on a row // in "r", so a consumer that reads "r" and checks "gating" cannot accidentally count someone // else's debt as this run's. Emitted (possibly empty) whenever a scope was given, so its // absence means "no scope", never "no disclosed rows". rw::emitRaw( stdout, "\"oos\":[" ); - emitQdJsonRows( stdout, j.outOfScope, /*gatingAllowed=*/false, rep.deltaRoot() ); + emitQdJsonRows( stdout, c.part.outOfScope, /*gatingAllowed=*/false, basis.deltaRoot ); rw::emitRaw( stdout, "]," ); } std::fputs( quality::staleAcksJsonArray( rep.saRows ).c_str(), stdout ); // L2 — "sa":[...], same taxonomy as the XML sa= rows - std::fputs( quality::improvedJson( basis.extras.improved, rep.deltaRoot() ).c_str(), stdout ); // QD-CREDIT-ROW (absent when none) + std::fputs( quality::improvedJson( basis.extras.improved, basis.deltaRoot ).c_str(), stdout ); // QD-CREDIT-ROW (absent when none) rw::emitRaw( stdout, "}" ); } -// 2026-09-06: what the sidecar readers skipped, on the root (absent means none) — see kQdBaseHeadUnreadable — plus the -// #228 head_basis= (present-only: its absence is the ordinary archived HEAD tree) and the dead-code exemption counts. -std::string qdSidecarHealthAttrs( const DeltaBasis& basis ) -{ - std::string out; - if( basis.baseSel.sidecarBadLines > 0 ) { out += " baseline_bad_lines=\"" + std::to_string( basis.baseSel.sidecarBadLines ) + "\""; } - if( basis.acksBadLines > 0 ) { out += " acks_bad_lines=\"" + std::to_string( basis.acksBadLines ) + "\""; } - if( basis.headBasis != nullptr ) { out += std::string( " head_basis=\"" ) + basis.headBasis + "\""; } - if( basis.declinedCallExcluded > 0 ) { out += " declined-call-excluded=\"" + std::to_string( basis.declinedCallExcluded ) + "\""; } - out += rw::countAttrXmlOrEmpty( "value-ref-excluded", basis.valueRefExcluded ); // absent at zero, beside its sibling - return out; -} - -// idea #11 — THE CLEAN-TREE PAYLOAD. A regression-free answer collapses its stale-ack rows to counts (stale= and +// idea #11 — THE CLEAN-TREE PAYLOAD. A regression-free answer folds its stale-ack rows to counts (stale= and // stale_by_kind=), and stale_next= is the call that prints them; on a tree that IS its HEAD (head_basis="identity": the // floor is this tree's own snapshot) with nothing else to disclose, the verdict is the whole answer. Foreign-scope rows are -// never collapsed: they are about findings suppressed RIGHT NOW. --show-stale restores today's document byte for byte, so -// every collapsed row and attribute is one flag away (PROCESS rule 5). `attrs` is empty when the answer does not collapse. -struct QdStaleCollapse +// never folded: they are about findings suppressed RIGHT NOW. --show-stale restores today's document byte for byte, so +// every folded row and attribute is one flag away (PROCESS rule 5). +struct QdStaleFold { - bool collapse = false; - bool verdictOnly = false; // the identity-tree VERDICT: the root line alone - std::string attrs; // stale_by_kind= + stale_next= + bool verdictOnly = false; // the identity-tree VERDICT: the root line alone (qdNothingElseToDisclose) + std::string attrs; // stale_by_kind= + stale_next=, on the folded root }; + // The identity-tree verdict's precondition: a working-tree answer whose floor is this tree's own snapshot // (head_basis="identity") with no scope, foreign or accepted ack, config warning, absorbed debt, new public surface or // unreadable sidecar line to disclose — so the root line alone loses nothing. bool qdNothingElseToDisclose( const QdReport& rep ) { - const QdJudged& j = rep.j; - const DeltaBasis& basis = j.basis; - return !j.refPair && basis.headBasis != nullptr && std::string_view( basis.headBasis ) == "identity" - && !j.scope.active() && j.foreignAcks.empty() && j.ackedCount == 0 && rep.configDiag.total() == 0 && rep.baselineAbsorbed == 0 - && basis.apiNewSurface == 0 && rep.baseSel().sidecarBadLines == 0 && basis.acksBadLines == 0; + const QdComparison& c = rep.c; + const DeltaBasis& basis = c.basis; + return !c.refPair && basis.headBasis != nullptr && std::string_view( basis.headBasis ) == "identity" + && !c.scope.active() && c.part.foreignAcks.empty() && c.part.ackedCount == 0 && rep.configDiag.total() == 0 && rep.baselineAbsorbed == 0 + && basis.apiNewSurface == 0 && basis.baseSel.sidecarBadLines == 0 && basis.acksBadLines == 0; } +// The stale fold this answer could ship (whether it PAYS is emitQualityDeltaXml's to measure), or nullopt when it has a +// regression, an out-of-scope row, no stale ack, or --show-stale. template -QdStaleCollapse qdStaleCollapse( const QdReport& rep, const Escape& ex ) +std::optional qdStaleFold( const QdReport& rep, const Escape& ex ) { using namespace rw; - const QdJudged& j = rep.j; - QdStaleCollapse c; - c.collapse = rep.regs().empty() && j.outOfScope.empty() && !j.cfg.showStale && !rep.staleAcks.empty(); - if( !c.collapse ) + const QdComparison& c = rep.c; + if( !c.basis.regs.empty() || !c.part.outOfScope.empty() || c.cfg.showStale || rep.staleAcks.empty() ) { - return c; + return std::nullopt; } const std::string kinds = quality::staleByKindValue( rep.staleAcks ); // shared with the MCP twin (lane lean2b) - std::string replay = j.cfg.qualityDeltaRange.empty() ? std::string( "--quality-delta" ) : rw::nextFlag( "--quality-delta=", j.cfg.qualityDeltaRange ); - if( j.scope.active() ) + std::string replay = c.cfg.qualityDeltaRange.empty() ? std::string( "--quality-delta" ) : rw::nextFlag( "--quality-delta=", c.cfg.qualityDeltaRange ); + if( c.scope.active() ) { - replay += " " + rw::nextFlag( "--scope=", j.cfg.qualityScope ); + replay += " " + rw::nextFlag( "--scope=", c.cfg.qualityScope ); } - c.attrs = " stale_by_kind=\"" + ex( kinds ) + "\"" + rw::nextAttrXml( replay + " --show-stale", "stale_next" ); - c.verdictOnly = qdNothingElseToDisclose( rep ); - return c; + return QdStaleFold{ .verdictOnly = qdNothingElseToDisclose( rep ), + .attrs = " stale_by_kind=\"" + ex( kinds ) + "\"" + rw::nextAttrXml( replay + " --show-stale", "stale_next" ) }; } // The whole XML document over one FILE*: legend, root, rows, improvements, the out-of-scope disclosure and the rows. -// `collapse` picks the stale rows' form: true serves only the foreign-scope rows and the stale_by_kind=/stale_next= counts. -void emitQdXmlDocument( std::FILE* out, const QdReport& rep, const QdStaleCollapse& stale, const std::string& atAttrs, bool collapse ) +// `fold` null renders every stale row; otherwise only the foreign-scope rows, with fold->attrs on the root. +void emitQdXmlDocument( std::FILE* out, const QdReport& rep, const QdStaleFold* fold ) { using namespace rw; - const QdJudged& j = rep.j; - const DeltaBasis& basis = j.basis; - const RefPairDelta& refs = j.refs; - std::vector esc; - const auto ex = [ & ]( std::string_view s ) -> std::string { return std::string( escapeXml( s, esc ) ); }; - const std::vector& served = collapse ? j.foreignAcks : rep.saRows; + const QdComparison& c = rep.c; + const DeltaBasis& basis = c.basis; + const RefPairDelta& refs = c.refs; + std::vector esc; + const auto ex = [ & ]( std::string_view s ) -> std::string { return std::string( escapeXml( s, esc ) ); }; + const std::vector& served = fold != nullptr ? c.part.foreignAcks : rep.saRows; // the legend is passed the same values the root element below prints, so "the legend defines what the header emits" is // read off one set of values rather than restated as a second condition that could drift from it - emitQualityDeltaLegend( { rep.baseSel().marker, j.refPair, rep.identity.first, !served.empty(), j.ackedCount > 0, - basis.registerMacroExcluded > 0, rep.configDiag.total() > 0, rep.regs(), j.outOfScope, - j.scope.active() || !j.foreignAcks.empty(), !j.foreignAcks.empty(), rep.baselineAbsorbed, - basis.headBasis, basis.declinedCallExcluded > 0, basis.valueRefExcluded > 0, collapse, + emitQualityDeltaLegend( { basis.baseSel.marker, c.refPair, rep.root.identity.xml, !served.empty(), c.part.ackedCount > 0, + basis.registerMacroExcluded > 0, rep.configDiag.total() > 0, basis.regs, c.part.outOfScope, + c.scope.active() || !c.part.foreignAcks.empty(), !c.part.foreignAcks.empty(), rep.baselineAbsorbed, + basis.headBasis, basis.declinedCallExcluded > 0, basis.valueRefExcluded > 0, fold != nullptr, refs.kinds != quality::kAllKinds, refs.degraded, !refs.memoryStop.empty(), rep.kd.peakOver != 0, rep.kd.memorySkipped != 0 && refs.selected != quality::kAllKinds, basis.historyUnread.any(), basis.rustTestExcluded, refs.staleTree, !basis.extras.ratchetRef.empty(), !basis.extras.improved.empty() }, out ); - // qd-memory-degrade: stale= and register-macro-excluded= are absent (never 0) when their pass did not run - const std::string staleX = refs.degraded ? std::string() : " stale=\"" + std::to_string( rep.staleAcks.size() ) + "\""; - const std::string rmeX = rep.deadRan ? " register-macro-excluded=\"" + std::to_string( basis.registerMacroExcluded ) + "\"" : std::string(); - rw::emitTo( out, "", - rep.baseSel().marker, rep.regs().size(), rep.counts.minor, j.ackedCount, staleX, rep.counts.preexisting, rep.counts.newSymbol, rep.counts.gating, - rmeX, basis.apiNewSurface, - // at= anchors this regression list to the commit (+dirty state) it was computed against. R-I: it is - // OMITTED for the ref-pair form rather than stamped with the working tree's sha, which would anchor the - // list to a commit it was not computed from. base_ref= and target_ref= are the anchor there, and they - // carry FULL shas because a wave measurement gets quoted into handoffs where a 9-char prefix is one - // collision from unverifiable. - atAttrs, refs.attrs, rep.identity.first, rep.scope.first, rep.configWarnAttr, rep.baselineAbsorbed == 0 ? std::string() : " baseline_absorbed=\"" + std::to_string( rep.baselineAbsorbed ) + "\"", - qdSidecarHealthAttrs( basis ) + ( collapse ? stale.attrs : std::string() ) + rep.kd.xml + rep.history.first + quality::ratchetAttrsXml( basis.extras, ex ) ); - for( const quality::Regression& r : rep.regs() ) - { - emitQdXmlRow( out, r, qdRowModel( r, /*gatingAllowed=*/true, rep.deltaRoot() ), ex ); - } - std::fputs( quality::improvedXml( basis.extras.improved, rep.deltaRoot(), ex ).c_str(), out ); // QD-CREDIT-ROW: never a row, never gating - if( j.scope.active() ) + // at= anchors this regression list to the commit (+dirty state) it was computed against (QdRootFields::at). R-I: the range + // form's base_ref= and target_ref= carry FULL shas because a wave measurement gets quoted into handoffs where a 9-char + // prefix is one collision from unverifiable. + rw::emitTo( out, "", + basis.baseSel.marker, basis.regs.size(), rep.counts.minor, c.part.ackedCount, rep.root.stale.xml, rep.counts.preexisting, + rep.counts.newSymbol, rep.counts.gating, rep.root.registerMacroExcluded.xml, basis.apiNewSurface, + qdRootTail( rep.root, QdFormat::Xml, fold != nullptr ? std::string_view( fold->attrs ) : std::string_view() ) ); + for( const quality::Regression& r : basis.regs ) + { + emitQdXmlRow( out, r, qdRowModel( r, /*gatingAllowed=*/true, basis.deltaRoot ), ex ); + } + std::fputs( quality::improvedXml( basis.extras.improved, basis.deltaRoot, ex ).c_str(), out ); // QD-CREDIT-ROW: never a row, never gating + if( c.scope.active() ) { // P1 — the DISCLOSURE half. Dropping these rows would make a scoped report a quieter lie than // the unscoped one it replaces: the debt is real, it is in the same tree, and it will be in @@ -3289,10 +3351,10 @@ void emitQdXmlDocument( std::FILE* out, const QdReport& rep, const QdStaleCollap // element then means "no scope was given", never "nobody else has anything open". rw::emitTo( out, "", - j.outOfScope.size(), j.scopedOutGating ); - for( const quality::Regression& r : j.outOfScope ) + c.part.outOfScope.size(), c.part.scopedOutGating ); + for( const quality::Regression& r : c.part.outOfScope ) { - emitQdXmlRow( out, r, qdRowModel( r, /*gatingAllowed=*/false, rep.deltaRoot() ), ex ); + emitQdXmlRow( out, r, qdRowModel( r, /*gatingAllowed=*/false, basis.deltaRoot ), ex ); } rw::emitRaw( out, "" ); } @@ -3303,8 +3365,8 @@ void emitQdXmlDocument( std::FILE* out, const QdReport& rep, const QdStaleCollap rw::emitRaw( out, "" ); } -// The identity-tree VERDICT (QdStaleCollapse::verdictOnly): the root line alone. -void emitQdVerdict( std::FILE* out, const QdReport& rep, const QdStaleCollapse& stale, const std::string& atAttrs ) +// The identity-tree VERDICT (QdStaleFold::verdictOnly): the root line alone. +void emitQdVerdict( std::FILE* out, const QdReport& rep, const QdStaleFold& fold ) { rw::emitTo( out, "" "", - rep.baseSel().marker, rep.staleAcks.size(), atAttrs, stale.attrs ); + rep.c.basis.baseSel.marker, rep.staleAcks.size(), rep.root.at.xml, fold.attrs ); } -// REPORT (render half), XML. +// RENDER, XML. // §B7.1 (CA4) — the heading used to open "only what changed for the WORSE vs .ripwire_quality_baseline", which is FALSE in // every state but one: three of the five floors this verb can use are not that file, and in one of them the file was judged // stale and DELETED from the user's tree during this very run. The floor actually used is named by baseline= on the root, @@ -3329,25 +3391,23 @@ void emitQdVerdict( std::FILE* out, const QdReport& rep, const QdStaleCollapse& void emitQualityDeltaXml( const QdReport& rep ) { using namespace rw; - std::vector esc; - const QdStaleCollapse stale = qdStaleCollapse( rep, [ & ]( std::string_view s ) -> std::string { return std::string( escapeXml( s, esc ) ); } ); - // R-I: at= is OMITTED for the ref-pair form (see the root). Read ONCE: both candidates print the same stamp. - const std::string atAttrs = rep.j.refPair ? std::string() : gitstamp::atAttr( rep.j.root ); - if( !stale.collapse ) + std::vector esc; + const std::optional fold = qdStaleFold( rep, [ & ]( std::string_view s ) -> std::string { return std::string( escapeXml( s, esc ) ); } ); + if( !fold ) { - emitQdXmlDocument( stdout, rep, stale, atAttrs, /*collapse=*/false ); + emitQdXmlDocument( stdout, rep, /*fold=*/nullptr ); return; } - const Rendered full = renderToString( [ & ]( std::FILE* f ) { emitQdXmlDocument( f, rep, stale, atAttrs, /*collapse=*/false ); } ); + const Rendered full = renderToString( [ & ]( std::FILE* f ) { emitQdXmlDocument( f, rep, /*fold=*/nullptr ); } ); const Rendered folded = renderToString( [ & ]( std::FILE* f ) { - if( stale.verdictOnly ) { emitQdVerdict( f, rep, stale, atAttrs ); } - else { emitQdXmlDocument( f, rep, stale, atAttrs, /*collapse=*/true ); } + if( fold->verdictOnly ) { emitQdVerdict( f, rep, *fold ); } + else { emitQdXmlDocument( f, rep, &*fold ); } } ); if( !full.ok || !folded.ok ) { // renderToString DISCLOSEd the failed buffer; the full document is the superset, written straight to stdout - emitQdXmlDocument( stdout, rep, stale, atAttrs, /*collapse=*/false ); + emitQdXmlDocument( stdout, rep, /*fold=*/nullptr ); return; } const std::string& chosen = foldPays( folded.text, full.text ) ? folded.text : full.text; // compactlegend.h: the margin and why @@ -3357,8 +3417,9 @@ void emitQualityDeltaXml( const QdReport& rep ) // --quality-baseline / --quality-delta (the convergence-loop oracle): snapshot ccx + clone groups + dead candidates to // .ripwire_quality_baseline; then report ONLY what a change made WORSE vs it. The "delta not absolute" discipline — a refine // loop targets the regression it introduced, not absolute numbers (the defense against metric-gaming). exit 2 if any new -// debt, like --arch. The phases: resolve the floor and the delta (resolveDeltaBasis), JUDGE (judgeQualityDelta), then -// either WRITE ACKS (runQualityAckWrite) or REPORT (qdReportOf, then the JSON or XML rendering). +// debt, like --arch. The phases: resolve the floor and the delta (resolveDeltaBasis), the scope and the ack ratchet +// (applyScopeAndAcks), then either WRITE ACKS (runQualityAckWrite) or COMPUTE the report (computeQdReport), print its +// stderr lines (emitQdStderrLines) and RENDER it as JSON or XML. std::optional runQualityDelta( const MainDispatch& d ) { using namespace rw; @@ -3424,7 +3485,7 @@ std::optional runQualityDelta( const MainDispatch& d ) } // `refs` is declared HERE because it owns both materialized trees' teardown and they must outlive every read of the - // delta (QdJudged's header). + // delta (QdComparison's header). RefPairDelta refs; DeltaBasis basis; if( const std::optional refused = applyKindSelector( cfg, refs ) ) @@ -3435,29 +3496,40 @@ std::optional runQualityDelta( const MainDispatch& d ) { return refused; } - const bool refPair = !cfg.qualityDeltaRange.empty(); - QdJudged judged{ .cfg = cfg, .root = d.root, .refs = refs, .basis = basis, .refPair = refPair, .judged = refPair ? refs.target().ing : d.ing, - .workingGraph = d.g }; - if( const std::optional refused = judgeQualityDelta( judged ) ) + const bool refPair = !cfg.qualityDeltaRange.empty(); + const IngestResult& judgedIndex = refPair ? refs.target().ing : d.ing; // the JUDGED tree's index: tree B in the range form + + // ── P1 SCOPE — the OWNERSHIP partition for a working tree with several writers in it ───────────── + quality::Scope scope = quality::parseScope( cfg.qualityScope ); + std::size_t diffFileCount = 0; // P1.2: 0 = the reserved diff token was not used + if( const std::optional refused = expandScopeDiff( scope, refPair, judgedIndex, d.root, basis.deltaRoot, diffFileCount ) ) { return refused; } - if( cfg.qualityAck ) + if( const std::optional refused = refuseUnusableScope( cfg, scope, judgedIndex, basis.deltaRoot, refs.scopeFiles() ) ) { - return runQualityAckWrite( judged, acksFile ); + return refused; } - - const QdReport report = qdReportOf( judged, baselineFile ); - // the stderr lines of a partial or over-the-limit answer come first: it says so on the channel a human reads before - // anything else - emitMemoryLines( report.kd, refs ); - // P2.5 — one stderr line NAMING the gating finding, in --token-budget's style ("ripwire: --token-budget - // exceeded: est_tokens=… > budget=…"). stdout is the machine artifact and a caller that only checks - // `$?` gets a number with no subject; this puts the WHICH on the channel a human reads, without - // touching the XML contract. Names the first gating row in the already-sorted list (deterministic). - // §A4 (minor): emitted BEFORE the format fork — the line is about the EXIT CODE, which both formats share, so it - // belongs to neither (under --json the fork used to return first, and a script reading `$?` got no subject). - emitQdGatingLine( report.regs(), report.counts.gating, report.deltaRoot() ); + const QdPartition part = applyScopeAndAcks( scope, basis ); + if( cfg.qualityAck ) + { + return runQualityAckWrite( cfg, scope, part, basis, acksFile ); + } + + // L2 — stale-ack disclosure (rationale: quality.h's computeStaleAcks). Checked against the CURRENT tree, not the baseline, + // so it costs one more computeSnapshot; skipped when the ledger is empty. Reported, never gated — the exit code reads the + // rows alone. R-I: "the CURRENT tree" is the JUDGED tree, which in the range form is tree B — checking the ledger against + // the working tree there would report acks as stale because of edits that have nothing to do with the comparison. + // qd-memory-degrade: refPairStaleAcks owns the two range-form departures (a changed-files answer judges none; a kind + // selection judges its own kinds' acks only). The bare form's snapshot is the working tree's own (d.ing, d.g) and reuses + // the clone and construct passes the delta already ran (QD-IDENTITY-ONCE), so it writes basis.passes — here, in view. + std::vector staleAcks = basis.acks.empty() ? std::vector{} + : refPair ? refPairStaleAcks( basis.acks, refs ) + : quality::computeStaleAcks( basis.acks, quality::computeSnapshot( d.ing, d.g, cfg.rootPath, nullptr, {}, &basis.passes ) ); + const QdComparison comparison{ .cfg = cfg, .root = d.root, .refs = refs, .basis = basis, .scope = scope, .part = part, + .judgedIndex = judgedIndex, .refPair = refPair, .diffFileCount = diffFileCount }; + const QdReport report = computeQdReport( comparison, std::move( staleAcks ), baselineFile ); + emitQdStderrLines( report ); if( cfg.json ) { emitQualityDeltaJson( report ); From c44850c94e518e7426e61a696fd219844298086b Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:55:13 -0500 Subject: [PATCH 03/61] refactor(quality): qdCountField reuses rw::countField countFieldOrEmpty's spelling moves into an always-present sibling, countField, so qd's root count disclosures (present at 0) share it instead of cloning the format. No output change. Co-Authored-By: Claude Opus 5.5 --- src/graphlegend.h | 11 ++++++----- src/verbs_quality.h | 9 ++------- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/src/graphlegend.h b/src/graphlegend.h index b0d6656a5..22b3ba8ef 100644 --- a/src/graphlegend.h +++ b/src/graphlegend.h @@ -906,15 +906,16 @@ inline const char* toValueRefsLegend( bool on ) noexcept { return on ? kToValueR // --skipped's extent_suspect_files=/macro_blanked_files= (root) and extent_suspect_syms=/macro_blanked= ( rows) // all spell through it, so the shape has one definition instead of a copy per verb. // `json` spells the same count as a key instead: `,"name":N` (imports_unresolved= is the one caller today). -inline std::string countFieldOrEmpty( std::string_view name, std::size_t count, bool json ) +// countField is the same spelling for a count that is present even at 0 (a pass that ran and found none). +inline std::string countField( std::string_view name, std::size_t count, bool json ) { - if( count == 0 ) - { - return {}; - } const std::string n = std::to_string( count ); return json ? ",\"" + std::string( name ) + "\":" + n : " " + std::string( name ) + "=\"" + n + "\""; } +inline std::string countFieldOrEmpty( std::string_view name, std::size_t count, bool json ) +{ + return count == 0 ? std::string() : countField( name, count, json ); +} inline std::string countAttrXmlOrEmpty( std::string_view name, std::size_t count ) { return countFieldOrEmpty( name, count, /*json=*/false ); diff --git a/src/verbs_quality.h b/src/verbs_quality.h index 102f96b39..2e496932f 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -2919,15 +2919,10 @@ struct QdRootField const std::string& in( QdFormat format ) const noexcept { return format == QdFormat::Xml ? xml : json; } }; -// A count as a root disclosure: ` name="N"` / `,"name":N` when `present`, else absent. +// A count as a root disclosure: ` name="N"` / `,"name":N` (rw::countField) when `present`, else absent. QdRootField qdCountField( std::string_view name, std::size_t count, bool present ) { - if( !present ) - { - return {}; - } - const std::string n = std::to_string( count ); - return { " " + std::string( name ) + "=\"" + n + "\"", ",\"" + std::string( name ) + "\":" + n }; + return present ? QdRootField{ rw::countField( name, count, /*json=*/false ), rw::countField( name, count, /*json=*/true ) } : QdRootField{}; } // Every root disclosure, each built once (qdRootFieldsOf). `stale` and `registerMacroExcluded` sit between the fixed From 0a263b59538ee6f18a4f0de2549e5959de3b7e1f Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:06:37 -0500 Subject: [PATCH 04/61] qd tangle: rule (b) gates; the ratchet reads the range base (TANGLE-GATE-B, QD-RATCHET-BASE) Owner 11-21 (tangle re-census): a new function at or over tangle 6, or one that crossed the bar, now GATES (not a moved body, not test code: the census's harness mains were its false class). A new-symbol tangle row that is major gates in rowGates, and the stderr gating line names it. QD-RATCHET-BASE: a function over the bar at the range base whose score is higher now (a tenth is enough) is a ratchet row, report-only in this commit. The tag-best compare (D4) no longer makes rows of its own: it adds ratchet="TAG" and "best since TAG" to rows the base made. Replay 11-21: its four own rows were functions the change did not grow (buildGraph in #706/#714, serialize in #705, captureTagsFacts 29.2 -> 29.1 in #714). tanglecheck: t1/b1/b3 (rule (b) gating, red on main), b2 (test code stays minor), k1 (grow1: a ratchet row under the rise step, red on main), k2/k3 (reflow same tenth, settle fell: no row; both rowed on main), r1 reads was= as HEAD's score. Fixture creep/nudge fold into one generator (byte-identical files). Co-Authored-By: Claude Opus 5.5 --- src/cli.h | 8 +-- src/compactlegend.h | 2 +- src/mcp.h | 2 +- src/quality.h | 140 +++++++++++++++++++++++-------------- src/verbs_quality.h | 40 +++++++---- test/lib/tanglefixtures.py | 49 ++++++++----- test/tanglecheck.sh | 73 +++++++++++++++---- 7 files changed, 210 insertions(+), 104 deletions(-) diff --git a/src/cli.h b/src/cli.h index 6bce28d0d..8f1c15e21 100644 --- a/src/cli.h +++ b/src/cli.h @@ -1913,12 +1913,12 @@ inline constexpr char kHelpHead[] = " — a regression-free answer keeps only stale= and stale_by_kind= (its rows collapsed), and on a tree\n" " that IS its HEAD only the verdict; either fold only when it saves a quarter of the bytes. Refused alone.\n" " --quality-delta before a PR: report ONLY what your change made worse, across 13 kinds\n" - " — pair with --test-gate. Each kind is measured against the baseline (complexity/verbosity/nesting/params/dup/dead/api-surface + error-masking/short-horizon-churn/new-clone-of-reused-helper + placeholder + defect-shape + tangle, report-only);\n" + " — pair with --test-gate. Each kind is measured against the baseline (complexity/verbosity/nesting/params/dup/dead/api-surface + error-masking/short-horizon-churn/new-clone-of-reused-helper + placeholder + defect-shape + tangle);\n" " every finding is classified by ORIGIN: a symbol that EXISTED at the baseline and got worse (preexisting-worse=\"N\", no attribute on the row) vs one that exists only\n" " because the code is NEW (new-symbol=\"N\", origin=\"new-symbol\" on the row). A small numeric delta is additionally sev=\"minor\". EXIT 2 ONLY on a major AND unacked row that is\n" - " preexisting-worse, defect-shape format-arity (any origin) or a new function at the ceiling — the gating=\"N\" header count. New-symbol rows are still PRINTED (they are the debt you are adding — read them);\n" - " new-symbol rows never gate, except defect-shape format-arity and a new function at the ceiling (4x the bar: ccx 60 or 240 lines,\n" - " not a moved body, not test code, ceiling= on the row); exit 0 means\n" + " preexisting-worse, defect-shape format-arity (any origin), a new function at the ceiling or a tangled new one — the gating=\"N\" header count. New-symbol rows are still PRINTED (they are the debt you are adding — read them);\n" + " new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling (4x the bar: ccx 60 or 240 lines,\n" + " not a moved body, not test code, ceiling= on the row) and a new one at tangle 6 or more (not moved, not test code); exit 0 means\n" " \"nothing that already existed got worse\", not \"clean\". Clone kinds classify by member set (new-symbol only if EVERY member is new); short-horizon-churn is preexisting\n" " by construction. LIMIT: origin is canonId (path::scope::name) identity; a function RENAMED or MOVED with its body unchanged (whitespace and its own name aside: one body that left its key, matched to one new key) keeps its identity and the move reports nothing (and a file rename git recorded keeps each symbol in it under its own name, twins and changed bodies included), while one whose body also changed reads as new and a regression carried in with it will not gate;\n" " a function over the ccx or line bar whose body moved with a small edit (a clone-sketch match to a body that left its key) reads origin=\"moved\" and never gates.\n" diff --git a/src/compactlegend.h b/src/compactlegend.h index a7a69660f..1dc5be188 100644 --- a/src/compactlegend.h +++ b/src/compactlegend.h @@ -1089,7 +1089,7 @@ inline constexpr CompactCompletenessTerm kCompactAttributeReadings[] = // D4 (src/quality.h ratchetAttrsXml): present when the tangle ratchet read its reference point { "ratchet_ref", "ratchet_ref=TAG ratchet_judged=N: the ratchet compared N touched over-bar functions with their best since TAG; ratchet_unread= / ratchet_cut=1: versions not measured", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, { "preexisting-worse", "preexisting-worse=N: regressions on symbols that existed at baseline; they gate when major", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, - { "new-symbol", "new-symbol=N: NEW code; new-symbol rows never gate, except defect-shape format-arity or a ceiling= row", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, + { "new-symbol", "new-symbol=N: NEW code; new-symbol rows never gate, except defect-shape format-arity, a ceiling= row or a tangle row", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, { "register-macro-excluded", "register-macro-excluded=N: symbols skipped: self-registering test/bench macros or Rust #[test]; a floor", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, { "declined-call-excluded", "declined-call-excluded=N: symbols kept out of dead-code only because a declined call may mean them; a floor", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, { "api-new-surface", "api-new-surface=N: new PUBLIC symbols; a count, never gates, not in regressions=", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, diff --git a/src/mcp.h b/src/mcp.h index 5a802eaf6..a659b7400 100644 --- a/src/mcp.h +++ b/src/mcp.h @@ -1383,7 +1383,7 @@ inline McpDispatchResult dispatchMcpLine( const std::string& line, int topK, boo // paraphrased — this stanza used to describe an ordering the selector does not use. "{\"name\":\"exemplar\",\"description\":\"BEFORE writing a function / method / class / struct / interface / variable, get the repo's single best-in-class instance of that kind to imitate — signature AND full body. The pick is chosen by ROLE, NEVER by text similarity to your task (complexity ceiling, then tested, fan-in, simplicity); the answer's legend gives the full order and low_confidence=/over_ccx_bar=.\"," + mcprefuse::toolMetadataFor( "exemplar", pathIsRequired ) + "}," - "{\"name\":\"quality_delta\",\"description\":\"Your PR self-check, run every time you think a change is DONE — pairs with the CLI-only --test-gate (names the tests to run + the untested blast radius; not MCP-exposed) to form the two-step pre-PR gate. Reports ONLY what your tree made WORSE vs baseline, in 13 kinds (complexity, verbosity, nesting, params, new duplication/dead code/public API, error-masking, short-horizon churn, helper clone, stub/TODO, defect shape, tangle). new-symbol rows never gate, except defect-shape format-arity and a new function at the ceiling; sev=minor never gates; acked findings hide until worse. Baseline: git HEAD, or a fresh pinned .ripwire_quality_baseline; at= names it (+dirty = tree differed).\"," + "{\"name\":\"quality_delta\",\"description\":\"Your PR self-check, run every time you think a change is DONE — pairs with the CLI-only --test-gate (names the tests to run + the untested blast radius; not MCP-exposed) to form the two-step pre-PR gate. Reports ONLY what your tree made WORSE vs baseline, in 13 kinds (complexity, verbosity, nesting, params, new duplication/dead code/public API, error-masking, short-horizon churn, helper clone, stub/TODO, defect shape, tangle). new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling and a tangled new function; sev=minor never gates; acked findings hide until worse. Baseline: git HEAD, or a fresh pinned .ripwire_quality_baseline; at= names it (+dirty = tree differed).\"," + mcprefuse::toolMetadataFor( "quality_delta", pathIsRequired ) + "}," "{\"name\":\"quality_baseline\",\"description\":\"PIN the quality floor: writes .ripwire_quality_baseline stamped with the current git HEAD sha, snapshotting complexity / duplication / dead-code / API surface. Call once at the start of non-trivial work; quality_delta then compares against it instead of HEAD. Writes a file: skip it for a simple 'before I push' check.\"," + mcprefuse::toolMetadataFor( "quality_baseline", pathIsRequired ) + "}," diff --git a/src/quality.h b/src/quality.h index 142efa70f..9a7f346f6 100644 --- a/src/quality.h +++ b/src/quality.h @@ -8350,9 +8350,12 @@ inline std::string rowValueText( const Regression& r, std::uint32_t v ) return metricValueText( r.kind, v ); } +// A new-symbol tangle row is major only under rule (b) (tangleCauseGates: a new function at or over the bar, not moved, not +// test code), so a major one gates like a ceiling row (QD-LESSONS-2, owner 11-21). inline bool rowGates( const Regression& r ) noexcept { - return !r.isMinor && ( !r.isNewSymbol || r.ceiling != 0 || ( r.kind == "defect-shape" && r.facet == defectshape::facetName( defectshape::Facet::FormatArity ) ) ); + return !r.isMinor + && ( !r.isNewSymbol || r.ceiling != 0 || r.kind == "tangle" || ( r.kind == "defect-shape" && r.facet == defectshape::facetName( defectshape::Facet::FormatArity ) ) ); } // B10.2 — kind → the ATTRIBUTE NAME its facet value is emitted under. `Regression::facet` carries only the @@ -11406,14 +11409,15 @@ inline std::uint32_t newSymbolCeilingGate( const Regression& r, SymKind measured return gates ? ceilingAt : 0; } -// ─── QD-TANGLE — the thirteenth kind, REPORT-ONLY (STAGE0 2; owner 11-19: length amplifies tangle, never stands alone) ─────────── +// ─── QD-TANGLE — the thirteenth kind (STAGE0 2; owner 11-19: length amplifies tangle, never stands alone; 11-21: rule (b) gates) ─ // // A row when a function's tangle score (model.h tangleScore10) is at or over the bar (S >= 6) AND the change made it so: the function -// is new, it crossed the bar, or an input rose — nesting +1, deep lines +kTangleDeepRise, or a new steering local. The trigger reads -// the INPUTS, not the score, on purpose: the score is a share, so 12 deep lines added to a 4000-line function move it a tenth, and a -// score trigger would let a monster grow forever (QD-MONSTER-GROWTH's lesson). Every row is sev="minor" and never gates in this -// stage; why= names the inputs that rose, fix= the shape the rise calls for (with its lines, from a re-walk of the ONE function: -// tangleDetailOf), locals= the steering locals. A long orchestrator of named steps or a long flat body scores 0 and never rows. +// is new, it crossed the bar, its score grew against the range base while over the bar (the RATCHET, QD-RATCHET-BASE), or an input +// rose — nesting +1, deep lines +kTangleDeepRise, or a new steering local. Rows on the score's growth catch a monster growing by a +// tenth per change (12 deep lines in a 4000-line function), which a size floor would let grow forever (QD-MONSTER-GROWTH's lesson). +// A new function or a crossing GATES (rule (b), owner 11-21: tangleCauseGates); every other row is sev="minor". why= names the +// inputs that changed, fix= the shape the rise calls for (with its lines, from a re-walk of the ONE function: tangleDetailOf), +// locals= the steering locals. A long orchestrator of named steps or a long flat body scores 0 and never rows. inline constexpr std::uint32_t kTangleDeepRise = 5; // deep lines that count as a rise (STAGE0 2.5's "worse" tier) struct TangleRise @@ -11559,6 +11563,48 @@ struct TangleDetailReader } }; +// What made a row over the bar (QD-LESSONS-2, owner 11-21): the function is new or crossed the bar (rule (b)); already over it, +// its score grew against the range base (the RATCHET, QD-RATCHET-BASE); or an input rose by the rise rule while the score did +// not grow. The caller has already left out a function under the bar now. +enum class TangleCause : std::uint8_t +{ + None, // over the bar before and after, the score did not grow and nothing rose: no row + New, // a new function at or over the bar + Crossed, // under the bar at the baseline, at or over it now + Grew, // over the bar at the baseline and the score is higher now (a tenth is enough: log-length scaling keeps steps small) + Rose, // over the bar at the baseline, the score not higher, an input rose (nest +1, deep +kTangleDeepRise, a steering local) +}; +inline TangleCause tangleCauseOf( bool isNew, std::uint32_t was10, std::uint32_t now10, const TangleRise& rise ) noexcept +{ + if( isNew ) + { + return TangleCause::New; + } + if( was10 < kTangleBar10 ) + { + return TangleCause::Crossed; + } + if( now10 > was10 ) + { + return TangleCause::Grew; + } + return rise.any() ? TangleCause::Rose : TangleCause::None; +} + +// The inputs that grew at all (the fix= reading of a ratchet row, whose growth can be under the rise rule's steps). +inline TangleRise tangleGrowth( const TangleInputs& was, const TangleInputs& now ) noexcept +{ + return { now.nest > was.nest, now.deep > was.deep, now.steer > was.steer }; +} + +// Rule (b): a new function at or over the bar, or one that crossed it, GATES — except a moved body (its code is not new; the +// re-census found no such row) and test code (the census's test-harness mains were its false class, and QD-ENTRY-CEILING exempts +// test drivers the same way). A ratchet row or a row of a rising input stays sev="minor". `rel` = the root-relative path. +inline bool tangleCauseGates( TangleCause cause, bool moved, std::string_view rel ) noexcept +{ + return ( cause == TangleCause::New || cause == TangleCause::Crossed ) && !moved && !isTestPath( rel ); +} + // QD-CREDIT-ROW for tangle (STAGE0 2.5): over the bar at the baseline, an input fell by the rise rule (tangleRise read backwards) and none rose, and the score is lower. inline bool tangleCredited( const TangleInputs& was, const TangleInputs& now ) noexcept { @@ -11567,20 +11613,19 @@ inline bool tangleCredited( const TangleInputs& was, const TangleInputs& now ) n return tangleScore10( was ) >= kTangleBar10 && tangleRise( now, was ).any() && !tangleRise( was, now ).any() && tangleScore10( now ) < tangleScore10( was ); } -// D4 RATCHET (report-only): each `ratchetable` key — over the bar now, existing at the baseline, inputs moved by this change — against its -// best since the reference point (extras.bestSince over those keys' files only). It fires when the score is above its best AND an input -// rose over its minimum by the same rise rule the baseline row uses (nest +1 past the free levels, deep +kTangleDeepRise, a new steering -// local): a function that crept up across merges, each step under the rise rule, is named once it has crept that far. On a key this -// pass already rowed, the ratchet adds its facet (ratchet="") and its reading to why=; otherwise it is a row of its own, was= the -// best score. A key the history never held (created in this working tree) is not judged. -template -inline void appendTangleRatchet( std::vector& regs, const IngestResult& ing, const Graph& g, - const std::vector>& ratchetable, const gtl::btree_map& rowOfKey, - TangleDetailReader& detailOf, Stamp&& stamp, std::string_view root, DeltaExtras& extras ) +// D4 (QD-RATCHET-BASE: a facet, never a row of its own): each tangle row on a function that existed at the baseline, against its best +// since the reference point (extras.bestSince over those rows' files only). When the score is above that best AND an input rose over +// its minimum by the rise rule, the row gets ratchet="" and why= adds "best since : ...": the context of a function that +// crept up across merges. Whether a function is judged at all is the range base's question (tangleCauseOf); replay 11-21: four of the +// nine rows the tag-best compare made on its own were functions this change did not grow (buildGraph twice, serialize, and a +// captureTagsFacts that fell 29.2 -> 29.1). A key the history never held (created after the tag) is not judged. +inline void appendTangleRatchet( std::vector& regs, const IngestResult& ing, + const std::vector>& rowed, const gtl::btree_map& rowOfKey, + std::string_view root, DeltaExtras& extras ) { std::vector paths; - paths.reserve( ratchetable.size() ); - for( const auto& [ key, nowOfKey ] : ratchetable ) + paths.reserve( rowed.size() ); + for( const auto& [ key, nowOfKey ] : rowed ) { paths.emplace_back( relForHash( ing.files[ ing.symbols[ nowOfKey->at ].fileId ], root ) ); } @@ -11593,37 +11638,23 @@ inline void appendTangleRatchet( std::vector& regs, const IngestResu { return; } - for( const auto& [ key, nowOfKey ] : ratchetable ) + for( const auto& [ key, nowOfKey ] : rowed ) { const BestSinceRow* row = store.find( key ); - if( row == nullptr ) + const auto at = rowOfKey.find( key ); + if( row == nullptr || at == rowOfKey.end() ) { continue; } ++extras.ratchetJudged; - const TangleNow& now = *nowOfKey; - const TangleBest best = unpackTangleBest( row->value ); - const std::uint32_t now10 = tangleScore10( now.in ); - const TangleRise rise = tangleRise( best.minima, now.in ); - if( now10 <= best.score10 || !rise.any() ) - { - continue; - } - const std::string since = "best since " + store.ref + ": " + tangleWhy( best.minima, now.in, /*isNew=*/false ); - if( const auto it = rowOfKey.find( key ); it != rowOfKey.end() ) + const TangleBest best = unpackTangleBest( row->value ); + if( tangleScore10( nowOfKey->in ) <= best.score10 || !tangleRise( best.minima, nowOfKey->in ).any() ) { - Regression& r = regs[ it->second ]; - r.facet = store.ref; - r.why += "; " + since; continue; } - const TangleDetailFacts detail = detailOf.of( ing.symbols[ now.at ] ); - Regression r{ "tangle", g.canonId[ now.at ], best.score10, now10, key, /*isMinor=*/true, store.ref, /*isNewSymbol=*/false, /*isMoved=*/false }; - r.why = since; - r.fix = tangleFix( rise, /*isNew=*/false, now.in, detail ); - r.locals = tangleLocals( detail ); - regs.push_back( std::move( r ) ); - stamp( now.at ); + Regression& r = regs[ at->second ]; + r.facet = store.ref; + r.why += "; best since " + store.ref + ": " + tangleWhy( best.minima, nowOfKey->in, /*isNew=*/false ); } } @@ -11852,7 +11883,7 @@ inline void appendRepeatedDecisionFixes( std::vector& regs, const In // The rows, appended to `regs` (stamped by the caller's `stamp( NodeId )`). `existed` and `movedAt` are computeDelta's own origin // oracles, so a tangle row's origin= reads exactly as every other per-symbol kind's. With `extras`, also the tangle credits and the -// D4 ratchet (appendTangleRatchet). +// D4 facet on the rows (appendTangleRatchet). // Judged only when the kind is selected and against a floor that recorded the tangle inputs — an older sidecar or blob has none, and // reading every function as new would bury the answer in rows that are not about this change. template @@ -11867,7 +11898,7 @@ inline void appendTangleRows( std::vector& regs, const IngestResult& const gtl::btree_map nowByKey = tangleNowByKey( ing, g, keyByNode ); TangleDetailReader detailOf{ ing }; gtl::btree_map rowOfKey; // the row this pass emitted for a key (the ratchet adds its facet there) - std::vector> ratchetable; // over the bar, existed, and the change moved its inputs (key, its nowByKey entry) + std::vector> rowed; // the rows on functions that existed at the baseline (D4 reads their history) for( const auto& [ key, best ] : nowByKey ) { const bool isNew = !existed( key ); @@ -11882,27 +11913,30 @@ inline void appendTangleRows( std::vector& regs, const IngestResult& { continue; // under the bar now: no row, whatever it was } - if( !isNew && packTangle( was ) != packTangle( best.in ) ) - { - ratchetable.emplace_back( key, &best ); - } - const TangleRise rise = tangleRise( was, best.in ); - if( !isNew && was10 >= kTangleBar10 && !rise.any() ) + const TangleRise rise = tangleRise( was, best.in ); + const TangleCause cause = tangleCauseOf( isNew, was10, now10, rise ); + if( cause == TangleCause::None ) { continue; // already over the bar and nothing rose: the change did not make it so } + const bool moved = isNew && movedAt( best.at ); + const bool gates = tangleCauseGates( cause, moved, relForHash( ing.files[ ing.symbols[ best.at ].fileId ], root ) ); const TangleDetailFacts detail = detailOf.of( ing.symbols[ best.at ] ); - Regression r{ "tangle", g.canonId[ best.at ], isNew ? 0u : was10, now10, key, /*isMinor=*/true, {}, isNew, isNew && movedAt( best.at ) }; + Regression r{ "tangle", g.canonId[ best.at ], isNew ? 0u : was10, now10, key, /*isMinor=*/!gates, {}, isNew, moved }; r.why = tangleWhy( was, best.in, isNew ); - r.fix = tangleFix( rise, isNew, best.in, detail ); + r.fix = tangleFix( cause == TangleCause::Grew ? tangleGrowth( was, best.in ) : rise, isNew, best.in, detail ); r.locals = tangleLocals( detail ); rowOfKey[ key ] = regs.size(); regs.push_back( std::move( r ) ); stamp( best.at ); + if( !isNew ) + { + rowed.emplace_back( key, &best ); + } } - if( extras != nullptr && extras->bestSince && !ratchetable.empty() ) + if( extras != nullptr && extras->bestSince && !rowed.empty() ) { - appendTangleRatchet( regs, ing, g, ratchetable, rowOfKey, detailOf, stamp, root, *extras ); + appendTangleRatchet( regs, ing, rowed, rowOfKey, root, *extras ); } } diff --git a/src/verbs_quality.h b/src/verbs_quality.h index 2e496932f..708cdc0f8 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -1477,13 +1477,13 @@ inline constexpr const char* kQdLegendCore = "score). THIRTEEN KINDS, and kind= on every row names which one: complexity over the ccx bar, verbosity " "(LOC), nesting, params, duplication, dead-code, api-surface (new public contract drift), " "error-masking, short-horizon-churn, new-clone-of-reused-helper, placeholder (added stub/TODO), " - "defect-shape (defect= names it), tangle (a long function's nesting, deep share and steering locals; report-only). " + "defect-shape (defect= names it), tangle (a long function's nesting, deep share and steering locals; a new or crossing one gates). " "THREE independent axes, in this " "order: (1) acked findings are suppressed entirely (acked= counts them); (2) ORIGIN — a finding on a " "symbol that EXISTED at the baseline is preexisting-worse (no origin attribute), one that exists only " "because the code is NEW carries origin=\"new-symbol\"; (3) MATERIALITY — a small numeric delta is " "sev=\"minor\", and minor= counts them. EXIT 2 fires only on preexisting-worse AND major, the gating= count; " - "new-symbol rows never gate, except defect-shape format-arity and a new function at the ceiling, so exit 0 " + "new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling and a tangled new function, so exit 0 " "is NOT a verdict on them — nothing that existed got worse, but the new debt is yours: read them. Clone kinds are new-symbol only when EVERY member is new; short-horizon-churn is " "preexisting by construction. preexisting-worse= and new-symbol= partition regressions=. stale= is a " "FOURTH axis, never gating and never counted in regressions=: rows in the .ripwire_quality_acks ledger " @@ -1744,23 +1744,25 @@ inline constexpr const char* kQdFailureDefaultLegend = // QD-TANGLE — emitted only when a tangle row is in the document. inline constexpr const char* kQdTangleLegend = - "tangle rows are REPORT-ONLY (always sev=\"minor\", never gating). was= and now= are the score S = T x log2(loc/50), " + "a tangle row GATES when the function is new or crossed the bar (not a moved body, not test code); a row an input rose on is " + "sev=\"minor\". was= and now= are the score S = T x log2(loc/50), " "T = nesting levels past 3 + deep%/5 + steering locals per 100 lines (deep%: the share of lines inside regions at nesting 4+, " "short arms of a flat switch or else-if chain of 4+ arms left out); bar= 6. Length only AMPLIFIES: a function of 50 lines or " "fewer, a long flat body and an orchestrator of named steps all score 0. A row means the change made it so: the function is " - "new, crossed the bar, or an input rose (nesting +1, deep lines +5, a new steering local); why= names those inputs, fix= the " + "new, crossed the bar, its score grew against the baseline while over the bar (the ratchet: a tenth counts), or an input rose " + "(nesting +1, deep lines +5, a new steering local); why= names the inputs that changed, fix= the " "shape the rise calls for with its lines, locals= the steering locals: a primitive local written again after its " "declaration and read by a branch condition 10 or more statements after that write. "; // D4 — present when the ratchet read its reference point (ratchet_ref= on the root). A ratchet= facet needs that read, so this one // sentence defines both. inline constexpr const char* kQdRatchetLegend = - "ratchet_ref= is the reference point the tangle ratchet read, the last tag reachable from HEAD: each function over the tangle bar " - "whose inputs this change moved is compared with its BEST since that tag (the lowest of each input and of the score over every first-parent " + "ratchet_ref= is the reference point the tangle rows' history read, the last tag reachable from HEAD: each tangle row on a function " + "that existed at the baseline is compared with its BEST since that tag (the lowest of each input and of the score over every first-parent " "version since it, or since the function's creation); ratchet_judged= counts those that had history, ratchet_unread= versions " "that could not be measured, ratchet_cut=\"1\" that only the 512 newest versions were read. ratchet=\"TAG\" on a tangle row: " "the score is above its best since TAG and an input rose over its minimum by the rise rule, so a function that crept up across " - "changes is named; why= then adds \"best since TAG: ...\", and on a row of its own was= is that best score. Report-only. "; + "changes says so; why= then adds \"best since TAG: ...\". A facet only: it makes no row and changes no severity. "; // QD-CREDIT-ROW — present when the document carries an section. inline constexpr const char* kQdImprovedLegend = @@ -2549,27 +2551,39 @@ inline void emitQdGatingLine( const std::vector& regs, // M12: displaySym, not first->sym raw — the XML/JSON rows both normalize sym's path segment // for display (quality::displaySym); this stderr line was the one caller that skipped it, // so it named "./src/…::rw::…" beside a row that named the same finding "src/…::rw::…". - // a gating row on NEW code is defect-shape format-arity or a new function at the ceiling (rowGates); the line names + // a gating row on NEW code is defect-shape format-arity, a new function at the ceiling or a tangled new function (rowGates); the line names // either part only when there is one, so every run without them keeps its bytes. const std::size_t newGating = static_cast( std::count_if( regs.begin(), regs.end(), []( const quality::Regression& r ) { return r.isNewSymbol && quality::rowGates( r ); } ) ); const std::size_t ceilingGating = static_cast( std::count_if( regs.begin(), regs.end(), []( const quality::Regression& r ) { return r.ceiling != 0 && quality::rowGates( r ); } ) ); + // a new-symbol tangle row gates under rule (b) (QD-LESSONS-2); was=/now= read as every surface prints them (a tangle score's tenths) + const std::size_t newTangleGating = static_cast( std::count_if( regs.begin(), regs.end(), []( const quality::Regression& r ) + { return r.isNewSymbol && r.kind == "tangle" && quality::rowGates( r ); } ) ); + const std::string was = quality::rowValueText( *first, first->was ), now = quality::rowValueText( *first, first->now ); if( ceilingGating != 0 ) { - rw::emitTo( stderr, "ripwire: --quality-delta gating: {} gating finding(s), {} of them a new function at the ceiling (ccx {} / {} lines); first: {} {}{} (was={} now={})\n", - gatingCount, ceilingGating, quality::newSymbolCeiling( quality::kCcxBar ), quality::newSymbolCeiling( quality::kLocBar ), - first->kind.c_str(), quality::displaySym( first->sym, deltaRoot ).c_str(), at.c_str(), first->was, first->now ); + const std::string tangled = newTangleGating == 0 ? std::string() + : std::format( ", {} a tangled new function (tangle {} or more)", newTangleGating, quality::metricValueText( "tangle", rw::kTangleBar10 ) ); + rw::emitTo( stderr, "ripwire: --quality-delta gating: {} gating finding(s), {} of them a new function at the ceiling (ccx {} / {} lines){}; first: {} {}{} (was={} now={})\n", + gatingCount, ceilingGating, quality::newSymbolCeiling( quality::kCcxBar ), quality::newSymbolCeiling( quality::kLocBar ), tangled, + first->kind.c_str(), quality::displaySym( first->sym, deltaRoot ).c_str(), at.c_str(), was, now ); } else if( newGating == 0 ) { rw::emitTo( stderr, "ripwire: --quality-delta gating: {} preexisting-worse major finding(s); first: {} {}{} (was={} now={})\n", - gatingCount, first->kind.c_str(), quality::displaySym( first->sym, deltaRoot ).c_str(), at.c_str(), first->was, first->now ); + gatingCount, first->kind.c_str(), quality::displaySym( first->sym, deltaRoot ).c_str(), at.c_str(), was, now ); + } + else if( newTangleGating != 0 ) + { + rw::emitTo( stderr, "ripwire: --quality-delta gating: {} gating finding(s), {} of them a tangled new function (tangle {} or more); first: {} {}{} (was={} now={})\n", + gatingCount, newTangleGating, quality::metricValueText( "tangle", rw::kTangleBar10 ), first->kind.c_str(), + quality::displaySym( first->sym, deltaRoot ).c_str(), at.c_str(), was, now ); } else { rw::emitTo( stderr, "ripwire: --quality-delta gating: {} gating finding(s), {} of them defect-shape format-arity on new code; first: {} {}{} (was={} now={})\n", - gatingCount, newGating, first->kind.c_str(), quality::displaySym( first->sym, deltaRoot ).c_str(), at.c_str(), first->was, first->now ); + gatingCount, newGating, first->kind.c_str(), quality::displaySym( first->sym, deltaRoot ).c_str(), at.c_str(), was, now ); } } diff --git a/test/lib/tanglefixtures.py b/test/lib/tanglefixtures.py index b97aa4cdd..e6f9b6fba 100644 --- a/test/lib/tanglefixtures.py +++ b/test/lib/tanglefixtures.py @@ -21,6 +21,13 @@ shrink — tangled at v1/c2; wt removes its deep region: credited in (tangle), no row. simplify — ccx 21 at v1/c2, ccx 11 in wt: credited in (complexity). nudge — tangled at v1/c2 (40 deep lines); wt drops 2 of them: under the rise step, so no entry (and no row). + crossing — 100 flat lines at v1/c2 (score 0); wt gives it tangled's body: it crossed the bar, a GATING row (rule (b), 11-21). + harnessmain — new in wt under test/: tangled's body, a row that stays sev="minor" (test code never gates by tangle). + The RATCHET against the range base (QD-RATCHET-BASE, replay 11-21), three over-bar functions (v1 40 deep lines): + grow1 — 40 at c2, 42 in wt: the score grew a little, under the rise step and under its best since v1's rise: a ratchet row. + reflow — 46 at c2 (+6 over v1), wt adds one flat line: its inputs moved but the score is the same tenth: no row (the replay's + buildGraph in #706, +28 lines at 56.9 -> 56.9, that the tag-best compare flagged). + settle — 48 at c2 (+8 over v1), 47 in wt: the score fell: no row (the replay's captureTagsFacts 29.2 -> 29.1 in #714). The wip stage cuts creep to 5 deep lines on the side branch, whose next commit (c2) grows it back: a version the first-parent line never stood at, so it must not become creep's best (r1 would read deep 8->49). """ @@ -40,15 +47,7 @@ def deep_block(n, depth_indent): def creep(extra): # depth: for(1) if(2) for(3) if(4) -> the deep region is the body of the 4th level - body = deep_block(40 + extra, 20) - tail = "".join(f" total = total * 3 + {k};\n" for k in range(70)) - return ("int creep( const std::vector& xs )\n{\n int total = 0;\n" - " for( int x : xs )\n {\n if( x > 0 )\n {\n" - " for( int y = 0; y < x; ++y )\n {\n" - " if( y % 2 )\n {\n" - + body + - " }\n }\n }\n }\n" - + tail + " return total;\n}\n") + return overbar("creep", 40 + extra, mult=3, gt=0, mod=2) def shrink(deep): @@ -72,19 +71,24 @@ def simplify(branches): def nudge(deep): + return overbar("nudge", deep, mult=11) + + +def overbar(name, deep, extra=0, mult=13, gt=2, mod=5): + # nudge's shape under another name: for(1) if(2) for(3) if(4), `deep` lines at depth 4, a flat tail of 70 + extra lines inner = deep_block(deep, 20) - tail = "".join(f" total = total * 11 + {k};\n" for k in range(70)) - return ("int nudge( const std::vector& xs )\n{\n int total = 0;\n" - " for( int x : xs )\n {\n if( x > 2 )\n {\n" + tail = "".join(f" total = total * {mult} + {k};\n" for k in range(70 + extra)) + return (f"int {name}( const std::vector& xs )\n{{\n int total = 0;\n" + f" for( int x : xs )\n {{\n if( x > {gt} )\n {{\n" " for( int y = 0; y < x; ++y )\n {\n" - " if( y % 5 )\n {\n" + inner + + f" if( y % {mod} )\n {{\n" + inner + " }\n }\n }\n }\n" + tail + " return total;\n}\n") -def tangled(): +def tangled(name="tangled"): deep = deep_block(25, 28) seq = "".join(f" total = total + {k};\n" for k in range(60)) - return ("int tangled( const std::vector& xs )\n{\n int total = 0;\n bool found = false;\n" + return (f"int {name}( const std::vector& xs )\n{{\n int total = 0;\n bool found = false;\n" " for( int x : xs )\n {\n if( x > 0 )\n {\n" " for( int y = 0; y < x; ++y )\n {\n" " if( y % 2 )\n {\n" @@ -96,9 +100,9 @@ def tangled(): + seq + " if( found )\n {\n total *= 2;\n }\n return total;\n}\n") -def sequential(): - return ("int sequential( int x )\n{\n int total = x;\n" - + "".join(f" total = total * 7 + {k};\n" for k in range(150)) + " return total;\n}\n") +def sequential(name="sequential", n=150): + return (f"int {name}( int x )\n{{\n int total = x;\n" + + "".join(f" total = total * 7 + {k};\n" for k in range(n)) + " return total;\n}\n") def orchestrator(): @@ -189,7 +193,16 @@ def main(): write(d, "shrink.cpp", hdr + shrink(stage != "wt")) write(d, "simplify.cpp", simplify(20 if stage != "wt" else 10)) write(d, "nudge.cpp", hdr + nudge(40 if stage != "wt" else 38)) + if stage != "wt": + write(d, "crossing.cpp", sequential("crossing", 100)) + write(d, "grow1.cpp", hdr + overbar("grow1", 42 if stage == "wt" else 40, mult=17)) + write(d, "reflow.cpp", hdr + overbar("reflow", 40 if stage == "v1" else 46, extra=1 if stage == "wt" else 0, mult=19)) + write(d, "settle.cpp", hdr + overbar("settle", {"v1": 40, "wt": 47}.get(stage, 48), mult=23)) if stage == "wt": + write(d, "crossing.cpp", hdr + tangled("crossing")) + os.makedirs(os.path.join(d, "test"), exist_ok=True) + with open(os.path.join(d, "test", "harness.cpp"), "w") as f: + f.write(hdr + tangled("harnessmain")) write(d, "tangled.cpp", hdr + tangled()) write(d, "sequential.cpp", sequential()) write(d, "orchestrator.cpp", orchestrator()) diff --git a/test/tanglecheck.sh b/test/tanglecheck.sh index 6b66c92b3..9ad032219 100755 --- a/test/tanglecheck.sh +++ b/test/tanglecheck.sh @@ -1,11 +1,14 @@ #!/usr/bin/env bash -# tanglecheck.sh — QD-TANGLE gate: the tangle kind (report-only), its steering-local fact, the D4 best-since ratchet and the +# tanglecheck.sh — QD-TANGLE gate: the tangle kind (rule (b) gates, owner 11-21), its steering-local fact, the D4 best-since ratchet and the # QD-CREDIT-ROW section (STAGE0 2.1-2.8; quality.h appendTangleRows / appendTangleRatchet, qdbestsince.h). # # One seeded C++ repo, four stages (test/lib/tanglefixtures.py): v1 (tagged); a side branch with wip (cuts creep) then c2, # merged --no-ff; the working tree (judged). -# (t1) TANGLED NEW: a depth-6 function with a steering flag rows: kind="tangle" sev="minor" origin="new-symbol", why= names the -# nesting, fix= an extraction with its lines, locals= the flag. +# (t1) TANGLED NEW: a depth-6 function with a steering flag rows: kind="tangle" origin="new-symbol" gating="1" (rule (b)), why= +# names the nesting, fix= an extraction with its lines, locals= the flag. +# (b1) CROSSING: crossing was 100 flat lines (score 0) and now has tangled's body: a preexisting row (no origin=) with gating="1". +# (b2) TEST CODE: harnessmain, new under test/ with tangled's body: a row with sev="minor" and no gating= (premise: the row exists). +# (b3) EXIT: the answer exits 2 and the root's gating= counts at least t1 + b1; the stderr line names a tangled new function. # (n1) LONG SEQUENTIAL, (n2) LONG ORCHESTRATOR, (n3) FLAT DISPATCHER, (n4) SHORT NESTED HELPER: no tangle row. Each counts its # premise in --metrics first (the function is there, and n3/n4 really reach depth 4+) and FAILS on a zero premise. # (n5) ARM NESTING: a 6-arm else-if chain whose short arms nest to depth 7, beside one depth-4 region outside it: no tangle row @@ -15,17 +18,26 @@ # an index (`xs[ pos ]`): no steer= (premise: steercursor in --metrics). Census 11-19: lexCpp's `j`, buildGraph's indices. # (s4) SCOPE: a counter rewritten in a block that closes, then a for-head local of the same name tested 12 statements # later: no steer= (premise: steerscope in --metrics). Census 11-19: genPathOf's `a`. -# (r1) RATCHET: creep gained 3 deep lines at c2 and 3 more in the working tree — each step under the rise rule (+5), so no -# baseline row reason exists, but against its best since v1 it rose 6: a tangle row with ratchet="v1"; root ratchet_ref="v1". +# (r1) RATCHET: creep gained 3 deep lines at c2 and 3 more in the working tree — each step under the rise rule (+5); its score +# grew against HEAD (a ratchet row, k1's rule), and against its best since v1 it rose 6: the row carries ratchet="v1" and why= +# "best since v1: ..."; root ratchet_ref="v1". # The wip side branch's 5-deep-line creep is not its best: the ratchet reads the first-parent line (replay 11-19). +# (k1) RATCHET VS THE BASE: grow1 (over the bar) gained 2 deep lines: under the rise step and under its best-since-v1 rise, yet +# its score grew against HEAD: a tangle row was= HEAD's score, now= higher, sev="minor", no ratchet= facet. +# (k2) MOVED, NOT GROWN: reflow's inputs moved (one flat line) but its score is HEAD's tenth: no row. Against its best since v1 +# it is 6 deep lines up, which made the tag-best compare row it (replay 11-21: buildGraph in #706). +# (k3) FELL: settle's score fell against HEAD (48 -> 47 deep lines), still 7 over v1: no row and no entry (under the +# rise step). Replay 11-21: captureTagsFacts 29.2 -> 29.1 in #714. k1-k3 read their premise from --metrics of HEAD and wt. # (r2) CREDIT: shrink lost its deep region: listed in as kind="tangle", and no tangle row. # (r4) NO CREDIT FOR A NUDGE: nudge (over the bar) lost 2 of its 40 deep lines, under the rise step: no entry # (premise: nudge over the bar in --metrics). Replay 11-19: buildGraph 56.9 -> 56.8 was credited for one deep line. # (r3) NEW FN: the tangled new function's row carries no ratchet= (a symbol created after the tag has no history here). # (c1) CREDIT: simplify ccx 21 -> 11: listed in as kind="complexity". -# (g) report-only: gating="0" on the root although tangle rows are present (premise: >= 1 tangle row). +# (g) only rule (b) gates: every gating tangle row is a new or crossing one (tangled, crossing); every other tangle row is sev="minor". # (j) --json carries the same tangle rows (count) and "improved". # (d) determinism: the working-tree run twice is byte-identical. +# Red before QD-LESSONS-2 (main 8861b0d4d): t1 b1 b3 (every tangle row minor), k1 (no row: no rise), k2 k3 (the tag-best rows); b2 +# is red only on a guard-off build (no test-path exemption). # Red before the lane (main's bin): t1 r1 r2 r3 c1 s1 (no tangle kind, no steer=, no improved); red before the census fixes (11-19): n5 s3 s4; before the replay fixes (11-19): r1 (wip best) r4. # Usage: test/tanglecheck.sh [BIN] set -u @@ -60,6 +72,8 @@ Q="$TMP/qd.xml" "$BIN" "$R" --quality-delta --no-cache >"$Q.2" 2>/dev/null; rc2=$? "$BIN" "$R" --quality-delta --json --no-cache >"$TMP/qd.json" 2>/dev/null; rcj=$? M="$( "$BIN" "$R" --metrics --no-cache 2>/dev/null )"; rcm=$? +mkdir -p "$TMP/head" && "${G[@]}" -C "$R" archive HEAD | tar -x -C "$TMP/head" +MH="$( "$BIN" "$TMP/head" --metrics --no-cache 2>/dev/null )" rc="$( cat "$Q.rc" )" case "$rc" in 0|2) ;; *) no "quality-delta exit status $rc (stderr: $( head -c 300 "$Q.err" ))";; esac if [ "$rc2" != "$rc" ] || [ "$rcj" != "$rc" ]; then no "quality-delta exit status differs between runs: $rc, again $rc2, --json $rcj"; fi @@ -69,15 +83,30 @@ if [ "$rcm" != 0 ]; then no "--metrics exit status $rcm"; fi trow(){ grep -oE "]*>" "$Q" | head -1; } attr(){ printf '%s' "$1" | grep -oE " $2=\"[^\"]*\"" | head -1 | sed -E "s/.*=\"([^\"]*)\"/\1/"; } mrow(){ printf '%s' "$M" | tr '>' '\n' | grep "n=\"$1\"" | head -1; } +hrow(){ printf '%s' "$MH" | tr '>' '\n' | grep "n=\"$1\"" | head -1; } +kpre(){ local h w; h="$( hrow "$1" )"; w="$( mrow "$1" )"; printf '%s %s %s %s' "$( attr "$h" tangle )" "$( attr "$w" tangle )" "$( attr "$h" loc )" "$( attr "$w" loc )"; } tangles="$( grep -oE '= 2 and the tangled-new stderr line; got rc=$rc gating=${rg:-none} stderr='$( grep -F 'gating:' "$Q.err" | head -c 300 )'"; fi # (n1)-(n4): premise from --metrics, then no row neg(){ local label="$1" sym="$2" need="$3" m; m="$( mrow "$sym" )" @@ -113,10 +142,25 @@ else if [ -z "$( attr "$ms" steer )" ]; then ok "(s4) steerscope: no steer= (clo # (r1) r="$( trow creep )" dw="$( attr "$r" why | sed -nE 's/.*best since v1: deep ([0-9]+)->([0-9]+) lines.*/\1 \2/p' )" -if [ -n "$r" ] && [ "$( attr "$r" ratchet )" = v1 ] && [ -n "$dw" ] && [ $(( ${dw#* } - ${dw% *} )) = 6 ]; then +read -r ht wt hl wl <<<"$( kpre creep )" +if [ -n "$r" ] && [ "$( attr "$r" ratchet )" = v1 ] && [ -n "$dw" ] && [ $(( ${dw#* } - ${dw% *} )) = 6 ] && [ "$( attr "$r" was )" = "$ht" ]; then ok "(r1) creep: ratchet=\"v1\" row: $r" -else no "(r1) creep: want a tangle row with ratchet=\"v1\" and why=best since v1: deep N->N+6 lines, got '${r:-none}'"; fi +else no "(r1) creep: want a tangle row was=\"$ht\" (HEAD) with ratchet=\"v1\" and why=best since v1: deep N->N+6 lines, got '${r:-none}'"; fi if grep -q 'ratchet_ref="v1"' "$Q"; then ok "(r1) root ratchet_ref=\"v1\""; else no "(r1) root: no ratchet_ref=\"v1\""; fi +# (k1)-(k3): the ratchet against the range base; premise from HEAD's and the working tree's --metrics +read -r ht wt hl wl <<<"$( kpre grow1 )"; r="$( trow grow1 )" +if [ -z "$ht" ] || [ -z "$wt" ] || [ "${ht%.*}" -lt 6 ] || [ "${ht/./}" -ge "${wt/./}" ]; then no "(k1) PREMISE: grow1 over the bar and higher in wt, got HEAD=$ht wt=$wt" +elif [ -n "$r" ] && [ "$( attr "$r" was )" = "$ht" ] && [ "$( attr "$r" now )" = "$wt" ] && [ "$( attr "$r" sev )" = minor ] && [ -z "$( attr "$r" ratchet )" ]; then + ok "(k1) grow1 $ht -> $wt: a minor ratchet row, no ratchet= facet: $r" +else no "(k1) grow1 $ht -> $wt: want a minor tangle row was=\"$ht\" now=\"$wt\" without ratchet=, got '${r:-none}'"; fi +read -r ht wt hl wl <<<"$( kpre reflow )" +if [ -z "$ht" ] || [ "$ht" != "$wt" ] || [ "$hl" = "$wl" ] || [ "${ht%.*}" -lt 6 ]; then no "(k2) PREMISE: reflow over the bar, same score, lines moved; got $ht/$wt, $hl/$wl lines" +elif [ -z "$( trow reflow )" ]; then ok "(k2) reflow (S $ht, $hl -> $wl lines): no tangle row" +else no "(k2) reflow: want no tangle row (score unchanged), got $( trow reflow )"; fi +read -r ht wt hl wl <<<"$( kpre settle )" +if [ -z "$ht" ] || [ -z "$wt" ] || [ "${wt%.*}" -lt 6 ] || [ "${wt/./}" -ge "${ht/./}" ]; then no "(k3) PREMISE: settle over the bar and lower in wt, got HEAD=$ht wt=$wt" +elif [ -z "$( trow settle )" ] && ! grep -qE ' $wt: no tangle row, no entry" +else no "(k3) settle $ht -> $wt: want no row and no credit, got row '$( trow settle )' / $( grep -oE ']*>' "$Q" )"; fi # (r2) / (c1) if grep -qE '"; else no "(r2) shrink: no entry"; fi if [ -z "$( trow shrink )" ]; then ok "(r2) shrink: no tangle row"; else no "(r2) shrink: unexpected tangle row $( trow shrink )"; fi @@ -130,10 +174,11 @@ elif grep -qE ' entry"; fi # (r3) if r="$( trow tangled )"; [ -n "$r" ] && [ -z "$( attr "$r" ratchet )" ]; then ok "(r3) tangled (new): no ratchet="; else no "(r3) tangled: want a row without ratchet=, got '${r:-none}'"; fi -# (g) report-only: no tangle row gates (other kinds' rows on these fixtures may) +# (g) only rule (b) gates: the gating tangle rows are exactly the new and crossing ones; every other tangle row is minor +gsyms="$( grep -oE ']*gating="1"[^>]*>' "$Q" | grep -oE ' sym="[^"]*"' | sed -E 's/.*(::|")([A-Za-z0-9_]+)"$/\2/' | sort | tr '\n' ' ' )" tg="$( grep -oE ']*>' "$Q" | grep -c 'gating="1"' )"; tm="$( grep -oE ']*>' "$Q" | grep -c 'sev="minor"' )" -if [ "$tangles" -ge 1 ] && [ "$tg" = 0 ] && [ "$tm" = "$tangles" ]; then ok "(g) report-only: $tangles tangle row(s), all sev=\"minor\", none gating" -else no "(g) tangle rows $tangles: gating $tg, minor $tm"; fi +if [ "$tangles" -ge 3 ] && [ "$gsyms" = "crossing tangled " ] && [ $(( tg + tm )) = "$tangles" ]; then ok "(g) $tangles tangle row(s): gating $gsyms, the other $tm sev=\"minor\"" +else no "(g) tangle rows $tangles: want gating exactly 'crossing tangled ', got '$gsyms' (gating $tg, minor $tm)"; fi # (j) the JSON twin: the same tangle rows in "r" and an "improved" list jt="$( python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(sum(1 for r in d["r"] if r.get("kind")=="tangle"), len(d.get("improved",[])))' "$TMP/qd.json" 2>/dev/null )" if [ "${jt% *}" = "$tangles" ] && [ "${jt#* }" -ge 2 ]; then ok "(j) --json: ${jt% *} tangle row(s) and ${jt#* } improved entries" From a1b540669b067ebe7d05ec05ab8bbc8899e2cd4a Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:13:54 -0500 Subject: [PATCH 05/61] qd tangle: the ratchet against the range base GATES (QD-RATCHET-BASE, owner 11-21) A function over tangle 6 at the range base whose score is higher now gates (not a moved body, not test code). Its own commit so it can be reverted alone. Expected effect (replay 11-21): a PR that grows buildGraph, serialize or captureTagsFacts by a tenth blocks until it is acked or the function is split (GE-BUILDGRAPH / GE-SERIALIZE / GE-CAPTURETAGS). tanglecheck k1 (grow1) and g read the ratchet rows as gating. Co-Authored-By: Claude Opus 5.5 --- src/quality.h | 12 +++++++----- src/verbs_quality.h | 4 ++-- test/tanglecheck.sh | 14 +++++++------- 3 files changed, 16 insertions(+), 14 deletions(-) diff --git a/src/quality.h b/src/quality.h index 9a7f346f6..65e3c0f12 100644 --- a/src/quality.h +++ b/src/quality.h @@ -11415,7 +11415,7 @@ inline std::uint32_t newSymbolCeilingGate( const Regression& r, SymKind measured // is new, it crossed the bar, its score grew against the range base while over the bar (the RATCHET, QD-RATCHET-BASE), or an input // rose — nesting +1, deep lines +kTangleDeepRise, or a new steering local. Rows on the score's growth catch a monster growing by a // tenth per change (12 deep lines in a 4000-line function), which a size floor would let grow forever (QD-MONSTER-GROWTH's lesson). -// A new function or a crossing GATES (rule (b), owner 11-21: tangleCauseGates); every other row is sev="minor". why= names the +// A new function, a crossing and a ratchet row GATE (owner 11-21: tangleCauseGates); every other row is sev="minor". why= names the // inputs that changed, fix= the shape the rise calls for (with its lines, from a re-walk of the ONE function: tangleDetailOf), // locals= the steering locals. A long orchestrator of named steps or a long flat body scores 0 and never rows. inline constexpr std::uint32_t kTangleDeepRise = 5; // deep lines that count as a rise (STAGE0 2.5's "worse" tier) @@ -11597,12 +11597,14 @@ inline TangleRise tangleGrowth( const TangleInputs& was, const TangleInputs& now return { now.nest > was.nest, now.deep > was.deep, now.steer > was.steer }; } -// Rule (b): a new function at or over the bar, or one that crossed it, GATES — except a moved body (its code is not new; the -// re-census found no such row) and test code (the census's test-harness mains were its false class, and QD-ENTRY-CEILING exempts -// test drivers the same way). A ratchet row or a row of a rising input stays sev="minor". `rel` = the root-relative path. +// What gates (owner 11-21): rule (b), a new function at or over the bar or one that crossed it, and the ratchet, a function over the +// bar whose score grew against the range base — except a moved body (its code is not new; the re-census found no such row) and test +// code (the census's test-harness mains were its false class, and QD-ENTRY-CEILING exempts test drivers the same way). A row of a +// rising input whose score did not grow stays sev="minor". `rel` = the root-relative path. Expected effect (replay 11-21): a change +// that grows buildGraph, serialize or captureTagsFacts by a tenth blocks until it is acked or the function is split. inline bool tangleCauseGates( TangleCause cause, bool moved, std::string_view rel ) noexcept { - return ( cause == TangleCause::New || cause == TangleCause::Crossed ) && !moved && !isTestPath( rel ); + return ( cause == TangleCause::New || cause == TangleCause::Crossed || cause == TangleCause::Grew ) && !moved && !isTestPath( rel ); } // QD-CREDIT-ROW for tangle (STAGE0 2.5): over the bar at the baseline, an input fell by the rise rule (tangleRise read backwards) and none rose, and the score is lower. diff --git a/src/verbs_quality.h b/src/verbs_quality.h index 708cdc0f8..94324d807 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -1744,8 +1744,8 @@ inline constexpr const char* kQdFailureDefaultLegend = // QD-TANGLE — emitted only when a tangle row is in the document. inline constexpr const char* kQdTangleLegend = - "a tangle row GATES when the function is new or crossed the bar (not a moved body, not test code); a row an input rose on is " - "sev=\"minor\". was= and now= are the score S = T x log2(loc/50), " + "a tangle row GATES when the function is new, crossed the bar or its score grew while over it (not a moved body, not test " + "code); a row an input rose on while the score did not grow is sev=\"minor\". was= and now= are the score S = T x log2(loc/50), " "T = nesting levels past 3 + deep%/5 + steering locals per 100 lines (deep%: the share of lines inside regions at nesting 4+, " "short arms of a flat switch or else-if chain of 4+ arms left out); bar= 6. Length only AMPLIFIES: a function of 50 lines or " "fewer, a long flat body and an orchestrator of named steps all score 0. A row means the change made it so: the function is " diff --git a/test/tanglecheck.sh b/test/tanglecheck.sh index 9ad032219..e992b63c2 100755 --- a/test/tanglecheck.sh +++ b/test/tanglecheck.sh @@ -23,7 +23,7 @@ # "best since v1: ..."; root ratchet_ref="v1". # The wip side branch's 5-deep-line creep is not its best: the ratchet reads the first-parent line (replay 11-19). # (k1) RATCHET VS THE BASE: grow1 (over the bar) gained 2 deep lines: under the rise step and under its best-since-v1 rise, yet -# its score grew against HEAD: a tangle row was= HEAD's score, now= higher, sev="minor", no ratchet= facet. +# its score grew against HEAD: a GATING tangle row was= HEAD's score, now= higher, no ratchet= facet (QD-RATCHET-BASE gate). # (k2) MOVED, NOT GROWN: reflow's inputs moved (one flat line) but its score is HEAD's tenth: no row. Against its best since v1 # it is 6 deep lines up, which made the tag-best compare row it (replay 11-21: buildGraph in #706). # (k3) FELL: settle's score fell against HEAD (48 -> 47 deep lines), still 7 over v1: no row and no entry (under the @@ -33,7 +33,7 @@ # (premise: nudge over the bar in --metrics). Replay 11-19: buildGraph 56.9 -> 56.8 was credited for one deep line. # (r3) NEW FN: the tangled new function's row carries no ratchet= (a symbol created after the tag has no history here). # (c1) CREDIT: simplify ccx 21 -> 11: listed in as kind="complexity". -# (g) only rule (b) gates: every gating tangle row is a new or crossing one (tangled, crossing); every other tangle row is sev="minor". +# (g) only rule (b) and the ratchet gate: the gating tangle rows are exactly creep crossing grow1 tangled; the rest are sev="minor". # (j) --json carries the same tangle rows (count) and "improved". # (d) determinism: the working-tree run twice is byte-identical. # Red before QD-LESSONS-2 (main 8861b0d4d): t1 b1 b3 (every tangle row minor), k1 (no row: no rise), k2 k3 (the tag-best rows); b2 @@ -150,9 +150,9 @@ if grep -q 'ratchet_ref="v1"' "$Q"; then ok "(r1) root ratchet_ref=\"v1\""; else # (k1)-(k3): the ratchet against the range base; premise from HEAD's and the working tree's --metrics read -r ht wt hl wl <<<"$( kpre grow1 )"; r="$( trow grow1 )" if [ -z "$ht" ] || [ -z "$wt" ] || [ "${ht%.*}" -lt 6 ] || [ "${ht/./}" -ge "${wt/./}" ]; then no "(k1) PREMISE: grow1 over the bar and higher in wt, got HEAD=$ht wt=$wt" -elif [ -n "$r" ] && [ "$( attr "$r" was )" = "$ht" ] && [ "$( attr "$r" now )" = "$wt" ] && [ "$( attr "$r" sev )" = minor ] && [ -z "$( attr "$r" ratchet )" ]; then - ok "(k1) grow1 $ht -> $wt: a minor ratchet row, no ratchet= facet: $r" -else no "(k1) grow1 $ht -> $wt: want a minor tangle row was=\"$ht\" now=\"$wt\" without ratchet=, got '${r:-none}'"; fi +elif [ -n "$r" ] && [ "$( attr "$r" was )" = "$ht" ] && [ "$( attr "$r" now )" = "$wt" ] && [ "$( attr "$r" gating )" = 1 ] && [ -z "$( attr "$r" ratchet )" ]; then + ok "(k1) grow1 $ht -> $wt: a gating ratchet row, no ratchet= facet: $r" +else no "(k1) grow1 $ht -> $wt: want a gating tangle row was=\"$ht\" now=\"$wt\" without ratchet=, got '${r:-none}'"; fi read -r ht wt hl wl <<<"$( kpre reflow )" if [ -z "$ht" ] || [ "$ht" != "$wt" ] || [ "$hl" = "$wl" ] || [ "${ht%.*}" -lt 6 ]; then no "(k2) PREMISE: reflow over the bar, same score, lines moved; got $ht/$wt, $hl/$wl lines" elif [ -z "$( trow reflow )" ]; then ok "(k2) reflow (S $ht, $hl -> $wl lines): no tangle row" @@ -177,8 +177,8 @@ if r="$( trow tangled )"; [ -n "$r" ] && [ -z "$( attr "$r" ratchet )" ]; then o # (g) only rule (b) gates: the gating tangle rows are exactly the new and crossing ones; every other tangle row is minor gsyms="$( grep -oE ']*gating="1"[^>]*>' "$Q" | grep -oE ' sym="[^"]*"' | sed -E 's/.*(::|")([A-Za-z0-9_]+)"$/\2/' | sort | tr '\n' ' ' )" tg="$( grep -oE ']*>' "$Q" | grep -c 'gating="1"' )"; tm="$( grep -oE ']*>' "$Q" | grep -c 'sev="minor"' )" -if [ "$tangles" -ge 3 ] && [ "$gsyms" = "crossing tangled " ] && [ $(( tg + tm )) = "$tangles" ]; then ok "(g) $tangles tangle row(s): gating $gsyms, the other $tm sev=\"minor\"" -else no "(g) tangle rows $tangles: want gating exactly 'crossing tangled ', got '$gsyms' (gating $tg, minor $tm)"; fi +if [ "$tangles" -ge 3 ] && [ "$gsyms" = "creep crossing grow1 tangled " ] && [ $(( tg + tm )) = "$tangles" ]; then ok "(g) $tangles tangle row(s): gating $gsyms, the other $tm sev=\"minor\"" +else no "(g) tangle rows $tangles: want gating exactly 'creep crossing grow1 tangled ', got '$gsyms' (gating $tg, minor $tm)"; fi # (j) the JSON twin: the same tangle rows in "r" and an "improved" list jt="$( python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(sum(1 for r in d["r"] if r.get("kind")=="tangle"), len(d.get("improved",[])))' "$TMP/qd.json" 2>/dev/null )" if [ "${jt% *}" = "$tangles" ] && [ "${jt#* }" -ge 2 ]; then ok "(j) --json: ${jt% *} tangle row(s) and ${jt#* } improved entries" From fdf598c5ad5b8c11ad70f090e565efd6eaf99a0c Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:39:24 -0500 Subject: [PATCH 06/61] shstatus: one nesting budget for the shell lexer and parser; a cut scan is disclosed (CR712-SHSTATUS-DEPTH) shstatus.h recursed with no bound through quotes and $( ) in the lexer (skipQuote <-> skipParen) and through compound commands in the parser (parseList -> ... -> parseCommand): 5,000 nested subshells, brace groups or if-then blocks in a shell file killed --quality-delta with SIGSEGV (rc 139 on main 8861b0d4d). Now one NestBudget (kMaxShellNest 64) is shared by the lexer's skips, the dq descent, every parseCommand and every substitution parser; past it the rest is left unparsed and Tree::cut is set. It replaces the silent 40-level substitution cap (kMaxSubDepth). Disclosure: defectSitesOf counts the shell files whose scan was cut into DeltaExtras::shellCut, and the root carries shell_cut="N" (XML and --json, through the extras' root-attribute helper; absent at 0), defined in the core legend and the compact dictionary (a static_assert ties the 64). capdisclose.map: kMaxShellNest sink:cut (shstatus.h joins the lint's scope). New gate test/shellnestcheck.sh (generated scripts, never committed): five 5,000-deep shapes exit 0/2 with shell_cut="1" (subshell/group/if crash on main; quote/subst were cut silently), --json carries it, and a 40-deep unhandled-arm site is still found with no shell_cut=. Co-Authored-By: Claude Opus 5.5 --- src/compactlegend.h | 4 +- src/defectshape.h | 19 +++++-- src/quality.h | 44 +++++++++------ src/shstatus.h | 119 ++++++++++++++++++++++++++++++---------- src/verbs_quality.h | 8 ++- test/capdisclose.map | 1 + test/lib/capdisclose.py | 4 +- test/regression.sh | 1 + test/shellnestcheck.sh | 78 ++++++++++++++++++++++++++ 9 files changed, 221 insertions(+), 57 deletions(-) create mode 100755 test/shellnestcheck.sh diff --git a/src/compactlegend.h b/src/compactlegend.h index 1dc5be188..1c931339a 100644 --- a/src/compactlegend.h +++ b/src/compactlegend.h @@ -1087,7 +1087,9 @@ inline constexpr CompactCompletenessTerm kCompactAttributeReadings[] = { "stale_by_kind", "stale_by_kind=: stale= split by ack kind (kind:N,...); the sa rows are collapsed", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, { "stale_next", "stale_next=: the call printing the sa rows and the full header", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, // D4 (src/quality.h ratchetAttrsXml): present when the tangle ratchet read its reference point - { "ratchet_ref", "ratchet_ref=TAG ratchet_judged=N: the ratchet compared N touched over-bar functions with their best since TAG; ratchet_unread= / ratchet_cut=1: versions not measured", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, + { "ratchet_ref", "ratchet_ref=TAG ratchet_judged=N: N tangle rows' functions compared with their best since TAG; ratchet_unread= / ratchet_cut=1: versions not measured", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, + // CR712-SHSTATUS-DEPTH (src/quality.h ratchetAttrsXml): present when not 0 + { "shell_cut", "shell_cut=N: shell files whose defect-shape scan stopped at nesting depth 64; deeper code not judged", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, { "preexisting-worse", "preexisting-worse=N: regressions on symbols that existed at baseline; they gate when major", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, { "new-symbol", "new-symbol=N: NEW code; new-symbol rows never gate, except defect-shape format-arity, a ceiling= row or a tangle row", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, { "register-macro-excluded", "register-macro-excluded=N: symbols skipped: self-registering test/bench macros or Rust #[test]; a floor", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, diff --git a/src/defectshape.h b/src/defectshape.h index 60ab60fcc..f0c393842 100644 --- a/src/defectshape.h +++ b/src/defectshape.h @@ -4060,13 +4060,17 @@ inline std::vector Script::sites() const } // namespace va -inline std::vector scanVacuousAssertBash( std::string_view src, const std::vector& /*spans*/ ) +inline std::vector scanVacuousAssertBash( std::string_view src, const std::vector& /*spans*/, bool* cut = nullptr ) { if( src.empty() ) { return {}; } const rw::shstatus::Tree tree = rw::shstatus::parse( src ); + if( cut != nullptr ) + { + *cut = *cut || tree.cut; // the nesting budget stopped the parse: sites past it were not judged + } const rw::shstatus::Analysis an = rw::shstatus::analyze( tree, src ); const va::Script script( src, tree, an ); return script.sites(); @@ -5842,13 +5846,17 @@ inline void assignedCaseSites( std::string_view src, const sh::Tree& t, const st } // namespace uash // Bash: a case with no *) arm whose result is read, in either form. -inline void scanUnhandledArmBash( std::string_view src, const std::vector& fnSpans, std::vector& out ) +inline void scanUnhandledArmBash( std::string_view src, const std::vector& fnSpans, std::vector& out, bool* cut = nullptr ) { if( src.find( "esac" ) == std::string_view::npos ) { return; } const rw::shstatus::Tree t = rw::shstatus::parse( src ); + if( cut != nullptr ) + { + *cut = *cut || t.cut; + } uash::endingCaseSites( src, t, out ); uash::assignedCaseSites( src, t, fnSpans, out ); } @@ -5945,10 +5953,11 @@ inline std::vector scanPython( std::string_view src, const std::vector scanBashTestScript( std::string_view src, const std::vector& fnSpans ) +// definitions, the scopes a capture and its guards are matched in. `cut` (optional) is set when the shell nesting budget +// (shstatus kMaxShellNest) stopped the parse. +inline std::vector scanBashTestScript( std::string_view src, const std::vector& fnSpans, bool* cut = nullptr ) { - return detail::scanVacuousAssertBash( src, fnSpans ); + return detail::scanVacuousAssertBash( src, fnSpans, cut ); } // Bash, any path: unhandled-arm (a case with no *) arm whose result is read), appended to `out`. diff --git a/src/quality.h b/src/quality.h index 65e3c0f12..53d716e26 100644 --- a/src/quality.h +++ b/src/quality.h @@ -6739,8 +6739,9 @@ inline defectshape::EnumTable cFamilyEnumTable( const IngestResult& ing, std::st // `macroOverride`, when given, is the macro-name set to scan C++ files against instead of this index's own — the whole // tree's, when this index holds only some of its files (a degraded --quality-delta=A..B's changed files). +// `shellCut`, when given, counts the shell files whose scan the nesting budget cut (shstatus kMaxShellNest): the answer's shell_cut=. inline std::vector defectSitesOf( const IngestResult& ing, std::string_view root, const std::vector* fileInBaseline, - const std::vector* macroOverride = nullptr ) + const std::vector* macroOverride = nullptr, std::uint32_t* shellCut = nullptr ) { std::vector out; const SymbolsByFile byFile = symbolsByFileInIdOrder( ing, []( const Symbol& s ) { return s.endByte > s.sigStartByte && s.kind != SymKind::ModuleScope; } ); @@ -6795,11 +6796,16 @@ inline std::vector defectSitesOf( const IngestResult& ing, std::st } else if( scan == DefectScan::Bash ) { + bool cut = false; // the shell nesting budget stopped a parse: the file's sites past it are not judged (shell_cut=) if( isTestScriptPath( rel ) ) // a test script: every assertion form (grep, [ ], cmp, case, rc=$?) is read { - sites = defectshape::scanBashTestScript( src, fnSpans ); + sites = defectshape::scanBashTestScript( src, fnSpans, &cut ); + } + defectshape::scanUnhandledArmBash( src, fnSpans, sites, &cut ); // any path: a case with no *) arm whose result is read + if( cut && shellCut != nullptr ) + { + ++*shellCut; } - defectshape::scanUnhandledArmBash( src, fnSpans, sites ); // any path: a case with no *) arm whose result is read } if( defectshape::looksGenerated( rel, src ) ) // unhandled-arm judges no generated switch: the fix is in the generator { @@ -8261,6 +8267,7 @@ struct DeltaExtras BestSinceSource bestSince; BaseBodySource baseBodies; // QD-SHRINK-PAIR (demoteShrinkOnlyClones): the base commit's bodies of the named files std::vector improved; + std::uint32_t shellCut = 0; // shell files whose defect-shape scan the nesting budget cut (shell_cut=) std::string ratchetRef; // the reference point the ratchet read ("" = not consulted: no candidate, or no source) std::uint32_t ratchetJudged = 0; // symbols judged against their best std::uint32_t ratchetUnread = 0; // history blobs that could not be measured @@ -10947,28 +10954,31 @@ inline std::string tangleRowAttrs( const Regression& r, bool json, Escape&& esc return out; } -// D4 — the ratchet's disclosure on the root: the reference point it read, and what it could not read. "" when it was not consulted. +// D4 — the ratchet's disclosure on the root: the reference point it read, and what it could not read ("" when it was not +// consulted); then CR712-SHSTATUS-DEPTH's shell_cut= (the shell files whose defect-shape scan the nesting budget cut; absent at 0). template inline std::string ratchetAttrsXml( const DeltaExtras& x, Escape&& ex ) { - if( x.ratchetRef.empty() ) + std::string out; + if( !x.ratchetRef.empty() ) { - return {}; + out = " ratchet_ref=\"" + ex( x.ratchetRef ) + "\" ratchet_judged=\"" + std::to_string( x.ratchetJudged ) + "\""; + out += x.ratchetUnread > 0 ? " ratchet_unread=\"" + std::to_string( x.ratchetUnread ) + "\"" : std::string(); + out += x.ratchetCut ? " ratchet_cut=\"1\"" : ""; } - std::string out = " ratchet_ref=\"" + ex( x.ratchetRef ) + "\" ratchet_judged=\"" + std::to_string( x.ratchetJudged ) + "\""; - out += x.ratchetUnread > 0 ? " ratchet_unread=\"" + std::to_string( x.ratchetUnread ) + "\"" : std::string(); - out += x.ratchetCut ? " ratchet_cut=\"1\"" : ""; + out += x.shellCut > 0 ? " shell_cut=\"" + std::to_string( x.shellCut ) + "\"" : std::string(); return out; } inline std::string ratchetAttrsJson( const DeltaExtras& x ) { - if( x.ratchetRef.empty() ) + std::string out; + if( !x.ratchetRef.empty() ) { - return {}; + out = ",\"ratchet_ref\":\"" + rw::jsonesc::escapeMcp( x.ratchetRef ) + "\",\"ratchet_judged\":" + std::to_string( x.ratchetJudged ); + out += x.ratchetUnread > 0 ? ",\"ratchet_unread\":" + std::to_string( x.ratchetUnread ) : std::string(); + out += x.ratchetCut ? ",\"ratchet_cut\":1" : ""; } - std::string out = ",\"ratchet_ref\":\"" + rw::jsonesc::escapeMcp( x.ratchetRef ) + "\",\"ratchet_judged\":" + std::to_string( x.ratchetJudged ); - out += x.ratchetUnread > 0 ? ",\"ratchet_unread\":" + std::to_string( x.ratchetUnread ) : std::string(); - out += x.ratchetCut ? ",\"ratchet_cut\":1" : ""; + out += x.shellCut > 0 ? ",\"shell_cut\":" + std::to_string( x.shellCut ) : std::string(); return out; } @@ -11135,9 +11145,9 @@ inline void appendSimilarArgsRows( std::vector& regs, const SimilarR template inline void appendDefectShapeRows( std::vector& regs, const IngestResult& ing, const Graph& g, const Snapshot& base, std::string_view root, ExistedFn&& existedAtBaseline, StampFn&& stampLoc, - const std::vector* macroOverride = nullptr ) + const std::vector* macroOverride = nullptr, std::uint32_t* shellCut = nullptr ) { - const std::vector nowSites = defectSitesOf( ing, root, nullptr, macroOverride ); + const std::vector nowSites = defectSitesOf( ing, root, nullptr, macroOverride, shellCut ); const auto isRealSite = []( std::uint64_t v ) { return v != kDefectFilePresent && v != kDefectFileUnreadable; }; std::vector baseVals, nowVals, baseUnreadable; for( const DefectSiteKey& d : base.defectSites ) @@ -12622,7 +12632,7 @@ inline std::vector computeDelta( const IngestResult& ing, const Grap if( kindSelected( scope.kinds, "defect-shape" ) ) { - appendDefectShapeRows( regs, ing, g, base, root, existedAtBaseline, stampLoc, scope.macroOverride ); // the twelfth kind (see its doc) + appendDefectShapeRows( regs, ing, g, base, root, existedAtBaseline, stampLoc, scope.macroOverride, extras != nullptr ? &extras->shellCut : nullptr ); // the twelfth kind (see its doc) } if( kindSelected( scope.kinds, "params" ) ) // QD-SWAP-1117 similar=: on by default, report-only (never gating) { diff --git a/src/shstatus.h b/src/shstatus.h index abb20d815..5c3dbd7b4 100644 --- a/src/shstatus.h +++ b/src/shstatus.h @@ -118,6 +118,36 @@ struct Tree std::vector nodes; std::vector lists; std::uint32_t top = kNone; + bool cut = false; // the nesting budget (kMaxShellNest) stopped the scan: what lies past it was not parsed +}; + +// ONE nesting budget for the lexer and the parser (CR712-SHSTATUS-DEPTH): every recursion of either — a quote or $( ) the +// lexer skips through, a compound command or a substitution the parser descends into — takes a level, so a script nested +// past kMaxShellNest is cut there (Tree::cut) instead of exhausting the stack (20,000 nested subshells crashed the scan). +inline constexpr int kMaxShellNest = 64; +struct NestBudget +{ + int depth = 0; + bool cut = false; +}; +// One level of the budget for the scope of a recursion; `over` = the budget is spent (and the cut is recorded). +class NestLevel +{ +public: + explicit NestLevel( NestBudget& b ) noexcept : b_( b ) + { + over_ = b_.depth >= kMaxShellNest; + b_.cut = b_.cut || over_; // the disclosure: Tree::cut, then the answer's shell_cut= (quality.h defectSitesOf) + ++b_.depth; + } + ~NestLevel() { --b_.depth; } + NestLevel( const NestLevel& ) = delete; + NestLevel& operator=( const NestLevel& ) = delete; + bool over() const noexcept { return over_; } + +private: + NestBudget& b_; + bool over_ = false; }; namespace detail @@ -462,9 +492,14 @@ inline bool isRedirOp( std::string_view o ) noexcept return o == "<" || o == ">" || o == ">>" || o == "&>" || o == "&>>" || o == ">&" || o == "<&" || o == "<>" || o == ">|" || o == "<<<" || o == "<<"; } -std::size_t skipParen( std::string_view s, std::size_t i ); -inline std::size_t skipQuote( std::string_view s, std::size_t i, char q ) // s[i] is the opening quote +std::size_t skipParen( std::string_view s, std::size_t i, NestBudget& nb ); +inline std::size_t skipQuote( std::string_view s, std::size_t i, char q, NestBudget& nb ) // s[i] is the opening quote { + const NestLevel level( nb ); + if( level.over() ) + { + return s.size(); // past the budget: the rest is one unscanned word (Tree::cut says so) + } ++i; while( i < s.size() ) { @@ -476,7 +511,7 @@ inline std::size_t skipQuote( std::string_view s, std::size_t i, char q ) // s } if( q == '"' && c == '$' && startsAt( s, i, "$(" ) ) { - i = skipParen( s, i + 1 ); + i = skipParen( s, i + 1, nb ); continue; } if( q == '"' && c == '`' ) @@ -493,8 +528,13 @@ inline std::size_t skipQuote( std::string_view s, std::size_t i, char q ) // s } return i; } -inline std::size_t skipParen( std::string_view s, std::size_t i ) // s[i] == '(' +inline std::size_t skipParen( std::string_view s, std::size_t i, NestBudget& nb ) // s[i] == '(' { + const NestLevel level( nb ); + if( level.over() ) + { + return s.size(); + } int depth = 0; while( i < s.size() ) { @@ -506,7 +546,7 @@ inline std::size_t skipParen( std::string_view s, std::size_t i ) // s[i] == ' } if( c == '\'' || c == '"' ) { - i = skipQuote( s, i, c ); + i = skipQuote( s, i, c, nb ); continue; } if( c == '#' && ( i == 0 || s[i - 1] == ' ' || s[i - 1] == '\t' || s[i - 1] == '\n' || s[i - 1] == ';' || s[i - 1] == '(' ) ) @@ -531,8 +571,13 @@ inline std::size_t skipParen( std::string_view s, std::size_t i ) // s[i] == ' } return i; } -inline std::size_t skipBrace( std::string_view s, std::size_t i ) // s[i] == '{' of a ${...} +inline std::size_t skipBrace( std::string_view s, std::size_t i, NestBudget& nb ) // s[i] == '{' of a ${...} { + const NestLevel level( nb ); + if( level.over() ) + { + return s.size(); + } int depth = 0; while( i < s.size() ) { @@ -544,7 +589,7 @@ inline std::size_t skipBrace( std::string_view s, std::size_t i ) // s[i] == ' } if( c == '\'' || c == '"' ) { - i = skipQuote( s, i, c ); + i = skipQuote( s, i, c, nb ); continue; } if( c == '{' ) @@ -567,7 +612,7 @@ inline std::size_t skipBrace( std::string_view s, std::size_t i ) // s[i] == ' // A double-quoted text with its own single quotes blanked: they are literal there ("don't"), but a quote inside a $( ) // or ` ` it holds is live ("$( grep -o '& out ) +inline void subsIn( std::string_view raw, std::uint32_t line, std::uint32_t base, std::vector& out, NestBudget& nb ) { std::size_t i = 0; while( i < raw.size() ) @@ -613,17 +658,17 @@ inline void subsIn( std::string_view raw, std::uint32_t line, std::uint32_t base } if( c == '\'' ) { - i = skipQuote( raw, i, '\'' ); + i = skipQuote( raw, i, '\'', nb ); continue; } if( startsAt( raw, i, "$((" ) ) { - i = skipParen( raw, i + 1 ); + i = skipParen( raw, i + 1, nb ); continue; } if( startsAt( raw, i, "$(" ) ) { - const std::size_t j = skipParen( raw, i + 1 ); + const std::size_t j = skipParen( raw, i + 1, nb ); out.push_back( { std::string( sliceOf( raw, i + 2, j - 1 ) ), static_cast( line + countNl( raw, 0, i ) ), static_cast( base + i + 2 ), kNone } ); i = j; continue; @@ -639,8 +684,13 @@ inline void subsIn( std::string_view raw, std::uint32_t line, std::uint32_t base if( c == '"' ) { // descend: substitutions inside double quotes are live (single quotes inside them are not quotes) - const std::size_t j = skipQuote( raw, i, '"' ); - subsIn( dqLiteralQuotes( sliceOf( raw, i + 1, j - 1 ) ), static_cast( line + countNl( raw, 0, i ) ), static_cast( base + i + 1 ), out ); + const std::size_t j = skipQuote( raw, i, '"', nb ); + const NestLevel level( nb ); // the descent is a recursion of its own + if( level.over() ) + { + return; + } + subsIn( dqLiteralQuotes( sliceOf( raw, i + 1, j - 1 ), nb ), static_cast( line + countNl( raw, 0, i ) ), static_cast( base + i + 1 ), out, nb ); i = j; continue; } @@ -703,7 +753,7 @@ inline std::size_t heredocDelim( std::string_view s, std::size_t k, std::string& class Lexer { public: - Lexer( std::string_view src, std::uint32_t line0, std::uint32_t base ) : src_( src ), n_( src.size() ), line_( line0 ), base_( base ) {} + Lexer( std::string_view src, std::uint32_t line0, std::uint32_t base, NestBudget& nb ) : src_( src ), n_( src.size() ), line_( line0 ), base_( base ), nb_( nb ) {} std::vector run() { @@ -725,6 +775,7 @@ class Lexer std::size_t i_ = 0; std::uint32_t line_; std::uint32_t base_; + NestBudget& nb_; std::vector> pending_; // heredoc delimiters waiting for the end of this line bool prevBlank_ = true; std::vector toks_; @@ -758,7 +809,7 @@ class Lexer t.word.pos = posAt( b ); if( withSubs ) { - subsIn( t.word.text, line_, t.word.pos, t.word.subs ); + subsIn( t.word.text, line_, t.word.pos, t.word.subs, nb_ ); } t.line = line_; t.pos = t.word.pos; @@ -933,7 +984,7 @@ class Lexer } if( d == '\'' || d == '"' ) { - return skipQuote( src_, i, d ); + return skipQuote( src_, i, d, nb_ ); } if( d == '`' ) { @@ -942,27 +993,26 @@ class Lexer } if( startsAt( src_, i, "$(" ) ) { - return skipParen( src_, i + 1 ); + return skipParen( src_, i + 1, nb_ ); } if( startsAt( src_, i, "${" ) ) { - return skipBrace( src_, i + 1 ); + return skipBrace( src_, i + 1, nb_ ); } if( d == '(' && i > start && src_[i - 1] == '=' ) // array assignment X=( ... ) { - return skipParen( src_, i ); + return skipParen( src_, i, nb_ ); } return i + 1; } }; -inline std::vector lex( std::string_view src, std::uint32_t line0, std::uint32_t base ) +inline std::vector lex( std::string_view src, std::uint32_t line0, std::uint32_t base, NestBudget& nb ) { - return Lexer( src, line0, base ).run(); + return Lexer( src, line0, base, nb ).run(); } // ── parser ────────────────────────────────────────────────────────────────────────────────────────────────────────── -inline constexpr int kMaxSubDepth = 40; // nested $( ) parsed past this depth are left unparsed (an empty list) struct Stops { @@ -976,7 +1026,7 @@ struct Stops class Parser { public: - Parser( Tree& tree, std::vector toks, int depth ) : t_( std::move( toks ) ), tree_( tree ), depth_( depth ) {} + Parser( Tree& tree, std::vector toks, NestBudget& nb ) : t_( std::move( toks ) ), tree_( tree ), nb_( nb ) {} std::uint32_t parseAll() { @@ -1000,7 +1050,7 @@ class Parser std::vector t_; std::size_t i_ = 0; Tree& tree_; - int depth_; + NestBudget& nb_; // shared with the lexer and every nested Parser: one budget for the whole script Tok eof_{}; const Tok& peek() const noexcept @@ -1057,11 +1107,12 @@ class Parser { for( Sub& s : w.subs ) { - if( depth_ >= kMaxSubDepth ) + const NestLevel level( nb_ ); + if( level.over() ) { - continue; + continue; // past the budget: an empty list (Tree::cut says so) } - Parser p( tree_, lex( s.inner, s.line, s.pos ), depth_ + 1 ); + Parser p( tree_, lex( s.inner, s.line, s.pos, nb_ ), nb_ ); s.list = p.parseAll(); } } @@ -1146,6 +1197,12 @@ class Parser } std::uint32_t parseCommand( const Stops& stops ) { + const NestLevel level( nb_ ); // every nested list (subshell, group, if, loop, case, function body) is reached through here + if( level.over() ) + { + i_ = t_.size(); // past the budget: the rest of this token stream is not parsed (Tree::cut says so) + return kNone; + } const Tok& p = peek(); if( p.kind == TokKind::Eof || stopped( stops ) ) { @@ -1453,8 +1510,10 @@ class Parser inline Tree parse( std::string_view src ) { Tree t; - detail::Parser p( t, detail::lex( src, 1, 0 ), 0 ); + NestBudget nb; + detail::Parser p( t, detail::lex( src, 1, 0, nb ), nb ); t.top = p.parseAll(); + t.cut = nb.cut; return t; } diff --git a/src/verbs_quality.h b/src/verbs_quality.h index 94324d807..ccdca0d9d 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -1477,7 +1477,7 @@ inline constexpr const char* kQdLegendCore = "score). THIRTEEN KINDS, and kind= on every row names which one: complexity over the ccx bar, verbosity " "(LOC), nesting, params, duplication, dead-code, api-surface (new public contract drift), " "error-masking, short-horizon-churn, new-clone-of-reused-helper, placeholder (added stub/TODO), " - "defect-shape (defect= names it), tangle (a long function's nesting, deep share and steering locals; a new or crossing one gates). " + "defect-shape (defect= names it), tangle (a long function's nesting, deep share and steering locals; a new, crossing or growing one gates). " "THREE independent axes, in this " "order: (1) acked findings are suppressed entirely (acked= counts them); (2) ORIGIN — a finding on a " "symbol that EXISTED at the baseline is preexisting-worse (no origin attribute), one that exists only " @@ -1495,7 +1495,11 @@ inline constexpr const char* kQdLegendCore = // P3 (L7): next= on gating rows, defined where the reader meets it "A gating row's next= is the one pasteable follow-up: expand on FILE:NAME, the body to fix (a duplication row names a SET and carries none). " // P8 (L7): the threshold beside the number - "bar= on a complexity/verbosity/nesting/params row is the threshold now= is judged against (ccx 15, loc 60, nest 4, params 5). "; + "bar= on a complexity/verbosity/nesting/params row is the threshold now= is judged against (ccx 15, loc 60, nest 4, params 5). " + // CR712-SHSTATUS-DEPTH: present only when not 0 + "shell_cut=N: shell files whose defect-shape scan stopped at nesting depth 64; what lies deeper was not judged. "; + +static_assert( rw::shstatus::kMaxShellNest == 64, "kQdLegendCore's and compactlegend.h's shell_cut= sentences say depth 64" ); // The macro FAMILIES, and why a member of one cannot be judged dead — printed only when the run actually // excluded something, because on a repo with no such macro the roster explains an empty set. diff --git a/test/capdisclose.map b/test/capdisclose.map index 8c1af525a..ff38fd900 100644 --- a/test/capdisclose.map +++ b/test/capdisclose.map @@ -188,6 +188,7 @@ kMaxQualifierHops pending:B43 ingest extraction bound (LARGE-PARTIAL-1 widened t kMaxRefs pending:B43 disclosed elsewhere: refs_omitted= (refsOmittedAttr, which the lint cannot tie to the cap) and a stderr warning (LARGE-PARTIAL-1) kMaxRenameProbeFiles none:a rename hint is never a claim (Stage 0 class d) kMaxRestDepth sink:noteCapped +kMaxShellNest sink:cut kMaxRestName pending:B43 ingest extraction bound (LARGE-PARTIAL-1 widened the lint to ingest*.h); the sibling lane NO-SKIP-INGEST owns the ingest limits and audits it kMaxRestUnits sink:noteCapped kMaxRoleBytes pending:B43 ingest extraction bound (LARGE-PARTIAL-1 widened the lint to ingest*.h); the sibling lane NO-SKIP-INGEST owns the ingest limits and audits it diff --git a/test/lib/capdisclose.py b/test/lib/capdisclose.py index de7204ce5..92bc47c06 100755 --- a/test/lib/capdisclose.py +++ b/test/lib/capdisclose.py @@ -6,7 +6,7 @@ Scope: a constant `constexpr kName = ` defined in an answer-path file (src/for*.h, src/verbs_*.h, src/pathroute.h, src/clones.h; LARGE-PARTIAL-1 added the size and git-sweep caps' files src/crossref.h, -src/ingest*.h, src/search.h, src/binstale.h) that some line of src/ compares as a bound (a CAP SITE, below), or whose +src/ingest*.h, src/search.h, src/binstale.h; CR712-SHSTATUS-DEPTH the shell parser's nesting budget, src/shstatus.h) that some line of src/ compares as a bound (a CAP SITE, below), or whose name says it bounds something (Max, Limit, Cap, Ceiling, Depth, Pairs), or that a `static_assert( kName == N, ... )` ties to legend text. The name alone is not the scope: #613's reader cap was kReaderCallerReaders. A name with `Min` is a threshold (a row needs at least N), not a cut, and is out of scope. A CAP SITE is a line that compares the @@ -47,7 +47,7 @@ def uncommented( text ): def answer_path( root ): out = [] for f in sorted( os.listdir( os.path.join( root, "src" ) ) ): - if ( f.startswith( ( "for", "verbs_", "ingest" ) ) and f.endswith( ".h" ) ) or f in ( "pathroute.h", "clones.h", "crossref.h", "search.h", "binstale.h" ): + if ( f.startswith( ( "for", "verbs_", "ingest" ) ) and f.endswith( ".h" ) ) or f in ( "pathroute.h", "clones.h", "crossref.h", "search.h", "binstale.h", "shstatus.h" ): out.append( "src/" + f ) return out diff --git a/test/regression.sh b/test/regression.sh index 65df4b2c8..001151779 100755 --- a/test/regression.sh +++ b/test/regression.sh @@ -1086,6 +1086,7 @@ for _g in \ shallowhistorycheck \ shapingflagcheck \ shellgateindexcheck \ + shellnestcheck \ showcasecapturecheck \ shrinkpaircheck \ sibliftcheck \ diff --git a/test/shellnestcheck.sh b/test/shellnestcheck.sh new file mode 100755 index 000000000..5925fca2f --- /dev/null +++ b/test/shellnestcheck.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# shellnestcheck.sh — CR712-SHSTATUS-DEPTH: the shell parser's ONE nesting budget (src/shstatus.h kMaxShellNest), shared by the +# lexer's quote / $( ) / ${ } skips and the parser's compound commands and substitutions, cuts a deeply nested script instead +# of exhausting the stack, and --quality-delta says so (shell_cut= on the root, XML and --json). +# +# The scripts are GENERATED here, never committed (PRODUCER_COMMON 12: a committed fixture that trips a cap would put a +# disclosure into every whole-repo run). Each is a new test script under test/ in a one-commit repo, so the defect-shape +# scan (vacuous-assert and unhandled-arm, both through shstatus::parse) reads it. +# (p1)-(p5) DEEP: 5,000 levels of one shape each — nested subshells, brace groups, if-then, "$( … "$( … )" … )" quotes and +# bare $( ) substitutions: the run exits 0 or 2 (no signal), within 60 s, and the root carries shell_cut="1". +# Red before the lane (main 8861b0d4d): subshell, group and if die on SIGSEGV (rc 139); quote and subst exit 0 with no +# disclosure (the old 40-level substitution cap cut them silently). At 20,000 levels ingest itself takes 60-70 s +# (tree-sitter on the file, outside this card), so the gate stays at 5,000. +# (j) --json on the subshell script: "shell_cut":1. +# (n1) UNDER THE BUDGET: a function ending in a case with no *) arm (unhandled-arm), 40 subshells deep: the unhandled-arm row is still found +# and there is no shell_cut= (the budget cut nothing real). Red on a build with a budget under 40. +# (n2) SHALLOW: the same file at depth 1: no shell_cut= (premise for n1: the row exists without nesting too). +# Usage: test/shellnestcheck.sh [BIN] +set -u +ROOT="$( cd "$( dirname "$0" )/.." && pwd )" +. "$ROOT/test/lib/clean-env.sh" +BIN="${1:-${RIPWIRE_BIN:-$ROOT/build/ripwire}}" +[ "${BIN#/}" = "$BIN" ] && BIN="$ROOT/$BIN" +[ -x "$BIN" ] || { echo "no ripwire binary at $BIN — build first"; exit 2; } +TMP="$( mktemp -d )"; trap 'rm -rf "$TMP"' EXIT +export TMPDIR="$TMP/cache"; mkdir -p "$TMPDIR" +export HOME="$TMP/home"; mkdir -p "$HOME" +fail=0 +ok(){ printf ' PASS %s\n' "$*" || { fail=1; printf ' FAIL could not write the PASS line for: %s\n' "$*"; }; return 0; } +no(){ printf ' FAIL %s\n' "$*"; fail=1; } +echo "shellnestcheck: BIN=$BIN" +G=( git -c user.name=t -c user.email=t@t -c commit.gpgsign=false ) + +# gen KIND N OUT — one script nested N levels in one shape (python: no shell recursion of our own) +gen(){ python3 - "$1" "$2" "$3" <<'PY' +import sys +kind, n, out = sys.argv[1], int(sys.argv[2]), sys.argv[3] +case = 'kindof() { case "$1" in a) echo x ;; b) echo y ;; esac; }; kindof a' +body = { + "subshell": "( " * n + "false" + " )" * n, + "group": "{ " * n + "false; " + "}; " * n, + "if": "if true; then " * n + "false" + "; fi" * n, + "quote": 'x="' + '$( echo "' * n + "y" + '" )' * n + '"', + "subst": "x=" + "$( echo " * n + "y" + " )" * n, + "case": "( " * n + case + " )" * n, +}[kind] +with open(out, "w") as f: + f.write("#!/usr/bin/env bash\nset -u\n" + body + "\n") +PY +} +# repo KIND N — a one-commit repo whose working tree adds test/deep_check.sh; prints its path +repo(){ local R="$TMP/r-$1-$2"; mkdir -p "$R/test"; "${G[@]}" -C "$R" init -q; echo 'echo hi' >"$R/test/a.sh" + "${G[@]}" -C "$R" add -A && "${G[@]}" -C "$R" commit -qm a; gen "$1" "$2" "$R/test/deep_check.sh"; printf '%s' "$R"; } +cutof(){ grep -oE ']*' "$1" | grep -oE ' shell_cut="[0-9]+"' | grep -oE '[0-9]+'; } + +for k in subshell group if quote subst; do + R="$( repo "$k" 5000 )"; s=$( date +%s ) + "$BIN" "$R" --quality-delta --no-cache >"$TMP/$k.xml" 2>"$TMP/$k.err"; rc=$?; t=$(( $( date +%s ) - s )) + c="$( cutof "$TMP/$k.xml" )" + if { [ "$rc" = 0 ] || [ "$rc" = 2 ]; } && [ "$t" -le 60 ] && [ "${c:-0}" = 1 ]; then ok "($k) 5000 deep: rc=$rc in ${t}s, shell_cut=\"$c\"" + else no "($k) 5000 deep: want rc 0/2 within 60 s and shell_cut=\"1\"; got rc=$rc in ${t}s, shell_cut='${c:-none}' ($( tail -c 160 "$TMP/$k.err" | tr '\n' ' ' ))"; fi +done +R="$TMP/r-subshell-5000" +j="$( "$BIN" "$R" --quality-delta --json --no-cache 2>/dev/null | python3 -c 'import json,sys; print(json.load(sys.stdin).get("shell_cut","absent"))' 2>/dev/null || echo unparseable )" +if [ "$j" = 1 ]; then ok "(j) --json: \"shell_cut\":1"; else no "(j) --json: want \"shell_cut\":1, got '$j'"; fi + +for n in 40 1; do + R="$( repo case "$n" )" + "$BIN" "$R" --quality-delta --no-cache >"$TMP/case$n.xml" 2>/dev/null + row="$( grep -oE ']*defect="unhandled-arm"[^>]*>' "$TMP/case$n.xml" | grep 'deep_check.sh' | head -1 )" + c="$( cutof "$TMP/case$n.xml" )" + label=n1; [ "$n" = 1 ] && label=n2 + if [ -n "$row" ] && [ -z "$c" ]; then ok "($label) case $n deep: the unhandled-arm row is found, no shell_cut=: $row" + else no "($label) case $n deep: want an unhandled-arm row in deep_check.sh and no shell_cut=; got row='${row:-none}' shell_cut='${c:-none}'"; fi +done + +[ "$fail" = 0 ] && echo "shellnestcheck: PASS" || echo "shellnestcheck: FAIL" +exit "$fail" From 8a5ae873adae654e2d023061a37eeacbff41f999 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:51:58 -0500 Subject: [PATCH 07/61] qd: re-file two-bit-era defect-shape acks to the three-bit key (CR712-ACK-KEY-MASK) QD-UNCHECKED-STATUS widened the defect site value's facet bits from two to three, which moved every site whose hash had bit 2 set and with it the defectRowKey of its row: about half of the format-arity acks written by v0.6.9/v0.6.10 stopped matching, so the acked row gated again and the ack was listed stale. Each defect site now also carries its two-bit value (defectLegacySiteValue); addDefectFacetSchemeAliases maps every (anchor, facet) row's two-bit key to its current key through the existing SCHEME alias path, only when the ledger holds a defect-shape ack. A legacy ack is suppressed, counted in acks_rekeyed_by_scheme=, and healed forward by the next --quality-ack; an ack written under the current scheme matches directly as before. Gate: test/defectackschemecheck.sh (legacy key recorded from v0.6.9; red on main 8861b0d4d: rc 2, stale=1, the row gates). Co-Authored-By: Claude Opus 5.5 --- src/quality.h | 73 ++++++++++++++++++++++++++++++- src/verbs_quality.h | 5 ++- test/defectackschemecheck.sh | 83 ++++++++++++++++++++++++++++++++++++ test/regression.sh | 1 + 4 files changed, 160 insertions(+), 2 deletions(-) create mode 100755 test/defectackschemecheck.sh diff --git a/src/quality.h b/src/quality.h index 53d716e26..abbf36ec7 100644 --- a/src/quality.h +++ b/src/quality.h @@ -1385,6 +1385,29 @@ inline std::uint64_t defectSiteValue( defectshape::Facet f, std::string_view tex return v; } +// CR712-ACK-KEY-MASK — the site value as the two-bit facet scheme spelled it (v0.6.10 and before: four facets, `& ~3`). +// QD-UNCHECKED-STATUS widened the facet bits to three, which moved every site value whose hash had bit 2 set, and with it the +// defectRowKey of every row holding such a site: a released ack of a format-arity row stopped matching and the row gated +// again. addDefectFacetSchemeAliases re-files such an ack to the current key; this is the old value it needs. A facet the +// two-bit scheme never had (unchecked-status, unhandled-arm) has none (0). +inline std::uint64_t defectLegacySiteValue( defectshape::Facet f, std::string_view text ) +{ + constexpr std::uint64_t kLegacyMask = 3; + if( static_cast( f ) > kLegacyMask ) + { + return 0; + } + std::string id( defectshape::facetName( f ) ); + id.push_back( '\0' ); + id.append( text ); + std::uint64_t h = fnv1a64( id ) & ~kLegacyMask; + if( h == 0 ) + { + h = kLegacyMask + 1; + } + return h | static_cast( f ); +} + // A defect-shape ROW's identity — the ack key: the anchor, the facet AND the identities of the anchor's sites of // that facet (each a defectSiteValue: facet + normalized offending text), so an ack covers exactly the defects it // named (checklist 16). A format-arity ack and a utf8-cut ack on one definition are two acks; and an ack of @@ -1439,6 +1462,7 @@ struct DefectSiteAt std::uint32_t line = 0; std::string_view call; // unchecked-status: the call whose status is dropped (defectshape's static spelling) std::string why; // unhandled-arm: what the classifier leaves without an outcome (defectshape's Site::why) + std::uint64_t legacySite = 0; // CR712-ACK-KEY-MASK: the site's value in the two-bit scheme (defectLegacySiteValue), 0 = none }; @@ -6817,7 +6841,7 @@ inline std::vector defectSitesOf( const IngestResult& ing, std::st const NodeId owner = enclosingDefOf( ing, byFile, f, st.startByte ); const std::uint64_t anchor = owner == kNoNode ? fileAnchor : qualityKey( ing, owner, root ); const std::uint32_t line = static_cast( 1 + std::count( src.begin(), src.begin() + st.startByte, '\n' ) ); - out.push_back( { { anchor, defectSiteValue( st.facet, st.text ) }, owner, f, line, st.call, st.why } ); + out.push_back( { { anchor, defectSiteValue( st.facet, st.text ) }, owner, f, line, st.call, st.why, defectLegacySiteValue( st.facet, st.text ) } ); } } std::stable_sort( out.begin(), out.end(), []( const DefectSiteAt& a, const DefectSiteAt& b ) { return a.key < b.key; } ); @@ -9751,6 +9775,52 @@ inline void addSchemeAliases( IdentityAliases& al, const IngestResult& ing, cons std::sort( al.schemeAmbiguousKeys.begin(), al.schemeAmbiguousKeys.end() ); } +// CR712-ACK-KEY-MASK — the defect-shape half of the SCHEME migration: for every current (anchor, facet) row whose key under the +// two-bit site values (defectLegacySiteValue) differs from its key now, legacy key -> current key, fed into the same toCurrent +// map addSchemeAliases fills, so remapAckIdentity re-files a released ack (acks_rekeyed_by_scheme=), computeStaleAcks reads it at +// its current key, and --quality-ack writes it back healed. It scans the tree's defect sites once, and only when the ledger +// holds a defect-shape ack. Add, never overwrite (a rename alias keeps precedence). +inline void addDefectFacetSchemeAliases( IdentityAliases& al, const gtl::btree_map& acks, const IngestResult& ing, + std::string_view root ) +{ + if( std::none_of( acks.begin(), acks.end(), []( const auto& kv ) { return kv.second.kind.starts_with( "defect-shape" ); } ) ) + { + return; + } + const std::vector sites = defectSitesOf( ing, root, nullptr ); // sorted by (anchor, site) + for( auto it = sites.begin(); it != sites.end(); ) + { + const auto end = std::find_if( it, sites.end(), [ & ]( const DefectSiteAt& d ) { return d.key.anchor != it->key.anchor; } ); + for( std::size_t f = 0; f < defectshape::kFacetCount; ++f ) + { + std::vector now, old; + for( auto d = it; d != end; ++d ) + { + if( d->legacySite != 0 && d->key.site != kDefectFilePresent && d->key.site != kDefectFileUnreadable + && defectFacetOf( d->key.site ) == static_cast( f ) ) + { + now.push_back( d->key.site ); + old.push_back( d->legacySite ); + } + } + if( now.empty() ) + { + continue; + } + std::sort( now.begin(), now.end() ); + std::sort( old.begin(), old.end() ); + const auto facet = static_cast( f ); + const std::uint64_t oldKey = defectRowKey( it->key.anchor, facet, old ), newKey = defectRowKey( it->key.anchor, facet, now ); + if( oldKey != newKey && al.toCurrent.emplace( oldKey, newKey ).second ) + { + al.schemeKeys.push_back( oldKey ); + } + } + it = end; + } + std::sort( al.schemeKeys.begin(), al.schemeKeys.end() ); +} + // The two transient rename facts the delta reads (Snapshot::renamedFrom, Snapshot::renamedKeys), from the RENAME aliases only and // BEFORE remapSnapshotIdentity: a key counts as re-filed only when the alias fills a hole (its source is in the baseline and its // target is not), so a file renamed long before the baseline (the ledger's 400-commit window) marks nothing. @@ -10307,6 +10377,7 @@ inline IdentityHealing healIdentity( Snapshot& base, gtl::btree_map\n#include \nint drive() { return 1; }\n' >"$1/src/a.cpp" + "${G[@]}" -C "$1" add -A && "${G[@]}" -C "$1" commit -qm a + printf '#include \n#include \nstd::string label1( int a )\n{\n return std::format( "{} 1", a, a );\n}\nint drive() { return 1; }\n' >"$1/src/a.cpp"; } +ackkey(){ grep -E '^ack defect-shape ' "$1/$LEDGER" | awk '{ print $3 }' | tr '\n' ' ' | sed 's/ $//'; } +root(){ grep -oE ']*' "$1"; } +attr(){ root "$2" | grep -oE " $1=\"[0-9]+\"" | grep -oE '[0-9]+'; } +ack(){ ( cd "$1" && "$BIN" . --quality-delta --no-cache --ack-only=format-arity --quality-ack="$2" >/dev/null 2>&1 ); } +run(){ ( cd "$1" && "$BIN" . --quality-delta --no-cache >"$2" 2>/dev/null ); } + +# (p) the binary's own key for this row +fixture "$TMP/cur"; ack "$TMP/cur" "current ack" +CUR="$( ackkey "$TMP/cur" )" +if [ -n "$CUR" ] && [ "$CUR" != "$LEGACY_KEY" ]; then ok "(p) the row's current key $CUR differs from its two-bit key $LEGACY_KEY" +else no "(p) want one current key different from $LEGACY_KEY; got '${CUR:-none}' — the fixture no longer exercises a moved site"; fi + +# (l) the legacy ledger row, verbatim as v0.6.9 wrote it +fixture "$TMP/leg" +printf 'ack defect-shape %s 1 now=1 was=0 facet=format-arity p=src/a.cpp:3 legacy ack\n' "$LEGACY_KEY" >"$TMP/leg/$LEDGER" +run "$TMP/leg" "$TMP/leg.xml"; rc=$? +a="$( attr acked "$TMP/leg.xml" )"; s="$( attr stale "$TMP/leg.xml" )"; g="$( attr gating "$TMP/leg.xml" )"; k="$( attr acks_rekeyed_by_scheme "$TMP/leg.xml" )" +if [ "$rc" = 0 ] && [ "$a" = 1 ] && [ "$s" = 0 ] && [ "$g" = 0 ] && [ "$k" = 1 ]; then ok "(l) the two-bit ack suppresses its row: rc=0 acked=1 stale=0 gating=0 acks_rekeyed_by_scheme=1" +else no "(l) want rc=0 acked=1 stale=0 gating=0 acks_rekeyed_by_scheme=1; got rc=$rc acked=${a:-?} stale=${s:-?} gating=${g:-?} acks_rekeyed_by_scheme=${k:-absent}"; fi + +# (c) the binary's own ack +run "$TMP/cur" "$TMP/cur.xml"; rc=$? +a="$( attr acked "$TMP/cur.xml" )"; k="$( attr acks_rekeyed_by_scheme "$TMP/cur.xml" )" +if [ "$rc" = 0 ] && [ "$a" = 1 ] && [ -z "$k" ]; then ok "(c) the current-key ack matches directly: rc=0 acked=1, no acks_rekeyed_by_scheme=" +else no "(c) want rc=0 acked=1 and no acks_rekeyed_by_scheme=; got rc=$rc acked=${a:-?} acks_rekeyed_by_scheme=${k:-absent}"; fi + +# (h) re-ack heals the legacy row forward +ack "$TMP/leg" "re-ack" +HK="$( ackkey "$TMP/leg" )"; reason="$( grep -cE '^ack defect-shape .* legacy ack$' "$TMP/leg/$LEDGER" )" +run "$TMP/leg" "$TMP/heal.xml"; rc=$?; k="$( attr acks_rekeyed_by_scheme "$TMP/heal.xml" )" +if [ "$HK" = "$CUR" ] && [ "$reason" = 1 ] && [ "$rc" = 0 ] && [ -z "$k" ]; then ok "(h) --quality-ack re-filed the row at $HK with its reason; the next run needs no alias" +else no "(h) want the ledger at $CUR with the legacy reason and a later run without acks_rekeyed_by_scheme=; got key='${HK:-none}' reason-rows=$reason rc=$rc acks_rekeyed_by_scheme=${k:-absent}"; fi + +# (r) optional: re-derive the recorded key with a two-bit binary +if [ -n "${RIPWIRE_LEGACY_BIN:-}" ]; then + fixture "$TMP/rec"; ( cd "$TMP/rec" && "$RIPWIRE_LEGACY_BIN" . --quality-delta --no-cache --ack-only=format-arity --quality-ack="legacy ack" >/dev/null 2>&1 ) + RK="$( ackkey "$TMP/rec" )" + if [ "$RK" = "$LEGACY_KEY" ]; then ok "(r) $RIPWIRE_LEGACY_BIN writes the recorded two-bit key $RK"; else no "(r) $RIPWIRE_LEGACY_BIN wrote '${RK:-none}', the recorded key is $LEGACY_KEY"; fi +fi + +[ "$fail" = 0 ] && echo "defectackschemecheck: PASS" || echo "defectackschemecheck: FAIL" +exit "$fail" diff --git a/test/regression.sh b/test/regression.sh index 001151779..088591b57 100755 --- a/test/regression.sh +++ b/test/regression.sh @@ -1087,6 +1087,7 @@ for _g in \ shapingflagcheck \ shellgateindexcheck \ shellnestcheck \ + defectackschemecheck \ showcasecapturecheck \ shrinkpaircheck \ sibliftcheck \ From 2d08a8d6d1e906060396ef22d4edf8f2bcf7bb8b Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:00:07 -0500 Subject: [PATCH 08/61] =?UTF-8?q?docs:=20tangle=20gates,=20shell=5Fcut,=20?= =?UTF-8?q?two-bit=20ack=20re-filing=20=E2=80=94=20README,=20EVALS,=20skil?= =?UTF-8?q?l,=20COMMANDS,=20changelog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The exception rule now names its third case everywhere it is stated: new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling and a tangled new function. defectshapecheck's surfaces arm requires it. EVALS records the 20-merge replay (main 0 gating / lane 9 over 5 PRs; the four non-growth tag-best rows print nothing). Three changelog fragments. Co-Authored-By: Claude Opus 5.5 --- README.md | 7 ++++--- changelog.d/defect-ack-two-bit.md | 3 +++ changelog.d/shell-nest-budget.md | 3 +++ changelog.d/tangle-gates.md | 3 +++ docs/COMMANDS.md | 4 ++-- docs/EVALS.md | 16 +++++++++++++--- skills/ripwire-quality-bar/SKILL.md | 4 ++-- skills/ripwire-quality-bar/drill-down.md | 2 +- test/defectshapecheck.sh | 7 ++++--- 9 files changed, 35 insertions(+), 14 deletions(-) create mode 100644 changelog.d/defect-ack-two-bit.md create mode 100644 changelog.d/shell-nest-budget.md create mode 100644 changelog.d/tangle-gates.md diff --git a/README.md b/README.md index 0060c66ac..31f8a67b9 100644 --- a/README.md +++ b/README.md @@ -965,10 +965,11 @@ AI-authored commits, a function rewritten again inside two weeks **+15%** more l `--quality-delta`'s 13 kinds each target one measured mode like those (the eleventh, `placeholder`, lists the stubs and TODOs a change adds, and never gates; the twelfth, `defect-shape`, catches four defect shapes review kept finding by hand — -new-symbol rows never gate, except defect-shape format-arity and a new function at the ceiling, +new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling and a tangled new function, because a format/argument mismatch is a defect, not debt, and a new function at 4x the bar — ccx 60 or 240 lines — -is how a 1,000-line function starts; the thirteenth, `tangle`, is report-only: a long function's nesting, deep share and -steering locals, with length only amplifying them, so a long orchestrator of named steps stays quiet), and it reports **only what your +is how a 1,000-line function starts; the thirteenth, `tangle`, scores a long function's nesting, deep share and +steering locals, with length only amplifying them, so a long orchestrator of named steps stays quiet, and gates a function +that is new at tangle 6 or more, crossed 6, or grew while over it), and it reports **only what your change made worse** — then `--exemplar` shows the pattern in your own repo to copy, and `--test-gate` names the tests that must run before "done." diff --git a/changelog.d/defect-ack-two-bit.md b/changelog.d/defect-ack-two-bit.md new file mode 100644 index 000000000..f7bf74d67 --- /dev/null +++ b/changelog.d/defect-ack-two-bit.md @@ -0,0 +1,3 @@ +### Fixed — format-arity acks written by 0.6.10 and earlier match again + +The unchecked-status facet widened the facet bits of a defect-shape site value from two to three, which changed the ack key of every row holding a site whose hash had bit 2 set (about half of all one-site rows; 4 of 8 in a fixture sample): an ack written by 0.6.10 or earlier stopped matching, the row gated again and the ack was listed stale. Such an ack is now re-filed to its current key on read (counted in `acks_rekeyed_by_scheme=`) and written back healed by the next `--quality-ack`. Only rows whose key moved are affected; acks written since are unchanged. New gate `test/defectackschemecheck.sh`, its legacy key recorded from the released 0.6.9 binary. diff --git a/changelog.d/shell-nest-budget.md b/changelog.d/shell-nest-budget.md new file mode 100644 index 000000000..7adaec24a --- /dev/null +++ b/changelog.d/shell-nest-budget.md @@ -0,0 +1,3 @@ +### Fixed — a deeply nested shell script no longer crashes `--quality-delta` + +The shell lexer and parser behind the Bash defect-shape facets recursed without a bound on subshells, brace groups, `if` and quote/substitution nesting; a test script 5,000 levels deep ended the run on SIGSEGV. One nesting budget (64 levels) now covers the lexer and the parser; a script that reaches it is cut there, and the run says so with `shell_cut=N` on the `` root (and `"shell_cut"` in `--json`): N shell files whose scan stopped, what lies deeper was not judged. The old silent 40-level substitution cap is gone. New gate `test/shellnestcheck.sh` (generated scripts, never committed). diff --git a/changelog.d/tangle-gates.md b/changelog.d/tangle-gates.md new file mode 100644 index 000000000..fce77ca4d --- /dev/null +++ b/changelog.d/tangle-gates.md @@ -0,0 +1,3 @@ +### Changed — `--quality-delta`'s tangle kind gates a new, crossing or growing tangle + +`tangle` was report-only. A row now gates (exit 2) when the function is new at tangle 6.0 or more, crossed 6.0, or its score grew against the range base while over 6.0; a moved body and test code never gate, and a row an input rose on while the score held stays `sev="minor"`. The best-since-tag ratchet is now a facet (`ratchet=`) on those rows, not a row of its own, so a function that only sits above its tag best no longer prints. Replayed on the 20 merges before 8861b0d4d (tangle kind, range form): main gated 0 rows; this gates 9 over 5 PRs, every one a function that crossed or grew in its own PR (#702 `runLsp` 2.1→11.0, eight growth rows of a tenth or more), and the four rows on functions that did not grow in their PR print nothing. What it does not mean: a function already over 6.0 that the change leaves no worse never gates. Method and table: `docs/EVALS.md`, the thirteen kinds. diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index d808ecf32..985d02fec 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -2980,7 +2980,7 @@ $ ./build/ripwire . --quality-delta --show-stale **Answers:** before a PR: report ONLY what your change made worse, across 13 kinds — pair with --test-gate. -Each kind is measured against the baseline (complexity/verbosity/nesting/params/dup/dead/api-surface + error-masking/short-horizon-churn/new-clone-of-reused-helper + placeholder + defect-shape + tangle, report-only); every finding is classified by ORIGIN: a symbol that EXISTED at the baseline and got worse (preexisting-worse="N", no attribute on the row) vs one that exists only because the code is NEW (new-symbol="N", origin="new-symbol" on the row). A small numeric delta is additionally sev="minor". EXIT 2 ONLY on a major AND unacked row that is preexisting-worse, defect-shape format-arity (any origin) or a new function at the ceiling — the gating="N" header count. New-symbol rows are still PRINTED (they are the debt you are adding — read them); new-symbol rows never gate, except defect-shape format-arity and a new function at the ceiling (4x the bar: ccx 60 or 240 lines, not a moved body, not test code, ceiling= on the row); exit 0 means "nothing that already existed got worse", not "clean". Clone kinds classify by member set (new-symbol only if EVERY member is new); short-horizon-churn is preexisting by construction. LIMIT: origin is canonId (path::scope::name) identity; a function RENAMED or MOVED with its body unchanged (whitespace and its own name aside: one body that left its key, matched to one new key) keeps its identity and the move reports nothing (and a file rename git recorded keeps each symbol in it under its own name, twins and changed bodies included), while one whose body also changed reads as new and a regression carried in with it will not gate; a function over the ccx or line bar whose body moved with a small edit (a clone-sketch match to a body that left its key) reads origin="moved" and never gates. error-masking = a NEW empty/pass/comment-only handler, or log-only (a broad handler whose body only logs and never names the error) or rethrow-only (the sole handler re-throws it unchanged); those two gate only where their precision was measured (Python) and are sev="minor" in every other language. Empty counts Go's `if err != nil {}` on a call's err and Rust's `if let Err(..) = f() {}` / `Err(..) => {}` or `=> ()`, and gates like Python's `except: pass`; log-only counts a Rust Err arm of print/log macros and a C++ catch of `std::cerr <<`, `LOG( x ) <<` or `fprintf( stderr, … )` (sev="minor"). facet="failure-default": a read, parse or spawn failure returned as an empty success (a TypeScript catch or .catch returning []/null/{}/false/0/'' around JSON.parse/fs reads/exec/spawn/fetch, in a function typed to return an array/boolean/object; a C++ value_or( empty ) on a file read); it never gates by itself. placeholder = a stub the change ADDED (todo!()/unimplemented!(), Kotlin TODO(), NotImplementedException, a bare raise NotImplementedError as a free function's body, a throw/raise/panic/assert saying "not implemented") or a comment line opening with TODO/FIXME that names no issue (#12, ABC-12, a URL); new-symbol by construction, so it never gates. Counted per enclosing symbol, like error-masking: a file-level TODO outside every definition is not counted. defect-shape = a known defect shape the change ADDED, named by defect=: format-arity (a literal std::format/print/format_to, fmt::, rw::emitTo/formatTo or Python "literal".format whose fields do not match its arguments — GATES on any origin, a defect not debt), utf8-cut and dedup-first (C++) and vacuous-assert (Bash test scripts) and unchecked-status (a dropped pclose/rename/write/system/fflush/close/waitpid status in C/C++; Python subprocess.run without check=, subprocess.call, os.system; the row carries call=) and unhandled-arm (a C/C++ switch with no default: that leaves an in-tree enum's enumerator out, a shell case with no *) arm whose result is read, a Python if/elif or match ending a value-returning function with no else; the row carries why=) — report-only, always sev="minor". A site is new only when its text occurs more often than in the baseline: a moved one is not. Test-fixture dirs + doc sections are exempt from dead-code/churn; churn needs COMMITTED thrash evidence (rewritten across recent commits AND again by this diff), never the current edit alone WHICH FLOOR IT COMPARES AGAINST, and a side effect: the sidecar is honored only when the sha it was pinned at EQUALS the current git HEAD (strict equality — an ancestor commit describes a DIFFERENT tree, so everything committed since would read as your regression). A sidecar pinned anywhere else is STALE: this verb then DELETES it from your working tree (self-heal, so the next run does not rediscover the dead pin) and auto-compares the working tree vs git HEAD instead. Re-pin with --quality-baseline. The read-only MCP quality_delta verb applies the SAME staleness test but never deletes. A sidecar at the current HEAD that ANOTHER ripwire build pinned (its producer stamp names other sources — a dead set depends on how calls were resolved) is FOREIGN: both arms ignore it, never delete it, and auto-compare vs git HEAD. Which floor was actually used is on every report as baseline=: sidecar | git-HEAD | git-HEAD (stale sidecar removed) | git-HEAD (stale sidecar ignored) | git-HEAD (foreign sidecar ignored) — the stale two say a stale sidecar existed, and 'removed' means the file is gone. A non-git root has no HEAD to fall back to, so its sidecar is honored whenever this build pinned it; without one there, or with another build's, the verb exits 1. +Each kind is measured against the baseline (complexity/verbosity/nesting/params/dup/dead/api-surface + error-masking/short-horizon-churn/new-clone-of-reused-helper + placeholder + defect-shape + tangle); every finding is classified by ORIGIN: a symbol that EXISTED at the baseline and got worse (preexisting-worse="N", no attribute on the row) vs one that exists only because the code is NEW (new-symbol="N", origin="new-symbol" on the row). A small numeric delta is additionally sev="minor". EXIT 2 ONLY on a major AND unacked row that is preexisting-worse, defect-shape format-arity (any origin), a new function at the ceiling or a tangled new one — the gating="N" header count. New-symbol rows are still PRINTED (they are the debt you are adding — read them); new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling (4x the bar: ccx 60 or 240 lines, not a moved body, not test code, ceiling= on the row) and a new one at tangle 6 or more (not moved, not test code); exit 0 means "nothing that already existed got worse", not "clean". Clone kinds classify by member set (new-symbol only if EVERY member is new); short-horizon-churn is preexisting by construction. LIMIT: origin is canonId (path::scope::name) identity; a function RENAMED or MOVED with its body unchanged (whitespace and its own name aside: one body that left its key, matched to one new key) keeps its identity and the move reports nothing (and a file rename git recorded keeps each symbol in it under its own name, twins and changed bodies included), while one whose body also changed reads as new and a regression carried in with it will not gate; a function over the ccx or line bar whose body moved with a small edit (a clone-sketch match to a body that left its key) reads origin="moved" and never gates. error-masking = a NEW empty/pass/comment-only handler, or log-only (a broad handler whose body only logs and never names the error) or rethrow-only (the sole handler re-throws it unchanged); those two gate only where their precision was measured (Python) and are sev="minor" in every other language. Empty counts Go's `if err != nil {}` on a call's err and Rust's `if let Err(..) = f() {}` / `Err(..) => {}` or `=> ()`, and gates like Python's `except: pass`; log-only counts a Rust Err arm of print/log macros and a C++ catch of `std::cerr <<`, `LOG( x ) <<` or `fprintf( stderr, … )` (sev="minor"). facet="failure-default": a read, parse or spawn failure returned as an empty success (a TypeScript catch or .catch returning []/null/{}/false/0/'' around JSON.parse/fs reads/exec/spawn/fetch, in a function typed to return an array/boolean/object; a C++ value_or( empty ) on a file read); it never gates by itself. placeholder = a stub the change ADDED (todo!()/unimplemented!(), Kotlin TODO(), NotImplementedException, a bare raise NotImplementedError as a free function's body, a throw/raise/panic/assert saying "not implemented") or a comment line opening with TODO/FIXME that names no issue (#12, ABC-12, a URL); new-symbol by construction, so it never gates. Counted per enclosing symbol, like error-masking: a file-level TODO outside every definition is not counted. defect-shape = a known defect shape the change ADDED, named by defect=: format-arity (a literal std::format/print/format_to, fmt::, rw::emitTo/formatTo or Python "literal".format whose fields do not match its arguments — GATES on any origin, a defect not debt), utf8-cut and dedup-first (C++) and vacuous-assert (Bash test scripts) and unchecked-status (a dropped pclose/rename/write/system/fflush/close/waitpid status in C/C++; Python subprocess.run without check=, subprocess.call, os.system; the row carries call=) and unhandled-arm (a C/C++ switch with no default: that leaves an in-tree enum's enumerator out, a shell case with no *) arm whose result is read, a Python if/elif or match ending a value-returning function with no else; the row carries why=) — report-only, always sev="minor". A site is new only when its text occurs more often than in the baseline: a moved one is not. Test-fixture dirs + doc sections are exempt from dead-code/churn; churn needs COMMITTED thrash evidence (rewritten across recent commits AND again by this diff), never the current edit alone WHICH FLOOR IT COMPARES AGAINST, and a side effect: the sidecar is honored only when the sha it was pinned at EQUALS the current git HEAD (strict equality — an ancestor commit describes a DIFFERENT tree, so everything committed since would read as your regression). A sidecar pinned anywhere else is STALE: this verb then DELETES it from your working tree (self-heal, so the next run does not rediscover the dead pin) and auto-compares the working tree vs git HEAD instead. Re-pin with --quality-baseline. The read-only MCP quality_delta verb applies the SAME staleness test but never deletes. A sidecar at the current HEAD that ANOTHER ripwire build pinned (its producer stamp names other sources — a dead set depends on how calls were resolved) is FOREIGN: both arms ignore it, never delete it, and auto-compare vs git HEAD. Which floor was actually used is on every report as baseline=: sidecar | git-HEAD | git-HEAD (stale sidecar removed) | git-HEAD (stale sidecar ignored) | git-HEAD (foreign sidecar ignored) — the stale two say a stale sidecar existed, and 'removed' means the file is gone. A non-git root has no HEAD to fall back to, so its sidecar is honored whenever this build pinned it; without one there, or with another build's, the verb exits 1. **Try it** @@ -2997,7 +2997,7 @@ $ ./build/ripwire . --quality-delta **Caveats (stated by the binary):** -- new-symbol rows never gate, except defect-shape format-arity and a new function at the ceiling (4x the bar: ccx 60 or 240 lines, not a moved body, not test code, ceiling= on the row); +- new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling (4x the bar: ccx 60 or 240 lines, not a moved body, not test code, ceiling= on the row) and a new one at tangle 6 or more (not moved, not test code); - LIMIT: origin is canonId (path::scope::name) identity; - a function over the ccx or line bar whose body moved with a small edit (a clone-sketch match to a body that left its key) reads origin="moved" and never gates. diff --git a/docs/EVALS.md b/docs/EVALS.md index 44531a187..f35e8e997 100644 --- a/docs/EVALS.md +++ b/docs/EVALS.md @@ -6282,14 +6282,24 @@ These are the exact `kind=` strings the binary emits, from `src/quality.h`: `complexity` · `verbosity` · `nesting` · `params` · `duplication` · `dead-code` · `api-surface` · `error-masking` · `short-horizon-churn` · `new-clone-of-reused-helper` · `placeholder` · `defect-shape` · `tangle` -`tangle` (QD-TANGLE, 2026-11-19) is report-only: always `sev="minor"`, a long function's nesting past 3, deep share and -steering locals amplified by length (AUC 0.986 on 44 hand labels; a long orchestrator of named steps scores 0). +`tangle` (QD-TANGLE, 2026-11-19) scores a long function's nesting past 3, deep share and steering locals amplified by +length (AUC 0.986 on 44 hand labels; a long orchestrator of named steps scores 0). It was report-only until +TANGLE-GATE-B / QD-RATCHET-BASE (2026-11-21): a row now gates when the function is new at 6.0 or more, crossed 6.0, or +its score grew against the range base while over 6.0 (not a moved body, not test code); a row an input rose on while the +score held stays `sev="minor"`, and the best-since-tag ratchet is a facet (`ratchet=`) on those rows, never a row of its +own. Replayed on the 20 merges before 8861b0d4d (range form, tangle kind only): main printed 3 minor rows and gated 0; +the lane gates 9 rows over 5 PRs — #702 `runLsp` 2.1→11.0 (crossed) and the 8 growth rows the re-census found +(#714 `serialize` 25.4→25.5 and `cc_walk` 9.1→9.7, #706 `runForLensPass` 16.4→16.5, #705 `buildGraph` 56.8→56.9, +#702 `serialize` 25.2→25.4, #688 `ElixirContext::prepare` 12.2→12.3 and `captureTagsFacts` 28.8→29.2); the four +tag-best rows on functions that did not grow in their PR (`buildGraph` #706/#714, `serialize` #705, `captureTagsFacts` +#714 29.2→29.1) print nothing. Expected effect: a PR that adds even a tenth to an over-bar function gates until it +leaves the function no worse (or acks it). The first ten each target a failure mode measured in the literature; `placeholder` (added 0.6.7) is an honesty check on "done" — a stub or TODO the change added — and never gates. `defect-shape` carries six facets in `defect=` (`format-arity`, `utf8-cut`, `dedup-first`, `vacuous-assert`, `unchecked-status`, `unhandled-arm`), shapes this project's own code review kept finding; only `format-arity` gates, and on any origin (new-symbol rows never gate, except -defect-shape format-arity; since QD-ENTRY-CEILING also a new function at the ceiling). Measured (2026-10-07): recall 7/8 on the eight review findings it was built +defect-shape format-arity, a new function at the ceiling (QD-ENTRY-CEILING) and a tangled new function (TANGLE-GATE-B)). Measured (2026-10-07): recall 7/8 on the eight review findings it was built from; with every site treated as new, 0 format-arity false positives on this tree (1,330 literal-format calls), on the Python 3.13 standard library (405 calls) and on libc++'s std::format tests (80 calls; the 24 hits are its deliberately ill-formed `.verify.cpp` calls); vacuous-assert sample precision 30/30 on this tree's gates diff --git a/skills/ripwire-quality-bar/SKILL.md b/skills/ripwire-quality-bar/SKILL.md index 3d112102b..be6ef7d26 100644 --- a/skills/ripwire-quality-bar/SKILL.md +++ b/skills/ripwire-quality-bar/SKILL.md @@ -3,7 +3,7 @@ name: ripwire-quality-bar description: > Code QUALITY of what YOU just wrote, before commit/'done' or a cleanup: --quality-delta lists what got WORSE in 13 kinds; exit 2 if old code did (new-symbol rows never gate, - except defect-shape format-arity and a new function at the ceiling); the fix each shape calls for. + except defect-shape format-arity, a new function at the ceiling and a tangled new one); the fix each shape calls for. Merge safety → change-check. Even a single-line leaf fix runs it. allowed-tools: Bash, Read --- @@ -34,7 +34,7 @@ anyway and stamps `baseline_absorbed="N"`). ## Read the exit code — it is narrower than it looks Exit 2 ONLY on a finding that is major AND unacked AND on code that already existed (`preexisting-worse`) — -exactly the header's `gating="N"`. Read `gating=`, not `regressions=`. The new-symbol rows never gate, except defect-shape format-arity and a new function at the ceiling +exactly the header's `gating="N"`. Read `gating=`, not `regressions=`. The new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling and a tangled new function (a format/argument mismatch is a defect, so it gates on new code too). **Exit 0 means "nothing that already existed got worse", NOT "clean"**: open the `origin="new-symbol"` rows — they are the debt you are adding. A renamed or moved symbol reads as new (`origin="moved"` never gates), so on a diff that moves code the exit code is weak evidence. Before an extract-method fix, read `ev=` diff --git a/skills/ripwire-quality-bar/drill-down.md b/skills/ripwire-quality-bar/drill-down.md index c4bf7f1b3..c466f1a2b 100644 --- a/skills/ripwire-quality-bar/drill-down.md +++ b/skills/ripwire-quality-bar/drill-down.md @@ -17,7 +17,7 @@ Thresholds/definitions are the catalog in [`quality-metrics.md`](quality-metrics | `new-clone-of-reused-helper` | `--clones` · `--callers=HELPER` | call the existing well-reused helper — reuse is declining in AI code (GitClear) | | `placeholder` (an added stub or TODO: `todo!()`, `NotImplementedException`, a "not implemented" throw/panic, a TODO/FIXME naming no issue) | `--expand=SYM` | finish it, or name the issue that tracks it — never gates, but do not call the work done over it | | `defect-shape` (`defect=`: `format-arity` — a literal format whose `{}` fields do not match its arguments; `utf8-cut` — a byte cap plus an ellipsis with no UTF-8 back-off; `dedup-first` — `std::unique` keeping the first of a run over a type with a severity field; `vacuous-assert` — a test script's assertion that passes on an empty text (absence, parity) read off a run whose failure is unchecked: a capture, a pipe without pipefail, a redirected file, a dropped wrapper status; also a FAIL reporter inside `$( )` and an unread `rc=$?`; `unchecked-status` — a dropped I/O or child status: C/C++ `pclose`/`rename`/`write`/`system`/`fflush`/`waitpid`, an `fclose`/`close` of what the function wrote, Python `subprocess.run` with no `check=`, `subprocess.call`, `os.system`; the row's `call=` names it and its `p=` is the site; `unhandled-arm` — a switch/case/if-chain over a closed set that gives an unnamed value no outcome: a C/C++ switch missing an in-tree enumerator with no `default:`, a shell case with no `*)`, a Python chain that falls off to `None`; `why=` names what is left out) | `--expand=SYM` | `format-arity` gates on any origin: match the fields to the arguments. The other five are `sev="minor"`: back off continuation bytes (or call the utf8 helper), sort worst-first before the unique, check the run's exit status before the absence, check the status (`check=True`) or `(void)` it with a reason, add the arm or a default that states the decision | -| `tangle` (report-only, always `sev="minor"`: a long function's nesting past 3, deep share and steering locals, amplified by length; `why=` names the input that rose, `locals=` the steering locals, `ratchet="TAG"` a function above its best since the last tag) | `--expand=SYM` · `--metrics` for `steer=`/`tangle=` | follow `fix=`: split the step that sets a steering local from the branch that reads it, extract the deep region it names, or split into named phases. A long orchestrator of named steps scores 0 — length alone is never the finding. `` lists what your change made better | +| `tangle` (gates a function that is new at 6.0 or more, crossed 6.0, or grew while over it — not a moved body, not test code; a row an input rose on while the score held is `sev="minor"`: a long function's nesting past 3, deep share and steering locals, amplified by length; `why=` names the input that rose, `locals=` the steering locals, `ratchet="TAG"` a function above its best since the last tag) | `--expand=SYM` · `--metrics` for `steer=`/`tangle=` | follow `fix=`: split the step that sets a steering local from the branch that reads it, extract the deep region it names, or split into named phases. A long orchestrator of named steps scores 0 — length alone is never the finding. `` lists what your change made better | These 13 kinds aren't a generic lint list. Ten target an agent-code degradation mode validated at large N (verbosity, structural erosion, smell rate, contract drift; passing tests ≠ clean design); `placeholder` is an diff --git a/test/defectshapecheck.sh b/test/defectshapecheck.sh index 94d76475b..19d6aa33e 100644 --- a/test/defectshapecheck.sh +++ b/test/defectshapecheck.sh @@ -2149,9 +2149,10 @@ fi # rule states the exception in ONE fixed phrase (PHRASE below), so no surface still reads unqualified. L="surfaces" PHRASE='new-symbol rows never gate, except defect-shape format-arity' -# QD-ENTRY-CEILING (2026-11-13) adds the second exception, a NEW function at 4x the bar: every statement of the -# rule names it too, in the long form (legend, help, MCP, docs) or the compact legend's ceiling= row. -CEILX='( and a new function at the ceiling| or a ceiling= row)' +# QD-ENTRY-CEILING (2026-11-13) adds the second exception, a NEW function at 4x the bar, and TANGLE-GATE-B (2026-11-21) +# the third, a new function at tangle 6 or more: every statement of the rule names both, in the long form (legend, +# help, MCP, docs) or the compact legend's ceiling= row and tangle row. +CEILX='(, a new function at the ceiling[^.;]* (and a tangled new (function|one)|and a new one at tangle 6 or more)|, a ceiling= row or a tangle row)' phrase_ok(){ # LABEL TEXT — the text states the exception, and every "new-symbol rows never gate" in it carries it local all qual flat # whitespace-normalized first: a sentence may wrap anywhere in a document flat="$( printf '%s' "$2" | tr '\n' ' ' | tr -s ' ' )" From 9be808dde9586655744a8434552e997249620df0 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:06:43 -0500 Subject: [PATCH 09/61] qd dogfood: pastBacktick and parseShellScan helpers (own-range qd) The lane's own range gated skipQuote's complexity (15 -> 16, the budget guard) and a duplication of scanVacuousAssertBash / scanUnhandledArmBash (the same parse-and-report-cut tail). One backquote skip now serves skipQuote, dqLiteralQuotes and Lexer::skipWordPart; one parseShellScan serves both Bash scans. Behaviour unchanged. Co-Authored-By: Claude Opus 5.5 --- src/defectshape.h | 24 ++++++++++++++---------- src/shstatus.h | 16 ++++++++++------ 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/src/defectshape.h b/src/defectshape.h index f0c393842..38bed4e97 100644 --- a/src/defectshape.h +++ b/src/defectshape.h @@ -4060,17 +4060,25 @@ inline std::vector Script::sites() const } // namespace va +// One shell parse for a Bash facet scan; `cut` (optional) is set when the nesting budget (shstatus kMaxShellNest) stopped it, +// so the sites past that point were not judged. +inline rw::shstatus::Tree parseShellScan( std::string_view src, bool* cut ) +{ + rw::shstatus::Tree tree = rw::shstatus::parse( src ); + if( cut != nullptr ) + { + *cut = *cut || tree.cut; + } + return tree; +} + inline std::vector scanVacuousAssertBash( std::string_view src, const std::vector& /*spans*/, bool* cut = nullptr ) { if( src.empty() ) { return {}; } - const rw::shstatus::Tree tree = rw::shstatus::parse( src ); - if( cut != nullptr ) - { - *cut = *cut || tree.cut; // the nesting budget stopped the parse: sites past it were not judged - } + const rw::shstatus::Tree tree = parseShellScan( src, cut ); const rw::shstatus::Analysis an = rw::shstatus::analyze( tree, src ); const va::Script script( src, tree, an ); return script.sites(); @@ -5852,11 +5860,7 @@ inline void scanUnhandledArmBash( std::string_view src, const std::vector& { return; } - const rw::shstatus::Tree t = rw::shstatus::parse( src ); - if( cut != nullptr ) - { - *cut = *cut || t.cut; - } + const rw::shstatus::Tree t = parseShellScan( src, cut ); uash::endingCaseSites( src, t, out ); uash::assignedCaseSites( src, t, fnSpans, out ); } diff --git a/src/shstatus.h b/src/shstatus.h index 5c3dbd7b4..19f2a06d9 100644 --- a/src/shstatus.h +++ b/src/shstatus.h @@ -492,6 +492,13 @@ inline bool isRedirOp( std::string_view o ) noexcept return o == "<" || o == ">" || o == ">>" || o == "&>" || o == "&>>" || o == ">&" || o == "<&" || o == "<>" || o == ">|" || o == "<<<" || o == "<<"; } +// s[i] is an opening backquote: the index past its closing one, or the end when it never closes. +inline std::size_t pastBacktick( std::string_view s, std::size_t i ) noexcept +{ + const std::size_t j = s.find( '`', i + 1 ); + return j == std::string_view::npos ? s.size() : j + 1; +} + std::size_t skipParen( std::string_view s, std::size_t i, NestBudget& nb ); inline std::size_t skipQuote( std::string_view s, std::size_t i, char q, NestBudget& nb ) // s[i] is the opening quote { @@ -516,8 +523,7 @@ inline std::size_t skipQuote( std::string_view s, std::size_t i, char q, NestBud } if( q == '"' && c == '`' ) { - const std::size_t j = s.find( '`', i + 1 ); - i = j == std::string_view::npos ? s.size() : j + 1; + i = pastBacktick( s, i ); continue; } if( c == q ) @@ -631,8 +637,7 @@ inline std::string dqLiteralQuotes( std::string_view s, NestBudget& nb ) } if( c == '`' ) { - const std::size_t j = s.find( '`', i + 1 ); - i = j == std::string_view::npos ? s.size() : j + 1; + i = pastBacktick( s, i ); continue; } if( c == '\'' ) @@ -988,8 +993,7 @@ class Lexer } if( d == '`' ) { - const std::size_t j = src_.find( '`', i + 1 ); - return j == std::string_view::npos ? n_ : j + 1; + return pastBacktick( src_, i ); // n_ == src_.size() } if( startsAt( src_, i, "$(" ) ) { From 62796724804d3054733e88f075652fa3ea9a727d Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:14:19 -0500 Subject: [PATCH 10/61] qd dogfood: one budget guard in skipParen; split defectRowKeysBothSchemes skipQuote and skipBrace recurse only through skipParen, so one guard there bounds the skip trio; the guards in skipQuote and skipBrace made the two a duplication row (and skipQuote's complexity 15 -> 16). The two-bit/current row-key pair of one (anchor, facet) is its own function, so addDefectFacetSchemeAliases is a loop over anchors (ccx 19 -> under the bar). Co-Authored-By: Claude Opus 5.5 --- src/quality.h | 47 +++++++++++++++++++++++++++-------------------- src/shstatus.h | 14 +++----------- 2 files changed, 30 insertions(+), 31 deletions(-) diff --git a/src/quality.h b/src/quality.h index abbf36ec7..207339efb 100644 --- a/src/quality.h +++ b/src/quality.h @@ -9775,6 +9775,29 @@ inline void addSchemeAliases( IdentityAliases& al, const IngestResult& ing, cons std::sort( al.schemeAmbiguousKeys.begin(), al.schemeAmbiguousKeys.end() ); } +// One (anchor, facet) row's key under the two-bit site values and under the current ones, from that anchor's sites; +// {0, 0} when it has no site of the facet the two-bit scheme knew (a file record carries no legacySite, so it never counts). +inline std::pair defectRowKeysBothSchemes( std::span anchorSites, defectshape::Facet f ) +{ + std::vector now, old; + for( const DefectSiteAt& d : anchorSites ) + { + if( d.legacySite != 0 && defectFacetOf( d.key.site ) == f ) + { + now.push_back( d.key.site ); + old.push_back( d.legacySite ); + } + } + if( now.empty() ) + { + return { 0, 0 }; + } + std::sort( now.begin(), now.end() ); + std::sort( old.begin(), old.end() ); + const std::uint64_t anchor = anchorSites.front().key.anchor; + return { defectRowKey( anchor, f, old ), defectRowKey( anchor, f, now ) }; +} + // CR712-ACK-KEY-MASK — the defect-shape half of the SCHEME migration: for every current (anchor, facet) row whose key under the // two-bit site values (defectLegacySiteValue) differs from its key now, legacy key -> current key, fed into the same toCurrent // map addSchemeAliases fills, so remapAckIdentity re-files a released ack (acks_rekeyed_by_scheme=), computeStaleAcks reads it at @@ -9787,30 +9810,14 @@ inline void addDefectFacetSchemeAliases( IdentityAliases& al, const gtl::btree_m { return; } - const std::vector sites = defectSitesOf( ing, root, nullptr ); // sorted by (anchor, site) + constexpr std::size_t kTwoBitFacets = 4; // format-arity, utf8-cut, dedup-first, vacuous-assert + const std::vector sites = defectSitesOf( ing, root, nullptr ); // sorted by (anchor, site) for( auto it = sites.begin(); it != sites.end(); ) { const auto end = std::find_if( it, sites.end(), [ & ]( const DefectSiteAt& d ) { return d.key.anchor != it->key.anchor; } ); - for( std::size_t f = 0; f < defectshape::kFacetCount; ++f ) + for( std::size_t f = 0; f < kTwoBitFacets; ++f ) { - std::vector now, old; - for( auto d = it; d != end; ++d ) - { - if( d->legacySite != 0 && d->key.site != kDefectFilePresent && d->key.site != kDefectFileUnreadable - && defectFacetOf( d->key.site ) == static_cast( f ) ) - { - now.push_back( d->key.site ); - old.push_back( d->legacySite ); - } - } - if( now.empty() ) - { - continue; - } - std::sort( now.begin(), now.end() ); - std::sort( old.begin(), old.end() ); - const auto facet = static_cast( f ); - const std::uint64_t oldKey = defectRowKey( it->key.anchor, facet, old ), newKey = defectRowKey( it->key.anchor, facet, now ); + const auto [ oldKey, newKey ] = defectRowKeysBothSchemes( { it, end }, static_cast( f ) ); if( oldKey != newKey && al.toCurrent.emplace( oldKey, newKey ).second ) { al.schemeKeys.push_back( oldKey ); diff --git a/src/shstatus.h b/src/shstatus.h index 19f2a06d9..ac48df2c7 100644 --- a/src/shstatus.h +++ b/src/shstatus.h @@ -502,11 +502,6 @@ inline std::size_t pastBacktick( std::string_view s, std::size_t i ) noexcept std::size_t skipParen( std::string_view s, std::size_t i, NestBudget& nb ); inline std::size_t skipQuote( std::string_view s, std::size_t i, char q, NestBudget& nb ) // s[i] is the opening quote { - const NestLevel level( nb ); - if( level.over() ) - { - return s.size(); // past the budget: the rest is one unscanned word (Tree::cut says so) - } ++i; while( i < s.size() ) { @@ -534,12 +529,14 @@ inline std::size_t skipQuote( std::string_view s, std::size_t i, char q, NestBud } return i; } +// The one budget guard of the skip trio: skipQuote and skipBrace recurse only through skipParen, so each nesting level of +// "$( … "$( … )" … )" or ${ … "$( … )" … } costs one level here. inline std::size_t skipParen( std::string_view s, std::size_t i, NestBudget& nb ) // s[i] == '(' { const NestLevel level( nb ); if( level.over() ) { - return s.size(); + return s.size(); // past the budget: the rest is one unscanned word (Tree::cut says so) } int depth = 0; while( i < s.size() ) @@ -579,11 +576,6 @@ inline std::size_t skipParen( std::string_view s, std::size_t i, NestBudget& nb } inline std::size_t skipBrace( std::string_view s, std::size_t i, NestBudget& nb ) // s[i] == '{' of a ${...} { - const NestLevel level( nb ); - if( level.over() ) - { - return s.size(); - } int depth = 0; while( i < s.size() ) { From 88edebed402209a6495e53424ea7c8d6d01f98e5 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:17:56 -0500 Subject: [PATCH 11/61] qd: ack the shstatus.h detail:: signature rows (nesting budget threading) Seven api-surface contract-change rows on shstatus.h's detail:: lexer and skip helpers: each now takes the NestBudget the lexer and parser share (CR712-SHSTATUS-DEPTH). detail:: is internal to the header and every caller changed in the same commit; not a public contract. Co-Authored-By: Claude Opus 5.5 --- .ripwire_quality_acks | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.ripwire_quality_acks b/.ripwire_quality_acks index 007ecec87..9f6ed4081 100644 --- a/.ripwire_quality_acks +++ b/.ripwire_quality_acks @@ -15,6 +15,7 @@ ack api-surface 105c48e20c80c896 3 cid=720fab31ea99ebde A2: unmeasuredHintNote g ack api-surface 1085f731a3dde7c8 7 cid=b012ca29106914d1 capture-audit 2026-09-04 wave-1 close: symbols two lanes each grew past the other's acked magnitude — runDoctor (L10 legend + blobs_floor=, L9 built_from=), writeEnsembleReport (L9 root=, L10 conditional unavailable=), runAffected/runVerify (L9 root-relative block, L4 gauge), writeTestGateReport (L4 gauge splice, L9 row-gated root=; the XML/JSON twins' duplication is the lockstep mcpclidiffcheck asserts, as L9 acked; graphGaugeAttrXml/Json are the same lockstep), writePanelReport (L10 conditional attrs, L4 counts_floor), printUsage/validateConfig (L1 H10 hoist + L5/L9/L10 help text). Re-acked at the merged magnitude; prior reasons kept ack api-surface 10f47dd5a3f35d86 5 fnbody-require lane: deliberate additive API widening (optional out-params, default nullptr, every existing caller unaffected) to disclose the lazy require/import distinction on --impact's importer tier; residual complexity/duplication is the twin-dialect emitter shape and the dual-mode importersOfFiles scan this feature requires, already extracted where a helper genuinely reduced it (scanImporterEdges, recordLazyPair); short-horizon-churn is this same commit's own edit history ack api-surface 1103e9ea8ace3099 5 cid=186a55a17ef44834 now=5 was=4 facet=contract-change p=src/exemplarfamily.h:2505 REDACT-TOUCH: every emitter that quotes a source, manifest or plan line takes the run's RedactCounts* (nullptr = --no-redact), the #686 pattern; the added parameter is the fix and every caller passes the tally it already holds (d.redactPtr, the MCP request's redactPtr, PathAnswerSurface::redact). +ack api-surface 11c919df1ef385d7 3 cid=d706aec64c7e594d now=3 was=2 facet=contract-change p=src/shstatus.h:502 CR712-SHSTATUS-DEPTH: shstatus.h detail:: recursion helpers (internal to the header, every caller updated in the same commit) take the one NestBudget the lexer and parser share; not a public contract ack api-surface 131068a6cedf0864 4 cid=9ead4ea91ba5d605 review of #219: the run= relativity claim is CONDITIONAL, so the predicate has to reach every site that states it — prLegendText and writeFlipHeader take rootRelativeRuns (and its root= attribute) because the legend sentence and the command spelling must be decided by ONE fact, testmap.h runsAreRootRelative; a legend that claims a relativity the spelling does not have is the defect this round fixes. The duplication row pairs that 19-token predicate with mcp.h mcpOmitsGitVerbs, which asks a different question about a different field and shares only the shape of a two-term boolean return — merging them would name neither. | prior: E1 follow-up (#214 CI): prLegendText gains the one pre-render fact that gates testmap.h's run=/run_unknown=/ clause (corpusHasTests) — its single caller writePrContext passes it; the unconditional clause put defaultceilingcheck's 120-file no-test bundle 25 tokens over its 8000 default budget ack api-surface 147451c4175d9f08 2 cid=6d5a9dab1a24c31f degrade disclosure: each read seam and the ref pool now take the DISCLOSE sink whose field the document reads ack api-surface 1520fa02411735c3 6 cid=69e2cb4c55a88771 C1 F-06/F-07/F-10 (the listing-paging round): three listing verbs learn to disclose and page their row listings, and every gating row is that one change. api-surface 14 = ONE trailing DEFAULTED parameter each (an int pageOffset, an McpPageArgs window, a SituPageArgs, or the next= invocation a header now carries) on the emitters that must be TOLD their window — writeFlags/writeGate, writeCappedRows/writeCappedList/writeFlip/writeFlipHeader/writeFlipLights, computeFlip, nearestGateNames (which gains its cap and its TOTAL, the disclosure itself), situShowingNote/writeSituation, and the three MCP twins flagsText/flipText/situationDiffJson; additive by construction, every pre-existing call site compiles unchanged, and the alternative — a second capped emitter per verb — is the drift this repo removes rather than adds, because two emitters that disagree about a window can drop the row that IS the answer. verbosity 3 = kDocDriftLegend +20 lines and writeDocDriftPage +10 are the in-band vocabulary a reader needs to read shown_failed=/failed_capped=/failed_total= where they meet it (the rationale and the next= scan were already hoisted OUT of the body into their own function and comment, which took the complexity row to zero and the LOC row from +48 to +10); dispatchMcpLine +12 is two pagedResult wrappers on a pre-existing 1376-line dispatcher this lane adds to rather than creates. complexity 1 = the same dispatcher, +9 on a base of 518. duplication 1 = flagsText | flipText at 110 tokens, down from 131 after the shared mcpRowCap fold; the residual is getIndex + compute + captureXml, the shape EVERY index-backed MCP twin in this file has, and merging two verbs that return different results behind one entry point would be worse code than the clone. short-horizon-churn 19 = this lane's own footprint across cli.h/docdrift.h/darkflags.h/flipimpact.h/situ.h/mcp*, plus cli.h symbols three other lanes touched the same day; none foreign, none thrash. @@ -54,6 +55,7 @@ ack api-surface 3478654139c90f0f 5 cid=fc086b8b559ee8c6 Review of #214, round 2. ack api-surface 3561d0281d324276 14 WAVE-2 close (2026-08-19), finding 3 of 3: the 76 remaining gating rows, ONE change. All of them are W2-E's root-relative p= landing (9beaa2c/fccea68/a271e6c/b3fe074 plus the f9108b7 correction), measured for the first time at WAVE granularity. The per-lane acks written during W2-E covered only the correction round's own diff (working-tree-vs-HEAD at that moment), so the original ~30-verb landing was never QD-acked; this ack closes that gap rather than re-accepting anything. Verified by reading the whole 20cdc04..860291c src/main.cpp diff line by line: 282 of 448 added lines match the root-relative predicate directly and every one of the remaining 127 is an existing std::printf rewritten from ing.files[...] to the root-relative rp local, plus four extracted emit helpers (computeDirModules, printJsonSymbolRows, writeOversizeRows, writeDropRows). No unrelated logic rides in. By kind: api-surface 28 = the +1 rootArg/rootPrefix parameter on the emitters that must now be TOLD their root (writeAbiCheck/Ref/Struct, emitColumnar*, packBodies/Deps/Lego/Outline/Signatures[Json], serialize[Json], writeLayout*, packConnect, buildD1Row and the report writers) - defaulted wherever a caller could stay unchanged. complexity 31 and verbosity 16 = the single-root-condition ternary and its guarded root= clause applied per emitter, with no new nesting level and no new control flow beyond that one conditional; the large absolute numbers (runStructureText 207->231, runLint 313->323, runMaintenanceViews 174->190, runCallHierarchy 71->80) are pre-existing dispatcher size the wave adds to, not creates - decomposing them is its own round and is recorded as a wave-2 follow-up. params 1 = writeNonLocalStateReport 4->6, the same contract. The three sibling lanes are individually clean: --quality-delta at f6ec56d..1732fd8 (W2-J), 1732fd8..9a41c74 (W2-K) and 9a41c74..20cdc04 (W2-F) each report gating=0. Full suite green at this head: gates=429 pass=427 skip=2 fail=0, ASan+LSan clean, byte-deterministic, xmllint clean. churn= is unavailable in ref-pair mode by construction (both trees materialized out of the repo), so short-horizon-churn is silent here and that silence is not evidence. ack api-surface 35e8077fb0c11e92 4 cid=f1030dd30da5863d now=4 was=3 facet=contract-change p=src/editcheck.h:733 PROVEN-SITE-KEEPS-NAMESAKES (lane edge-strays-1118): CallSiteCalleeTest/EditCheckCalleeTest take ONE trailing span, the graph's provenSites, and reaches() takes the site's ref index, so a proven call site counts only for its own targets (red-first in test/callerscheck.sh SP1-SP4); every caller passes g.provenSites and the ref index in the same commit. ack api-surface 3703c22e2f2112bd 5 cid=e07b67ecf3068d1d by=src/* Phase 5 (docs/EVALS.md): the external-name veto (@external, externalnames.h tables, ExternalVeto predicate, import-name bindings at ingest) and the receiver MRO walk (rule1BaseWalk, SuperObj); every gating row is this one change — the four deliberate contract changes (serialize/serializeJson gain externalCalls, captureIncludes gains binds, methodOnTypeOrBases gains skipSelf/unionOnMulti), the ladder's two new steps in buildGraph, the census's tenth mechanism, kParserVer 77, and the two lexical clone false-positives (a one-line binary_search vs a counts total; a key-buffer probe vs a JSON string writer) +ack api-surface 372b1abf43677adf 4 cid=c4cd86becfdabe6d now=4 was=3 facet=contract-change p=src/shstatus.h:1006 CR712-SHSTATUS-DEPTH: shstatus.h detail:: recursion helpers (internal to the header, every caller updated in the same commit) take the one NestBudget the lexer and parser share; not a public contract ack api-surface 3877dd1e9b4ae997 4 R-E (2026-08-17 harvest): narrowLegoToRenderedSigs needs an explicit rootPrefix param because packSignatures' sigsRendered rows are already root-relative while the function's own escaped path comparison was still absolute -- every comparison silently failed, narrowing legoScoped to nothing on every --for run whose rendered sigs hit this path. The +1 param (defaulted, so every other caller is unaffected) and the small cx/LOC bump on narrowLegoToRenderedSigs and its one caller runForLens are the minimal fix; caught by legobundlecheck.sh going red for the wrong reason. churn=self is this lane's own edit window. ack api-surface 39588f57bd7b46b5 6 cid=2116294439c0a50f M13 paging/budget parity: each of these nine gained exactly ONE trailing DEFAULTED parameter (an McpPageArgs window, a token budget, or the legend posture) so its MCP twin can honor the flag its CLI twin already honors. Additive by construction - every pre-existing call site compiles unchanged and was verified to - and the alternative, a second overload per verb, is the clone seam this repo removes rather than adds. ack api-surface 3a54ea98a485670c 2 W1-S2 churn-keying fix (pathQualifiedKey): bodyHashesBySym's pathQualified-param drop is the deliberate contract change (one keying, no mode); pathQualifiedKey is canonicalId/voteKey-SHAPED but a distinct key domain — canonicalId's bare-name degrade IS the bug this fixes, voteKey is a rename-vote pair with a different separator and value type; churn=self is this fix's own edit trail; gate: qualitysignalcheck.sh §1d @@ -71,10 +73,12 @@ ack api-surface 44bac7b0ded56eb7 3 one grouped astQuery walk for --lint three bu ack api-surface 451442e5d1031096 5 R-R root-relative emission lane: threading the corpus root into 8 emitters is the change itself — +1 param each (contract-change), +3 cx from each pathRel lambda, and the verbosity of the relativization plus its comments. Reviewed row by row; none is avoidable without abandoning root-relative emission. Storage keys unmoved (baseline + ack ledger byte-identical across the cure). ack api-surface 49e172c2aa455e68 6 cid=0ece6180949ad4aa C1 F-06/F-07/F-10 (the listing-paging round): three listing verbs learn to disclose and page their row listings, and every gating row is that one change. api-surface 14 = ONE trailing DEFAULTED parameter each (an int pageOffset, an McpPageArgs window, a SituPageArgs, or the next= invocation a header now carries) on the emitters that must be TOLD their window — writeFlags/writeGate, writeCappedRows/writeCappedList/writeFlip/writeFlipHeader/writeFlipLights, computeFlip, nearestGateNames (which gains its cap and its TOTAL, the disclosure itself), situShowingNote/writeSituation, and the three MCP twins flagsText/flipText/situationDiffJson; additive by construction, every pre-existing call site compiles unchanged, and the alternative — a second capped emitter per verb — is the drift this repo removes rather than adds, because two emitters that disagree about a window can drop the row that IS the answer. verbosity 3 = kDocDriftLegend +20 lines and writeDocDriftPage +10 are the in-band vocabulary a reader needs to read shown_failed=/failed_capped=/failed_total= where they meet it (the rationale and the next= scan were already hoisted OUT of the body into their own function and comment, which took the complexity row to zero and the LOC row from +48 to +10); dispatchMcpLine +12 is two pagedResult wrappers on a pre-existing 1376-line dispatcher this lane adds to rather than creates. complexity 1 = the same dispatcher, +9 on a base of 518. duplication 1 = flagsText | flipText at 110 tokens, down from 131 after the shared mcpRowCap fold; the residual is getIndex + compute + captureXml, the shape EVERY index-backed MCP twin in this file has, and merging two verbs that return different results behind one entry point would be worse code than the clone. short-horizon-churn 19 = this lane's own footprint across cli.h/docdrift.h/darkflags.h/flipimpact.h/situ.h/mcp*, plus cli.h symbols three other lanes touched the same day; none foreign, none thrash. ack api-surface 49ea9954a4e77a06 6 cid=cf442ef6cda47ce0 P4.1 grep fast path — the mechanical footprint of threading two modes through one call chain, and nothing else. FOUR api-surface contract-change rows: spanTiersOfFiles (decl+def), grepApplySpanTiers and emitGrepReport each gained exactly ONE parameter, defaulted where it has more than one caller, so every existing call site is unchanged; RIPWIRE_BASE= argvdiffcheck reports 607/610 argv vectors byte-identical (the 3 diffs are the disclosed --version sha stamp and --run-trace duration_ms), and test/grepfastcheck.sh arm 6 byte-compares the whole --grep option matrix against the same base binary. TWO short-horizon-churn churn=self rows on the same two symbols: the footprint of having edited them in this window, not new debt. ONE complexity row, spanTiersOfFiles 49 to 52: the memo consult is a single branch inside the per-file worker, at the nesting that worker already had; extracting the whole worker body would be a refactor of the pre-existing tree-sitter parse path and was deliberately NOT bundled into a change whose claim is byte-identical output. What was FIXED rather than acked in this same pass: the duplication row (spanTierMemoPath now reuses quality.h's shaKeyedCachePath/headSnapRepoHex/exclConfigHex composition instead of a fourth hand-rolled name builder), main's complexity and verbosity rows (the prefetch launch/join moved into verbs_grep.h seams), and spanTiersOfFiles' verbosity row (prose moved out of the body onto the seams). +ack api-surface 4adca5de6c27054a 5 cid=bf23095f84826b6d now=5 was=4 facet=contract-change p=src/shstatus.h:645 CR712-SHSTATUS-DEPTH: shstatus.h detail:: recursion helpers (internal to the header, every caller updated in the same commit) take the one NestBudget the lexer and parser share; not a public contract ack api-surface 4b788e6f0a75bc80 6 WAVE-2 close (2026-08-19), finding 3 of 3: the 76 remaining gating rows, ONE change. All of them are W2-E's root-relative p= landing (9beaa2c/fccea68/a271e6c/b3fe074 plus the f9108b7 correction), measured for the first time at WAVE granularity. The per-lane acks written during W2-E covered only the correction round's own diff (working-tree-vs-HEAD at that moment), so the original ~30-verb landing was never QD-acked; this ack closes that gap rather than re-accepting anything. Verified by reading the whole 20cdc04..860291c src/main.cpp diff line by line: 282 of 448 added lines match the root-relative predicate directly and every one of the remaining 127 is an existing std::printf rewritten from ing.files[...] to the root-relative rp local, plus four extracted emit helpers (computeDirModules, printJsonSymbolRows, writeOversizeRows, writeDropRows). No unrelated logic rides in. By kind: api-surface 28 = the +1 rootArg/rootPrefix parameter on the emitters that must now be TOLD their root (writeAbiCheck/Ref/Struct, emitColumnar*, packBodies/Deps/Lego/Outline/Signatures[Json], serialize[Json], writeLayout*, packConnect, buildD1Row and the report writers) - defaulted wherever a caller could stay unchanged. complexity 31 and verbosity 16 = the single-root-condition ternary and its guarded root= clause applied per emitter, with no new nesting level and no new control flow beyond that one conditional; the large absolute numbers (runStructureText 207->231, runLint 313->323, runMaintenanceViews 174->190, runCallHierarchy 71->80) are pre-existing dispatcher size the wave adds to, not creates - decomposing them is its own round and is recorded as a wave-2 follow-up. params 1 = writeNonLocalStateReport 4->6, the same contract. The three sibling lanes are individually clean: --quality-delta at f6ec56d..1732fd8 (W2-J), 1732fd8..9a41c74 (W2-K) and 9a41c74..20cdc04 (W2-F) each report gating=0. Full suite green at this head: gates=429 pass=427 skip=2 fail=0, ASan+LSan clean, byte-deterministic, xmllint clean. churn= is unavailable in ref-pair mode by construction (both trees materialized out of the repo), so short-horizon-churn is silent here and that silence is not evidence. ack api-surface 4b8467d6559779e4 3 fnbody-require lane: deliberate additive API widening (optional out-params, default nullptr, every existing caller unaffected) to disclose the lazy require/import distinction on --impact's importer tier; residual complexity/duplication is the twin-dialect emitter shape and the dual-mode importersOfFiles scan this feature requires, already extracted where a helper genuinely reduced it (scanImporterEdges, recordLazyPair); short-horizon-churn is this same commit's own edit history ack api-surface 4be283ea1e39ca3b 3 cid=711b1fede0bf0fe8 by=src/* lane/n3-a phase 3 (2026-09-03): PinCensus::addRow gains the call-site line (6 to 7 params) and addOracleRow the sentinel kind (2 to 3) — the census format v2 join keys registered in docs/EVALS.md Phase 3; eval-only struct with two call sites, both in graph.h ack api-surface 4c3f4f250744d20d 4 cid=da1d80ac704b57a2 P9 the folded edit receipt: runEditVerb gains the postCheck opt-out parameter (defaulted true, so every existing call site is source-compatible) and the line-range + post-check splice; editplan's ensureStage and receipt each gain the root parameter they need to spell one identity (M12's root-relative rule, applied to the sibling it missed) and to run the per-op post-check. The +15 LOC in runEditVerb is the copy-out-before-the-index-rebuild discipline the fold requires — every reference into ing dangles once getIndex re-ingests, and that is stated in the code. +ack api-surface 52961f8157cf72f3 4 cid=85d6402f654152eb now=4 was=3 facet=contract-change p=src/shstatus.h:503 CR712-SHSTATUS-DEPTH: shstatus.h detail:: recursion helpers (internal to the header, every caller updated in the same commit) take the one NestBudget the lexer and parser share; not a public contract ack api-surface 5361e2bced6f1988 8 cid=9cf2c52c10b9d878 M12 follow-up (capture-audit L9): --ensemble gained root=/root-relative p= — writeEnsembleReport's 3 new default-valued params (singleRoot/rootPrefix/rootAttr, back-compat) thread the caller's already-computed single-root spelling through; short-horizon-churn on the touched dispatcher. ack api-surface 5383f63ad718935c 7 cid=170e3fe466966e87 L10: printLintRuleTallyRow's compiled= param and runLintRules' uncompiled-query mapping loop disambiguate a lint-rules query that failed to compile from one that legitimately found zero matches (see docs/PLAN lane L10, finding 3) — deliberate, backward-compatible (defaulted param, incompatible=0) ack api-surface 5391ffd9aa5765bf 6 cid=8a2aed10e80ed270 P2.2 register-macro dead-code fix: additive params on computeDelta/isDeadCandidate, complexity/verbosity growth in computeDelta and runQualityViews (the --dead-code verb), and the kQSnapCacheScheme bump line sit inside the in-window churn threshold - all eight gating rows are this lane's own footprint, none foreign @@ -131,15 +135,18 @@ ack api-surface 85dd951a8f730eec 4 cid=4e0fbe2c7a019909 P7 (terminality round A, ack api-surface 861092ef53c6c2dd 4 cid=48c86b50ca49ddb4 capture-audit 2026-09-04 wave-1 close: deliberate contract changes, each --edit-check incompatible=0 in its lane report — L4 (lane-L4.md, Symbols whose contract changed): pageDisclosure/computePageDisclosure +collectionCapped (defaulted), packLego +graphCountFloorAttr (defaulted), packConnect/writePrRootOpen/writeTestGateReport/writeTestGateReportJson/memberUsesArm +const Graph& for the M15 gauge; L5: enumerateRefs +filterNameHits out-param (defaulted, three callers source-compatible); L3: emitGrepUnindexed/grepAuxJson +window (the H4 paging fix, caller updated) ack api-surface 86db2ff4e22cae54 6 cid=b9c9829a2aac834e C1 F-06/F-07/F-10 (the listing-paging round): three listing verbs learn to disclose and page their row listings, and every gating row is that one change. api-surface 14 = ONE trailing DEFAULTED parameter each (an int pageOffset, an McpPageArgs window, a SituPageArgs, or the next= invocation a header now carries) on the emitters that must be TOLD their window — writeFlags/writeGate, writeCappedRows/writeCappedList/writeFlip/writeFlipHeader/writeFlipLights, computeFlip, nearestGateNames (which gains its cap and its TOTAL, the disclosure itself), situShowingNote/writeSituation, and the three MCP twins flagsText/flipText/situationDiffJson; additive by construction, every pre-existing call site compiles unchanged, and the alternative — a second capped emitter per verb — is the drift this repo removes rather than adds, because two emitters that disagree about a window can drop the row that IS the answer. verbosity 3 = kDocDriftLegend +20 lines and writeDocDriftPage +10 are the in-band vocabulary a reader needs to read shown_failed=/failed_capped=/failed_total= where they meet it (the rationale and the next= scan were already hoisted OUT of the body into their own function and comment, which took the complexity row to zero and the LOC row from +48 to +10); dispatchMcpLine +12 is two pagedResult wrappers on a pre-existing 1376-line dispatcher this lane adds to rather than creates. complexity 1 = the same dispatcher, +9 on a base of 518. duplication 1 = flagsText | flipText at 110 tokens, down from 131 after the shared mcpRowCap fold; the residual is getIndex + compute + captureXml, the shape EVERY index-backed MCP twin in this file has, and merging two verbs that return different results behind one entry point would be worse code than the clone. short-horizon-churn 19 = this lane's own footprint across cli.h/docdrift.h/darkflags.h/flipimpact.h/situ.h/mcp*, plus cli.h symbols three other lanes touched the same day; none foreign, none thrash. ack api-surface 8a92173ded649e17 14 cid=f76e97c84ac7c168 by=src/* lane 2 of the Graft head-to-head (2026-09-07): packSignatures and packSignaturesJson each gain ONE defaulted trailing out-parameter, the ids of the sigs rows they actually emitted, so the file-grain tail can exclude those files instead of the whole 40-candidate surface (three single-file answers at candidate rank 5/10/5 were served nowhere on rocksdb). Every existing caller is byte-identical; the facet is the deliberate arity change the ack-only help names. | prior: A2 (dropped_positive, 2026-09-03): packSignatures gained one trailing droppedPositiveOut out-param and the post-ladder accounting inside the rank-adaptive branch — same shared-arithmetic reason as its JSON sibling. +ack api-surface 8d454d9290626445 2 cid=8e10fcb30385d76d now=2 was=1 facet=contract-change p=src/shstatus.h:613 CR712-SHSTATUS-DEPTH: shstatus.h detail:: recursion helpers (internal to the header, every caller updated in the same commit) take the one NestBudget the lexer and parser share; not a public contract ack api-surface 8d58de9bb922f582 4 T1 completeness claims (complete= on grep/whereis): the +1 on streamBlobs is the deliberate DEFAULTED StreamBlobStats* param (null-object sink inside, no per-site null test; every existing caller byte-identical) so whereis can prove its scan exhaustive before claiming; cx/LOC on streamBlobs/computeWhereis/writeWhereisPage/emitGrepReport is the claim computation plus its in-band legend (the honesty text IS the feature); churn=self on those plus grepCollect/dispatchMcpLine is this lane own edit window. Gated red-first by test/completecheck.sh (24 arms, 10 red pre-fix; mutation arms force cap/offset/budget/unreadable-file/regex-mode/oversized-blob and assert the attribute VANISHES); full plain suite green, 21 touched-family gates green under ASan+LSan, determinism x3, xmllint clean ack api-surface 8fa8514c421e478d 4 cid=7826a06c6d682763 now=4 was=3 facet=contract-change p=src/editcheck.h:833 train 30 fcall-forward nit N1 (d62c00e0): ONE trailing span parameter, the graph's keptForwards, so this call-site reader applies the one model.h forwardCounts rule (--uses' own) instead of counting a forward buildGraph dropped; every caller passes g.keptForwards in the same commit; red-first in test/fcallforwardcheck.sh S1-S3. ack api-surface 924ff0444d20c178 3 cid=6f30f513c0918d3b now=3 was=2 facet=contract-change p=src/forsigx.h:190 lane TL1 (M1 follow-up): compactSigsWithin, added one commit earlier in this lane with one caller (verbs_for.h fittedAnswerFirst), gains the render's ledger so a compacted budget answer re-prices EXACTLY (formaxtokenscheck (C) byte accounting); short-horizon-churn rows are this lane's own M1/M2 helpers ack api-surface 925094be92085dae 3 cid=714cea1e1b31a1ae A6: rollbackMessage gained a 'cause' parameter one commit after this lane introduced it (57fe5fc). It is a header-inline helper in namespace rw::editplan with two callers, both in the same function in the same file; no consumer outside this lane ever saw the 2-arg form. The parameter is what lets the concurrent-write abort reuse the rollback disposition wording instead of growing a second copy of it. +ack api-surface 92749d497bf1775c 3 cid=747ebe8bc9af81a4 now=3 was=2 facet=contract-change p=src/shstatus.h:577 CR712-SHSTATUS-DEPTH: shstatus.h detail:: recursion helpers (internal to the header, every caller updated in the same commit) take the one NestBudget the lexer and parser share; not a public contract ack api-surface 92784a33434e383d 2 cid=e19f01572dacdb87 now=2 was=1 facet=contract-change p=src/hopbody.h:121 fix1: intended internal signature changes (graph for the hop hedge, language for the comment rule, the answer-wide follow budget); every caller updated in the same commit ack api-surface 92ac9caf38b8aab0 4 root-relative coverage round (verifier E1-E4 + two gaps the widened gate exposed, 2026-08-19): every gating row here is the SAME three-line pattern every verb in the original root-relative round already pays — a singleRoot bool, a rootPrefix, a rootAttr, and one ternary per path emission (the shape clones/prcontext/situ/mcp-path all carry verbatim). --tree (runStructureText) +8 ccx / +13 LOC and --quality-panel (writePanelReport) +4 ccx / +12 LOC are those lines plus the finding comment; forTaskText and packTaskBundleText are argument threading only. packBodiesJson api-surface 3 to 4 params is a DELIBERATE contract change: a defaulted trailing rootArg, identical in name, position and default to the one packSignatures/packBodies/packLego/packOutline already take, so the emitter family stays one shape and every existing call site is unaffected. churn=self/ambient is this change's own edit window. Payoff: 1340 absolute paths removed from four surfaces (tree 1212, analyze 85, panel 40, mcp-for 3) plus 5 in the pack-task JSON tail that the gate had been scoring on an empty document, and every single-root run now discloses its root exactly once. All red-first in test/rootrelcheck.sh ack api-surface 93848617cae1fe4e 2 cid=a42863f577100fa6 A3: TestRunnerIndex takes the run's crawl root so run= is spelled relative to root= (one absolute root per document, test/rootrelemitcheck.sh ARM 9). The parameter is the fix; every caller passes the root it already holds. ack api-surface 95cc88ca4aab7039 4 cid=25c411d4871bda46 C1 F-06/F-07/F-10 (the listing-paging round): three listing verbs learn to disclose and page their row listings, and every gating row is that one change. api-surface 14 = ONE trailing DEFAULTED parameter each (an int pageOffset, an McpPageArgs window, a SituPageArgs, or the next= invocation a header now carries) on the emitters that must be TOLD their window — writeFlags/writeGate, writeCappedRows/writeCappedList/writeFlip/writeFlipHeader/writeFlipLights, computeFlip, nearestGateNames (which gains its cap and its TOTAL, the disclosure itself), situShowingNote/writeSituation, and the three MCP twins flagsText/flipText/situationDiffJson; additive by construction, every pre-existing call site compiles unchanged, and the alternative — a second capped emitter per verb — is the drift this repo removes rather than adds, because two emitters that disagree about a window can drop the row that IS the answer. verbosity 3 = kDocDriftLegend +20 lines and writeDocDriftPage +10 are the in-band vocabulary a reader needs to read shown_failed=/failed_capped=/failed_total= where they meet it (the rationale and the next= scan were already hoisted OUT of the body into their own function and comment, which took the complexity row to zero and the LOC row from +48 to +10); dispatchMcpLine +12 is two pagedResult wrappers on a pre-existing 1376-line dispatcher this lane adds to rather than creates. complexity 1 = the same dispatcher, +9 on a base of 518. duplication 1 = flagsText | flipText at 110 tokens, down from 131 after the shared mcpRowCap fold; the residual is getIndex + compute + captureXml, the shape EVERY index-backed MCP twin in this file has, and merging two verbs that return different results behind one entry point would be worse code than the clone. short-horizon-churn 19 = this lane's own footprint across cli.h/docdrift.h/darkflags.h/flipimpact.h/situ.h/mcp*, plus cli.h symbols three other lanes touched the same day; none foreign, none thrash. ack api-surface 96fdcdff2f0ff0f7 4 R-H span tiers (2026-08-19 wave-3 lane, harvest R-H / experiment E5). The nine gating rows are ONE change, read line by line before acking. (1) api-surface grepHitsJson 3->4 params + verbosity: the MCP grep verb takes the span-tier MODE, because the escape hatch has to exist on the MCP surface too — an MCP-only agent that reads suppressed_comment= has no CLI to re-ask from; deliberate contract-change. WAVE-3 VERIFIER CORRECTION (P6-1): this reason originally read 'both callers updated in the same commit' and that was FALSE - src/mcpverbs.h's batch arm still took the defaulted GrepIn::Code and read no 'in' field at all, so the hatch was closed on the ONE surface that had no CLI fallback. Closed in the wave-3 fix lane: both callers now read the value through the same closed-value reader (mcpverbs.h::grepInModeFromArg), 'in' is a declared kBatchSubQueryFields member, and greptiercheck arms (9b)/(9c) pin the batch hatch and its refusal. (2) parseArgs +6 cx / +14 LOC and dispatchMcpLine +3 cx: one new closed-value flag arm (--grep-in=code|any) and its MCP twin, the same shape --grep-scope= added; a flag cannot be added to a hand-rolled parser without them. (3) churn=self on emitGrepReport / grepHitsJson / measure_set: this change's own edit window, not a history signal. (4) emitGrepReport +20 LOC / grepHitsJson +14 LOC: the filter call plus its wiring — the six conditional appends and the legend clause were already lifted into grepTierAttrs/grepTierLegend/grepTierKeys (the grepUnindexedAttrs/grepUnindexedKeys pattern), which is why the COMPLEXITY regressions on both are gone. Nothing here is a shortcut: the tier policy lives in search.h::grepApplySpanTiers and the parse in ingest.cpp::spanTiersOfFiles, both new symbols with their own gate (test/greptiercheck.sh - 30 arms at the wave-3 fix-lane head, 18 FAIL on the clean adb0831 pre-lane binary, 0 here; this text read '22 arms, 12 red', written against an earlier revision of the gate and never refreshed - WAVE-3 VERIFIER CORRECTION P6-7, and an ack's reason is the artifact a future reader trusts instead of re-deriving). +ack api-surface 9700dd1faa4b268d 4 cid=80480bc14e175681 now=4 was=3 facet=contract-change p=src/shstatus.h:750 CR712-SHSTATUS-DEPTH: shstatus.h detail:: recursion helpers (internal to the header, every caller updated in the same commit) take the one NestBudget the lexer and parser share; not a public contract ack api-surface 983814f2b5912a90 3 cid=fe2cfa34166f503a M13 paging/budget parity: each of these nine gained exactly ONE trailing DEFAULTED parameter (an McpPageArgs window, a token budget, or the legend posture) so its MCP twin can honor the flag its CLI twin already honors. Additive by construction - every pre-existing call site compiles unchanged and was verified to - and the alternative, a second overload per verb, is the clone seam this repo removes rather than adds. ack api-surface 9b27b4a434a22d52 5 cid=d77ea26ba88a5261 now=5 was=4 facet=contract-change p=src/editcheck.h:814 train 30 fcall-forward nit N1 (d62c00e0): ONE trailing span parameter, the graph's keptForwards, so this call-site reader applies the one model.h forwardCounts rule (--uses' own) instead of counting a forward buildGraph dropped; every caller passes g.keptForwards in the same commit; red-first in test/fcallforwardcheck.sh S1-S3. ack api-surface 9ebbafddddd086b4 7 cid=50e8788010378ebe capture-audit 2026-09-04 wave-1 close, lane L5 (refusal population, lane-L5.md) + lane L0 H13: guard code and its reasoning, not accidental growth — H6 file-list refusal (writeSituation/dispatchMcpLine/runChangeViews), H7 empty-selection refusals (runCrossRef flags/stray-content, evalStray badRefs, writeWhereisPage line-seed + near-miss), M7 named-file inputs + M8 --since validated once before any verb (main), M9 edit-verb refusals (runCliEdit/nearestNames/resolveOneForEdit), M20 seed disclosure (serialize + MapAnnotations::SeedDisclosure, packLego defs=, packConnect terminal defs=), F10/F14 empty list items (runPath/packConnect). L5 left these un-acked on purpose (shared-ledger race, H10); acked at close against the lane's own ec5e3c3 measurement | prior: WAVE-2 close (2026-08-19), finding 3 of 3: the 76 remaining gating rows, ONE change. All of them are W2-E's root-relative p= landing (9beaa2c/fccea68/a271e6c/b3fe074 plus the f9108b7 correction), measured for the first time at WAVE granularity. The per-lane acks written during W2-E covered only the correction round's own diff (working-tree-vs-HEAD at that moment), so the original ~30-verb landing was never QD-acked; this ack closes that gap rather than re-accepting anything. Verified by reading the whole 20cdc04..860291c src/main.cpp diff line by line: 282 of 448 added lines match the root-relative predicate directly and every one of the remaining 127 is an existing std::printf rewritten from ing.files[...] to the root-relative rp local, plus four extracted emit helpers (computeDirModules, printJsonSymbolRows, writeOversizeRows, writeDropRows). No unrelated logic rides in. By kind: api-surface 28 = the +1 rootArg/rootPrefix parameter on the emitters that must now be TOLD their root (writeAbiCheck/Ref/Struct, emitColumnar*, packBodies/Deps/Lego/Outline/Signatures[Json], serialize[Json], writeLayout*, packConnect, buildD1Row and the report writers) - defaulted wherever a caller could stay unchanged. complexity 31 and verbosity 16 = the single-root-condition ternary and its guarded root= clause applied per emitter, with no new nesting level and no new control flow beyond that one conditional; the large absolute numbers (runStructureText 207->231, runLint 313->323, runMaintenanceViews 174->190, runCallHierarchy 71->80) are pre-existing dispatcher size the wave adds to, not creates - decomposing them is its own round and is recorded as a wave-2 follow-up. params 1 = writeNonLocalStateReport 4->6, the same contract. The three sibling lanes are individually clean: --quality-delta at f6ec56d..1732fd8 (W2-J), 1732fd8..9a41c74 (W2-K) and 9a41c74..20cdc04 (W2-F) each report gating=0. Full suite green at this head: gates=429 pass=427 skip=2 fail=0, ASan+LSan clean, byte-deterministic, xmllint clean. churn= is unavailable in ref-pair mode by construction (both trees materialized out of the repo), so short-horizon-churn is silent here and that silence is not evidence. From 998e337c655dc6e1886acdbe66e645671246104d Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:32:06 -0500 Subject: [PATCH 12/61] qd: tangle's gating rule only in the present-only tangle legend; pins The always-emitted legend core no longer says how tangle rows gate (the tangle row legend, emitted only beside a tangle row, already does), so the clean "am I done" legend pays 13 B less for tangle than before the lane. Pins: legend dictv in COMMANDS.md and the 11-20 showcase capture, the printf parity golden (help_all), the qscheme tripwire (defectSitesOf moved, blob shape unchanged, kQSnapCacheScheme stays 38). The new gates check every exit status they rely on (prereview CI10). Co-Authored-By: Claude Opus 5.5 --- docs/captures/COMMANDS_showcase_2026-11-20.md | 2 +- src/verbs_quality.h | 2 +- test/defectackschemecheck.sh | 7 ++++--- test/qschemetripcheck.sh | 6 ++++++ test/shellnestcheck.sh | 8 +++++--- test/tanglecheck.sh | 4 ++-- 6 files changed, 19 insertions(+), 10 deletions(-) diff --git a/docs/captures/COMMANDS_showcase_2026-11-20.md b/docs/captures/COMMANDS_showcase_2026-11-20.md index a3f728743..cf84407d5 100644 --- a/docs/captures/COMMANDS_showcase_2026-11-20.md +++ b/docs/captures/COMMANDS_showcase_2026-11-20.md @@ -5981,7 +5981,7 @@ ripwire: --run-timeout=SECONDS modifies --run-trace — pass it too (e.g. ripwir *The session legend dictionary the MCP server serves as ripwire://legend-dict/full — one definition per line, headed by its dictv= version; no corpus needed. =roster lists the completeness attributes it defines.* ````` -ripwire legend dictionary ripwire.dict/v1 dictv=c40ddf725e4befcb entries=1177 +ripwire legend dictionary ripwire.dict/v1 dictv=f068f81fdac8104f entries=1178 : this LAST child is only the legend pointer; the root keeps every attribute it carries inline, unchanged (schema=, each count, cut and floor); rows follow it; legend="ref": a definition is sent once per session (this dictionary's core, or the first answer that needs … [line truncated: 80 more bytes on this line] schema=ripwire.KEY/v1: the line ripwire.KEY/v1 below reads the answer's rows window: shown= total= capped= has_more= next_offset= offset= limit= page a list (capped=1 cut; next_offset= pastes as offset=) diff --git a/src/verbs_quality.h b/src/verbs_quality.h index 386ab15b7..d26dc2217 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -1477,7 +1477,7 @@ inline constexpr const char* kQdLegendCore = "score). THIRTEEN KINDS, and kind= on every row names which one: complexity over the ccx bar, verbosity " "(LOC), nesting, params, duplication, dead-code, api-surface (new public contract drift), " "error-masking, short-horizon-churn, new-clone-of-reused-helper, placeholder (added stub/TODO), " - "defect-shape (defect= names it), tangle (a long function's nesting, deep share and steering locals; a new, crossing or growing one gates). " + "defect-shape (defect= names it), tangle (a long function's nesting, deep share and steering locals). " "THREE independent axes, in this " "order: (1) acked findings are suppressed entirely (acked= counts them); (2) ORIGIN — a finding on a " "symbol that EXISTED at the baseline is preexisting-worse (no origin attribute), one that exists only " diff --git a/test/defectackschemecheck.sh b/test/defectackschemecheck.sh index b38f9ed85..756720807 100755 --- a/test/defectackschemecheck.sh +++ b/test/defectackschemecheck.sh @@ -46,7 +46,8 @@ ack(){ ( cd "$1" && "$BIN" . --quality-delta --no-cache --ack-only=format-arity run(){ ( cd "$1" && "$BIN" . --quality-delta --no-cache >"$2" 2>/dev/null ); } # (p) the binary's own key for this row -fixture "$TMP/cur"; ack "$TMP/cur" "current ack" +fixture "$TMP/cur"; ack "$TMP/cur" "current ack"; arc=$? +[ "$arc" = 0 ] || no "(p) --quality-ack on the fresh row exited $arc, want 0" CUR="$( ackkey "$TMP/cur" )" if [ -n "$CUR" ] && [ "$CUR" != "$LEGACY_KEY" ]; then ok "(p) the row's current key $CUR differs from its two-bit key $LEGACY_KEY" else no "(p) want one current key different from $LEGACY_KEY; got '${CUR:-none}' — the fixture no longer exercises a moved site"; fi @@ -66,7 +67,7 @@ if [ "$rc" = 0 ] && [ "$a" = 1 ] && [ -z "$k" ]; then ok "(c) the current-key ac else no "(c) want rc=0 acked=1 and no acks_rekeyed_by_scheme=; got rc=$rc acked=${a:-?} acks_rekeyed_by_scheme=${k:-absent}"; fi # (h) re-ack heals the legacy row forward -ack "$TMP/leg" "re-ack" +ack "$TMP/leg" "re-ack" # status: exits 1 by design (the row is already acked through the alias: nothing new to accept); (h) judges the ledger it re-serialised HK="$( ackkey "$TMP/leg" )"; reason="$( grep -cE '^ack defect-shape .* legacy ack$' "$TMP/leg/$LEDGER" )" run "$TMP/leg" "$TMP/heal.xml"; rc=$?; k="$( attr acks_rekeyed_by_scheme "$TMP/heal.xml" )" if [ "$HK" = "$CUR" ] && [ "$reason" = 1 ] && [ "$rc" = 0 ] && [ -z "$k" ]; then ok "(h) --quality-ack re-filed the row at $HK with its reason; the next run needs no alias" @@ -74,7 +75,7 @@ else no "(h) want the ledger at $CUR with the legacy reason and a later run with # (r) optional: re-derive the recorded key with a two-bit binary if [ -n "${RIPWIRE_LEGACY_BIN:-}" ]; then - fixture "$TMP/rec"; ( cd "$TMP/rec" && "$RIPWIRE_LEGACY_BIN" . --quality-delta --no-cache --ack-only=format-arity --quality-ack="legacy ack" >/dev/null 2>&1 ) + fixture "$TMP/rec"; ( cd "$TMP/rec" && "$RIPWIRE_LEGACY_BIN" . --quality-delta --no-cache --ack-only=format-arity --quality-ack="legacy ack" >/dev/null 2>&1 ) # status: (r) judges the key the legacy binary wrote, not its exit RK="$( ackkey "$TMP/rec" )" if [ "$RK" = "$LEGACY_KEY" ]; then ok "(r) $RIPWIRE_LEGACY_BIN writes the recorded two-bit key $RK"; else no "(r) $RIPWIRE_LEGACY_BIN wrote '${RK:-none}', the recorded key is $LEGACY_KEY"; fi fi diff --git a/test/qschemetripcheck.sh b/test/qschemetripcheck.sh index 8b049587f..2236f5187 100755 --- a/test/qschemetripcheck.sh +++ b/test/qschemetripcheck.sh @@ -81,6 +81,12 @@ PIN="$ROOT/test/qschemetrip.hash" # 2026-11-19, lane qual-ns-call-bind (stacked on lane/import-proved-splits 4787d1ed0): RE-PINNED with UPDATE_GOLDEN=1. kParserVer # 335 PLACEHOLDER (C++ using-declarations + namespace aliases recorded, ingest_binds.h kCppCallScopeFacts; mirrored in quality.h); # the train renumbers and re-pins. kCacheVersion and kQSnapCacheScheme unchanged. +# 2026-11-21, lane QD-LESSONS-2a (on main 8861b0d4d): RE-PINNED with UPDATE_GOLDEN=1 (hash 269831ba67…15a52a). defectSitesOf moved: +# it takes an optional shell-cut counter (CR712-SHSTATUS-DEPTH) and each site record also carries its two-bit value +# (legacySite, CR712-ACK-KEY-MASK), which computeSnapshot does not store. The blob shape is unchanged; the Bash scanners +# now stop at the one nesting budget (64) instead of crashing (subshell/group/if) or cutting $( ) at 40, which changes +# the site set only for a script nested that deep, and the producer identity keeps this build's blobs apart, so +# kQSnapCacheScheme stays 38 (the cr-qd-kinds-068 fix-round-1 precedent below). # 2026-11-20, train 1117d2-s (std-namesake, rust-reexport, rust-modalias-glob, rust-self-chain, rust-macro-args, # rust-path-unhedged, redact-touch, qd-swap, qd-similar-default, py-class-spray; rebased onto main ee8d1a50e, #705 = train 1117d1): # RE-PINNED ONCE with UPDATE_GOLDEN=1 from the rebased build (hash 14b63d9888…d246329). kParserVer 333 (rich 334) replaces the diff --git a/test/shellnestcheck.sh b/test/shellnestcheck.sh index 5925fca2f..50aa0f91d 100755 --- a/test/shellnestcheck.sh +++ b/test/shellnestcheck.sh @@ -61,12 +61,14 @@ for k in subshell group if quote subst; do else no "($k) 5000 deep: want rc 0/2 within 60 s and shell_cut=\"1\"; got rc=$rc in ${t}s, shell_cut='${c:-none}' ($( tail -c 160 "$TMP/$k.err" | tr '\n' ' ' ))"; fi done R="$TMP/r-subshell-5000" -j="$( "$BIN" "$R" --quality-delta --json --no-cache 2>/dev/null | python3 -c 'import json,sys; print(json.load(sys.stdin).get("shell_cut","absent"))' 2>/dev/null || echo unparseable )" -if [ "$j" = 1 ]; then ok "(j) --json: \"shell_cut\":1"; else no "(j) --json: want \"shell_cut\":1, got '$j'"; fi +"$BIN" "$R" --quality-delta --json --no-cache >"$TMP/j.json" 2>/dev/null; jrc=$? +j="$( python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("shell_cut","absent"))' "$TMP/j.json" 2>/dev/null || echo unparseable )" +if { [ "$jrc" = 0 ] || [ "$jrc" = 2 ]; } && [ "$j" = 1 ]; then ok "(j) --json: \"shell_cut\":1"; else no "(j) --json: want rc 0/2 and \"shell_cut\":1, got rc=$jrc '$j'"; fi for n in 40 1; do R="$( repo case "$n" )" - "$BIN" "$R" --quality-delta --no-cache >"$TMP/case$n.xml" 2>/dev/null + "$BIN" "$R" --quality-delta --no-cache >"$TMP/case$n.xml" 2>/dev/null; crc=$? + case "$crc" in 0|2) ;; *) no "(case $n) --quality-delta exited $crc";; esac row="$( grep -oE ']*defect="unhandled-arm"[^>]*>' "$TMP/case$n.xml" | grep 'deep_check.sh' | head -1 )" c="$( cutof "$TMP/case$n.xml" )" label=n1; [ "$n" = 1 ] && label=n2 diff --git a/test/tanglecheck.sh b/test/tanglecheck.sh index e992b63c2..ebbbda3e0 100755 --- a/test/tanglecheck.sh +++ b/test/tanglecheck.sh @@ -73,11 +73,11 @@ Q="$TMP/qd.xml" "$BIN" "$R" --quality-delta --json --no-cache >"$TMP/qd.json" 2>/dev/null; rcj=$? M="$( "$BIN" "$R" --metrics --no-cache 2>/dev/null )"; rcm=$? mkdir -p "$TMP/head" && "${G[@]}" -C "$R" archive HEAD | tar -x -C "$TMP/head" -MH="$( "$BIN" "$TMP/head" --metrics --no-cache 2>/dev/null )" +MH="$( "$BIN" "$TMP/head" --metrics --no-cache 2>/dev/null )"; rcmh=$? rc="$( cat "$Q.rc" )" case "$rc" in 0|2) ;; *) no "quality-delta exit status $rc (stderr: $( head -c 300 "$Q.err" ))";; esac if [ "$rc2" != "$rc" ] || [ "$rcj" != "$rc" ]; then no "quality-delta exit status differs between runs: $rc, again $rc2, --json $rcj"; fi -if [ "$rcm" != 0 ]; then no "--metrics exit status $rcm"; fi +if [ "$rcm" != 0 ] || [ "$rcmh" != 0 ]; then no "--metrics exit status $rcm (working tree), $rcmh (HEAD)"; fi # tangle row for a symbol (sym= ends in ::NAME or is NAME), or empty trow(){ grep -oE "]*>" "$Q" | head -1; } From 7141a993d0a3ea16c81df5be236acbd6120acc09 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:43:42 -0500 Subject: [PATCH 13/61] qd: fit the tangle exception into the MCP and compact legend budgets; pins The quality_delta MCP description (tools/list ceiling 47,420 B; prose never moves it) and the compact new-symbol= reading (stair target 940 B) each paid for the tangle exception in fewer words elsewhere: "a tangled one", "hide until worse", "never gates", "a fresh pinned ... sidecar"; compact "ceiling=, tangle". qdrefpaircheck arm E re-pinned 8 -> 10 (packBodies grew over the bar, collectSources crossed it: tangle gates now). The new gate sorts into regression.sh's list; dictv pins follow the legend. Co-Authored-By: Claude Opus 5.5 --- docs/captures/COMMANDS_showcase_2026-11-20.md | 2 +- src/compactlegend.h | 2 +- test/defectshapecheck.sh | 2 +- test/qdrefpaircheck.sh | 12 +++++++++--- test/regression.sh | 2 +- 5 files changed, 13 insertions(+), 7 deletions(-) diff --git a/docs/captures/COMMANDS_showcase_2026-11-20.md b/docs/captures/COMMANDS_showcase_2026-11-20.md index cf84407d5..b32febb29 100644 --- a/docs/captures/COMMANDS_showcase_2026-11-20.md +++ b/docs/captures/COMMANDS_showcase_2026-11-20.md @@ -5981,7 +5981,7 @@ ripwire: --run-timeout=SECONDS modifies --run-trace — pass it too (e.g. ripwir *The session legend dictionary the MCP server serves as ripwire://legend-dict/full — one definition per line, headed by its dictv= version; no corpus needed. =roster lists the completeness attributes it defines.* ````` -ripwire legend dictionary ripwire.dict/v1 dictv=f068f81fdac8104f entries=1178 +ripwire legend dictionary ripwire.dict/v1 dictv=6ad237691d743450 entries=1178 : this LAST child is only the legend pointer; the root keeps every attribute it carries inline, unchanged (schema=, each count, cut and floor); rows follow it; legend="ref": a definition is sent once per session (this dictionary's core, or the first answer that needs … [line truncated: 80 more bytes on this line] schema=ripwire.KEY/v1: the line ripwire.KEY/v1 below reads the answer's rows window: shown= total= capped= has_more= next_offset= offset= limit= page a list (capped=1 cut; next_offset= pastes as offset=) diff --git a/src/compactlegend.h b/src/compactlegend.h index 1c931339a..cab9e9e4f 100644 --- a/src/compactlegend.h +++ b/src/compactlegend.h @@ -1091,7 +1091,7 @@ inline constexpr CompactCompletenessTerm kCompactAttributeReadings[] = // CR712-SHSTATUS-DEPTH (src/quality.h ratchetAttrsXml): present when not 0 { "shell_cut", "shell_cut=N: shell files whose defect-shape scan stopped at nesting depth 64; deeper code not judged", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, { "preexisting-worse", "preexisting-worse=N: regressions on symbols that existed at baseline; they gate when major", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, - { "new-symbol", "new-symbol=N: NEW code; new-symbol rows never gate, except defect-shape format-arity, a ceiling= row or a tangle row", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, + { "new-symbol", "new-symbol=N: NEW code; new-symbol rows never gate, except defect-shape format-arity, ceiling=, tangle", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, { "register-macro-excluded", "register-macro-excluded=N: symbols skipped: self-registering test/bench macros or Rust #[test]; a floor", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, { "declined-call-excluded", "declined-call-excluded=N: symbols kept out of dead-code only because a declined call may mean them; a floor", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, { "api-new-surface", "api-new-surface=N: new PUBLIC symbols; a count, never gates, not in regressions=", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, diff --git a/test/defectshapecheck.sh b/test/defectshapecheck.sh index 19d6aa33e..377574162 100644 --- a/test/defectshapecheck.sh +++ b/test/defectshapecheck.sh @@ -2152,7 +2152,7 @@ PHRASE='new-symbol rows never gate, except defect-shape format-arity' # QD-ENTRY-CEILING (2026-11-13) adds the second exception, a NEW function at 4x the bar, and TANGLE-GATE-B (2026-11-21) # the third, a new function at tangle 6 or more: every statement of the rule names both, in the long form (legend, # help, MCP, docs) or the compact legend's ceiling= row and tangle row. -CEILX='(, a new function at the ceiling[^.;]* (and a tangled new (function|one)|and a new one at tangle 6 or more)|, a ceiling= row or a tangle row)' +CEILX='(, a new function at the ceiling[^.;]* (and a tangled (new )?(function|one)|and a new one at tangle 6 or more)|, ceiling=, tangle)' phrase_ok(){ # LABEL TEXT — the text states the exception, and every "new-symbol rows never gate" in it carries it local all qual flat # whitespace-normalized first: a sentence may wrap anywhere in a document flat="$( printf '%s' "$2" | tr '\n' ' ' | tr -s ' ' )" diff --git a/test/qdrefpaircheck.sh b/test/qdrefpaircheck.sh index 36ad1baf8..308a210da 100755 --- a/test/qdrefpaircheck.sh +++ b/test/qdrefpaircheck.sh @@ -277,6 +277,12 @@ printf 'register_macros = NOPE_NEVER_USED\n' >"$RC/.ripwire_config" # ── (E) DECISIVE: ripwire's own recorded harvest wave, against the live-recomputed overlay oracle ───────── # RE-PIN LOG for the recorded literal below (it is a bare number, so its justification has to live here). +# 2026-11-21, lane QD-LESSONS-2a (TANGLE-GATE-B / QD-RATCHET-BASE): 8 → 10 gating rows on this wave. Both new rows are +# tangle rows the kind now gates by design (it was report-only): +# (over the bar and grew: deep 45->49, 257->277 lines) +# (crossed the bar: deep 14->22, 182->213 lines) +# The eight rows before are unchanged, and (E)'s row-for-row oracle comparison stays green (7 rows = the 5 before + these 2), +# so 7 + 3 churn = 10. # 2026-09-20, integration/train-13 (lane/t13-honesty-fixes fix 2): 9 → 8 gating rows on this wave, and the # row that left is EXACTLY the row train 12 added below. Fix 2 gives `reuse-decline` # (new-clone-of-reused-helper) the two demotions its sibling `duplication` already had, one of which is @@ -342,9 +348,9 @@ else # the two RECORDED literals from the round record — a cross-check that these shas still name that wave overlayTotal=$(( oracleN + overlayChurn )) - [ "$overlayTotal" = 8 ] \ - && ok "(E) the overlay reproduces the pinned 8 gating rows (= $oracleN + $overlayChurn churn; 9 between #60 and reuse-decline's test-script skip, 8 before #60, 18 pre-dial)" \ - || no "(E) the overlay gave $overlayTotal gating rows; this binary is pinned at 8 (9 between #60's file-scope callers and reuse-decline's all-test-script skip, 8 before #60, 18 before the 2026-09-10 dial round) — the shas, the corpus, a kind's tier or a kind's EVIDENCE moved; the RE-PIN LOG above arm (E) records how the last move was justified" + [ "$overlayTotal" = 10 ] \ + && ok "(E) the overlay reproduces the pinned 10 gating rows (= $oracleN + $overlayChurn churn; 8 before tangle gated, 9 between #60 and reuse-decline's test-script skip, 8 before #60, 18 pre-dial)" \ + || no "(E) the overlay gave $overlayTotal gating rows; this binary is pinned at 10 (8 before tangle gated (QD-LESSONS-2a), 9 between #60's file-scope callers and reuse-decline's all-test-script skip, 8 before #60, 18 before the 2026-09-10 dial round) — the shas, the corpus, a kind's tier or a kind's EVIDENCE moved; the RE-PIN LOG above arm (E) records how the last move was justified" dmmVal="$( "$BIN" "$ROOT" "--dmm=$WAVE_A..$WAVE_B" 2>/dev/null | grep -o ' dmm="[0-9.]*"' | head -1 | sed -E 's/.*"([0-9.]*)".*/\1/' )" # tolerance band, not equality: dmm is a float printed to 3 places (house float rule). if [ -n "$dmmVal" ] && awk -v v="$dmmVal" 'BEGIN{ exit !(v > 0.525 && v < 0.535) }'; then diff --git a/test/regression.sh b/test/regression.sh index 088591b57..93d832fc8 100755 --- a/test/regression.sh +++ b/test/regression.sh @@ -459,6 +459,7 @@ for _g in \ decltodefcheck \ deeptailcheck \ defaultceilingcheck \ + defectackschemecheck \ defectshapecheck \ defoverdeclcheck \ defslookupcheck \ @@ -1087,7 +1088,6 @@ for _g in \ shapingflagcheck \ shellgateindexcheck \ shellnestcheck \ - defectackschemecheck \ showcasecapturecheck \ shrinkpaircheck \ sibliftcheck \ From 6fe4be7d7e8181b409173a11d399d8dd1abc00b2 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:38:24 -0500 Subject: [PATCH 14/61] docs: LIMITS.md lists kMaxShellNest (replaces kMaxSubDepth) The shell nesting budget's declaration carries its effect, so the generated cap table says what a cut does and where it is disclosed (shell_cut=N). Co-Authored-By: Claude Opus 5.5 --- docs/LIMITS.md | 2 +- src/shstatus.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/LIMITS.md b/docs/LIMITS.md index 880a1b34c..d31a52332 100644 --- a/docs/LIMITS.md +++ b/docs/LIMITS.md @@ -1550,7 +1550,7 @@ Discloses: **none** | constant | value | class | note | | --- | --- | --- | --- | -| `kMaxSubDepth` | `40` | — | nested $( ) parsed past this depth are left unparsed (an empty list) | +| `kMaxShellNest` | `64` | — | shell nesting past this depth is cut and not judged; --quality-delta says shell_cut=N | ### `src/siblift.h` diff --git a/src/shstatus.h b/src/shstatus.h index ac48df2c7..06296848e 100644 --- a/src/shstatus.h +++ b/src/shstatus.h @@ -124,7 +124,7 @@ struct Tree // ONE nesting budget for the lexer and the parser (CR712-SHSTATUS-DEPTH): every recursion of either — a quote or $( ) the // lexer skips through, a compound command or a substitution the parser descends into — takes a level, so a script nested // past kMaxShellNest is cut there (Tree::cut) instead of exhausting the stack (20,000 nested subshells crashed the scan). -inline constexpr int kMaxShellNest = 64; +inline constexpr int kMaxShellNest = 64; // shell nesting past this depth is cut and not judged; --quality-delta says shell_cut=N struct NestBudget { int depth = 0; From d472f9447815c9d52cae49099001e560152330a3 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:50:02 -0500 Subject: [PATCH 15/61] qd: shell_cut= is a QdRootField and its legend sentence is present-only shell_cut= moves out of ratchetAttrsXml/Json (it is not a ratchet fact) into QdRootFields::shellCut, one qdCountField built in qdRootFieldsOf and named in qdRootTail's order right after the ratchet (same bytes, same place). The MCP quality_delta object adds the same countFieldOrEmpty after the ratchet attrs. The legend sentence leaves kQdLegendCore for kQdShellCutLegend, emitted only when QualityDeltaLegendParts.shellCut (basis.extras.shellCut > 0): a clean answer no longer pays 109 B for an attribute it does not carry (donelegendcheck full:qd_* targets). Co-Authored-By: Claude Opus 5.5 --- src/compactlegend.h | 2 +- src/mcpverbs.h | 1 + src/quality.h | 25 +++++++++++-------------- src/verbs_quality.h | 20 +++++++++++++++----- 4 files changed, 28 insertions(+), 20 deletions(-) diff --git a/src/compactlegend.h b/src/compactlegend.h index cab9e9e4f..a3724faa4 100644 --- a/src/compactlegend.h +++ b/src/compactlegend.h @@ -1088,7 +1088,7 @@ inline constexpr CompactCompletenessTerm kCompactAttributeReadings[] = { "stale_next", "stale_next=: the call printing the sa rows and the full header", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, // D4 (src/quality.h ratchetAttrsXml): present when the tangle ratchet read its reference point { "ratchet_ref", "ratchet_ref=TAG ratchet_judged=N: N tangle rows' functions compared with their best since TAG; ratchet_unread= / ratchet_cut=1: versions not measured", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, - // CR712-SHSTATUS-DEPTH (src/quality.h ratchetAttrsXml): present when not 0 + // CR712-SHSTATUS-DEPTH (src/verbs_quality.h QdRootFields::shellCut): present when not 0 { "shell_cut", "shell_cut=N: shell files whose defect-shape scan stopped at nesting depth 64; deeper code not judged", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, { "preexisting-worse", "preexisting-worse=N: regressions on symbols that existed at baseline; they gate when major", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, { "new-symbol", "new-symbol=N: NEW code; new-symbol rows never gate, except defect-shape format-arity, ceiling=, tangle", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, diff --git a/src/mcpverbs.h b/src/mcpverbs.h index aec238487..0d7bfd997 100644 --- a/src/mcpverbs.h +++ b/src/mcpverbs.h @@ -5187,6 +5187,7 @@ inline std::pair qualityDeltaJson( const std::string& + ( oc.headBasis == nullptr ? std::string() : std::string( ",\"head_basis\":\"" ) + mcpdetail::jsonEscape( oc.headBasis ) + "\"" ) + oc.historyJson + rw::quality::ratchetAttrsJson( oc.extras ) + + countFieldOrEmpty( "shell_cut", oc.extras.shellCut, /*json=*/true ) // CR712-SHSTATUS-DEPTH (QdRootFields::shellCut) + ",\"at\":" + atJson + ",\"r\":["; bool first = true; for( const rw::quality::Regression& r : oc.regs ) diff --git a/src/quality.h b/src/quality.h index 207339efb..aba3c0aa5 100644 --- a/src/quality.h +++ b/src/quality.h @@ -11032,31 +11032,28 @@ inline std::string tangleRowAttrs( const Regression& r, bool json, Escape&& esc return out; } -// D4 — the ratchet's disclosure on the root: the reference point it read, and what it could not read ("" when it was not -// consulted); then CR712-SHSTATUS-DEPTH's shell_cut= (the shell files whose defect-shape scan the nesting budget cut; absent at 0). +// D4 — the ratchet's disclosure on the root: the reference point it read, and what it could not read. "" when it was not consulted. template inline std::string ratchetAttrsXml( const DeltaExtras& x, Escape&& ex ) { - std::string out; - if( !x.ratchetRef.empty() ) + if( x.ratchetRef.empty() ) { - out = " ratchet_ref=\"" + ex( x.ratchetRef ) + "\" ratchet_judged=\"" + std::to_string( x.ratchetJudged ) + "\""; - out += x.ratchetUnread > 0 ? " ratchet_unread=\"" + std::to_string( x.ratchetUnread ) + "\"" : std::string(); - out += x.ratchetCut ? " ratchet_cut=\"1\"" : ""; + return {}; } - out += x.shellCut > 0 ? " shell_cut=\"" + std::to_string( x.shellCut ) + "\"" : std::string(); + std::string out = " ratchet_ref=\"" + ex( x.ratchetRef ) + "\" ratchet_judged=\"" + std::to_string( x.ratchetJudged ) + "\""; + out += x.ratchetUnread > 0 ? " ratchet_unread=\"" + std::to_string( x.ratchetUnread ) + "\"" : std::string(); + out += x.ratchetCut ? " ratchet_cut=\"1\"" : ""; return out; } inline std::string ratchetAttrsJson( const DeltaExtras& x ) { - std::string out; - if( !x.ratchetRef.empty() ) + if( x.ratchetRef.empty() ) { - out = ",\"ratchet_ref\":\"" + rw::jsonesc::escapeMcp( x.ratchetRef ) + "\",\"ratchet_judged\":" + std::to_string( x.ratchetJudged ); - out += x.ratchetUnread > 0 ? ",\"ratchet_unread\":" + std::to_string( x.ratchetUnread ) : std::string(); - out += x.ratchetCut ? ",\"ratchet_cut\":1" : ""; + return {}; } - out += x.shellCut > 0 ? ",\"shell_cut\":" + std::to_string( x.shellCut ) : std::string(); + std::string out = ",\"ratchet_ref\":\"" + rw::jsonesc::escapeMcp( x.ratchetRef ) + "\",\"ratchet_judged\":" + std::to_string( x.ratchetJudged ); + out += x.ratchetUnread > 0 ? ",\"ratchet_unread\":" + std::to_string( x.ratchetUnread ) : std::string(); + out += x.ratchetCut ? ",\"ratchet_cut\":1" : ""; return out; } diff --git a/src/verbs_quality.h b/src/verbs_quality.h index d26dc2217..f0f227702 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -1495,11 +1495,13 @@ inline constexpr const char* kQdLegendCore = // P3 (L7): next= on gating rows, defined where the reader meets it "A gating row's next= is the one pasteable follow-up: expand on FILE:NAME, the body to fix (a duplication row names a SET and carries none). " // P8 (L7): the threshold beside the number - "bar= on a complexity/verbosity/nesting/params row is the threshold now= is judged against (ccx 15, loc 60, nest 4, params 5). " - // CR712-SHSTATUS-DEPTH: present only when not 0 + "bar= on a complexity/verbosity/nesting/params row is the threshold now= is judged against (ccx 15, loc 60, nest 4, params 5). "; + +// CR712-SHSTATUS-DEPTH — present-only: rides with shell_cut= on the root (QdRootFields::shellCut), absent at 0. +inline constexpr const char* kQdShellCutLegend = "shell_cut=N: shell files whose defect-shape scan stopped at nesting depth 64; what lies deeper was not judged. "; -static_assert( rw::shstatus::kMaxShellNest == 64, "kQdLegendCore's and compactlegend.h's shell_cut= sentences say depth 64" ); +static_assert( rw::shstatus::kMaxShellNest == 64, "kQdShellCutLegend's and compactlegend.h's shell_cut= sentences say depth 64" ); // The macro FAMILIES, and why a member of one cannot be judged dead — printed only when the run actually // excluded something, because on a repo with no such macro the roster explains an empty set. @@ -1904,6 +1906,7 @@ struct QualityDeltaLegendParts bool staleTree = false; // D3 QD-STALE-HEADER: stale_tree= is on the root bool ratchetRead = false; // D4: ratchet_ref= is on the root bool anyImproved = false; // QD-CREDIT-ROW: the section is in the document + bool shellCut = false; // CR712-SHSTATUS-DEPTH: shell_cut= is on the root }; // qd-memory-degrade — present-only: each rides only with the attributes it defines. No double dash anywhere in them @@ -2131,6 +2134,10 @@ inline void emitQualityDeltaLegend( const QualityDeltaLegendParts& p, std::FILE* { rw::emitRaw( out, kQdImprovedLegend ); // QD-CREDIT-ROW } + if( p.shellCut ) + { + rw::emitRaw( out, kQdShellCutLegend ); // CR712-SHSTATUS-DEPTH + } if( p.scoped ) { @@ -2964,6 +2971,7 @@ struct QdRootFields QdRootField kinds; // qd-memory-degrade: kinds not run, why, the replay, the peak (kindsDisclosure) QdRootField history; // hwh-fix4 (N1): history a gating kind could not read (unread_history=) QdRootField ratchet; // D4: the ratchet's reference point and what it could not read + QdRootField shellCut; // CR712-SHSTATUS-DEPTH: shell files whose defect-shape scan the nesting budget cut }; // The root's tail in one order for both formats. `foldAttrs` (XML only) is the stale fold's stale_by_kind=/stale_next=, @@ -2977,7 +2985,7 @@ std::string qdRootTail( const QdRootFields& f, QdFormat format, std::string_view out += field->in( format ); } out += foldAttrs; - for( const QdRootField* field : { &f.kinds, &f.history, &f.ratchet } ) + for( const QdRootField* field : { &f.kinds, &f.history, &f.ratchet, &f.shellCut } ) { out += field->in( format ); } @@ -3036,6 +3044,7 @@ QdRootFields qdRootFieldsOf( const QdReport& rep ) f.history = fromPair( quality::historyUnreadDisclosure( basis.historyUnread ) ); f.ratchet = { quality::ratchetAttrsXml( basis.extras, [ & ]( std::string_view s ) { return std::string( escapeXml( s, esc ) ); } ), quality::ratchetAttrsJson( basis.extras ) }; + f.shellCut = qdCountField( "shell_cut", basis.extras.shellCut, basis.extras.shellCut != 0 ); return f; } @@ -3345,7 +3354,8 @@ void emitQdXmlDocument( std::FILE* out, const QdReport& rep, const QdStaleFold* basis.headBasis, basis.declinedCallExcluded > 0, basis.valueRefExcluded > 0, fold != nullptr, refs.kinds != quality::kAllKinds, refs.degraded, !refs.memoryStop.empty(), rep.kd.peakOver != 0, rep.kd.memorySkipped != 0 && refs.selected != quality::kAllKinds, basis.historyUnread.any(), - basis.rustTestExcluded, refs.staleTree, !basis.extras.ratchetRef.empty(), !basis.extras.improved.empty() }, out ); + basis.rustTestExcluded, refs.staleTree, !basis.extras.ratchetRef.empty(), !basis.extras.improved.empty(), + basis.extras.shellCut > 0 }, out ); // at= anchors this regression list to the commit (+dirty state) it was computed against (QdRootFields::at). R-I: the range // form's base_ref= and target_ref= carry FULL shas because a wave measurement gets quoted into handoffs where a 9-char // prefix is one collision from unverifiable. From 04412836f650d13f3c9013faa3e4c4b8b0380892 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:42:56 -0500 Subject: [PATCH 16/61] refactor(ingest): captureTagsFacts runs one match through named steps The 948-line tags pass (tangle S 29.1, nest 6, 222 deep lines, five steering locals) becomes an orchestrator over a file's TagsPass state and one match's TagsMatch: - readTagsMatch reads a match's captures once (role, name, keyword head) and emits its @import.* facts in capture order, as before. - captureTagsMatch runs the capture-time drop decisions in their order, then the definition or the reference arm. - captureDefinition: definitionSpanOf (the declarator climb is climbDeclaratorToDefinition, its stop set isDeclaratorClimbStop), fillDefinitionExtent / fillDefinitionShape, nameDefinition, scopeDefinition, captureDefinitionEdges. - captureReference: consumeSpecialReference, qualifyElixirReference, qualifyPathReference, readReceiverFacts. - Ruby's file passes are captureRubyFilePasses. Byte-identical: every step runs in the order the loop body ran it. The name facts reuse ingest_names.h DefNameFacts; the complexity fill saturates with saturatedTo (the fnOrMethod gates were redundant: off a callable the Complexity is all zeros). Co-Authored-By: Claude Opus 5.5 --- src/ingest_sidecap.h | 2004 ++++++++++++++++++++++++------------------ 1 file changed, 1150 insertions(+), 854 deletions(-) diff --git a/src/ingest_sidecap.h b/src/ingest_sidecap.h index 4c7573dfc..7473a6980 100644 --- a/src/ingest_sidecap.h +++ b/src/ingest_sidecap.h @@ -1894,6 +1894,1147 @@ inline void applyAnnotationRename( RawDef& d, const AnnotationRename& renamed, T // the best-since store's reading of a history blob (ingest.h tangleInputsOfBlob). enum class TagsCapture : std::uint8_t { Full, DefinitionsOnly, DefinitionsAndShape }; +// ── captureTagsFacts, as named steps (GE-CAPTURETAGS) ──────────────────────────────────────────────────────────────────────── +// One file's pass state (TagsPass), one match's captures read once into a TagsMatch (readTagsMatch), then the capture-time drop +// decisions in order (captureTagsMatch) and the definition or reference arm (captureDefinition / captureReference), each a +// sequence of named steps. Every step runs in the order the single loop body ran it; the outputs are byte-identical. + +// One file's tags pass: the facts every match reads and the sinks it appends to. Built once per file by captureTagsFacts. +struct TagsPass +{ + const LangEntry& le; + std::uint32_t fileId; + std::string_view src; + TSNode root; + std::vector& defs; + std::vector& refs; + std::vector& binds; + std::vector& includes; + ExtractShortfall& shortfall; + ElixirContext& elixir; + std::string_view fileStem; // the name of a bare `module.exports = ` (JS) + bool full; // TagsCapture::Full: references, imports and the def arm's IS-A / HAS-A / macro-body edges too + bool shape; // the callables' cc_walk facts (Full or DefinitionsAndShape) + bool fileHasError; // extent honesty: the recovered-bit walk (parseRecoveredBits) only exists in a file the parser had to recover +}; + +// What one tags match captured. A tags pattern yields one @definition/@reference node plus a child @name: the role capture sets +// kind, the capture's name and roleNode; the @name capture sets the four name facts, and every later re-seat (C++ declarator, +// macro annotation, test-macro title) moves all four at once. +struct TagsMatch +{ + SymKind kind = SymKind::Other; + bool isDef = false; + bool isRef = false; + std::string_view defCap; // the @definition capture's name — dropGatedCapture keys the constant/cjsexport/protomethod gates on it + std::string_view refCap; // the @reference capture's name — "reference.import" routes the using-declaration role (r9 loss bucket 1) + TSNode roleNode {}; + DefNameFacts name {}; // the @name identifier: its node (for C++ scope/qualifier, E#4), text, start byte and 0-based row + bool keywordHead = false; // #355: the pattern carried @_keyword, a head its tags.scm predicates accepted + + bool hasRole() const noexcept { return isDef || isRef; } + bool hasName() const noexcept { return !ts_node_is_null( name.node ); } + void reseatName( TSNode node, std::string_view text ) noexcept + { + name = DefNameFacts{ node, text, ts_node_start_byte( node ), ts_node_start_point( node ).row }; + } +}; + +// A C++ conversion operator's declarator is an `operator_cast` node whose text spans the WHOLE `operator () const` (the +// tags query captures the declarator itself — there is no sub-node spanning just `operator bool`). Its name ends at the end of +// the `type` field, so the symbol name is `operator bool` / `operator MyType`, not the param list. Symbolic ops +// (operator==/[]/()) go through operator_name and are untouched — trimming at `(` there would wrongly cut `operator()`, so +// this is operator_cast-only. Every other @name ends where its node does. +inline std::uint32_t capturedNameEnd( TSNode node ) noexcept +{ + const std::uint32_t end = ts_node_end_byte( node ); + if( !kindIs( ts_node_type( node ), "operator_cast" ) ) + { + return end; + } + const TSNode typeNode = fieldChild( node, NodeField::Type ); + if( ts_node_is_null( typeNode ) ) + { + return end; + } + const std::uint32_t typeEnd = ts_node_end_byte( typeNode ); + return typeEnd > ts_node_start_byte( node ) && typeEnd <= end ? typeEnd : end; +} + +// The @name capture's four facts; a null node when its span falls outside `src` (the match then has no name from this capture). +inline DefNameFacts capturedNameOf( TSNode node, std::string_view src ) noexcept +{ + const std::uint32_t start = ts_node_start_byte( node ); + const std::uint32_t end = capturedNameEnd( node ); + if( end > src.size() || start > end ) + { + return DefNameFacts{}; + } + return DefNameFacts{ node, src.substr( start, end - start ), start, ts_node_start_point( node ).row }; +} + +// #358: an `@import.*` capture, emitted here in capture order, not in a second pass. Matches arrive by start byte and captures +// within a match in query order, so a staging vector would produce the identical order while costing an allocation and a drain +// block. `import.names` / `import.alias` are one clause's target and its optional alias, paired once the match is read. +inline void noteImportCapture( const TagsPass& pass, std::string_view capSv, TSNode node, TSNode& importNames, TSNode& importAlias ) +{ + if( !pass.full ) + { + return; + } + if( capSv == "import.path" ) + { + emitCapturedImport( node, pass.fileId, pass.le.lang, pass.src, pass.includes, pass.refs, pass.shortfall ); + } + else if( capSv == "import.names" ) + { + importNames = node; + } + else if( capSv == "import.alias" ) + { + importAlias = node; + } +} + +// Walk one match's captures into a TagsMatch: the role node and its capture, the name, the keyword head. The match's imports are +// emitted on the way (noteImportCapture), and its import clause's bind (emitCapturedImportBind) after the walk. +inline TagsMatch readTagsMatch( const TagsPass& pass, TSQuery* query, const TSQueryMatch& match ) +{ + TagsMatch m; + TSNode importNames {}; + TSNode importAlias {}; + for( uint16_t ci = 0; ci < match.capture_count; ++ci ) + { + const TSQueryCapture& cap = match.captures[ ci ]; + + uint32_t nameLen = 0; + const char* capName = ts_query_capture_name_for_id( query, cap.index, &nameLen ); + const std::string_view capSv( capName, nameLen ); + if( capSv == "_keyword" ) + { + m.keywordHead = true; // a predicate-only capture: roleOf ignores it, the definition keyword is its pattern's #any-of? + } + + SymKind k = SymKind::Other; + switch( roleOf( capSv, k ) ) + { + case CapRole::Def: + { + m.isDef = true; + m.kind = k; + m.defCap = capSv; + m.roleNode = cap.node; + } + break; + + case CapRole::Ref: + { + m.isRef = true; + m.refCap = capSv; + m.roleNode = cap.node; + } + break; + + case CapRole::NameOnly: + { + if( const DefNameFacts name = capturedNameOf( cap.node, pass.src ); !ts_node_is_null( name.node ) ) + { + m.name = name; + } + } + break; + + case CapRole::Ignore: + break; + + case CapRole::Import: + { + noteImportCapture( pass, capSv, cap.node, importNames, importAlias ); + } + break; + } + } + if( !ts_node_is_null( importNames ) ) + { + emitCapturedImportBind( importNames, importAlias, pass.fileId, pass.le.lang, pass.src, pass.binds ); + } + return m; +} + +// MACRO-P0 (ingest_names.h): a macro invocation read as a typeless declarator mints no definition of its own; the site is a +// call-shaped use of the macro (model.h retagMacroCallReferences makes it role="macro" when the #define is indexed and its name +// is uniquely a macro). No argument count: the "parameters" are macro arguments. MACRO-P1: when the grammar read the real +// function's own `f()` as a variable (ingest_names.h annotationRenamedName), this definition is the only one f gets — it +// carries f's name, from f's own start (`renamed`). false: the capture ends here (a macro use and nothing renamed behind it). +inline bool keepAfterMacroInvocation( const TagsPass& pass, TagsMatch& m, AnnotationRename& renamed ) +{ + if( !cFamilyMacroInvocationCapture( m.defCap, pass.le.lang, m.name.text, m.roleNode, pass.src ) ) // defCap: set by a @definition capture only + { + return true; + } + RawRef r; + r.fileId = pass.fileId; + r.startByte = ts_node_start_byte( m.roleNode ); + r.line = ts_node_start_point( m.roleNode ).row + 1; + r.lang = pass.le.lang; + r.role = RefRole::Call; + r.name = m.name.text; + pass.refs.push_back( std::move( r ) ); + renamed = annotationRenamedName( m.roleNode, pass.src ); + if( ts_node_is_null( renamed.name ) ) + { + return false; + } + m.reseatName( renamed.name, nodeTextOf( renamed.name, pass.src ) ); + m.kind = renamedAnnotationKind( renamed.name ); + return true; +} + +// INDEX-ALIAS-CONST (src/aliasdef.h, the one alias reader): a C++ alias form is a definition unless it is function-local +// (ingest_relations.h insideFunctionBody: a function-local alias is a local name, the local-const rule). std::nullopt: the capture +// is dropped; form None: not an alias definition. +inline std::optional aliasShapeOfCapture( Lang lang, const TagsMatch& m ) +{ + if( !m.isDef || !langFacts( lang ).aliasTargetDefs || m.defCap != "definition.alias" ) + { + return AliasShape{}; + } + if( insideFunctionBody( m.roleNode ) ) + { + return std::nullopt; + } + return aliasShapeOf( Lang::Cpp, m.roleNode ); +} + +// INDEX-ALIAS-CONST: where an alias's written target starts when it ENDS the declaration (--defs to=), else 0 (a typedef). The +// target is a suffix when every child after it is the `;` or a comment (`using X = Y /* c */ ;` keeps its target; the printer +// drops the comment, defslookup.h aliasTargetText); one cursor walk (infra/tschildren.h). Only `using`/namespace alias rows +// reach here (a typedef capture is never definition.alias). +inline std::uint32_t aliasTargetStartOf( TSNode roleNode, const AliasShape& aliasShape ) +{ + const std::uint32_t tEnd = ts_node_end_byte( aliasShape.target ); + bool suffix = true; + ChildCursor cursor( roleNode ); + forEachChild( roleNode, cursor.cur, [ & ]( TSNode c ) + { + const char* k = ts_node_type( c ); + suffix = ts_node_start_byte( c ) < tEnd || kindIs( k, ";" ) || kindIs( k, "comment" ); + return suffix; + } ); + return suffix ? ts_node_start_byte( aliasShape.target ) : 0u; +} + +// Elixir's capture filters a tags pattern cannot state: elixirKeepCapture's syntax filters; a bare name is a call only off a pipe +// (bare pipe targets have their own capture) and past lexical variable exclusion; the special-form operators are no calls. +inline bool keepElixirCapture( const TagsPass& pass, const TagsMatch& m ) +{ + if( !elixirKeepCapture( m.roleNode, m.name.node, ElixirCaptureRole{ m.isDef, m.kind, m.keywordHead }, pass.src, pass.elixir.keywords ) ) + { + return false; + } + if( m.refCap == "reference.bare" ) + { + const TSNode parent = parentOf( m.name.node ); + const bool pipeTarget = elixirNodeIs( parent, "binary_operator" ) && nodeFieldText( parent, NodeField::Operator, pass.src ) == "|>" + && ts_node_eq( fieldChild( parent, NodeField::Right ), m.name.node ); + return !pipeTarget && pass.elixir.bareCall( m.name.node ); + } + if( m.refCap == "reference.operator" ) + { + constexpr std::string_view special[] = { "=", "<-", "\\\\", "::", "|>", "when", "|", "^", "&", "@" }; + if( std::find( std::begin( special ), std::end( special ), m.name.text ) != std::end( special ) ) + { + return false; + } + const TSNode parent = parentOf( m.roleNode ); + return !( m.name.text == "/" && elixirNodeIs( parent, "unary_operator" ) && nodeFieldText( parent, NodeField::Operator, pass.src ) == "&" ); + } + return true; +} + +// The per-language capture filters (Elixir's, Clojure's); a Clojure definition's kind is its head's shape. +inline bool keepLanguageCapture( const TagsPass& pass, TagsMatch& m ) +{ + if( pass.le.lang == Lang::Elixir ) + { + return keepElixirCapture( pass, m ); + } + if( pass.le.lang != Lang::Clojure ) + { + return true; + } + if( !clojureKeepCapture( m.roleNode, m.isDef, pass.src ) ) + { + return false; + } + if( m.isDef ) + { + m.kind = clojureDefinitionShape( m.roleNode, pass.src ).kind; + } + return true; +} + +// A capture inside an inert quote region: call/operator/named-capture candidates are kept as declined facts, never edges. Heads, +// special forms and non-call operators already failed their syntax filters. Bare AST names remain variable-shaped syntax unless +// they explicitly name a function capture. true: the capture was in such a region (consumed here). +inline bool consumeInertQuoteCapture( const TagsPass& pass, const TagsMatch& m ) +{ + if( !langFacts( pass.le.lang ).hasInertQuoteRegions || !elixirInert( m.roleNode, pass.src ) ) + { + return false; + } + const bool candidate = m.isRef && ( m.refCap == "reference.call" || m.refCap == "reference.operator" + || ( m.refCap == "reference.bare" && pass.elixir.namedCapture( m.name.node ) ) ); + if( !candidate ) + { + return true; + } + RawRef r; + r.fileId = pass.fileId; + r.startByte = ts_node_start_byte( m.roleNode ); + r.line = m.name.row + 1; + r.lang = Lang::Elixir; + r.role = RefRole::Inert; + auto [ count, known ] = elixirCallArity( m.roleNode, m.name.node, pass.src ); + if( m.refCap == "reference.operator" ) { count = elixirNodeIs( m.roleNode, "binary_operator" ) ? 2 : 1; known = true; } + r.name = known ? elixirFunctionName( m.name.text, count ) : std::string( m.name.text ); + pass.refs.push_back( std::move( r ) ); + return true; +} + +// Where a definition's code lives: the node its span covers, its body (null: a declaration), the function literal a name is bound +// to (kFnLiteralBinding: params/cx/nest read from it), and whether the body is a SIBLING the span runs through. +struct DefCodeNodes +{ + TSNode defNode {}; + TSNode body {}; + TSNode literal {}; + bool testMacroBlock = false; // LB-E: the def is TWO SIBLING nodes (testMacroBlockPartsOf) + bool spanThroughBody = false; // the code this symbol owns lives in a SIBLING node: byte/row extents and complexity run through it +}; + +// LB-E testmacroblock: adopt the sibling compound_statement as the body and the title literal as the name BEFORE the shared +// span/complexity steps. The span's endByte and the loc row window run past defNode's own end (no single node covers both +// siblings). false: not a test macro block after all (dropGatedCapture already vetoed non-candidates — guard, don't assert). +inline bool adoptTestMacroBlock( const TagsPass& pass, TagsMatch& m, DefCodeNodes& span ) +{ + const TestMacroBlockParts parts = testMacroBlockPartsOf( m.roleNode, pass.src ); + if( !parts.ok ) + { + return false; + } + span.body = parts.body; + m.reseatName( parts.title, testMacroTitleOf( parts.title, pass.src ) ); + return true; +} + +// The declarator climb's STOP set: a type/namespace/file scope — a function's body never lives above one of these, so reaching +// one means the role node is a prototype/declaration with no body (without this, an in-class method declaration would climb into +// class_specifier and wrongly grab the whole CLASS body as its span — corrupting spans + ref attribution) — and a C-family +// function BODY: a block-scope `Type v(args);` (most-vexing-parse) must not climb up and steal its enclosing function's span. A +// real function definition's declarator parents directly to function_definition (found at hop 1), so that never fires for it. +inline bool isDeclaratorClimbStop( const char* pt ) noexcept +{ + return kindIs( pt, "class_specifier" ) || kindIs( pt, "struct_specifier" ) + || kindIs( pt, "field_declaration_list" ) || kindIs( pt, "declaration_list" ) + || kindIs( pt, "namespace_definition" ) || kindIs( pt, "enum_specifier" ) + || kindIs( pt, "translation_unit" ) || kindIs( pt, "source_file" ) // Swift top + || kindIs( pt, "class_body" ) || kindIs( pt, "protocol_body" ) // Swift type bodies + || kindIs( pt, "enum_class_body" ) + || kindIs( pt, "class_interface" ) || kindIs( pt, "class_implementation" ) // ObjC + || kindIs( pt, "implementation_definition" ) || kindIs( pt, "protocol_declaration" ) + || kindIs( pt, "compound_statement" ) || kindIs( pt, "block" ); +} + +// What the declarator climb found: the span to adopt (null: keep the capture's own), the body it owns, and whether the role node +// is a body-less C/C++ type specifier in a function's signature (a type use, never a definition). +struct DeclaratorClimb +{ + TSNode span {}; + TSNode body {}; + bool typeUseInSignature = false; +}; + +// At a scope stop: the member/decl wrapper the climb came up through (a prototype's span, so the RETURN TYPE is included), else null. +inline TSNode declarationWrapperOrNull( TSNode child ) noexcept +{ + const char* ct = ts_node_type( child ); + return kindIs( ct, "field_declaration" ) || kindIs( ct, "declaration" ) ? child : TSNode{}; +} + +// At the first ancestor owning a body: adopt it when the role node is its signature (outside the body) and not a body-less type +// specifier; a body-less type specifier outside the body is a type use in the signature. +inline DeclaratorClimb bodyOwnerClimb( TSNode owner, TSNode ownerBody, TSNode roleNode, bool bodylessTypeSpec ) +{ + const bool outsideBody = !spanContains( ownerBody, roleNode ); + if( outsideBody && !bodylessTypeSpec ) + { + return DeclaratorClimb{ .span = owner, .body = ownerBody }; + } + return DeclaratorClimb{ .typeUseInSignature = outsideBody && bodylessTypeSpec }; +} + +// The C++ tags query captures @definition on the function_declarator (name+params) — its span excludes the return type AND the +// body. Walk up to the nearest ancestor owning a "body" field (the real function_definition) so [startByte,endByte) spans the +// WHOLE def: return type + signature + body. Fixes --expand bodies, --pack-signatures return-types, AND reference +// enclosing-attribution (a call in a body is now inside its function span). At a scope stop, a prototype/declaration takes its +// member/decl wrapper as the span so the RETURN TYPE is included (not just the declarator), WITHOUT grabbing the class body. +// +// An ancestor's span is adopted only if the role node sits OUTSIDE its body — i.e. it is the ancestor's own signature/declarator +// (the C++ function_declarator → function_definition hop this climb exists for). A def spelled INSIDE the body is a different, +// NESTED definition — a JS/TS named const-closure (`const f = (..) => {..}` in a function body) — and adopting here broadcast the +// encloser's whole span (loc/cx/params/nest) onto every such closure (webpack lib/html/syntax.js: eight closures inside the +// 3439-line `tokenize` all reported loc=3439 cx=487). The enclosing statement_block is not in the scope-stop list (only C-family +// compound_statement/block are), so nested defs escaped upward; containment is the grammar-agnostic stop. Gate: +// test/jsnestedcheck.sh. +// +// A BODY-LESS C/C++ type specifier — `enum cmd_retval` as a return type (`static enum cmd_retval⏎fn(…)`, tmux's style) or a +// parameter type — is captured by the tags query's bare enum/class pattern, and the climb ADOPTED the enclosing +// function_definition, whose body it sits outside of: the specifier took the WHOLE function's span, so --at chained +// `struct cmd_retval` around the function, --grep labelled its hits in="cmd_retval" and its calls were attributed to a `struct +// box_lines` caller (comparison table tmux-07/15, test/ccheck.sh). The adoption is for a function DECLARATOR. A type specifier +// whose climb reaches a body owner it sits outside of is a type USE in that function's signature, not a definition, so it mints +// NO def: keeping it as a small def of its own put a span in the return-type position wholly before the name — extentsuspect.h +// R3's derailed-parse signature — and flagged clean functions extent_suspect="head" (review of this lane, ccheck arm (f)). The +// declaration-wrapper rule at a scope stop is unchanged (`enum E : int;`, a prototype). +inline DeclaratorClimb climbDeclaratorToDefinition( TSNode roleNode, bool bodylessTypeSpec ) +{ + TSNode child = roleNode; + TSNode p = parentOf( roleNode ); + for( int guard = 0; !ts_node_is_null( p ) && guard < 4; ++guard ) + { + if( isDeclaratorClimbStop( ts_node_type( p ) ) ) + { + return DeclaratorClimb{ .span = declarationWrapperOrNull( child ) }; + } + if( const TSNode pb = fieldChild( p, NodeField::Body ); !ts_node_is_null( pb ) ) + { + return bodyOwnerClimb( p, pb, roleNode, bodylessTypeSpec ); + } + child = p; + p = parentOf( p ); + } + return DeclaratorClimb{}; +} + +// ObjC/Kotlin body-field fallback for the grammars that expose a body as an unnamed CHILD, not a named "body" field. C++ +// function_definition owns a "body" field (found by the climb); the ObjC grammar never does, so the field lookup returns null and +// bodyByte would stay 0 for a real definition — making an @implementation def indistinguishable from its @interface DECL (both +// bodyByte==0). That breaks BOTH the same-file decl/def collapse (3a-bis) and graph.h's cross-file hasBody +// (endByte > sigEndByte), doubling every ObjC symbol node AND its call edges. Recover the body-present signal from a direct child: +// - a METHOD def: a bare `compound_statement` / `function_body` / `block` child (the `{...}`). +// - an ObjC CLASS: an @implementation carries `implementation_definition` member children; the +// matching @interface carries only `method_declaration`s → so an `implementation_definition` +// child is exactly "this is the class's definition, not its forward @interface". +// - Kotlin: `function_body` / `class_body` / `enum_class_body` are positional children too +// (function_declaration's only named field is `receiver`), and the cost of missing them is +// the same collapse bug in the other direction — a Kotlin definition read as bodyless is +// deleted from the candidate pool as a forward declaration whenever a same-named Java +// definition exists (test/kotlincheck.sh §5). `enum_class_body` (`enum class Status { … }`) +// was the one omission a second-opinion review caught: `class_declaration`'s enum-class form +// nests its members under that node, not `class_body` — verified via a raw parse of +// `enum class Status { READY, DONE }` → `(class_declaration (type_identifier) +// (enum_class_body (enum_entry …) (enum_entry …)))`. +// A bodyLESS declaration (@interface method / @interface class) has none of these children → bodyByte stays 0 → it stays a decl +// (a bodyless KOTLIN TYPE does too, and is still a definition: model.h isDefinitionNotDeclaration). GATED to ObjC and Kotlin so +// C++/Python/Rust/Go/TS/Swift bodyByte — and therefore their sigEndByte, spans, and node/edge output — are BYTE-for-byte unchanged +// (a .mm's C++ functions take the C "body"-field path and never reach here). See test/langcheck.sh c.m and the byte-identical +// src/ regression gate. O(children): `- (void) m /*…*/ { }` puts the comments in the method_definition, before its body — 24x at +// 16 000 (test/childwalkscalecheck.sh, arm B35). +// +// Proto (PROTO-INDEX): the grammar names no `body:` field. A message's or enum's body is its *_body child; a service's, an rpc's +// option block's and a oneof's body starts at its `{` token (an rpc ending in `;` has none). +inline TSNode positionalBodyOf( Lang lang, TSNode defNode ) +{ + TSNode body {}; + if( lang == Lang::ObjC || lang == Lang::Kotlin ) + { + body = firstChildOfKind( defNode, /*namedOnly=*/false, + { "compound_statement", "function_body", "block", "implementation_definition", "class_body", "enum_class_body" } ); + } + if( ts_node_is_null( body ) && langFacts( lang ).generatedSchema ) + { + body = firstChildOfKind( defNode, /*namedOnly=*/false, { "message_body", "enum_body", "{" } ); + } + return body; +} + +// A definition's span and body. defBodyNodeOf = the `body:` field, PLUS the macro-edges round's one addition: a #define's +// replacement text (`value:` field) is adopted as a macro symbol's body, set before the climb so the climb is skipped for macros +// — PLUS a name bound to a function literal (kFnLiteralBinding): the literal's body, with `literal` the node params/cx/nest read +// from. Grammars whose @definition node already owns the body (class/struct/enum) don't climb. +// +// A Var's span is its own declaration — never climb. The climb exists to find a FUNCTION's body; for a var it can only steal a +// container's span (a Ruby class-level constant's parent chain is body_statement → class, and class owns a "body" field, so the +// climb would hand the constant THE WHOLE CLASS — the exact Rust-method span bug the H4 W3 note describes). No-op for every +// pre-existing Var capture (Swift/C#/Go/Python parents hit a scope-stop or the file root before any "body"-owning ancestor — +// verified byte-identical on the gate corpora). A Field's span is its own field_declaration / defining assignment — the Var rule, +// same reason. std::nullopt: the capture mints no definition (a test macro block without its parts, a type use in a signature). +inline std::optional definitionSpanOf( const TagsPass& pass, TagsMatch& m ) +{ + const Lang lang = pass.le.lang; + const DefBodyNodes own = lang == Lang::Elixir ? DefBodyNodes{ elixirBody( m.roleNode, pass.src ), {}, m.roleNode } + : defBodyNodeOf( m.roleNode, m.name.node, m.kind, lang ); + DefCodeNodes span; + span.defNode = own.span; + span.body = own.body; + span.literal = own.literal; + span.testMacroBlock = m.defCap == "definition.testmacroblock"; + if( span.testMacroBlock && !adoptTestMacroBlock( pass, m, span ) ) + { + return std::nullopt; + } + if( ts_node_is_null( span.body ) && m.kind != SymKind::Var && m.kind != SymKind::Field && lang != Lang::Elixir ) + { + const DeclaratorClimb climb = climbDeclaratorToDefinition( m.roleNode, isCFamilyTypeSpecifier( lang, m.roleNode ) ); + if( climb.typeUseInSignature ) + { + return std::nullopt; // a body-less C/C++ specifier in a function's signature: a type use, never a definition + } + span.defNode = ts_node_is_null( climb.span ) ? span.defNode : climb.span; + span.body = climb.body; + } + + // MACRO-P1: a prototype adopts its trailing annotation's definition body, its span running THROUGH that sibling + const TSNode ownBody = span.body; + span.body = annotatedSiblingBody( span.body, lang, m.kind, m.roleNode, pass.src ); + bool siblingBody = !ts_node_eq( span.body, ownBody ); + if( ts_node_is_null( span.body ) ) + { + span.body = positionalBodyOf( lang, span.defNode ); + } + // Dart's body is a SIBLING of the signature, so neither defBodyNodeOf nor the climb can find it and the span would stop at the + // signature — see dartFollowingBody (ingest_relations.h) for the measurement and for why an abstract member still comes back null. + if( ts_node_is_null( span.body ) && lang == Lang::Dart ) + { + span.body = dartFollowingBody( span.defNode ); + siblingBody = !ts_node_is_null( span.body ); + } + span.spanThroughBody = span.testMacroBlock || siblingBody; + return span; +} + +// The byte extents: the span (LB-E: through the sibling block), the name, the body. INDEX-ALIAS-CONST: a body-less alias row's +// target start rides bodyByte to the model, which moves it to IngestResult::aliasTargets and keeps the whole declaration as the +// signature (ingest_model.h rawDefIsAliasRow); 0 when the target is not a suffix. +inline void fillDefinitionExtent( RawDef& d, const DefCodeNodes& span, std::uint32_t nameByte, std::uint32_t aliasTargetStart ) noexcept +{ + d.startByte = ts_node_start_byte( span.defNode ); + d.endByte = span.spanThroughBody ? ts_node_end_byte( span.body ) : ts_node_end_byte( span.defNode ); + d.nameByte = nameByte; + d.bodyByte = ts_node_is_null( span.body ) ? 0u : ts_node_start_byte( span.body ); + if( d.bodyByte == 0 && aliasTargetStart > d.startByte && aliasTargetStart < d.endByte ) + { + d.bodyByte = aliasTargetStart; // INDEX-ALIAS-CONST: the transport only (ingest_model.h rawDefIsAliasRow) + } +} + +// A callable's cc_walk facts (complexityOf) onto its definition: all 0 off a callable, where complexityOf did not run. The narrower +// fields saturate on purpose — ppalt (model.h Symbol::ppAlt): a def past 65535 is beyond every triage threshold, and the attribute's +// claim ("the body carries alternatives") is already made at 1; the nesting profile (model.h Symbol::humps/deepLoc): deepLoc is a +// floor already, so a clamp there stays honest in the direction the attribute already claims; essential complexity (model.h +// Symbol::ev) is already saturated inside ev_finalize, 0 for non-function kinds and outside evCountedLang, matching the emitters' +// omission rule; QD-TANGLE's steering locals and dispatch share (model.h Symbol::steer, ::dispatchShare). +inline void fillDefinitionComplexity( RawDef& d, const Complexity& c ) noexcept +{ + d.cx = c.cx; + d.ccx = c.ccx; + d.locals = c.locals; // Phase 1: floor count, C/C++ only (model.h localsCountedLang) — 0 elsewhere, never emitted there + d.ppAlt = saturatedTo( c.ppAlt ); + d.maxNest = saturatedTo( c.maxNest ); + d.steer = saturatedTo( c.steer ); + d.deepDispatch = saturatedTo( c.deepDispatch ); + d.nestArmCut = saturatedTo( c.nestArmCut ); + d.humps = saturatedTo( c.humps ); + d.deepLoc = saturatedTo( c.deepLoc ); + d.ev = saturatedTo( c.ev ); + d.evWhy = c.evWhy; +} + +// A callable's parameter count: Elixir's and Clojure's heads have their own readers; every other language counts the list. +inline std::uint16_t definitionParamCount( Lang lang, TSNode defNode, TSNode metricNode, bool literalBound, std::string_view src ) +{ + if( lang == Lang::Elixir ) + { + return elixirParams( defNode, src ); + } + return lang == Lang::Clojure ? clojureParams( defNode, src ) : paramCountOf( metricNode, literalBound ); +} + +// The definition's shape: complexity (LB-E: a testmacroblock's body SIBLING is where the code lives — complexityOf walks INSIDE its +// root node, so handing it defNode, the bare macro statement, would count nothing; a literal-bound name measures its LITERAL; every +// other def measures defNode), Q4 size smells (SIZE = master variable: physical LOC = span line count; param count + max nesting +// for functions/methods only, 0 otherwise, absent in emit — all descriptive), the parameter shape, the in-file test-scope bit. +inline void fillDefinitionShape( const TagsPass& pass, RawDef& d, const TagsMatch& m, const DefCodeNodes& span, const AnnotationRename& renamed ) +{ + const Lang lang = pass.le.lang; + const bool fnOrMethod = ( m.kind == SymKind::Function || m.kind == SymKind::Method ); + const bool literalBound = !ts_node_is_null( span.literal ); + const TSNode metricNode = literalBound ? span.literal : span.defNode; + fillDefinitionComplexity( d, + fnOrMethod && pass.shape ? complexityOf( span.spanThroughBody ? span.body : metricNode, pass.src, lang ) + : Complexity{ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, {}, 0u, 0u, 0u } ); + const std::uint32_t startRow = ts_node_start_point( span.defNode ).row; + const std::uint32_t endRow = ts_node_end_point( span.spanThroughBody ? span.body : span.defNode ).row; // LB-E: rows through the sibling block + d.loc = ( endRow >= startRow ) ? ( endRow - startRow + 1u ) : 1u; + d.params = fnOrMethod ? definitionParamCount( lang, span.defNode, metricNode, literalBound, pass.src ) : std::uint16_t( 0 ); + // LB-E: a testmacroblock's parameter surface is the MACRO's business, not visible here — claim inexact so the resolver's arity + // narrowing never trusts params=0 on a test-title symbol. B2.2: the fixed-arity bit and the minimum (fewest arguments a call can + // pass) come from ONE scan of the list. A minimum above the counted params (a literal-bound bare parameter countParams cannot + // see) is not trusted. + const ParamShape paramShape = ( fnOrMethod && !span.testMacroBlock && lang != Lang::Clojure ) ? cc_paramShape( metricNode, lang, m.kind, pass.src ) : ParamShape{}; + d.arityExact = paramShape.exact ? std::uint8_t( 1 ) : std::uint8_t( 0 ); + d.paramsMin = paramShape.minimum <= d.params ? paramShape.minimum : std::uint16_t( 0 ); + applyAnnotationRename( d, renamed, span.defNode ); // MACRO-P1: the real function's parameters and start, not the annotation's + // L8: the in-file test-scope bit, for EVERY kind (a `#[cfg(test)] mod` and a `class TestFoo` are themselves symbols, and dropping + // the members while keeping the shell would be a worse answer than either). Runs on defNode, whose ancestors are the enclosing scopes. + d.testScope = span.testMacroBlock ? std::uint8_t( 1 ) : std::uint8_t( inFileTestScope( span.defNode, pass.src, lang ) ); // LB-E: a test macro IS the in-file convention + d.kind = m.kind; + d.lang = lang; +} + +// An Elixir module attribute's definition name: a typed attribute (@type/@callback and kin) is named with its arity, any other +// attribute is `@name`. +inline std::string elixirAttributeDefName( std::string_view attribute, const TagsMatch& m ) +{ + if( !elixirTypedAttribute( attribute ) ) + { + return "@" + std::string( m.name.text ); + } + const TSNode args = elixirArguments( parentOf( m.name.node ) ); + std::uint32_t arity = 0; + for( std::uint32_t i = 0; !ts_node_is_null( args ) && i < ts_node_named_child_count( args ); ++i ) + { + arity += elixirNodeIs( ts_node_named_child( args, i ), "comment" ) ? 0u : 1u; + } + return ( attribute == "callback" || attribute == "macrocallback" ? "@callback " : "@type " ) + elixirFunctionName( m.name.text, arity ); +} + +// `defimpl P, for: T` — the @name capture is just the protocol alias, but the module Elixir generates is `P.T`, which is what the +// impl's own defs carry as their scope. A protocol is an Interface, a module that defines a struct (or exception) a Struct. +inline SymKind elixirModuleKind( const TagsPass& pass, TSNode roleNode, const std::string& module ) +{ + const SymKind kind = elixirTarget( roleNode, pass.src ) == "defprotocol" ? SymKind::Interface : SymKind::Class; + for( TSNode call : pass.elixir.calls ) + { + const auto keyword = elixirTarget( call, pass.src ); + if( ( keyword == "defstruct" || keyword == "defexception" ) && pass.elixir.scopeOf( call ) == module ) + { + return SymKind::Struct; + } + } + return kind; +} + +// Elixir's definition names: a static ExUnit title (interpolation was rejected by elixirKeepCapture), a module attribute, a +// generated module. false: a module with no name to give it. +inline bool nameElixirDefinition( const TagsPass& pass, RawDef& d, const TagsMatch& m ) +{ + if( elixirTarget( m.roleNode, pass.src ) == "test" ) + { + d.name = "test " + std::string( m.name.text.substr( 1, m.name.text.size() - 2 ) ); + d.testScope = 1; + return true; + } + if( const std::string_view attribute = elixirAttribute( m.roleNode, pass.src ); !attribute.empty() ) + { + d.name = elixirAttributeDefName( attribute, m ); + return true; + } + if( m.kind != SymKind::Other ) + { + return true; + } + d.name = pass.elixir.moduleName( m.roleNode ); + if( d.name.empty() ) + { + return false; + } + d.kind = elixirModuleKind( pass, m.roleNode, d.name ); + return true; +} + +// The definition's name: the capture's (LB-E: a test title is a display string — see testMacroTitleOf), the file's stem for the +// module's own CommonJS export function (lane js-def-naming, ingest_names.h isCjsModuleExportsItself), Elixir's own. false: the +// capture mints no row (no stem to name an anonymous export by, as before; an unnamed Elixir module). +inline bool nameDefinition( const TagsPass& pass, RawDef& d, const TagsMatch& m, bool testMacroBlock ) +{ + d.name = testMacroBlock ? std::string( m.name.text ) : defNameFromCapture( pass.le.lang, m.name.text ); + if( m.defCap == "definition.cjsexport" && isCjsModuleExportsItself( m.name.node, pass.src ) ) + { + if( pass.fileStem.empty() ) + { + return false; + } + d.name = std::string( pass.fileStem ); + } + return pass.le.lang != Lang::Elixir || nameElixirDefinition( pass, d, m ); +} + +// A FUNCTION bound inside another function's body records that function's span (ingest_names.h enclosingFunctionScope): graph.h +// reachableByName ranks it below every def a call outside it can name. Descend to the OUTER of the two def nodes: a C-family def's +// defNode climbed from its declarator (the role node) to the function_definition, which must not read as the function enclosing +// itself; a multi-name binding's defNode narrowed to one declarator, whose declaration (the role node) holds no scope node and is +// not a 20k-child list to rescan per name. +inline void noteEnclosingFunctionScope( const TagsPass& pass, RawDef& d, const TagsMatch& m, TSNode defNode ) +{ + if( !pass.full || m.kind != SymKind::Function || bindsOutsideItsFunction( m.roleNode, pass.le.lang ) ) + { + return; + } + const bool defIsOuter = ts_node_start_byte( defNode ) <= ts_node_start_byte( m.roleNode ) && ts_node_end_byte( defNode ) >= ts_node_end_byte( m.roleNode ); + const FnScope fnScope = enclosingFunctionScope( pass.root, defIsOuter ? defNode : m.roleNode ); + d.fnScopeStart = fnScope.start; + d.fnScopeEnd = fnScope.end; +} + +// `defdelegate f(x), to: M, as: g`: the delegating clause calls M.g with its own arity. +inline void emitElixirDelegate( const TagsPass& pass, const RawDef& d, const TagsMatch& m ) +{ + RawRef delegated; + delegated.fileId = pass.fileId; delegated.startByte = d.startByte; delegated.line = d.line; + delegated.lang = pass.le.lang; delegated.recv = RecvKind::ElixirModule; + delegated.qualifier = pass.elixir.moduleOf( elixirKeywordValue( m.roleNode, "to:", pass.src ), m.roleNode ); + const auto as = nodeTextOf( elixirKeywordValue( m.roleNode, "as:", pass.src ), pass.src ); + delegated.name = elixirFunctionName( as.starts_with( ":" ) ? as.substr( 1 ) : m.name.text, d.params ); + delegated.argCount = d.params; delegated.argCountKnown = true; + if( !delegated.qualifier.empty() ) { pass.refs.push_back( std::move( delegated ) ); } +} + +// An Elixir definition's scope, and for a def head (#355: the match's own @_keyword capture, decided by tags.scm, not a C++ keyword +// list) its arity-qualified name. B2.2 for Elixir: a clause's arity IS its parameter count (no variadic form), so `params` is +// call-comparable unless a `\\` default widens the callable to more than one arity. cc_paramShape's language gate leaves this at 0, +// which made every Elixir caller unflaggable by --edit-check (test/elixirnamearitycheck.sh arm C: run(x) -> run(x, y) must flag +// run(x) callers; run(x, y \\ 1) must flag none). +inline void scopeElixirDefinition( const TagsPass& pass, RawDef& d, const TagsMatch& m ) +{ + d.scope = m.kind == SymKind::Other ? std::string{} : pass.elixir.scopeOf( m.roleNode ); + if( !m.keywordHead ) + { + return; + } + d.name = elixirFunctionName( m.name.text, d.params ); + d.arityExact = elixirHeadDefaultCount( m.roleNode, pass.src ) == 0 ? std::uint8_t( 1 ) : std::uint8_t( 0 ); + elixirDefinitionFacts( d, m.roleNode, pass.src, pass.binds, pass.elixir.keywords ); + if( elixirTarget( m.roleNode, pass.src ) == "defdelegate" ) + { + emitElixirDelegate( pass, d, m ); + } +} + +// A C++ definition's canonical scope (E#4): out-of-line `A::b` → "A", else the enclosing class/namespace. +inline void scopeCppDefinition( RawDef& d, TSNode nameNode, std::string_view src ) +{ + d.scope = qualifierOfDefinition( nameNode, src ); // `Box::grow` (primary) → "Box"; a specialization keeps its id + if( d.scope.empty() ) + { + d.scope = enclosingScopeOf( nameNode, src ); + } + // #150: is this def genuinely INSIDE namespace std, at ANY nesting depth — not just a def + // whose immediate scope happens to spell a segment std also uses? See Symbol::scopeRootsStd. + d.scopeRootsStd = cppDefinitionRootsStd( nameNode, src ) ? std::uint8_t( 1 ) : std::uint8_t( 0 ); +} + +// The definition's scope, per language. +inline void scopeDefinition( const TagsPass& pass, RawDef& d, const TagsMatch& m, TSNode defNode ) +{ + const Lang lang = pass.le.lang; + if( lang == Lang::Cpp ) + { + scopeCppDefinition( d, m.name.node, pass.src ); + } + else if( enumTableAt( kDefScopeWalkerOfLang, lang, DefScopeWalker::None ) != DefScopeWalker::None ) + { // Python, Go, Rust, Kotlin: the language's row in ingest_names.h kDefScopeWalkerOfLang + d.scope = defScopeOf( lang, m.name.node, pass.src ); + } + else if( lang == Lang::Elixir ) + { + scopeElixirDefinition( pass, d, m ); + } + else if( lang == Lang::Ruby ) + { // enclosing class/module → id= addressability, per-class overload sets, editCheckImplicitReceiver + d.scope = rubyEnclosingScopeOf( m.name.node, pass.src ); // (test/rubyscopecheck.sh) + if( m.kind == SymKind::Method || m.kind == SymKind::Function ) + { + rubyNoteClassSideDef( defNode, pass.fileId, d.name, pass.src, pass.binds ); // a class object's method (test/rubyclassrecvcheck.sh) + } + } + else if( ( lang == Lang::JavaScript || lang == Lang::TypeScript ) && m.defCap == "definition.protomethod" ) + { // only the five built-in ctors: every Foo.prototype.bar gaining sc= would mint a new + // canonical id and move quality baselines (node lib/ has ~163 anonymous protomethods) + const std::string_view ctor = prototypeCtorName( m.name.node, pass.src ); + if( isJsTsBuiltinCtor( ctor ) ) + { + d.scope = std::string( ctor ); + } + } +} + +// The reference edges a definition mints (TagsCapture::Full only): a type's IS-A and HAS-A edges, a macro's body calls. +inline void captureDefinitionEdges( const TagsPass& pass, const TagsMatch& m, TSNode defNode ) +{ + const Lang lang = pass.le.lang; + if( m.kind == SymKind::Class || isStructOrNamedType( m.kind ) || m.kind == SymKind::Interface ) + { + // #446: a language on the bases-as-captures port reads its bases through the + // @reference.base reader (LangFacts::basesAsCaptures; C++ is the first). The + // others keep the walk; C++'s own walk survives for captureSpecializationHeader. + if( !langFacts( lang ).basesAsCaptures ) + { + captureBases( defNode, pass.fileId, lang, pass.src, pass.refs ); // IS-A: inheritance edges (derived → base) + } + if( m.defCap == "definition.classfactory" ) // lane lego-transitive (M2): the factory's receiver is the base + { + emitBaseRef( jsClassFactoryReceiver( m.name.node, pass.src ), pass.fileId, lang, pass.src, pass.refs, defNode ); + } + captureFields( defNode, pass.fileId, lang, pass.src, pass.refs ); // HAS-A: member-variable type edges (S5-E) + } + else if( m.kind == SymKind::Macro ) + { + captureMacroBodyCalls( m.roleNode, pass.fileId, lang, pass.src, pass.refs ); // macro-edges: the graph connects THROUGH the macro + if( langFacts( lang ).bangMacros ) // Rust: `$crate` exists only where `name!` macros do + { + captureRustTranscriberMacroCalls( m.roleNode, pass.fileId, pass.src, pass.refs ); // RUST-MACRO-PATH: `$crate::m!` in a transcriber + } + } +} + +// The definition arm: span, extents, shape, name, linkage, function scope, scope and parse-recovery bits into one RawDef, then +// (Full) the edges it mints. `renamed`: MACRO-P1's annotation rename; `aliasTargetStart`: INDEX-ALIAS-CONST's written target. +void captureDefinition( const TagsPass& pass, TagsMatch& m, const AnnotationRename& renamed, std::uint32_t aliasTargetStart ) +{ + if( pass.le.lang == Lang::Elixir && m.defCap == "definition.attribute" ) { m.kind = SymKind::Var; } + const std::optional span = definitionSpanOf( pass, m ); + if( !span ) + { + return; + } + RawDef d; + d.fileId = pass.fileId; + d.line = m.name.row + 1; // the identifier's line — most accurate, dedup-stable (a test macro block's: its title's, re-seated above) + fillDefinitionExtent( d, *span, m.name.byte, aliasTargetStart ); + fillDefinitionShape( pass, d, m, *span, renamed ); + if( !nameDefinition( pass, d, m, span->testMacroBlock ) ) + { + return; + } + // Internal linkage (model.h Symbol::internalLinkage): C and C++ only, read off defNode — the node that owns + // the storage class and whose ancestors are the enclosing namespaces (ingest_names.h::cppInternalLinkage). + d.internalLinkage = internalLinkageBit( pass.le.lang, span->defNode, pass.src ); + noteEnclosingFunctionScope( pass, d, m, span->defNode ); + scopeDefinition( pass, d, m, span->defNode ); + // extent honesty: did the parse RECOVER this def's container or kind? Only asked in a file whose root + // holds an error (fileHasError, one O(1) flag test per file) — see parseRecoveredBits. + d.recovered = pass.fileHasError ? parseRecoveredBits( span->defNode, m.kind, pass.le.lang, d.scope.empty() ) : std::uint8_t( 0 ); + pass.defs.push_back( std::move( d ) ); + if( pass.full ) // TagsCapture::DefinitionsOnly: the reference edges feed no definition + { + captureDefinitionEdges( pass, m, span->defNode ); + } +} + +// The reference captures that are not a plain use-site. true: consumed here — emitted as their own fact, or dropped. +inline bool consumeSpecialReference( const TagsPass& pass, const TagsMatch& m ) +{ + const Lang lang = pass.le.lang; + // An element access: @name is its RECEIVER, and the site names the receiver class's subscript operator + // method (ingest_binds.h subscriptOperatorRef) — never a call by itself (RefRole::Subscript). + if( m.refCap == "reference.subscript" ) + { + if( std::optional sub = subscriptOperatorRef( m.roleNode, m.name.node, pass.fileId, lang, pass.src ) ) + { + pass.refs.push_back( std::move( *sub ) ); + } + return true; + } + // H4: a C++ cast keyword is not a call — see isCppCastKeyword. Valid input, skipped, no alert. + if( lang == Lang::Cpp && isCppCastKeyword( m.name.text ) ) + { + return true; + } + // #285: an intrinsic JSX tag (`
`, `

`) is not a call — see isJsxIntrinsicTagIdentifier. + // Valid input, skipped, no alert; a qualified (``) or namespaced (``) + // tag never reaches this test (see that function's note for why). + if( ( lang == Lang::TypeScript || lang == Lang::JavaScript ) && isJsxIntrinsicTagIdentifier( m.roleNode, m.name.node, m.name.text ) ) + { + return true; + } + // using-declaration re-exports (r9 loss bucket 1): @reference.import marks the C++ + // `using ns::name;` tags pattern. The site becomes a role="import" use-site of the target + // (never a call edge — graph.h admits Call+Macro only), and the grammar KEYWORD forms + // (`using namespace ns;` / `using enum E;`) are dropped here at capture time, where the + // query predicate a tags pattern cannot express IS enforceable (see the helper's note). + if( m.refCap == "reference.import" && usingDeclarationIsDirective( m.roleNode ) ) + { + return true; + } + // family 4 / slice 4a: a @reference.mixin capture is Ruby's `include`/`extend`/`prepend` — the shape + // lives in queries/ruby/tags.scm, so the capture IS the language gate and no Lang:: branch is spent + // here. The two guards a tags pattern cannot state (the directive's TEXT, and its POSITION) live in + // the Ruby reader, ingest_ruby.h emitCapturedRubyMixinBase, which takes the language from this call + // site and EXPECTS Ruby: Ruby is the capture's only emitter today, and a second language adds its own + // reader and dispatch here rather than reusing Ruby's. The directive's own CALL reference is a + // separate match. + if( m.refCap == "reference.mixin" ) + { + emitCapturedRubyMixinBase( m.roleNode, m.name.node, pass.fileId, lang, pass.src, pass.refs ); + return true; + } + // #446: a @reference.base capture is a base-clause type on the class-def path — + // queries//tags.scm names the clause's type node, so the capture IS the language + // gate. The clause's parent is the class node (emitBaseRef's `self`), the same pairing + // the captureBases walk passed; C++ is the first language on this capture. + if( m.refCap == "reference.base" ) + { + emitBaseRef( m.name.node, pass.fileId, lang, pass.src, pass.refs, parentOf( m.roleNode ) ); + return true; + } + return false; +} + +// An Elixir reference's module, role and arity-qualified name. false: `r` is finished here — an attribute read pushed as its own +// fact, or a call whose module or arity is unknown (dropped). +inline bool qualifyElixirReference( const TagsPass& pass, const TagsMatch& m, RawRef& r ) +{ + r.qualifier = pass.elixir.scopeOf( m.roleNode ); + if( m.refCap == "reference.attribute" ) + { + r.role = RefRole::Read; r.name = "@" + std::string( m.name.text ); + pass.refs.push_back( std::move( r ) ); + return false; + } + const TSNode target = fieldChild( m.roleNode, NodeField::Target ); + if( !ts_node_is_null( target ) && kindIs( ts_node_type( target ), "dot" ) ) + { + const TSNode receiver = fieldChild( target, NodeField::Left ); + r.qualifier = pass.elixir.moduleOf( receiver, m.roleNode ); + if( r.qualifier.empty() ) { return false; } + // `__MODULE__` spelled, or an alias of it (`alias __MODULE__, as: Current`): the receiver names the + // enclosing module, and the reference is re-attributed per implementation of a multi-target defimpl + r.recv = nodeTextOf( receiver, pass.src ).starts_with( "__MODULE__" ) || pass.elixir.selfRelativeAlias( receiver, m.roleNode ) + ? RecvKind::ElixirSelfModule : RecvKind::ElixirModule; + } + auto [ count, known ] = elixirCallArity( m.roleNode, m.name.node, pass.src ); + if( m.refCap == "reference.operator" ) { count = elixirNodeIs( m.roleNode, "binary_operator" ) ? 2 : 1; known = true; } + if( !known ) { return false; } + r.argCount = count; r.argCountKnown = true; + r.name = elixirFunctionName( m.name.text, count ); + return true; +} + +// A C++ or Rust reference's qualifier as written. Returns RULE3-MEMBER-GUARD fix 4's Rust path-call qualifier as written, when +// longer than one segment ("" otherwise) — set by readReceiverFacts once the receiver fields are. +inline std::string qualifyPathReference( const TagsPass& pass, const TagsMatch& m, RawRef& r ) +{ + const Lang lang = pass.le.lang; + std::string rustWritten; + if( lang == Lang::Cpp ) + { + r.qualifier = qualifierOf( m.name.node, pass.src ); // `A::b()` → "A" (E#4 canonical resolve) + // #150: the FULL written chain's root, BEFORE the H4 re-split below overwrites r.qualifier + // with the immediate segment only (`std::ranges::move` loses "std", keeps "ranges") — see + // Reference::qualifierRootsStd and graph.h::keepStdQualifiedCandidates. + r.qualifierRootsStd = cppQualifiedChainRootsStd( m.name.node, pass.src ); + cppResplitRefName( r, m.name.text ); // H4 RE-SPLIT at 3+ segments, operator tails, `template` disambiguator + } + else if( langFacts( lang ).bangMacros && r.role == RefRole::Macro ) + { + // RUST-MACRO-PATH: `crate::m!`, `axum_core::m!`, `serde_json::json!`: the written path, which graph.h requires to prove the macro + const TSNode parent = parentOf( m.name.node ); + if( !ts_node_is_null( parent ) && kindIs( ts_node_type( parent ), "scoped_identifier" ) ) + { + std::string qualifier; + rustMacroPathOf( nodeTextOf( fieldChild( parent, NodeField::Path ), pass.src ), qualifier, rustWritten ); + r.qualifier = qualifier; + } + } + else if( lang == Lang::Rust ) + { + r.qualifier = rustQualifierOf( m.name.node, pass.src ); // H4: `Widget::new()` → "Widget" + if( r.role == RefRole::Call ) + { + rustWritten = rustWrittenQualifier( m.name.node, pass.src ); + } + } + return rustWritten; +} + +// A call site's receiver and argument facts (an import site has no receiver and no argument list — the defaults, +// RecvKind::None and argCountKnown=false, are the truth there; Elixir's were read by qualifyElixirReference). +inline void readReceiverFacts( const TagsPass& pass, const TagsMatch& m, RawRef& r, std::string rustWritten ) +{ + const Lang lang = pass.le.lang; + // FE-B: a Java method INVOCATION reads its receiver like every other language (a member call or a bare + // implicit-this call); only a method REFERENCE (`T::m`) keeps issue #74's type-candidate shape. + const bool javaMethodRef = lang == Lang::Java && !ts_node_is_null( m.roleNode ) && kindIs( ts_node_type( m.roleNode ), "method_reference" ); + RecvShape rs = javaMethodRef + ? javaMethodReferenceReceiver( m.roleNode, pass.src ) + : receiverOf( m.name.node, lang, pass.src ); // P2-D: `this`/`self`/`x`/`base.field` shape + r.recv = rs.kind; r.recvVar = rs.var; // → one-hop narrowing in resolve.h + r.setFieldName( std::move( rs.field ) ); // depth-2 intermediate field; "" otherwise + r.viaArrow = rs.viaArrow; // `p->m()`: Rule 2b's smart-pointer pointee needs it + r.memberCall = rs.member; r.memberRoot = rs.root; // FE-A: a Go/JS/TS/Rust member call and its receiver root + r.setMemberPath( std::move( rs.path ) ); r.setMemberCtor( std::move( rs.ctor ) ); // FE-B: the rest of that receiver chain + if( lang == Lang::Ruby && r.recv == RecvKind::NamedVar ) + { + r.setFieldName( rubyReceiverWrittenPath( m.name.node, r.recvVar, pass.src ) ); // parser version 137: a constant's path as written + } + auto [ ac, ak ] = callArity( m.name.node, lang, pass.src ); // B2.2: call-site positional arg count + r.argCount = ac; r.argCountKnown = ak; // → arity filter in graph.h + if( langFacts( lang ).trailingLambdaScopeFns ) + { + r.trailingLambda = kotlinTrailingLambda( m.roleNode ); // #155: `x.run { }` / `with( x ) { }` — graph.h FalseEdgeRules' Kotlin arm + } + if( !rustWritten.empty() ) + { + r.setFieldName( std::move( rustWritten ) ); // a Rust path call's whole written qualifier (model.h Reference::fieldName) + } + if( isQueueLang( lang ) && isQueueCallName( r.name ) ) + { + if( const std::uint8_t kw = callKeywords( m.name.node, pass.src ); kw != 0 ) + { + r.setComposeRel( pyKwTag( kw ) ); // a queue call's keywords, for QueueHops (model.h pyKwTag) + } + } +} + +// The reference arm (TagsCapture::Full only): a use-site's role, name, qualifier and receiver facts into one RawRef. +void captureReference( const TagsPass& pass, const TagsMatch& m ) +{ + if( consumeSpecialReference( pass, m ) ) + { + return; + } + const Lang lang = pass.le.lang; + const bool isImportRef = ( m.refCap == "reference.import" ); + RawRef r; + r.fileId = pass.fileId; + r.startByte = ts_node_start_byte( m.roleNode ); + r.line = ts_node_start_point( m.roleNode ).row + 1; // ABS-3: 1-based use-site line for --uses + r.lang = lang; + // ABS-3: @reference.call is a call use-site; @reference.import a using-decl re-export. EDGE-PRELUDE-VETO: @reference.macro is a macro + // invocation the grammar spells as one (Rust `name!(..)`): role Macro, so it binds only to an indexed macro of the name (graph.h). + r.role = isImportRef ? RefRole::Import : ( m.refCap == "reference.macro" ? RefRole::Macro : RefRole::Call ); + r.name = finalSegment( m.name.text ); + if( lang == Lang::Clojure ) + { + r.qualifier = nodeFieldText( parentOf( m.name.node ), NodeField::Namespace, pass.src ); + } + if( lang == Lang::Elixir ) + { + if( !qualifyElixirReference( pass, m, r ) ) + { + return; + } + } + else if( lang == Lang::Ruby && rubyCallIsAssignmentTarget( m.name.node ) ) + { + r.name.push_back( '=' ); // `obj.name = v` calls `name=`, never the getter `name` (test/rubysettercheck.sh) + } + std::string rustWritten = qualifyPathReference( pass, m, r ); + if( !isImportRef && lang != Lang::Elixir ) + { + readReceiverFacts( pass, m, r, std::move( rustWritten ) ); + } + pass.refs.push_back( std::move( r ) ); +} + +// One match with a role and a name, through the capture-time drop decisions in their order, then into the definition or the +// reference arm. +void captureTagsMatch( const TagsPass& pass, TagsMatch& m ) +{ + const Lang lang = pass.le.lang; + if( captureSpecializationHeader( m.isDef, lang, m.defCap, m.roleNode, m.name.node, pass.fileId, pass.src, pass.refs ) ) + { + return; // a C++ specialization header: its base clause only, never a symbol + } + + // C1 (memgraph F1) — see cppDefNameReseat. A null node is "nothing to re-seat". + if( const DefNameFacts reseated = cppDefNameReseat( m.isDef && lang == Lang::Cpp, m.name.node, pass.src ); !ts_node_is_null( reseated.node ) ) + { + m.name = reseated; + } + + // F5: drop Swift function-local `let`/`var` bindings — they are not module symbols and, left in, + // they steal the enclosing function's call edges (the last local binding above the call sites + // becomes the nearest enclosing symbol). roleNode is the `property_declaration`; a `statements` + // ancestor marks it as local. Real stored/computed members (class/struct/enum/top-level) survive. + if( m.isDef && m.kind == SymKind::Var && lang == Lang::Swift && isSwiftLocalBinding( m.roleNode ) ) + { + return; + } + + const std::optional aliasShape = aliasShapeOfCapture( lang, m ); + if( !aliasShape ) + { + return; + } + AnnotationRename renamed {}; + if( !keepAfterMacroInvocation( pass, m, renamed ) ) + { + return; + } + // the gated capture classes — r3 q10 constants (plus the §7b CUDA memory-space policy for the + // uninitialized C++ shape, which needs the captured declaration node), JS export/prototype + // assignments — in one drop decision (see dropGatedCapture for the per-class rationale and why + // none of this can live in the query as a #match?/#eq? predicate). + if( m.isDef && dropGatedCapture( m.defCap, lang, m.name.text, m.name.node, m.roleNode, pass.src ) ) + { + return; + } + const std::uint32_t aliasTargetStart = aliasShape->form != AliasForm::None ? aliasTargetStartOf( m.roleNode, *aliasShape ) : 0u; + + if( !keepLanguageCapture( pass, m ) ) + { + return; + } + if( consumeInertQuoteCapture( pass, m ) ) + { + return; + } + + if( m.isDef ) + { + captureDefinition( pass, m, renamed, aliasTargetStart ); + } + else if( m.isRef && pass.full ) + { + captureReference( pass, m ); + } +} + +// Ruby's own passes over the file, after the dead/field folds — neither touches Ruby (no preprocessor; Var is not a Field kind): +// Parser version 121 (test/rubyattrscheck.sh): the Ruby attr family's Var defs, inside the same defs window, so the lex build and +// cache round-trip treat these defs like captured ones. +// Parser version 130 (test/rubybarecallcheck.sh): Ruby's bare-word calls, by Ruby's own local rule, into the +// same refs window — the tags query cannot tell a bare call from a local read (both are an (identifier)). +// Parser version 132 (test/rubytypedrecvcheck.sh): the same walk types each call receiver the file builds, written +// into the call references this window holds; and FactoryBot's factory definitions, into binds. +// Parser version 135 (test/rubyrakejbuildercheck.sh): `helper_method` declarations into binds, and a Jbuilder +// template's `json` — a local, typed JbuilderTemplate — in the refs window. +// Parser version 137 (test/rubyclassrecvcheck.sh): the accessors a `class << self` declares, into binds as singleton +// methods — beside each singleton def, which the def capture notes. +// Parser version 145 (test/rubyclassrecvcheck.sh): the mixins the class object's lookup reaches — an `extend`, an +// `include` in `class << self` — into binds, beside the inherit reference each mixin already is. +inline void captureRubyFilePasses( const TagsPass& pass ) +{ + captureRubyDefs( pass.root, pass.fileId, pass.src, pass.defs ); // #339: the Definitions-only walker (attr defs + rendered db/schema.rb columns) + if( !pass.full ) + { + return; // TagsCapture::DefinitionsOnly: the passes below write references and binds only + } + captureRubyBareCalls( pass.root, pass.fileId, pass.src, pass.refs ); + captureRubyFactories( pass.root, pass.fileId, pass.src, pass.binds ); + captureRubyHelperMethods( pass.root, pass.fileId, pass.src, pass.binds ); + captureRubySingletonAccessors( pass.root, pass.fileId, pass.src, pass.binds ); + captureRubyClassMixins( pass.root, pass.fileId, pass.src, pass.binds ); + captureRubyMainMixins( pass.root, pass.fileId, pass.src, pass.binds ); + if( pass.le.ext == kJbuilderExt ) + { + typeRubyJbuilderLocal( pass.fileId, pass.refs ); + } +} + /// Append definitions and references captured by the language query, with language-specific filtering. /// Captured spans refer to src and root; a null cursor appends nothing. Existing output rows are retained. /// `ppDead` is this file's decided-dead byte ranges (preprocDeadRangesFor, computed ONCE per file by the @@ -1904,8 +3045,6 @@ void captureTagsFacts( TSQueryCursor* cursor, const LangEntry& le, std::uint32_t const std::vector& ppDead, ExtractShortfall& shortfall, TagsCapture mode = TagsCapture::Full, std::string_view fileStem = {} ) // the file's stem: the name of a bare `module.exports = ` (JS) { - const bool full = mode == TagsCapture::Full; - const bool shape = mode != TagsCapture::DefinitionsOnly; // the callables' cc_walk facts (Full or DefinitionsAndShape) if( cursor == nullptr ) { return; @@ -1936,9 +3075,9 @@ void captureTagsFacts( TSQueryCursor* cursor, const LangEntry& le, std::uint32_t elixir.shortfall = &shortfall; if( le.lang == Lang::Elixir ) { elixir.prepare( cursor, query, root, src, fileId, binds, includes, refs ); } - // extent honesty: the recovered-bit walk (parseRecoveredBits) only exists in a file the parser had to recover. - const bool fileHasError = ts_node_has_error( root ); - + const TagsPass pass{ .le = le, .fileId = fileId, .src = src, .root = root, .defs = defs, .refs = refs, .binds = binds, .includes = includes, + .shortfall = shortfall, .elixir = elixir, .fileStem = fileStem, .full = mode == TagsCapture::Full, .shape = mode != TagsCapture::DefinitionsOnly, + .fileHasError = ts_node_has_error( root ) }; { PROFILE_SCOPE_DESCRIBE( "ingest/extractFile: tags query exec+captures" ); ts_query_cursor_exec( cursor, query, root ); @@ -1953,828 +3092,12 @@ void captureTagsFacts( TSQueryCursor* cursor, const LangEntry& le, std::uint32_t { continue; } - // A tags pattern yields one @definition/@reference node + a child @name. - // Walk this match's captures: remember the role node + the name text. - SymKind kind = SymKind::Other; - bool isDef = false; - bool isRef = false; - std::string_view defCapSv; // the @definition capture's name — dropGatedCapture keys the constant/cjsexport/protomethod gates on it - std::string_view refCapSv; // the @reference capture's name — "reference.import" routes the using-declaration role (r9 loss bucket 1) - TSNode roleNode {}; - bool haveRole = false; - std::string_view nameTxt; - uint32_t nameByte = 0; - uint32_t nameRow = 0; // 0-based row of the @name identifier - bool haveName = false; - TSNode nameNode {}; // the @name identifier node — for C++ scope/qualifier (E#4) - TSNode importNamesNode {}; // one clause's target, paired with its optional alias (emitCapturedImportBind) - TSNode importAliasNode {}; - bool keywordHead = false; // #355: the pattern carried @_keyword, a head its tags.scm predicates accepted - - for( uint16_t ci = 0; ci < match.capture_count; ++ci ) - { - const TSQueryCapture& cap = match.captures[ ci ]; - - uint32_t nameLen = 0; - const char* capName = ts_query_capture_name_for_id( query, cap.index, &nameLen ); - const std::string_view capSv( capName, nameLen ); - if( capSv == "_keyword" ) - { - keywordHead = true; // a predicate-only capture: roleOf ignores it, the definition keyword is its pattern's #any-of? - } - - SymKind k = SymKind::Other; - switch( roleOf( capSv, k ) ) - { - case CapRole::Def: - { - isDef = true; - kind = k; - defCapSv = capSv; - roleNode = cap.node; - haveRole = true; - } - break; - - case CapRole::Ref: - { - isRef = true; - refCapSv = capSv; - roleNode = cap.node; - haveRole = true; - } - break; - - case CapRole::NameOnly: - { - const uint32_t a = ts_node_start_byte( cap.node ); - uint32_t b = ts_node_end_byte( cap.node ); - - // A C++ conversion operator's declarator is an `operator_cast` node whose text spans - // the WHOLE `operator () const` (the tags query captures the declarator itself — - // there is no sub-node spanning just `operator bool`). Trim the name's end to the end of - // the `type` field so the symbol name is `operator bool` / `operator MyType`, not the - // param list. Symbolic ops (operator==/[]/()) go through operator_name and are untouched — - // trimming at `(` there would wrongly cut `operator()`, so this is operator_cast-only. - if( kindIs( ts_node_type( cap.node ), "operator_cast" ) ) - { - const TSNode typeNode = fieldChild( cap.node, NodeField::Type ); - if( !ts_node_is_null( typeNode ) ) - { - const uint32_t typeEnd = ts_node_end_byte( typeNode ); - if( typeEnd > a && typeEnd <= b ) - { - b = typeEnd; - } - } - } - - if( b <= src.size() && a <= b ) - { - nameTxt = src.substr( a, b - a ); - nameByte = a; - nameRow = ts_node_start_point( cap.node ).row; - nameNode = cap.node; - haveName = true; - } - } - break; - - case CapRole::Ignore: - break; - - // #358: `@import.path` — emit here, not in a second pass. Matches arrive by start byte and captures - // within a match in query order, so a staging vector would produce the identical - // order while costing an allocation and a drain block. - case CapRole::Import: - { - if( full && capSv == "import.path" ) - { - emitCapturedImport( cap.node, fileId, le.lang, src, includes, refs, shortfall ); - } - else if( full && capSv == "import.names" ) - { - importNamesNode = cap.node; - } - else if( full && capSv == "import.alias" ) - { - importAliasNode = cap.node; - } - } - break; - } - } - - if( !ts_node_is_null( importNamesNode ) ) - { - emitCapturedImportBind( importNamesNode, importAliasNode, fileId, le.lang, src, binds ); - } - if( !haveName ) - { - continue; - } - - // Some patterns (e.g. a bare (identifier) @name) carry no @definition/@reference - // wrapper. Treat a wrapper-less @name as a reference fallback only when the pattern - // had a role; otherwise skip (avoids turning every identifier into an edge). - if( !haveRole ) - { - continue; - } - if( captureSpecializationHeader( isDef, le.lang, defCapSv, roleNode, nameNode, fileId, src, refs ) ) - { - continue; // a C++ specialization header: its base clause only, never a symbol - } - - // C1 (memgraph F1) — see cppDefNameReseat. A null node is "nothing to re-seat". - const auto [ reNode, reTxt, reByte, reRow ] = cppDefNameReseat( isDef && le.lang == Lang::Cpp, nameNode, src ); - if( !ts_node_is_null( reNode ) ) - { - nameNode = reNode; nameTxt = reTxt; nameByte = reByte; nameRow = reRow; - } - - // F5: drop Swift function-local `let`/`var` bindings — they are not module symbols and, left in, - // they steal the enclosing function's call edges (the last local binding above the call sites - // becomes the nearest enclosing symbol). roleNode is the `property_declaration`; a `statements` - // ancestor marks it as local. Real stored/computed members (class/struct/enum/top-level) survive. - if( isDef && kind == SymKind::Var && le.lang == Lang::Swift && isSwiftLocalBinding( roleNode ) ) - { - continue; - } - - // the gated capture classes — r3 q10 constants (plus the §7b CUDA memory-space policy for the - // uninitialized C++ shape, which needs the captured declaration node), JS export/prototype - // assignments — in one drop decision (see dropGatedCapture for the per-class rationale and why - // none of this can live in the query as a #match?/#eq? predicate). - // INDEX-ALIAS-CONST (src/aliasdef.h, the one alias reader): a C++ alias form is a definition unless it is - // function-local. aliasTargetStart: where the written target starts when it ENDS the declaration (--defs to=); it - // rides the RawDef's bodyByte to the model, which moves it to IngestResult::aliasTargets and keeps the whole - // declaration as the signature (ingest_model.h rawDefIsAliasRow); 0 when the target is not a suffix (a typedef). - std::uint32_t aliasTargetStart = 0; - AliasShape aliasShape {}; - if( isDef && langFacts( le.lang ).aliasTargetDefs && defCapSv == "definition.alias" ) - { - if( insideFunctionBody( roleNode ) ) // ingest_relations.h: a function-local alias is a local name (the local-const rule) - { - continue; - } - aliasShape = aliasShapeOf( Lang::Cpp, roleNode ); - } - AnnotationRename renamed {}; - if( cFamilyMacroInvocationCapture( defCapSv, le.lang, nameTxt, roleNode, src ) ) // defCapSv: set by a @definition capture only - { - // MACRO-P0 (ingest_names.h): a macro invocation read as a typeless declarator mints no definition of its own; the site is - // a call-shaped use of the macro (model.h retagMacroCallReferences makes it role="macro" when the #define is - // indexed and its name is uniquely a macro). No argument count: the "parameters" are macro arguments. - RawRef r; - r.fileId = fileId; - r.startByte = ts_node_start_byte( roleNode ); - r.line = ts_node_start_point( roleNode ).row + 1; - r.lang = le.lang; - r.role = RefRole::Call; - r.name = nameTxt; - refs.push_back( std::move( r ) ); - // MACRO-P1: when the grammar read the real function's own `f()` as a variable (ingest_names.h - // annotationRenamedName), this definition is the only one f gets — it carries f's name, from f's own start. - renamed = annotationRenamedName( roleNode, src ); - if( ts_node_is_null( renamed.name ) ) - { - continue; - } - nameNode = renamed.name; - nameTxt = nodeTextOf( renamed.name, src ); - nameByte = ts_node_start_byte( renamed.name ); - nameRow = ts_node_start_point( renamed.name ).row; - kind = renamedAnnotationKind( renamed.name ); - } - if( isDef && dropGatedCapture( defCapSv, le.lang, nameTxt, nameNode, roleNode, src ) ) - { - continue; - } - if( aliasShape.form != AliasForm::None ) - { - // the target is a suffix when every child after it is the `;` or a comment (`using X = Y /* c */ ;` keeps its - // target; the printer drops the comment, defslookup.h aliasTargetText); one cursor walk (infra/tschildren.h) - const std::uint32_t tEnd = ts_node_end_byte( aliasShape.target ); - bool suffix = true; // only `using`/namespace alias rows reach here (a typedef capture is never definition.alias) - ChildCursor cursor( roleNode ); - forEachChild( roleNode, cursor.cur, [ & ]( TSNode c ) - { - const char* k = ts_node_type( c ); - suffix = ts_node_start_byte( c ) < tEnd || kindIs( k, ";" ) || kindIs( k, "comment" ); - return suffix; - } ); - aliasTargetStart = suffix ? ts_node_start_byte( aliasShape.target ) : 0u; - } - - if( le.lang == Lang::Elixir && !elixirKeepCapture( roleNode, nameNode, ElixirCaptureRole{ isDef, kind, keywordHead }, src, elixir.keywords ) ) - { - continue; - } - if( le.lang == Lang::Clojure ) - { - if( !clojureKeepCapture( roleNode, isDef, src ) ) - { - continue; - } - if( isDef ) - { - kind = clojureDefinitionShape( roleNode, src ).kind; - } - } - if( le.lang == Lang::Elixir && refCapSv == "reference.bare" ) - { - // Bare pipe targets have their own capture; every other bare name needs lexical variable exclusion. - const TSNode parent = parentOf( nameNode ); - if( ( elixirNodeIs( parent, "binary_operator" ) && nodeFieldText( parent, NodeField::Operator, src ) == "|>" - && ts_node_eq( fieldChild( parent, NodeField::Right ), nameNode ) ) || !elixir.bareCall( nameNode ) ) { continue; } - } - if( le.lang == Lang::Elixir && refCapSv == "reference.operator" ) - { - constexpr std::string_view special[] = { "=", "<-", "\\\\", "::", "|>", "when", "|", "^", "&", "@" }; - if( std::find( std::begin( special ), std::end( special ), nameTxt ) != std::end( special ) ) { continue; } - const TSNode parent = parentOf( roleNode ); - if( nameTxt == "/" && elixirNodeIs( parent, "unary_operator" ) && nodeFieldText( parent, NodeField::Operator, src ) == "&" ) { continue; } - } - - if( langFacts( le.lang ).hasInertQuoteRegions && elixirInert( roleNode, src ) ) - { - // Keep call/operator/named-capture candidates as declined facts, never edges. Heads, - // special forms and non-call operators already failed their syntax filters. Bare AST - // names remain variable-shaped syntax unless they explicitly name a function capture. - if( isRef && ( refCapSv == "reference.call" || refCapSv == "reference.operator" - || ( refCapSv == "reference.bare" && elixir.namedCapture( nameNode ) ) ) ) - { - RawRef r; - r.fileId = fileId; - r.startByte = ts_node_start_byte( roleNode ); - r.line = nameRow + 1; - r.lang = Lang::Elixir; - r.role = RefRole::Inert; - auto [ count, known ] = elixirCallArity( roleNode, nameNode, src ); - if( refCapSv == "reference.operator" ) { count = elixirNodeIs( roleNode, "binary_operator" ) ? 2 : 1; known = true; } - r.name = known ? elixirFunctionName( nameTxt, count ) : std::string( nameTxt ); - refs.push_back( std::move( r ) ); - } - continue; - } - - if( isDef ) - { - if( le.lang == Lang::Elixir && defCapSv == "definition.attribute" ) { kind = SymKind::Var; } - RawDef d; - d.fileId = fileId; - d.line = nameRow + 1; // the identifier's line — most accurate, dedup-stable - // The C++ tags query captures @definition on the function_declarator (name+params) — its - // span excludes the return type AND the body. Walk up to the nearest ancestor owning a - // "body" field (the real function_definition) so [startByte,endByte) spans the WHOLE def: - // return type + signature + body. Fixes --expand bodies, --pack-signatures return-types, - // AND reference enclosing-attribution (a call in a body is now inside its function span). - // Grammars whose @definition node already owns the body (class/struct/enum) don't climb. - // defBodyNodeOf = the `body:` field, PLUS the macro-edges round's one addition: a #define's - // replacement text (`value:` field) is adopted as a macro symbol's body, set before the climb - // below so the climb is skipped for macros — PLUS a name bound to a function literal - // (kFnLiteralBinding): the literal's body, with `literal` the node params/cx/nest read from. - const DefBodyNodes own = le.lang == Lang::Elixir ? DefBodyNodes{ elixirBody( roleNode, src ), {}, roleNode } - : defBodyNodeOf( roleNode, nameNode, kind, le.lang ); - TSNode defNode = own.span; - TSNode body = own.body; - // LB-E testmacroblock: the def is TWO SIBLING nodes (see testMacroBlockPartsOf) — adopt the - // sibling compound_statement as the body and the title literal as the name BEFORE the shared - // span/complexity code below. The span's endByte and the loc row window are extended past - // defNode's own end further down (no single node covers both siblings). - const bool isTestMacroBlock = ( defCapSv == "definition.testmacroblock" ); - if( isTestMacroBlock ) - { - const TestMacroBlockParts parts = testMacroBlockPartsOf( roleNode, src ); - if( !parts.ok ) - { - continue; // dropGatedCapture already vetoed non-candidates — guard, don't assert - } - body = parts.body; - nameNode = parts.title; - nameTxt = testMacroTitleOf( parts.title, src ); - nameByte = ts_node_start_byte( parts.title ); - nameRow = ts_node_start_point( parts.title ).row; - d.line = nameRow + 1; // re-seat: d.line above was filled from the @name capture (the macro identifier) - } - // A Var's span is its own declaration — never climb. The climb exists to find a FUNCTION's - // body; for a var it can only steal a container's span (a Ruby class-level constant's parent - // chain is body_statement → class, and class owns a "body" field, so the climb would hand the - // constant THE WHOLE CLASS — the exact Rust-method span bug the H4 W3 note above describes). - // No-op for every pre-existing Var capture (Swift/C#/Go/Python parents hit a scope-stop or the - // file root before any "body"-owning ancestor — verified byte-identical on the gate corpora). - // A Field's span is its own field_declaration / defining assignment — the Var rule, same reason. - // A BODY-LESS C/C++ type specifier — `enum cmd_retval` as a return type (`static enum cmd_retval⏎fn(…)`, tmux's - // style) or a parameter type — is captured by the tags query's bare enum/class pattern, and the climb below - // ADOPTED the enclosing function_definition, whose body it sits outside of: the specifier took the WHOLE - // function's span, so --at chained `struct cmd_retval` around the function, --grep labelled its hits - // in="cmd_retval" and its calls were attributed to a `struct box_lines` caller (comparison table tmux-07/15, - // test/ccheck.sh). The adoption is for a function DECLARATOR. A type specifier whose climb reaches a body owner - // it sits outside of is a type USE in that function's signature, not a definition, so it mints NO def: keeping - // it as a small def of its own put a span in the return-type position wholly before the name — extentsuspect.h - // R3's derailed-parse signature — and flagged clean functions extent_suspect="head" (review of this lane, - // ccheck arm (f)). The declaration-wrapper rule at a scope stop is unchanged (`enum E : int;`, a prototype). - const bool bodylessTypeSpec = isCFamilyTypeSpecifier( le.lang, roleNode ); - bool typeUseInSignature = false; - if( ts_node_is_null( body ) && kind != SymKind::Var && kind != SymKind::Field && le.lang != Lang::Elixir ) - { - TSNode child = roleNode; - TSNode p = parentOf( roleNode ); - for( int guard = 0; !ts_node_is_null( p ) && guard < 4; ++guard ) - { - const char* pt = ts_node_type( p ); - // STOP at a type/namespace/file scope: a function's body never lives above one of - // these, so reaching here means roleNode is a prototype/declaration with no body. - // (Without this, an in-class method declaration would climb into class_specifier and - // wrongly grab the whole CLASS body as its span — corrupting spans + ref attribution.) - const bool scope = kindIs( pt, "class_specifier" ) || kindIs( pt, "struct_specifier" ) - || kindIs( pt, "field_declaration_list" ) || kindIs( pt, "declaration_list" ) - || kindIs( pt, "namespace_definition" ) || kindIs( pt, "enum_specifier" ) - || kindIs( pt, "translation_unit" ) || kindIs( pt, "source_file" ) // Swift top - || kindIs( pt, "class_body" ) || kindIs( pt, "protocol_body" ) // Swift type bodies - || kindIs( pt, "enum_class_body" ) - || kindIs( pt, "class_interface" ) || kindIs( pt, "class_implementation" ) // ObjC - || kindIs( pt, "implementation_definition" ) || kindIs( pt, "protocol_declaration" ) - || kindIs( pt, "compound_statement" ) || kindIs( pt, "block" ); // a function BODY: a block-scope - // `Type v(args);` (most-vexing-parse) must not climb up and steal its enclosing function's span. A real - // function definition's declarator parents directly to function_definition (found at hop 1, above), so this never fires for it. - if( scope ) - { - // prototype/declaration: use the member/decl wrapper as the span so the RETURN - // TYPE is included (not just the declarator), WITHOUT grabbing the class body. - const char* ct = ts_node_type( child ); - if( kindIs( ct, "field_declaration" ) || kindIs( ct, "declaration" ) ) - { - defNode = child; - } - break; - } - // Adopt an ancestor's span only if roleNode sits OUTSIDE its body — i.e. roleNode is the - // ancestor's own signature/declarator (the C++ function_declarator → function_definition - // hop this climb exists for). A def spelled INSIDE the body is a different, NESTED - // definition — a JS/TS named const-closure (`const f = (..) => {..}` in a function body) — - // and adopting here broadcast the encloser's whole span (loc/cx/params/nest) onto every - // such closure (webpack lib/html/syntax.js: eight closures inside the 3439-line `tokenize` - // all reported loc=3439 cx=487). The enclosing statement_block is not in the scope-stop - // list above (only C-family compound_statement/block are), so nested defs escaped upward; - // containment is the grammar-agnostic stop. Gate: test/jsnestedcheck.sh. - const TSNode pb = fieldChild( p, NodeField::Body ); - if( !ts_node_is_null( pb ) ) - { - const bool outsideBody = !spanContains( pb, roleNode ); - if( outsideBody && !bodylessTypeSpec ) { defNode = p; body = pb; } - typeUseInSignature = outsideBody && bodylessTypeSpec; - break; - } - child = p; - p = parentOf( p ); - } - } - if( typeUseInSignature ) - { - continue; // a body-less C/C++ specifier in a function's signature: a type use, never a definition - } - - // MACRO-P1: a prototype adopts its trailing annotation's definition body, its span running THROUGH that sibling - const TSNode ownBody = body; - body = annotatedSiblingBody( body, le.lang, kind, roleNode, src ); - const bool annotatedBody = !ts_node_eq( body, ownBody ); - - // ObjC/Kotlin body-field fallback for the grammars that expose a body as an unnamed CHILD, not a - // named "body" field. C++ function_definition owns a "body" field (found above); the ObjC grammar - // never does, so the field lookup returns null and bodyByte would stay 0 for a real definition — - // making an @implementation def indistinguishable from its @interface DECL (both bodyByte==0). That - // breaks BOTH the same-file decl/def collapse (3a-bis) and graph.h's cross-file hasBody - // (endByte > sigEndByte), doubling every ObjC symbol node AND its call edges. Recover the - // body-present signal from a direct child: - // - a METHOD def: a bare `compound_statement` / `function_body` / `block` child (the `{...}`). - // - an ObjC CLASS: an @implementation carries `implementation_definition` member children; the - // matching @interface carries only `method_declaration`s → so an `implementation_definition` - // child is exactly "this is the class's definition, not its forward @interface". - // - Kotlin: `function_body` / `class_body` / `enum_class_body` are positional children too - // (function_declaration's only named field is `receiver`), and the cost of missing them is - // the same collapse bug in the other direction — a Kotlin definition read as bodyless is - // deleted from the candidate pool as a forward declaration whenever a same-named Java - // definition exists (test/kotlincheck.sh §5). `enum_class_body` (`enum class Status { … }`) - // was the one omission a second-opinion review caught: `class_declaration`'s enum-class form - // nests its members under that node, not `class_body` — verified via a raw parse of - // `enum class Status { READY, DONE }` → `(class_declaration (type_identifier) - // (enum_class_body (enum_entry …) (enum_entry …)))`. - // A bodyLESS declaration (@interface method / @interface class) has none of these children → - // bodyByte stays 0 → it stays a decl (a bodyless KOTLIN TYPE does too, and is still a definition: model.h isDefinitionNotDeclaration). GATED to ObjC and - // Kotlin so C++/Python/Rust/Go/TS/Swift bodyByte — and therefore their sigEndByte, spans, and - // node/edge output — are BYTE-for-byte unchanged (a .mm's C++ functions take the C "body"-field - // path above and never reach here). See test/langcheck.sh c.m and the byte-identical src/ - // regression gate. - if( ts_node_is_null( body ) && ( le.lang == Lang::ObjC || le.lang == Lang::Kotlin ) ) - { - // O(children): `- (void) m /*…*/ { }` puts the comments in the method_definition, before its - // body — 24x at 16 000 (test/childwalkscalecheck.sh, arm B35) - body = firstChildOfKind( defNode, /*namedOnly=*/false, - { "compound_statement", "function_body", "block", "implementation_definition", "class_body", "enum_class_body" } ); - } - - // Proto (PROTO-INDEX): the grammar names no `body:` field. A message's or enum's body is its *_body child; a service's, - // an rpc's option block's and a oneof's body starts at its `{` token (an rpc ending in `;` has none). - if( ts_node_is_null( body ) && langFacts( le.lang ).generatedSchema ) - { - body = firstChildOfKind( defNode, /*namedOnly=*/false, { "message_body", "enum_body", "{" } ); - } - - // Dart's body is a SIBLING of the signature, so neither defBodyNodeOf nor the climb above can - // find it and the span would stop at the signature — see dartFollowingBody (ingest_relations.h) - // for the measurement and for why an abstract member still comes back null. - bool siblingBody = annotatedBody; // MACRO-P1's annotated sibling above, or Dart's here - if( ts_node_is_null( body ) && le.lang == Lang::Dart ) - { - body = dartFollowingBody( defNode ); - siblingBody = !ts_node_is_null( body ); - } - // Both flags mean the same thing to the three span consumers below: the code this symbol - // owns lives in a SIBLING node, so byte/row extents and complexity must run through it. - const bool spanThroughBody = isTestMacroBlock || siblingBody; - - d.startByte = ts_node_start_byte( defNode ); - d.endByte = spanThroughBody ? ts_node_end_byte( body ) : ts_node_end_byte( defNode ); // LB-E: the span runs THROUGH the sibling block - d.nameByte = nameByte; - d.bodyByte = ts_node_is_null( body ) ? 0u : ts_node_start_byte( body ); - if( d.bodyByte == 0 && aliasTargetStart > d.startByte && aliasTargetStart < d.endByte ) - { - d.bodyByte = aliasTargetStart; // INDEX-ALIAS-CONST: the transport only (ingest_model.h rawDefIsAliasRow) - } - const bool fnOrMethod = ( kind == SymKind::Function || kind == SymKind::Method ); - // LB-E: for a testmacroblock the body SIBLING is where the code lives — complexityOf walks - // INSIDE its root node, so handing it defNode (the bare macro statement) would count nothing. - // A literal-bound name measures its LITERAL; every other def measures defNode, as before. - const bool literalBound = !ts_node_is_null( own.literal ); - const TSNode metricNode = literalBound ? own.literal : defNode; - const auto [ cxVal, ccxVal, nestVal, localsVal, ppAltVal, humpsVal, deepVal, evVal, evWhyVal, steerVal, dispatchVal, nestCutVal ] = fnOrMethod && shape ? complexityOf( spanThroughBody ? body : metricNode, src, le.lang ) : Complexity{ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, {}, 0u, 0u, 0u }; - d.cx = cxVal; - d.ccx = ccxVal; - d.locals = localsVal; // Phase 1: floor count, C/C++ only (model.h localsCountedLang) — 0 elsewhere, never emitted there - // ppalt disclosure (model.h Symbol::ppAlt). Saturating at 65535 on purpose: a def past that - // bound is beyond every triage threshold, and the attribute's claim ("the body carries - // alternatives") is already made at 1. - d.ppAlt = fnOrMethod ? std::uint16_t( ppAltVal > 65535u ? 65535u : ppAltVal ) : std::uint16_t( 0 ); - // Q4 size smells (SIZE = master variable): physical LOC = span line count (end row − start row + 1); - // param count + max nesting for functions/methods only (0 otherwise, absent in emit). All descriptive. - { - const std::uint32_t startRow = ts_node_start_point( defNode ).row; - const std::uint32_t endRow = ts_node_end_point( spanThroughBody ? body : defNode ).row; // LB-E: rows through the sibling block - d.loc = ( endRow >= startRow ) ? ( endRow - startRow + 1u ) : 1u; - } - d.params = fnOrMethod ? ( le.lang == Lang::Elixir ? elixirParams( defNode, src ) - : le.lang == Lang::Clojure ? clojureParams( defNode, src ) - : paramCountOf( metricNode, literalBound ) ) : std::uint16_t( 0 ); - // LB-E: a testmacroblock's parameter surface is the MACRO's business, not visible here — claim - // inexact so the resolver's arity narrowing never trusts params=0 on a test-title symbol. - // B2.2: the fixed-arity bit and the minimum (fewest arguments a call can pass) come from ONE scan of the list. - // A minimum above the counted params (a literal-bound bare parameter countParams cannot see) is not trusted. - const ParamShape shape = ( fnOrMethod && !isTestMacroBlock && le.lang != Lang::Clojure ) ? cc_paramShape( metricNode, le.lang, kind, src ) : ParamShape{}; - d.arityExact = shape.exact ? std::uint8_t( 1 ) : std::uint8_t( 0 ); - d.paramsMin = shape.minimum <= d.params ? shape.minimum : std::uint16_t( 0 ); - applyAnnotationRename( d, renamed, defNode ); // MACRO-P1: the real function's parameters and start, not the annotation's - // L8: the in-file test-scope bit, for EVERY kind (a `#[cfg(test)] mod` and a `class TestFoo` - // are themselves symbols, and dropping the members while keeping the shell would be a worse - // answer than either). Runs on defNode, whose ancestors are the enclosing scopes. - d.testScope = isTestMacroBlock ? std::uint8_t( 1 ) : std::uint8_t( inFileTestScope( defNode, src, le.lang ) ); // LB-E: a test macro IS the in-file convention - d.maxNest = fnOrMethod ? std::uint8_t( nestVal > 255u ? 255u : nestVal ) : std::uint8_t( 0 ); - // QD-TANGLE (model.h Symbol::steer, ::dispatchShare): 0 off a callable, where complexityOf did not run - d.steer = saturatedTo( steerVal ); - d.deepDispatch = saturatedTo( dispatchVal ); - d.nestArmCut = saturatedTo( nestCutVal ); - // The nesting profile (model.h Symbol::humps/deepLoc). Saturating at 65535 on purpose: a def past - // either bound is beyond every triage threshold, and deepLoc is a floor already, so a clamp there - // stays honest in the direction the attribute already claims. - d.humps = fnOrMethod ? std::uint16_t( humpsVal > 65535u ? 65535u : humpsVal ) : std::uint16_t( 0 ); - d.deepLoc = fnOrMethod ? std::uint16_t( deepVal > 65535u ? 65535u : deepVal ) : std::uint16_t( 0 ); - // essential complexity (model.h Symbol::ev): already saturated inside ev_finalize; 0 for - // non-function kinds and outside evCountedLang, matching the emitters' omission rule. - d.ev = fnOrMethod ? std::uint16_t( evVal > 65535u ? 65535u : evVal ) : std::uint16_t( 0 ); - d.evWhy = fnOrMethod ? evWhyVal : std::array{}; - d.kind = kind; - d.lang = le.lang; - d.name = isTestMacroBlock ? std::string( nameTxt ) : defNameFromCapture( le.lang, nameTxt ); // LB-E: a title is a display string — see testMacroTitleOf - if( defCapSv == "definition.cjsexport" && isCjsModuleExportsItself( nameNode, src ) ) - { // lane js-def-naming: the module's own export function, named by the file's stem (ingest_names.h isCjsModuleExportsItself) - if( fileStem.empty() ) - { - continue; // no path to name it by: no row, as before - } - d.name = std::string( fileStem ); - } - if( le.lang == Lang::Elixir && elixirTarget( roleNode, src ) == "test" ) - { - // Static ExUnit title; interpolation was rejected by elixirKeepCapture. - d.name = "test " + std::string( nameTxt.substr( 1, nameTxt.size() - 2 ) ); - d.testScope = 1; - } - else if( le.lang == Lang::Elixir && !elixirAttribute( roleNode, src ).empty() ) - { - const auto attribute = elixirAttribute( roleNode, src ); - if( elixirTypedAttribute( attribute ) ) - { - const TSNode args = elixirArguments( parentOf( nameNode ) ); - std::uint32_t arity = 0; - for( std::uint32_t i = 0; !ts_node_is_null( args ) && i < ts_node_named_child_count( args ); ++i ) - { - arity += elixirNodeIs( ts_node_named_child( args, i ), "comment" ) ? 0u : 1u; - } - d.name = ( attribute == "callback" || attribute == "macrocallback" ? "@callback " : "@type " ) + elixirFunctionName( nameTxt, arity ); - } - else { d.name = "@" + std::string( nameTxt ); } - } - else if( le.lang == Lang::Elixir && kind == SymKind::Other ) - { - // `defimpl P, for: T` — the @name capture is just the protocol alias, but the module Elixir - // generates is `P.T`, which is what the impl's own defs carry as their scope. - d.name = elixir.moduleName( roleNode ); - if( d.name.empty() ) { continue; } - d.kind = elixirTarget( roleNode, src ) == "defprotocol" ? SymKind::Interface : SymKind::Class; - for( TSNode call : elixir.calls ) - { - const auto keyword = elixirTarget( call, src ); - if( ( keyword == "defstruct" || keyword == "defexception" ) && elixir.scopeOf( call ) == d.name ) { d.kind = SymKind::Struct; break; } - } - } - // Internal linkage (model.h Symbol::internalLinkage): C and C++ only, read off defNode — the node that owns - // the storage class and whose ancestors are the enclosing namespaces (ingest_names.h::cppInternalLinkage). - d.internalLinkage = internalLinkageBit( le.lang, defNode, src ); - // A FUNCTION bound inside another function's body records that function's span (ingest_names.h - // enclosingFunctionScope): graph.h reachableByName ranks it below every def a call outside it can name. - if( full && kind == SymKind::Function && !bindsOutsideItsFunction( roleNode, le.lang ) ) - { - // Descend to the OUTER of the two def nodes: a C-family def's defNode climbed from its declarator (the role - // node) to the function_definition, which must not read as the function enclosing itself; a multi-name - // binding's defNode narrowed to one declarator, whose declaration (the role node) holds no scope node - // and is not a 20k-child list to rescan per name. - const bool defIsOuter = ts_node_start_byte( defNode ) <= ts_node_start_byte( roleNode ) && ts_node_end_byte( defNode ) >= ts_node_end_byte( roleNode ); - const FnScope fnScope = enclosingFunctionScope( root, defIsOuter ? defNode : roleNode ); - d.fnScopeStart = fnScope.start; - d.fnScopeEnd = fnScope.end; - } - if( le.lang == Lang::Cpp ) // canonical scope (E#4): out-of-line `A::b` → "A", else enclosing class/namespace - { - d.scope = qualifierOfDefinition( nameNode, src ); // `Box::grow` (primary) → "Box"; a specialization keeps its id - if( d.scope.empty() ) - { - d.scope = enclosingScopeOf( nameNode, src ); - } - // #150: is this def genuinely INSIDE namespace std, at ANY nesting depth — not just a def - // whose immediate scope happens to spell a segment std also uses? See Symbol::scopeRootsStd. - d.scopeRootsStd = cppDefinitionRootsStd( nameNode, src ) ? std::uint8_t( 1 ) : std::uint8_t( 0 ); - } - else if( enumTableAt( kDefScopeWalkerOfLang, le.lang, DefScopeWalker::None ) != DefScopeWalker::None ) - { // Python, Go, Rust, Kotlin: the language's row in ingest_names.h kDefScopeWalkerOfLang - d.scope = defScopeOf( le.lang, nameNode, src ); - } - else if( le.lang == Lang::Elixir ) - { - d.scope = kind == SymKind::Other ? std::string{} : elixir.scopeOf( roleNode ); - if( keywordHead ) // #355: the match's own @_keyword capture, decided by tags.scm, not a C++ keyword list - { - d.name = elixirFunctionName( nameTxt, d.params ); - // B2.2 for Elixir: a clause's arity IS its parameter count (no variadic form), so `params` - // is call-comparable unless a `\\` default widens the callable to more than one arity. - // cc_paramShape's language gate leaves this at 0, which made every Elixir caller - // unflaggable by --edit-check (test/elixirnamearitycheck.sh arm C: run(x) -> run(x, y) - // must flag run(x) callers; run(x, y \\ 1) must flag none). - d.arityExact = elixirHeadDefaultCount( roleNode, src ) == 0 ? std::uint8_t( 1 ) : std::uint8_t( 0 ); - elixirDefinitionFacts( d, roleNode, src, binds, elixir.keywords ); - if( elixirTarget( roleNode, src ) == "defdelegate" ) - { - RawRef delegated; - delegated.fileId = fileId; delegated.startByte = d.startByte; delegated.line = d.line; - delegated.lang = le.lang; delegated.recv = RecvKind::ElixirModule; - delegated.qualifier = elixir.moduleOf( elixirKeywordValue( roleNode, "to:", src ), roleNode ); - const auto as = nodeTextOf( elixirKeywordValue( roleNode, "as:", src ), src ); - delegated.name = elixirFunctionName( as.starts_with( ":" ) ? as.substr( 1 ) : nameTxt, d.params ); - delegated.argCount = d.params; delegated.argCountKnown = true; - if( !delegated.qualifier.empty() ) { refs.push_back( std::move( delegated ) ); } - } - } - } - else if( le.lang == Lang::Ruby ) - { // enclosing class/module → id= addressability, per-class overload sets, editCheckImplicitReceiver - d.scope = rubyEnclosingScopeOf( nameNode, src ); // (test/rubyscopecheck.sh) - if( kind == SymKind::Method || kind == SymKind::Function ) - { - rubyNoteClassSideDef( defNode, fileId, d.name, src, binds ); // a class object's method (test/rubyclassrecvcheck.sh) - } - } - else if( ( le.lang == Lang::JavaScript || le.lang == Lang::TypeScript ) - && defCapSv == "definition.protomethod" ) - { // only the five built-in ctors: every Foo.prototype.bar gaining sc= would mint a new - // canonical id and move quality baselines (node lib/ has ~163 anonymous protomethods) - const std::string_view ctor = prototypeCtorName( nameNode, src ); - if( isJsTsBuiltinCtor( ctor ) ) - { - d.scope = std::string( ctor ); - } - } - // extent honesty: did the parse RECOVER this def's container or kind? Only asked in a file whose root - // holds an error (fileHasError, one O(1) flag test per file) — see parseRecoveredBits. - d.recovered = fileHasError ? parseRecoveredBits( defNode, kind, le.lang, d.scope.empty() ) : std::uint8_t( 0 ); - defs.push_back( std::move( d ) ); - if( !full ) - { - continue; // TagsCapture::DefinitionsOnly: the reference edges below feed no definition - } - if( kind == SymKind::Class || isStructOrNamedType( kind ) || kind == SymKind::Interface ) - { - // #446: a language on the bases-as-captures port reads its bases through the - // @reference.base reader above (LangFacts::basesAsCaptures; C++ is the first). The - // others keep the walk; C++'s own walk survives for captureSpecializationHeader. - if( !langFacts( le.lang ).basesAsCaptures ) - { - captureBases( defNode, fileId, le.lang, src, refs ); // IS-A: inheritance edges (derived → base) - } - if( defCapSv == "definition.classfactory" ) // lane lego-transitive (M2): the factory's receiver is the base - { - emitBaseRef( jsClassFactoryReceiver( nameNode, src ), fileId, le.lang, src, refs, defNode ); - } - captureFields( defNode, fileId, le.lang, src, refs ); // HAS-A: member-variable type edges (S5-E) - } - else if( kind == SymKind::Macro ) - { - captureMacroBodyCalls( roleNode, fileId, le.lang, src, refs ); // macro-edges: the graph connects THROUGH the macro - if( langFacts( le.lang ).bangMacros ) // Rust: `$crate` exists only where `name!` macros do - { - captureRustTranscriberMacroCalls( roleNode, fileId, src, refs ); // RUST-MACRO-PATH: `$crate::m!` in a transcriber - } - } - } - else if( isRef && full ) + TagsMatch m = readTagsMatch( pass, query, match ); + // Some patterns (e.g. a bare (identifier) @name) carry no @definition/@reference wrapper: a name without a role is + // skipped (avoids turning every identifier into an edge), and so is a role without a name. + if( m.hasName() && m.hasRole() ) { - // An element access: @name is its RECEIVER, and the site names the receiver class's subscript operator - // method (ingest_binds.h subscriptOperatorRef) — never a call by itself (RefRole::Subscript). - if( refCapSv == "reference.subscript" ) - { - if( std::optional sub = subscriptOperatorRef( roleNode, nameNode, fileId, le.lang, src ) ) - { - refs.push_back( std::move( *sub ) ); - } - continue; - } - // H4: a C++ cast keyword is not a call — see isCppCastKeyword. Valid input, skipped, no alert. - if( le.lang == Lang::Cpp && isCppCastKeyword( nameTxt ) ) - { - continue; - } - - // #285: an intrinsic JSX tag (`
`, `

`) is not a call — see isJsxIntrinsicTagIdentifier. - // Valid input, skipped, no alert; a qualified (``) or namespaced (``) - // tag never reaches this test (see that function's note for why). - if( ( le.lang == Lang::TypeScript || le.lang == Lang::JavaScript ) - && isJsxIntrinsicTagIdentifier( roleNode, nameNode, nameTxt ) ) - { - continue; - } - - // using-declaration re-exports (r9 loss bucket 1): @reference.import marks the C++ - // `using ns::name;` tags pattern. The site becomes a role="import" use-site of the target - // (never a call edge — graph.h admits Call+Macro only), and the grammar KEYWORD forms - // (`using namespace ns;` / `using enum E;`) are dropped here at capture time, where the - // query predicate a tags pattern cannot express IS enforceable (see the helper's note). - const bool isImportRef = ( refCapSv == "reference.import" ); - if( isImportRef && usingDeclarationIsDirective( roleNode ) ) - { - continue; - } - - // family 4 / slice 4a: a @reference.mixin capture is Ruby's `include`/`extend`/`prepend` — the shape - // lives in queries/ruby/tags.scm, so the capture IS the language gate and no Lang:: branch is spent - // here. The two guards a tags pattern cannot state (the directive's TEXT, and its POSITION) live in - // the Ruby reader, ingest_ruby.h emitCapturedRubyMixinBase, which takes the language from this call - // site and EXPECTS Ruby: Ruby is the capture's only emitter today, and a second language adds its own - // reader and dispatch here rather than reusing Ruby's. The directive's own CALL reference is a - // separate match, below. - if( refCapSv == "reference.mixin" ) - { - emitCapturedRubyMixinBase( roleNode, nameNode, fileId, le.lang, src, refs ); - continue; - } - - // #446: a @reference.base capture is a base-clause type on the class-def path — - // queries//tags.scm names the clause's type node, so the capture IS the language - // gate. The clause's parent is the class node (emitBaseRef's `self`), the same pairing - // the captureBases walk passed; C++ is the first language on this capture. - if( refCapSv == "reference.base" ) - { - emitBaseRef( nameNode, fileId, le.lang, src, refs, parentOf( roleNode ) ); - continue; - } - - RawRef r; - r.fileId = fileId; - r.startByte = ts_node_start_byte( roleNode ); - r.line = ts_node_start_point( roleNode ).row + 1; // ABS-3: 1-based use-site line for --uses - r.lang = le.lang; - // ABS-3: @reference.call is a call use-site; @reference.import a using-decl re-export. EDGE-PRELUDE-VETO: @reference.macro is a macro - // invocation the grammar spells as one (Rust `name!(..)`): role Macro, so it binds only to an indexed macro of the name (graph.h). - r.role = isImportRef ? RefRole::Import : ( refCapSv == "reference.macro" ? RefRole::Macro : RefRole::Call ); - r.name = finalSegment( nameTxt ); - if( le.lang == Lang::Clojure ) - { - r.qualifier = nodeFieldText( parentOf( nameNode ), NodeField::Namespace, src ); - } - if( le.lang == Lang::Elixir ) - { - r.qualifier = elixir.scopeOf( roleNode ); - if( refCapSv == "reference.attribute" ) - { - r.role = RefRole::Read; r.name = "@" + std::string( nameTxt ); - refs.push_back( std::move( r ) ); - continue; - } - const TSNode target = fieldChild( roleNode, NodeField::Target ); - if( !ts_node_is_null( target ) && kindIs( ts_node_type( target ), "dot" ) ) - { - const TSNode receiver = fieldChild( target, NodeField::Left ); - r.qualifier = elixir.moduleOf( receiver, roleNode ); - if( r.qualifier.empty() ) { continue; } - // `__MODULE__` spelled, or an alias of it (`alias __MODULE__, as: Current`): the receiver names the - // enclosing module, and the reference is re-attributed per implementation of a multi-target defimpl - r.recv = nodeTextOf( receiver, src ).starts_with( "__MODULE__" ) || elixir.selfRelativeAlias( receiver, roleNode ) - ? RecvKind::ElixirSelfModule : RecvKind::ElixirModule; - } - auto [ count, known ] = elixirCallArity( roleNode, nameNode, src ); - if( refCapSv == "reference.operator" ) { count = elixirNodeIs( roleNode, "binary_operator" ) ? 2 : 1; known = true; } - if( !known ) { continue; } - r.argCount = count; r.argCountKnown = true; - r.name = elixirFunctionName( nameTxt, count ); - } - else if( le.lang == Lang::Ruby && rubyCallIsAssignmentTarget( nameNode ) ) - { - r.name.push_back( '=' ); // `obj.name = v` calls `name=`, never the getter `name` (test/rubysettercheck.sh) - } - std::string rustWritten; // RULE3-MEMBER-GUARD fix 4: a Rust path call's qualifier as written, when longer than one segment - if( le.lang == Lang::Cpp ) - { - r.qualifier = qualifierOf( nameNode, src ); // `A::b()` → "A" (E#4 canonical resolve) - // #150: the FULL written chain's root, BEFORE the H4 re-split below overwrites r.qualifier - // with the immediate segment only (`std::ranges::move` loses "std", keeps "ranges") — see - // Reference::qualifierRootsStd and graph.h::keepStdQualifiedCandidates. - r.qualifierRootsStd = cppQualifiedChainRootsStd( nameNode, src ); - cppResplitRefName( r, nameTxt ); // H4 RE-SPLIT at 3+ segments, operator tails, `template` disambiguator - } - else if( langFacts( le.lang ).bangMacros && r.role == RefRole::Macro ) - { - // RUST-MACRO-PATH: `crate::m!`, `axum_core::m!`, `serde_json::json!`: the written path, which graph.h requires to prove the macro - const TSNode parent = parentOf( nameNode ); - if( !ts_node_is_null( parent ) && kindIs( ts_node_type( parent ), "scoped_identifier" ) ) - { - std::string qualifier; - rustMacroPathOf( nodeTextOf( fieldChild( parent, NodeField::Path ), src ), qualifier, rustWritten ); - r.qualifier = qualifier; - } - } - else if( le.lang == Lang::Rust ) - { - r.qualifier = rustQualifierOf( nameNode, src ); // H4: `Widget::new()` → "Widget" - if( r.role == RefRole::Call ) - { - rustWritten = rustWrittenQualifier( nameNode, src ); // the whole written qualifier, set below once the receiver fields are - } - } - - if( !isImportRef && le.lang != Lang::Elixir ) // an import site has no receiver and no argument list — - { // the defaults (RecvKind::None, argCountKnown=false) are the truth - // FE-B: a Java method INVOCATION reads its receiver like every other language (a member call or a bare - // implicit-this call); only a method REFERENCE (`T::m`) keeps issue #74's type-candidate shape. - const bool javaMethodRef = le.lang == Lang::Java && !ts_node_is_null( roleNode ) && kindIs( ts_node_type( roleNode ), "method_reference" ); - RecvShape rs = javaMethodRef - ? javaMethodReferenceReceiver( roleNode, src ) - : receiverOf( nameNode, le.lang, src ); // P2-D: `this`/`self`/`x`/`base.field` shape - r.recv = rs.kind; r.recvVar = rs.var; // → one-hop narrowing in resolve.h - r.setFieldName( std::move( rs.field ) ); // depth-2 intermediate field; "" otherwise - r.viaArrow = rs.viaArrow; // `p->m()`: Rule 2b's smart-pointer pointee needs it - r.memberCall = rs.member; r.memberRoot = rs.root; // FE-A: a Go/JS/TS/Rust member call and its receiver root - r.setMemberPath( std::move( rs.path ) ); r.setMemberCtor( std::move( rs.ctor ) ); // FE-B: the rest of that receiver chain - if( le.lang == Lang::Ruby && r.recv == RecvKind::NamedVar ) - { - r.setFieldName( rubyReceiverWrittenPath( nameNode, r.recvVar, src ) ); // parser version 137: a constant's path as written - } - auto [ ac, ak ] = callArity( nameNode, le.lang, src ); // B2.2: call-site positional arg count - r.argCount = ac; r.argCountKnown = ak; // → arity filter in graph.h - if( langFacts( le.lang ).trailingLambdaScopeFns ) - { - r.trailingLambda = kotlinTrailingLambda( roleNode ); // #155: `x.run { }` / `with( x ) { }` — graph.h FalseEdgeRules' Kotlin arm - } - if( !rustWritten.empty() ) - { - r.setFieldName( std::move( rustWritten ) ); // a Rust path call's whole written qualifier (model.h Reference::fieldName) - } - if( isQueueLang( le.lang ) && isQueueCallName( r.name ) ) - { - if( const std::uint8_t kw = callKeywords( nameNode, src ); kw != 0 ) - { - r.setComposeRel( pyKwTag( kw ) ); // a queue call's keywords, for QueueHops (model.h pyKwTag) - } - } - } - refs.push_back( std::move( r ) ); + captureTagsMatch( pass, m ); } } } @@ -2815,36 +3138,9 @@ void captureTagsFacts( TSQueryCursor* cursor, const LangEntry& le, std::uint32_t if( le.lang == Lang::Elixir ) { elixirExpandImplementations( elixir, defs, firstDefOfFile, binds, firstBindOfFile ); } foldFieldDefs( defs, firstDefOfFile, le.lang ); // member-variable round: owner-less fields drop, Python fields fold to one per (class, name) - // Parser version 121 (test/rubyattrscheck.sh): the Ruby attr family's Var defs. Appended after the - // dead/field folds — neither touches Ruby (no preprocessor; Var is not a Field kind) — and inside the - // same defs window, so the lex build and cache round-trip treat these defs like captured ones. - // Parser version 130 (test/rubybarecallcheck.sh): Ruby's bare-word calls, by Ruby's own local rule, into the - // same refs window — the tags query cannot tell a bare call from a local read (both are an (identifier)). - // Parser version 132 (test/rubytypedrecvcheck.sh): the same walk types each call receiver the file builds, written - // into the call references this window holds; and FactoryBot's factory definitions, into binds. - // Parser version 135 (test/rubyrakejbuildercheck.sh): `helper_method` declarations into binds, and a Jbuilder - // template's `json` — a local, typed JbuilderTemplate — in the refs window. - // Parser version 137 (test/rubyclassrecvcheck.sh): the accessors a `class << self` declares, into binds as singleton - // methods — beside each singleton def, which the def capture above notes. - // Parser version 145 (test/rubyclassrecvcheck.sh): the mixins the class object's lookup reaches — an `extend`, an - // `include` in `class << self` — into binds, beside the inherit reference each mixin already is. if( le.lang == Lang::Ruby ) { - captureRubyDefs( root, fileId, src, defs ); // #339: the Definitions-only walker (attr defs + rendered db/schema.rb columns) - if( !full ) - { - return; // TagsCapture::DefinitionsOnly: the passes below write references and binds only - } - captureRubyBareCalls( root, fileId, src, refs ); - captureRubyFactories( root, fileId, src, binds ); - captureRubyHelperMethods( root, fileId, src, binds ); - captureRubySingletonAccessors( root, fileId, src, binds ); - captureRubyClassMixins( root, fileId, src, binds ); - captureRubyMainMixins( root, fileId, src, binds ); - if( le.ext == kJbuilderExt ) - { - typeRubyJbuilderLocal( fileId, refs ); - } + captureRubyFilePasses( pass ); } } From fc3621b7029fcc7d678d924e6310109ab6d604c8 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:47:02 -0500 Subject: [PATCH 17/61] refactor(ingest): the declarator climb's stop set and wrapper test read through rw::isOneOf qd-range named the two extracted kindIs chains shape clones of isFunctionBoundaryKind and isRubyConstantNode; as tables they are what they are, a set lookup (the climb runs per body-less definition, not per node). Co-Authored-By: Claude Opus 5.5 --- src/ingest_sidecap.h | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/src/ingest_sidecap.h b/src/ingest_sidecap.h index 7473a6980..6e5690e1e 100644 --- a/src/ingest_sidecap.h +++ b/src/ingest_sidecap.h @@ -2233,18 +2233,17 @@ inline bool adoptTestMacroBlock( const TagsPass& pass, TagsMatch& m, DefCodeNode // class_specifier and wrongly grab the whole CLASS body as its span — corrupting spans + ref attribution) — and a C-family // function BODY: a block-scope `Type v(args);` (most-vexing-parse) must not climb up and steal its enclosing function's span. A // real function definition's declarator parents directly to function_definition (found at hop 1), so that never fires for it. -inline bool isDeclaratorClimbStop( const char* pt ) noexcept -{ - return kindIs( pt, "class_specifier" ) || kindIs( pt, "struct_specifier" ) - || kindIs( pt, "field_declaration_list" ) || kindIs( pt, "declaration_list" ) - || kindIs( pt, "namespace_definition" ) || kindIs( pt, "enum_specifier" ) - || kindIs( pt, "translation_unit" ) || kindIs( pt, "source_file" ) // Swift top - || kindIs( pt, "class_body" ) || kindIs( pt, "protocol_body" ) // Swift type bodies - || kindIs( pt, "enum_class_body" ) - || kindIs( pt, "class_interface" ) || kindIs( pt, "class_implementation" ) // ObjC - || kindIs( pt, "implementation_definition" ) || kindIs( pt, "protocol_declaration" ) - || kindIs( pt, "compound_statement" ) || kindIs( pt, "block" ); -} +inline constexpr std::string_view kDeclaratorClimbStops[] = { + "class_specifier", "struct_specifier", + "field_declaration_list", "declaration_list", + "namespace_definition", "enum_specifier", + "translation_unit", "source_file", // Swift top + "class_body", "protocol_body", // Swift type bodies + "enum_class_body", + "class_interface", "class_implementation", // ObjC + "implementation_definition", "protocol_declaration", + "compound_statement", "block", +}; // What the declarator climb found: the span to adopt (null: keep the capture's own), the body it owns, and whether the role node // is a body-less C/C++ type specifier in a function's signature (a type use, never a definition). @@ -2258,8 +2257,7 @@ struct DeclaratorClimb // At a scope stop: the member/decl wrapper the climb came up through (a prototype's span, so the RETURN TYPE is included), else null. inline TSNode declarationWrapperOrNull( TSNode child ) noexcept { - const char* ct = ts_node_type( child ); - return kindIs( ct, "field_declaration" ) || kindIs( ct, "declaration" ) ? child : TSNode{}; + return isOneOf( ts_node_type( child ), { "field_declaration", "declaration" } ) ? child : TSNode{}; } // At the first ancestor owning a body: adopt it when the role node is its signature (outside the body) and not a body-less type @@ -2303,7 +2301,7 @@ inline DeclaratorClimb climbDeclaratorToDefinition( TSNode roleNode, bool bodyle TSNode p = parentOf( roleNode ); for( int guard = 0; !ts_node_is_null( p ) && guard < 4; ++guard ) { - if( isDeclaratorClimbStop( ts_node_type( p ) ) ) + if( isOneOf( ts_node_type( p ), kDeclaratorClimbStops ) ) { return DeclaratorClimb{ .span = declarationWrapperOrNull( child ) }; } From d32bc146e4a1eb80a4333661ade1006bbae44971 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:52:22 -0500 Subject: [PATCH 18/61] refactor(ingest): langidentity ceiling 321 -> 317 (captureTagsFacts' Elixir arms ask the language once) Co-Authored-By: Claude Opus 5.5 --- test/langidentity/ratchet.tsv | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/langidentity/ratchet.tsv b/test/langidentity/ratchet.tsv index 20b526167..d02d511df 100644 --- a/test/langidentity/ratchet.tsv +++ b/test/langidentity/ratchet.tsv @@ -36,7 +36,9 @@ # 324 -> 321 (train ge2, the composed tree): qd-unchecked-status + qd-unhandled-arm added two C-family predicates (the enum table's # Cpp/C filter, the C scanner branch) and the composed tree counted 326; quality.h defectSitesOf and cFamilyEnumTable now read # langfacts.h's DefectScan column, so all six defect-shape language tests (four of them main's) left the count. -ceiling 321 +# 321 -> 317 (GE-CAPTURETAGS): captureTagsFacts' three Elixir capture filters and its three Elixir definition-name arms each ask +# the language once, in a named step (ingest_sidecap.h keepLanguageCapture, nameDefinition). +ceiling 317 perlang ingest_elixir.h perlang elixir_resolve.h perlang ingest_clojure.h From a7defa40561eeb3a6ea9aaea087f515a3c49eb09 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:50:37 -0500 Subject: [PATCH 19/61] refactor(ingest): captureTagsFacts decides a definition's identity once; one writer per field, one drop protocol Round 2 of the captureTagsFacts great-engineer pass (blind review's top 3): - definitionIdentityOf decides a definition's name and kind before the arms run, in one place: the C++ out-of-line re-seat, the macro-annotation rename, the test-macro title, Clojure's head shape and Elixir's attribute -> Var. TagsMatch is immutable after readTagsMatch. The macro-invocation call site is its own step (emitMacroInvocationCall). - Each RawDef field has one writer: extent (with the annotation rename's start and loc), complexity, parameters (rename and Elixir arityExact included), and the pure indexedNameOf / definitionScopeOf, whose results captureDefinition writes. The Elixir head binds and defdelegate call leave the scope step for emitElixirHeadFacts. - One drop protocol: CaptureFate {Keep, Drop, Emitted} for every step that can end a match. optional is gone. captureTagsMatch documents the order it depends on. The read-only file facts (TagsFile) are split from the output sinks (TagsSinks&), so a signature shows whether the step emits. Byte-identical: every fact is decided as before. Co-Authored-By: Claude Opus 5.5 --- src/ingest_sidecap.h | 983 +++++++++++++++++++++++-------------------- 1 file changed, 528 insertions(+), 455 deletions(-) diff --git a/src/ingest_sidecap.h b/src/ingest_sidecap.h index 6e5690e1e..4a585990b 100644 --- a/src/ingest_sidecap.h +++ b/src/ingest_sidecap.h @@ -1865,25 +1865,6 @@ inline SymKind renamedAnnotationKind( TSNode name ) noexcept return member ? SymKind::Method : SymKind::Function; } -// MACRO-P1: a renamed annotation definition's facts that are the real function's, not the macro's: the parameter list in it is -// the ANNOTATION's (`( mu_ )`), the real one was the empty `()` emptyCallInitName requires, and its span and rows start at -// the real function's own declaration. No-op when nothing was renamed. -inline void applyAnnotationRename( RawDef& d, const AnnotationRename& renamed, TSNode defNode ) noexcept -{ - if( ts_node_is_null( renamed.name ) ) - { - return; - } - d.params = 0; - d.paramsMin = 0; - d.arityExact = 1; - if( !ts_node_is_null( renamed.start ) ) - { - d.startByte = ts_node_start_byte( renamed.start ); - d.loc = ts_node_end_point( defNode ).row - ts_node_start_point( renamed.start ).row + 1u; - } -} - // The two postures of one tags pass. Full: every fact the index keeps. DefinitionsOnly (definitionLinesInBlobs, --whereis on // other refs): the SAME definitions — every step that decides a definition's existence, name, line, kind or scope runs // unchanged — without the work only references, imports and metrics read: the @reference arm, @import emission, @@ -1895,51 +1876,64 @@ inline void applyAnnotationRename( RawDef& d, const AnnotationRename& renamed, T enum class TagsCapture : std::uint8_t { Full, DefinitionsOnly, DefinitionsAndShape }; // ── captureTagsFacts, as named steps (GE-CAPTURETAGS) ──────────────────────────────────────────────────────────────────────── -// One file's pass state (TagsPass), one match's captures read once into a TagsMatch (readTagsMatch), then the capture-time drop -// decisions in order (captureTagsMatch) and the definition or reference arm (captureDefinition / captureReference), each a -// sequence of named steps. Every step runs in the order the single loop body ran it; the outputs are byte-identical. +// One file's facts (TagsFile, read-only) and its output sinks (TagsSinks: a step whose signature takes them emits; one that does +// not is a pure reader). readTagsMatch reads one match's captures ONCE into an immutable TagsMatch; definitionIdentityOf decides a +// definition's name and kind ONCE into an immutable DefIdentity; captureTagsMatch runs the capture-time drop rules in their +// load-bearing order (its own comment lists it); then the definition arm writes each RawDef field in exactly one step, and the +// reference arm qualifies one RawRef. Every fact is decided as the single loop body this replaced decided it: byte-identical output. -// One file's tags pass: the facts every match reads and the sinks it appends to. Built once per file by captureTagsFacts. -struct TagsPass +// One file's facts, read by every step. Nothing here is written during the pass. +struct TagsFile +{ + const LangEntry& le; + std::uint32_t fileId; + std::string_view src; + TSNode root; + const ElixirContext& elixir; // Elixir's per-file module/alias/keyword tables (prepared before the match loop) + std::string_view fileStem; // the name of a bare `module.exports = ` (JS) + bool full; // TagsCapture::Full: references, imports and the def arm's IS-A / HAS-A / macro-body edges too + bool shape; // the callables' cc_walk facts (Full or DefinitionsAndShape) + bool fileHasError; // extent honesty: the recovered-bit walk (parseRecoveredBits) only exists in a file the parser had to recover +}; + +// Where the pass writes. A step that takes a TagsSinks& may append to these; no other step can. +struct TagsSinks { - const LangEntry& le; - std::uint32_t fileId; - std::string_view src; - TSNode root; std::vector& defs; std::vector& refs; std::vector& binds; std::vector& includes; - ExtractShortfall& shortfall; - ElixirContext& elixir; - std::string_view fileStem; // the name of a bare `module.exports = ` (JS) - bool full; // TagsCapture::Full: references, imports and the def arm's IS-A / HAS-A / macro-body edges too - bool shape; // the callables' cc_walk facts (Full or DefinitionsAndShape) - bool fileHasError; // extent honesty: the recovered-bit walk (parseRecoveredBits) only exists in a file the parser had to recover + ExtractShortfall& shortfall; // a capture the pass could not read whole says so here }; -// What one tags match captured. A tags pattern yields one @definition/@reference node plus a child @name: the role capture sets -// kind, the capture's name and roleNode; the @name capture sets the four name facts, and every later re-seat (C++ declarator, -// macro annotation, test-macro title) moves all four at once. +// What a step decided about the match — the ONE drop protocol of this pass. Every step that can end a match returns a fate, and +// its caller stops at the first one that is not Keep. Drop: the match writes nothing more. Emitted: the step wrote the match's own +// fact, and nothing more follows. +enum class CaptureFate : std::uint8_t { Keep, Drop, Emitted }; + +// What one tags match captured, read once by readTagsMatch and never written after. A tags pattern yields one +// @definition/@reference node plus a child @name. struct TagsMatch { - SymKind kind = SymKind::Other; + SymKind kind = SymKind::Other; // the role capture's kind, as the query spelled it (a definition's final kind: DefIdentity) bool isDef = false; bool isRef = false; std::string_view defCap; // the @definition capture's name — dropGatedCapture keys the constant/cjsexport/protomethod gates on it std::string_view refCap; // the @reference capture's name — "reference.import" routes the using-declaration role (r9 loss bucket 1) TSNode roleNode {}; - DefNameFacts name {}; // the @name identifier: its node (for C++ scope/qualifier, E#4), text, start byte and 0-based row + DefNameFacts name {}; // the @name identifier as captured: its node, text, start byte and 0-based row bool keywordHead = false; // #355: the pattern carried @_keyword, a head its tags.scm predicates accepted bool hasRole() const noexcept { return isDef || isRef; } bool hasName() const noexcept { return !ts_node_is_null( name.node ); } - void reseatName( TSNode node, std::string_view text ) noexcept - { - name = DefNameFacts{ node, text, ts_node_start_byte( node ), ts_node_start_point( node ).row }; - } }; +// The four name facts of `node`, spelled `text`. +inline DefNameFacts nameFactsAt( TSNode node, std::string_view text ) noexcept +{ + return DefNameFacts{ node, text, ts_node_start_byte( node ), ts_node_start_point( node ).row }; +} + // A C++ conversion operator's declarator is an `operator_cast` node whose text spans the WHOLE `operator () const` (the // tags query captures the declarator itself — there is no sub-node spanning just `operator bool`). Its name ends at the end of // the `type` field, so the symbol name is `operator bool` / `operator MyType`, not the param list. Symbolic ops @@ -1976,15 +1970,15 @@ inline DefNameFacts capturedNameOf( TSNode node, std::string_view src ) noexcept // #358: an `@import.*` capture, emitted here in capture order, not in a second pass. Matches arrive by start byte and captures // within a match in query order, so a staging vector would produce the identical order while costing an allocation and a drain // block. `import.names` / `import.alias` are one clause's target and its optional alias, paired once the match is read. -inline void noteImportCapture( const TagsPass& pass, std::string_view capSv, TSNode node, TSNode& importNames, TSNode& importAlias ) +inline void noteImportCapture( const TagsFile& file, TagsSinks& sinks, std::string_view capSv, TSNode node, TSNode& importNames, TSNode& importAlias ) { - if( !pass.full ) + if( !file.full ) { return; } if( capSv == "import.path" ) { - emitCapturedImport( node, pass.fileId, pass.le.lang, pass.src, pass.includes, pass.refs, pass.shortfall ); + emitCapturedImport( node, file.fileId, file.le.lang, file.src, sinks.includes, sinks.refs, sinks.shortfall ); } else if( capSv == "import.names" ) { @@ -1998,7 +1992,7 @@ inline void noteImportCapture( const TagsPass& pass, std::string_view capSv, TSN // Walk one match's captures into a TagsMatch: the role node and its capture, the name, the keyword head. The match's imports are // emitted on the way (noteImportCapture), and its import clause's bind (emitCapturedImportBind) after the walk. -inline TagsMatch readTagsMatch( const TagsPass& pass, TSQuery* query, const TSQueryMatch& match ) +inline TagsMatch readTagsMatch( const TagsFile& file, TagsSinks& sinks, TSQuery* query, const TSQueryMatch& match ) { TagsMatch m; TSNode importNames {}; @@ -2037,7 +2031,7 @@ inline TagsMatch readTagsMatch( const TagsPass& pass, TSQuery* query, const TSQu case CapRole::NameOnly: { - if( const DefNameFacts name = capturedNameOf( cap.node, pass.src ); !ts_node_is_null( name.node ) ) + if( const DefNameFacts name = capturedNameOf( cap.node, file.src ); !ts_node_is_null( name.node ) ) { m.name = name; } @@ -2049,73 +2043,126 @@ inline TagsMatch readTagsMatch( const TagsPass& pass, TSQuery* query, const TSQu case CapRole::Import: { - noteImportCapture( pass, capSv, cap.node, importNames, importAlias ); + noteImportCapture( file, sinks, capSv, cap.node, importNames, importAlias ); } break; } } if( !ts_node_is_null( importNames ) ) { - emitCapturedImportBind( importNames, importAlias, pass.fileId, pass.le.lang, pass.src, pass.binds ); + emitCapturedImportBind( importNames, importAlias, file.fileId, file.le.lang, file.src, sinks.binds ); } return m; } -// MACRO-P0 (ingest_names.h): a macro invocation read as a typeless declarator mints no definition of its own; the site is a -// call-shaped use of the macro (model.h retagMacroCallReferences makes it role="macro" when the #define is indexed and its name -// is uniquely a macro). No argument count: the "parameters" are macro arguments. MACRO-P1: when the grammar read the real -// function's own `f()` as a variable (ingest_names.h annotationRenamedName), this definition is the only one f gets — it -// carries f's name, from f's own start (`renamed`). false: the capture ends here (a macro use and nothing renamed behind it). -inline bool keepAfterMacroInvocation( const TagsPass& pass, TagsMatch& m, AnnotationRename& renamed ) +// A definition's identity: the name it is indexed under and its kind, decided once (definitionIdentityOf) and never written after. +struct DefIdentity +{ + DefNameFacts declarator {}; // the @name as declared — C++: the innermost name of a qualified out-of-line declarator (C1) + DefNameFacts name {}; // the name the definition is indexed under: the declarator, the real function behind a macro + // annotation (MACRO-P1) or a test macro block's title (LB-E) + SymKind kind = SymKind::Other; // the definition's kind: the capture's, or the renamed function's, Clojure's head shape, + // Var for an Elixir module attribute. Spans, metrics, scopes and edges read THIS kind; + // only the index row of an Elixir defimpl/defprotocol module shows another (elixirIndexedName) + AnnotationRename renamed {}; // MACRO-P1: the real function's name and start when a macro annotation hid it; null otherwise + bool macroUse = false; // MACRO-P0: the declarator is a macro invocation — a call site of the macro (emitMacroInvocationCall) + CaptureFate fate = CaptureFate::Keep; // Drop: mints no definition — a macro use with no function behind it, a test macro + // block without its parts (dropGatedCapture's own veto, guarded here, not asserted) +}; + +// Decide a definition's name and kind, in one place: +// - C1 (memgraph F1, ingest_names.h cppDefNameReseat): a C++ out-of-line definition is named by the innermost name of its +// qualified declarator. +// - MACRO-P0/P1 (ingest_names.h): a macro invocation read as a typeless declarator mints no definition of its own; when the grammar +// read the real function's own `f()` as a variable (annotationRenamedName), this definition is the only one f gets — it carries +// f's name and kind (renamedAnnotationKind), from f's own start. +// - LB-E testmacroblock: the def is TWO SIBLING nodes (testMacroBlockPartsOf); its name is the title literal (a display string). +// - Clojure: the kind is the head's shape (`defn`, `defmacro`, `defprotocol` …); Elixir: a module attribute (`@doc`, `@type`) is a Var. +// Pure: what a later step drops, it drops on these facts. +inline DefIdentity definitionIdentityOf( const TagsFile& file, const TagsMatch& m ) { - if( !cFamilyMacroInvocationCapture( m.defCap, pass.le.lang, m.name.text, m.roleNode, pass.src ) ) // defCap: set by a @definition capture only + const Lang lang = file.le.lang; + DefIdentity id; + id.kind = m.kind; + const DefNameFacts reseated = cppDefNameReseat( lang == Lang::Cpp, m.name.node, file.src ); // a null node: nothing to re-seat + id.declarator = ts_node_is_null( reseated.node ) ? m.name : reseated; + id.name = id.declarator; + id.macroUse = cFamilyMacroInvocationCapture( m.defCap, lang, id.declarator.text, m.roleNode, file.src ); + if( id.macroUse ) { - return true; + id.renamed = annotationRenamedName( m.roleNode, file.src ); + if( ts_node_is_null( id.renamed.name ) ) + { + id.fate = CaptureFate::Drop; + return id; + } + id.name = nameFactsAt( id.renamed.name, nodeTextOf( id.renamed.name, file.src ) ); + id.kind = renamedAnnotationKind( id.renamed.name ); + } + else if( m.defCap == "definition.testmacroblock" ) + { + const TestMacroBlockParts parts = testMacroBlockPartsOf( m.roleNode, file.src ); + if( !parts.ok ) + { + id.fate = CaptureFate::Drop; + return id; + } + id.name = nameFactsAt( parts.title, testMacroTitleOf( parts.title, file.src ) ); + } + else if( lang == Lang::Clojure ) + { + id.kind = clojureDefinitionShape( m.roleNode, file.src ).kind; + } + else if( lang == Lang::Elixir && m.defCap == "definition.attribute" ) + { + id.kind = SymKind::Var; + } + return id; +} + +// MACRO-P0: a macro invocation's site is a call-shaped use of the macro (model.h retagMacroCallReferences makes it role="macro" when +// the #define is indexed and its name is uniquely a macro). No argument count: the "parameters" are macro arguments. +inline void emitMacroInvocationCall( const TagsFile& file, TagsSinks& sinks, const TagsMatch& m, const DefIdentity& id ) +{ + if( !id.macroUse ) + { + return; } RawRef r; - r.fileId = pass.fileId; + r.fileId = file.fileId; r.startByte = ts_node_start_byte( m.roleNode ); r.line = ts_node_start_point( m.roleNode ).row + 1; - r.lang = pass.le.lang; + r.lang = file.le.lang; r.role = RefRole::Call; - r.name = m.name.text; - pass.refs.push_back( std::move( r ) ); - renamed = annotationRenamedName( m.roleNode, pass.src ); - if( ts_node_is_null( renamed.name ) ) - { - return false; - } - m.reseatName( renamed.name, nodeTextOf( renamed.name, pass.src ) ); - m.kind = renamedAnnotationKind( renamed.name ); - return true; + r.name = id.declarator.text; + sinks.refs.push_back( std::move( r ) ); } -// INDEX-ALIAS-CONST (src/aliasdef.h, the one alias reader): a C++ alias form is a definition unless it is function-local -// (ingest_relations.h insideFunctionBody: a function-local alias is a local name, the local-const rule). std::nullopt: the capture -// is dropped; form None: not an alias definition. -inline std::optional aliasShapeOfCapture( Lang lang, const TagsMatch& m ) +// INDEX-ALIAS-CONST (src/aliasdef.h, the one alias reader): a C++ alias form (`using X = Y;`, a namespace alias) is a definition. +inline bool isAliasDefinition( Lang lang, const TagsMatch& m ) noexcept { - if( !m.isDef || !langFacts( lang ).aliasTargetDefs || m.defCap != "definition.alias" ) + return m.isDef && langFacts( lang ).aliasTargetDefs && m.defCap == "definition.alias"; +} + +// INDEX-ALIAS-CONST: where an alias definition's written target starts when it ENDS the declaration (--defs to=), else 0 (a typedef, +// or no alias). The target is a suffix when every child after it is the `;` or a comment (`using X = Y /* c */ ;` keeps its target; +// the printer drops the comment, defslookup.h aliasTargetText); one cursor walk (infra/tschildren.h). Only `using`/namespace alias +// rows reach the walk (a typedef capture is never definition.alias). +inline std::uint32_t aliasTargetStartOf( const TagsFile& file, const TagsMatch& m ) +{ + if( !isAliasDefinition( file.le.lang, m ) ) { - return AliasShape{}; + return 0u; } - if( insideFunctionBody( m.roleNode ) ) + const AliasShape aliasShape = aliasShapeOf( Lang::Cpp, m.roleNode ); + if( aliasShape.form == AliasForm::None ) { - return std::nullopt; + return 0u; } - return aliasShapeOf( Lang::Cpp, m.roleNode ); -} - -// INDEX-ALIAS-CONST: where an alias's written target starts when it ENDS the declaration (--defs to=), else 0 (a typedef). The -// target is a suffix when every child after it is the `;` or a comment (`using X = Y /* c */ ;` keeps its target; the printer -// drops the comment, defslookup.h aliasTargetText); one cursor walk (infra/tschildren.h). Only `using`/namespace alias rows -// reach here (a typedef capture is never definition.alias). -inline std::uint32_t aliasTargetStartOf( TSNode roleNode, const AliasShape& aliasShape ) -{ const std::uint32_t tEnd = ts_node_end_byte( aliasShape.target ); bool suffix = true; - ChildCursor cursor( roleNode ); - forEachChild( roleNode, cursor.cur, [ & ]( TSNode c ) + ChildCursor cursor( m.roleNode ); + forEachChild( m.roleNode, cursor.cur, [ & ]( TSNode c ) { const char* k = ts_node_type( c ); suffix = ts_node_start_byte( c ) < tEnd || kindIs( k, ";" ) || kindIs( k, "comment" ); @@ -2124,82 +2171,76 @@ inline std::uint32_t aliasTargetStartOf( TSNode roleNode, const AliasShape& alia return suffix ? ts_node_start_byte( aliasShape.target ) : 0u; } -// Elixir's capture filters a tags pattern cannot state: elixirKeepCapture's syntax filters; a bare name is a call only off a pipe -// (bare pipe targets have their own capture) and past lexical variable exclusion; the special-form operators are no calls. -inline bool keepElixirCapture( const TagsPass& pass, const TagsMatch& m ) +// Elixir's capture filters a tags pattern cannot state, on the capture AS CAPTURED (its query kind): elixirKeepCapture's syntax +// filters; a bare name is a call only off a pipe (bare pipe targets have their own capture) and past lexical variable exclusion; +// the special-form operators are no calls. +inline CaptureFate elixirFilterFate( const TagsFile& file, const TagsMatch& m ) { - if( !elixirKeepCapture( m.roleNode, m.name.node, ElixirCaptureRole{ m.isDef, m.kind, m.keywordHead }, pass.src, pass.elixir.keywords ) ) + if( !elixirKeepCapture( m.roleNode, m.name.node, ElixirCaptureRole{ m.isDef, m.kind, m.keywordHead }, file.src, file.elixir.keywords ) ) { - return false; + return CaptureFate::Drop; } if( m.refCap == "reference.bare" ) { const TSNode parent = parentOf( m.name.node ); - const bool pipeTarget = elixirNodeIs( parent, "binary_operator" ) && nodeFieldText( parent, NodeField::Operator, pass.src ) == "|>" + const bool pipeTarget = elixirNodeIs( parent, "binary_operator" ) && nodeFieldText( parent, NodeField::Operator, file.src ) == "|>" && ts_node_eq( fieldChild( parent, NodeField::Right ), m.name.node ); - return !pipeTarget && pass.elixir.bareCall( m.name.node ); + return !pipeTarget && file.elixir.bareCall( m.name.node ) ? CaptureFate::Keep : CaptureFate::Drop; } if( m.refCap == "reference.operator" ) { constexpr std::string_view special[] = { "=", "<-", "\\\\", "::", "|>", "when", "|", "^", "&", "@" }; if( std::find( std::begin( special ), std::end( special ), m.name.text ) != std::end( special ) ) { - return false; + return CaptureFate::Drop; } - const TSNode parent = parentOf( m.roleNode ); - return !( m.name.text == "/" && elixirNodeIs( parent, "unary_operator" ) && nodeFieldText( parent, NodeField::Operator, pass.src ) == "&" ); + const TSNode parent = parentOf( m.roleNode ); + const bool capture = m.name.text == "/" && elixirNodeIs( parent, "unary_operator" ) && nodeFieldText( parent, NodeField::Operator, file.src ) == "&"; + return capture ? CaptureFate::Drop : CaptureFate::Keep; } - return true; + return CaptureFate::Keep; } -// The per-language capture filters (Elixir's, Clojure's); a Clojure definition's kind is its head's shape. -inline bool keepLanguageCapture( const TagsPass& pass, TagsMatch& m ) +// The per-language capture filters: Elixir's, and Clojure's (a definition needs a defining head, a reference must not be a special form). +inline CaptureFate languageFilterFate( const TagsFile& file, const TagsMatch& m ) { - if( pass.le.lang == Lang::Elixir ) + if( file.le.lang == Lang::Elixir ) { - return keepElixirCapture( pass, m ); + return elixirFilterFate( file, m ); } - if( pass.le.lang != Lang::Clojure ) + if( file.le.lang == Lang::Clojure && !clojureKeepCapture( m.roleNode, m.isDef, file.src ) ) { - return true; - } - if( !clojureKeepCapture( m.roleNode, m.isDef, pass.src ) ) - { - return false; - } - if( m.isDef ) - { - m.kind = clojureDefinitionShape( m.roleNode, pass.src ).kind; + return CaptureFate::Drop; } - return true; + return CaptureFate::Keep; } -// A capture inside an inert quote region: call/operator/named-capture candidates are kept as declined facts, never edges. Heads, -// special forms and non-call operators already failed their syntax filters. Bare AST names remain variable-shaped syntax unless -// they explicitly name a function capture. true: the capture was in such a region (consumed here). -inline bool consumeInertQuoteCapture( const TagsPass& pass, const TagsMatch& m ) +// A capture inside an inert quote region ends here: call/operator/named-capture candidates are kept as declined facts, never edges +// (Emitted); every other capture is dropped. Heads, special forms and non-call operators already failed their syntax filters. Bare +// AST names remain variable-shaped syntax unless they explicitly name a function capture. +inline CaptureFate inertQuoteFate( const TagsFile& file, TagsSinks& sinks, const TagsMatch& m ) { - if( !langFacts( pass.le.lang ).hasInertQuoteRegions || !elixirInert( m.roleNode, pass.src ) ) + if( !langFacts( file.le.lang ).hasInertQuoteRegions || !elixirInert( m.roleNode, file.src ) ) { - return false; + return CaptureFate::Keep; } const bool candidate = m.isRef && ( m.refCap == "reference.call" || m.refCap == "reference.operator" - || ( m.refCap == "reference.bare" && pass.elixir.namedCapture( m.name.node ) ) ); + || ( m.refCap == "reference.bare" && file.elixir.namedCapture( m.name.node ) ) ); if( !candidate ) { - return true; + return CaptureFate::Drop; } RawRef r; - r.fileId = pass.fileId; + r.fileId = file.fileId; r.startByte = ts_node_start_byte( m.roleNode ); r.line = m.name.row + 1; r.lang = Lang::Elixir; r.role = RefRole::Inert; - auto [ count, known ] = elixirCallArity( m.roleNode, m.name.node, pass.src ); + auto [ count, known ] = elixirCallArity( m.roleNode, m.name.node, file.src ); if( m.refCap == "reference.operator" ) { count = elixirNodeIs( m.roleNode, "binary_operator" ) ? 2 : 1; known = true; } r.name = known ? elixirFunctionName( m.name.text, count ) : std::string( m.name.text ); - pass.refs.push_back( std::move( r ) ); - return true; + sinks.refs.push_back( std::move( r ) ); + return CaptureFate::Emitted; } // Where a definition's code lives: the node its span covers, its body (null: a declaration), the function literal a name is bound @@ -2209,25 +2250,10 @@ struct DefCodeNodes TSNode defNode {}; TSNode body {}; TSNode literal {}; - bool testMacroBlock = false; // LB-E: the def is TWO SIBLING nodes (testMacroBlockPartsOf) + bool testMacroBlock = false; // LB-E: the def is TWO SIBLING nodes (testMacroBlockPartsOf): the macro statement and its block bool spanThroughBody = false; // the code this symbol owns lives in a SIBLING node: byte/row extents and complexity run through it }; -// LB-E testmacroblock: adopt the sibling compound_statement as the body and the title literal as the name BEFORE the shared -// span/complexity steps. The span's endByte and the loc row window run past defNode's own end (no single node covers both -// siblings). false: not a test macro block after all (dropGatedCapture already vetoed non-candidates — guard, don't assert). -inline bool adoptTestMacroBlock( const TagsPass& pass, TagsMatch& m, DefCodeNodes& span ) -{ - const TestMacroBlockParts parts = testMacroBlockPartsOf( m.roleNode, pass.src ); - if( !parts.ok ) - { - return false; - } - span.body = parts.body; - m.reseatName( parts.title, testMacroTitleOf( parts.title, pass.src ) ); - return true; -} - // The declarator climb's STOP set: a type/namespace/file scope — a function's body never lives above one of these, so reaching // one means the role node is a prototype/declaration with no body (without this, an in-class method declaration would climb into // class_specifier and wrongly grab the whole CLASS body as its span — corrupting spans + ref attribution) — and a C-family @@ -2262,7 +2288,7 @@ inline TSNode declarationWrapperOrNull( TSNode child ) noexcept // At the first ancestor owning a body: adopt it when the role node is its signature (outside the body) and not a body-less type // specifier; a body-less type specifier outside the body is a type use in the signature. -inline DeclaratorClimb bodyOwnerClimb( TSNode owner, TSNode ownerBody, TSNode roleNode, bool bodylessTypeSpec ) +inline DeclaratorClimb adoptBodyOwnerOrTypeUse( TSNode owner, TSNode ownerBody, TSNode roleNode, bool bodylessTypeSpec ) { const bool outsideBody = !spanContains( ownerBody, roleNode ); if( outsideBody && !bodylessTypeSpec ) @@ -2307,7 +2333,7 @@ inline DeclaratorClimb climbDeclaratorToDefinition( TSNode roleNode, bool bodyle } if( const TSNode pb = fieldChild( p, NodeField::Body ); !ts_node_is_null( pb ) ) { - return bodyOwnerClimb( p, pb, roleNode, bodylessTypeSpec ); + return adoptBodyOwnerOrTypeUse( p, pb, roleNode, bodylessTypeSpec ); } child = p; p = parentOf( p ); @@ -2357,84 +2383,110 @@ inline TSNode positionalBodyOf( Lang lang, TSNode defNode ) return body; } -// A definition's span and body. defBodyNodeOf = the `body:` field, PLUS the macro-edges round's one addition: a #define's -// replacement text (`value:` field) is adopted as a macro symbol's body, set before the climb so the climb is skipped for macros -// — PLUS a name bound to a function literal (kFnLiteralBinding): the literal's body, with `literal` the node params/cx/nest read -// from. Grammars whose @definition node already owns the body (class/struct/enum) don't climb. +// A definition's code nodes. defBodyNodeOf = the `body:` field, PLUS the macro-edges round's one addition: a #define's replacement +// text (`value:` field) is adopted as a macro symbol's body, set before the climb so the climb is skipped for macros — PLUS a name +// bound to a function literal (kFnLiteralBinding): the literal's body, with `literal` the node params/cx/nest read from. Grammars +// whose @definition node already owns the body (class/struct/enum) don't climb. LB-E: a test macro block's body is its sibling +// block, so it never climbs either. // // A Var's span is its own declaration — never climb. The climb exists to find a FUNCTION's body; for a var it can only steal a // container's span (a Ruby class-level constant's parent chain is body_statement → class, and class owns a "body" field, so the // climb would hand the constant THE WHOLE CLASS — the exact Rust-method span bug the H4 W3 note describes). No-op for every // pre-existing Var capture (Swift/C#/Go/Python parents hit a scope-stop or the file root before any "body"-owning ancestor — // verified byte-identical on the gate corpora). A Field's span is its own field_declaration / defining assignment — the Var rule, -// same reason. std::nullopt: the capture mints no definition (a test macro block without its parts, a type use in a signature). -inline std::optional definitionSpanOf( const TagsPass& pass, TagsMatch& m ) +// same reason. std::nullopt: no definition — a body-less C/C++ specifier in a function's signature is a type use. +inline std::optional definitionCodeOf( const TagsFile& file, const TagsMatch& m, const DefIdentity& id ) { - const Lang lang = pass.le.lang; - const DefBodyNodes own = lang == Lang::Elixir ? DefBodyNodes{ elixirBody( m.roleNode, pass.src ), {}, m.roleNode } - : defBodyNodeOf( m.roleNode, m.name.node, m.kind, lang ); - DefCodeNodes span; - span.defNode = own.span; - span.body = own.body; - span.literal = own.literal; - span.testMacroBlock = m.defCap == "definition.testmacroblock"; - if( span.testMacroBlock && !adoptTestMacroBlock( pass, m, span ) ) + const Lang lang = file.le.lang; + const DefBodyNodes own = lang == Lang::Elixir ? DefBodyNodes{ elixirBody( m.roleNode, file.src ), {}, m.roleNode } + : defBodyNodeOf( m.roleNode, id.name.node, id.kind, lang ); + DefCodeNodes code; + code.defNode = own.span; + code.body = own.body; + code.literal = own.literal; + code.testMacroBlock = m.defCap == "definition.testmacroblock"; + if( code.testMacroBlock ) { - return std::nullopt; + code.body = testMacroBlockPartsOf( m.roleNode, file.src ).body; // its parts were read whole: definitionIdentityOf } - if( ts_node_is_null( span.body ) && m.kind != SymKind::Var && m.kind != SymKind::Field && lang != Lang::Elixir ) + if( ts_node_is_null( code.body ) && id.kind != SymKind::Var && id.kind != SymKind::Field && lang != Lang::Elixir ) { const DeclaratorClimb climb = climbDeclaratorToDefinition( m.roleNode, isCFamilyTypeSpecifier( lang, m.roleNode ) ); if( climb.typeUseInSignature ) { - return std::nullopt; // a body-less C/C++ specifier in a function's signature: a type use, never a definition + return std::nullopt; } - span.defNode = ts_node_is_null( climb.span ) ? span.defNode : climb.span; - span.body = climb.body; + code.defNode = ts_node_is_null( climb.span ) ? code.defNode : climb.span; + code.body = climb.body; } // MACRO-P1: a prototype adopts its trailing annotation's definition body, its span running THROUGH that sibling - const TSNode ownBody = span.body; - span.body = annotatedSiblingBody( span.body, lang, m.kind, m.roleNode, pass.src ); - bool siblingBody = !ts_node_eq( span.body, ownBody ); - if( ts_node_is_null( span.body ) ) + const TSNode ownBody = code.body; + code.body = annotatedSiblingBody( code.body, lang, id.kind, m.roleNode, file.src ); + bool siblingBody = !ts_node_eq( code.body, ownBody ); + if( ts_node_is_null( code.body ) ) { - span.body = positionalBodyOf( lang, span.defNode ); + code.body = positionalBodyOf( lang, code.defNode ); } // Dart's body is a SIBLING of the signature, so neither defBodyNodeOf nor the climb can find it and the span would stop at the // signature — see dartFollowingBody (ingest_relations.h) for the measurement and for why an abstract member still comes back null. - if( ts_node_is_null( span.body ) && lang == Lang::Dart ) + if( ts_node_is_null( code.body ) && lang == Lang::Dart ) { - span.body = dartFollowingBody( span.defNode ); - siblingBody = !ts_node_is_null( span.body ); + code.body = dartFollowingBody( code.defNode ); + siblingBody = !ts_node_is_null( code.body ); } - span.spanThroughBody = span.testMacroBlock || siblingBody; - return span; + code.spanThroughBody = code.testMacroBlock || siblingBody; + return code; } -// The byte extents: the span (LB-E: through the sibling block), the name, the body. INDEX-ALIAS-CONST: a body-less alias row's -// target start rides bodyByte to the model, which moves it to IngestResult::aliasTargets and keeps the whole declaration as the -// signature (ingest_model.h rawDefIsAliasRow); 0 when the target is not a suffix. -inline void fillDefinitionExtent( RawDef& d, const DefCodeNodes& span, std::uint32_t nameByte, std::uint32_t aliasTargetStart ) noexcept +// The definition's extent — its byte span (LB-E: through the sibling block), name byte, body byte and line count (Q4 size smell: +// physical LOC = span line count). MACRO-P1: a renamed annotation definition's span and rows start at the real function's own +// declaration. INDEX-ALIAS-CONST: a body-less alias row's target start rides bodyByte to the model, which moves it to +// IngestResult::aliasTargets and keeps the whole declaration as the signature (ingest_model.h rawDefIsAliasRow); 0 when the target +// is not a suffix. +inline void fillDefinitionExtent( RawDef& d, const DefCodeNodes& code, const DefIdentity& id, std::uint32_t aliasTargetStart ) noexcept { - d.startByte = ts_node_start_byte( span.defNode ); - d.endByte = span.spanThroughBody ? ts_node_end_byte( span.body ) : ts_node_end_byte( span.defNode ); - d.nameByte = nameByte; - d.bodyByte = ts_node_is_null( span.body ) ? 0u : ts_node_start_byte( span.body ); - if( d.bodyByte == 0 && aliasTargetStart > d.startByte && aliasTargetStart < d.endByte ) + const std::uint32_t spanStart = ts_node_start_byte( code.defNode ); + const TSNode spanEnd = code.spanThroughBody ? code.body : code.defNode; + const TSNode realStart = ts_node_is_null( id.renamed.name ) ? TSNode{} : id.renamed.start; + d.endByte = ts_node_end_byte( spanEnd ); + d.nameByte = id.name.byte; + d.bodyByte = ts_node_is_null( code.body ) ? 0u : ts_node_start_byte( code.body ); + if( d.bodyByte == 0 && aliasTargetStart > spanStart && aliasTargetStart < d.endByte ) { d.bodyByte = aliasTargetStart; // INDEX-ALIAS-CONST: the transport only (ingest_model.h rawDefIsAliasRow) } + if( !ts_node_is_null( realStart ) ) + { + d.startByte = ts_node_start_byte( realStart ); + d.loc = ts_node_end_point( code.defNode ).row - ts_node_start_point( realStart ).row + 1u; + return; + } + const std::uint32_t startRow = ts_node_start_point( code.defNode ).row; + const std::uint32_t endRow = ts_node_end_point( spanEnd ).row; + d.startByte = spanStart; + d.loc = ( endRow >= startRow ) ? ( endRow - startRow + 1u ) : 1u; } -// A callable's cc_walk facts (complexityOf) onto its definition: all 0 off a callable, where complexityOf did not run. The narrower -// fields saturate on purpose — ppalt (model.h Symbol::ppAlt): a def past 65535 is beyond every triage threshold, and the attribute's -// claim ("the body carries alternatives") is already made at 1; the nesting profile (model.h Symbol::humps/deepLoc): deepLoc is a -// floor already, so a clamp there stays honest in the direction the attribute already claims; essential complexity (model.h -// Symbol::ev) is already saturated inside ev_finalize, 0 for non-function kinds and outside evCountedLang, matching the emitters' -// omission rule; QD-TANGLE's steering locals and dispatch share (model.h Symbol::steer, ::dispatchShare). -inline void fillDefinitionComplexity( RawDef& d, const Complexity& c ) noexcept +inline bool isCallableKind( SymKind kind ) noexcept { + return kind == SymKind::Function || kind == SymKind::Method; +} + +// A callable's cc_walk facts (complexityOf) onto its definition. complexityOf runs on a callable only (and only with `shape`); off a +// callable every fact is 0 — the zero Complexity below, which is what keeps ppAlt, maxNest, the nesting profile and ev absent on a +// type. LB-E: a test macro block's body SIBLING is where the code lives — complexityOf walks INSIDE its root node, so handing it +// defNode, the bare macro statement, would count nothing; a literal-bound name measures its LITERAL; every other def measures defNode. +// The narrower fields saturate on purpose — ppalt (model.h Symbol::ppAlt): a def past 65535 is beyond every triage threshold, and the +// attribute's claim ("the body carries alternatives") is already made at 1; the nesting profile (model.h Symbol::humps/deepLoc): +// deepLoc is a floor already, so a clamp there stays honest in the direction the attribute already claims; essential complexity +// (model.h Symbol::ev) is already saturated inside ev_finalize, 0 outside evCountedLang, matching the emitters' omission rule; +// QD-TANGLE's steering locals and dispatch share (model.h Symbol::steer, ::dispatchShare). +inline void fillDefinitionComplexity( RawDef& d, const TagsFile& file, const DefIdentity& id, const DefCodeNodes& code ) +{ + const TSNode measured = code.spanThroughBody ? code.body : ( ts_node_is_null( code.literal ) ? code.defNode : code.literal ); + const Complexity c = isCallableKind( id.kind ) && file.shape ? complexityOf( measured, file.src, file.le.lang ) + : Complexity{ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, {}, 0u, 0u, 0u }; d.cx = c.cx; d.ccx = c.ccx; d.locals = c.locals; // Phase 1: floor count, C/C++ only (model.h localsCountedLang) — 0 elsewhere, never emitted there @@ -2459,64 +2511,61 @@ inline std::uint16_t definitionParamCount( Lang lang, TSNode defNode, TSNode met return lang == Lang::Clojure ? clojureParams( defNode, src ) : paramCountOf( metricNode, literalBound ); } -// The definition's shape: complexity (LB-E: a testmacroblock's body SIBLING is where the code lives — complexityOf walks INSIDE its -// root node, so handing it defNode, the bare macro statement, would count nothing; a literal-bound name measures its LITERAL; every -// other def measures defNode), Q4 size smells (SIZE = master variable: physical LOC = span line count; param count + max nesting -// for functions/methods only, 0 otherwise, absent in emit — all descriptive), the parameter shape, the in-file test-scope bit. -inline void fillDefinitionShape( const TagsPass& pass, RawDef& d, const TagsMatch& m, const DefCodeNodes& span, const AnnotationRename& renamed ) -{ - const Lang lang = pass.le.lang; - const bool fnOrMethod = ( m.kind == SymKind::Function || m.kind == SymKind::Method ); - const bool literalBound = !ts_node_is_null( span.literal ); - const TSNode metricNode = literalBound ? span.literal : span.defNode; - fillDefinitionComplexity( d, - fnOrMethod && pass.shape ? complexityOf( span.spanThroughBody ? span.body : metricNode, pass.src, lang ) - : Complexity{ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, {}, 0u, 0u, 0u } ); - const std::uint32_t startRow = ts_node_start_point( span.defNode ).row; - const std::uint32_t endRow = ts_node_end_point( span.spanThroughBody ? span.body : span.defNode ).row; // LB-E: rows through the sibling block - d.loc = ( endRow >= startRow ) ? ( endRow - startRow + 1u ) : 1u; - d.params = fnOrMethod ? definitionParamCount( lang, span.defNode, metricNode, literalBound, pass.src ) : std::uint16_t( 0 ); - // LB-E: a testmacroblock's parameter surface is the MACRO's business, not visible here — claim inexact so the resolver's arity - // narrowing never trusts params=0 on a test-title symbol. B2.2: the fixed-arity bit and the minimum (fewest arguments a call can - // pass) come from ONE scan of the list. A minimum above the counted params (a literal-bound bare parameter countParams cannot - // see) is not trusted. - const ParamShape paramShape = ( fnOrMethod && !span.testMacroBlock && lang != Lang::Clojure ) ? cc_paramShape( metricNode, lang, m.kind, pass.src ) : ParamShape{}; - d.arityExact = paramShape.exact ? std::uint8_t( 1 ) : std::uint8_t( 0 ); - d.paramsMin = paramShape.minimum <= d.params ? paramShape.minimum : std::uint16_t( 0 ); - applyAnnotationRename( d, renamed, span.defNode ); // MACRO-P1: the real function's parameters and start, not the annotation's - // L8: the in-file test-scope bit, for EVERY kind (a `#[cfg(test)] mod` and a `class TestFoo` are themselves symbols, and dropping - // the members while keeping the shell would be a worse answer than either). Runs on defNode, whose ancestors are the enclosing scopes. - d.testScope = span.testMacroBlock ? std::uint8_t( 1 ) : std::uint8_t( inFileTestScope( span.defNode, pass.src, lang ) ); // LB-E: a test macro IS the in-file convention - d.kind = m.kind; - d.lang = lang; +// The definition's parameter surface: how many (functions/methods only, 0 otherwise, absent in emit), the fewest a call can pass +// and whether the count is exact (B2.2: one scan of the list). A minimum above the counted params (a literal-bound bare parameter +// countParams cannot see) is not trusted. LB-E: a test macro block's parameter surface is the MACRO's business, not visible here — +// claimed inexact so the resolver's arity narrowing never trusts params=0 on a test-title symbol. MACRO-P1: a renamed annotation +// definition's list is the ANNOTATION's (`( mu_ )`); the real one was the empty `()` emptyCallInitName requires. B2.2 for an Elixir +// def head: a clause's arity IS its parameter count (no variadic form), so `params` is call-comparable unless a `\\` default widens +// the callable to more than one arity; cc_paramShape's language gate leaves it at 0, which made every Elixir caller unflaggable by +// --edit-check (test/elixirnamearitycheck.sh arm C: run(x) -> run(x, y) must flag run(x) callers; run(x, y \\ 1) must flag none). +inline void fillDefinitionParameters( RawDef& d, const TagsFile& file, const TagsMatch& m, const DefIdentity& id, const DefCodeNodes& code ) +{ + if( !ts_node_is_null( id.renamed.name ) ) + { + d.params = 0; + d.paramsMin = 0; + d.arityExact = 1; + return; + } + const Lang lang = file.le.lang; + const bool callable = isCallableKind( id.kind ); + const bool literalBound = !ts_node_is_null( code.literal ); + const TSNode metricNode = literalBound ? code.literal : code.defNode; + const auto counted = callable ? definitionParamCount( lang, code.defNode, metricNode, literalBound, file.src ) : std::uint16_t( 0 ); + const ParamShape paramShape = ( callable && !code.testMacroBlock && lang != Lang::Clojure ) ? cc_paramShape( metricNode, lang, id.kind, file.src ) : ParamShape{}; + const bool elixirHead = lang == Lang::Elixir && m.keywordHead; + d.params = counted; + d.paramsMin = paramShape.minimum <= counted ? paramShape.minimum : std::uint16_t( 0 ); + d.arityExact = ( elixirHead ? elixirHeadDefaultCount( m.roleNode, file.src ) == 0 : paramShape.exact ) ? std::uint8_t( 1 ) : std::uint8_t( 0 ); } // An Elixir module attribute's definition name: a typed attribute (@type/@callback and kin) is named with its arity, any other // attribute is `@name`. -inline std::string elixirAttributeDefName( std::string_view attribute, const TagsMatch& m ) +inline std::string elixirAttributeDefName( std::string_view attribute, const DefNameFacts& name ) { if( !elixirTypedAttribute( attribute ) ) { - return "@" + std::string( m.name.text ); + return "@" + std::string( name.text ); } - const TSNode args = elixirArguments( parentOf( m.name.node ) ); + const TSNode args = elixirArguments( parentOf( name.node ) ); std::uint32_t arity = 0; for( std::uint32_t i = 0; !ts_node_is_null( args ) && i < ts_node_named_child_count( args ); ++i ) { arity += elixirNodeIs( ts_node_named_child( args, i ), "comment" ) ? 0u : 1u; } - return ( attribute == "callback" || attribute == "macrocallback" ? "@callback " : "@type " ) + elixirFunctionName( m.name.text, arity ); + return ( attribute == "callback" || attribute == "macrocallback" ? "@callback " : "@type " ) + elixirFunctionName( name.text, arity ); } -// `defimpl P, for: T` — the @name capture is just the protocol alias, but the module Elixir generates is `P.T`, which is what the -// impl's own defs carry as their scope. A protocol is an Interface, a module that defines a struct (or exception) a Struct. -inline SymKind elixirModuleKind( const TagsPass& pass, TSNode roleNode, const std::string& module ) +// The kind an Elixir defimpl/defprotocol module is INDEXED as: a protocol is an Interface, a module that defines a struct (or +// exception) a Struct, any other a Class. +inline SymKind elixirModuleKind( const TagsFile& file, TSNode roleNode, const std::string& module ) { - const SymKind kind = elixirTarget( roleNode, pass.src ) == "defprotocol" ? SymKind::Interface : SymKind::Class; - for( TSNode call : pass.elixir.calls ) + const SymKind kind = elixirTarget( roleNode, file.src ) == "defprotocol" ? SymKind::Interface : SymKind::Class; + for( TSNode call : file.elixir.calls ) { - const auto keyword = elixirTarget( call, pass.src ); - if( ( keyword == "defstruct" || keyword == "defexception" ) && pass.elixir.scopeOf( call ) == module ) + const auto keyword = elixirTarget( call, file.src ); + if( ( keyword == "defstruct" || keyword == "defexception" ) && file.elixir.scopeOf( call ) == module ) { return SymKind::Struct; } @@ -2524,49 +2573,76 @@ inline SymKind elixirModuleKind( const TagsPass& pass, TSNode roleNode, const st return kind; } -// Elixir's definition names: a static ExUnit title (interpolation was rejected by elixirKeepCapture), a module attribute, a -// generated module. false: a module with no name to give it. -inline bool nameElixirDefinition( const TagsPass& pass, RawDef& d, const TagsMatch& m ) +inline bool isExUnitTest( const TagsFile& file, const TagsMatch& m ) +{ + return file.le.lang == Lang::Elixir && elixirTarget( m.roleNode, file.src ) == "test"; +} + +// The name a definition is indexed under, and its kind there. Drop: the capture mints no row. +struct IndexedName +{ + std::string name; + SymKind kind = SymKind::Other; + CaptureFate fate = CaptureFate::Keep; +}; + +// An Elixir definition's index name and kind. A def head (#355: the match's own @_keyword capture, decided by tags.scm, not a C++ +// keyword list) is named with its arity (`f/2`, `params`); a static ExUnit title (interpolation was rejected by elixirKeepCapture) is +// `test `; a module attribute is elixirAttributeDefName's; a `defimpl P, for: T` — whose @name capture is just the protocol +// alias — is the module Elixir generates, `P.T`, which is what the impl's own defs carry as their scope (indexed as +// elixirModuleKind's kind; Drop when it has no name). Anything else keeps the capture's name. +inline IndexedName elixirIndexedName( const TagsFile& file, const TagsMatch& m, const DefIdentity& id, std::uint16_t params ) { - if( elixirTarget( m.roleNode, pass.src ) == "test" ) + const bool exUnitTest = isExUnitTest( file, m ); + const std::string_view attribute = exUnitTest ? std::string_view{} : elixirAttribute( m.roleNode, file.src ); + const bool generatedModule = !exUnitTest && attribute.empty() && id.kind == SymKind::Other; + std::string module = generatedModule ? file.elixir.moduleName( m.roleNode ) : std::string{}; + if( generatedModule && module.empty() ) { - d.name = "test " + std::string( m.name.text.substr( 1, m.name.text.size() - 2 ) ); - d.testScope = 1; - return true; + return IndexedName{ .fate = CaptureFate::Drop }; } - if( const std::string_view attribute = elixirAttribute( m.roleNode, pass.src ); !attribute.empty() ) + const SymKind kind = generatedModule ? elixirModuleKind( file, m.roleNode, module ) : id.kind; + if( m.keywordHead ) { - d.name = elixirAttributeDefName( attribute, m ); - return true; + return IndexedName{ elixirFunctionName( id.name.text, params ), kind }; } - if( m.kind != SymKind::Other ) + if( exUnitTest ) { - return true; + return IndexedName{ "test " + std::string( id.name.text.substr( 1, id.name.text.size() - 2 ) ), kind }; } - d.name = pass.elixir.moduleName( m.roleNode ); - if( d.name.empty() ) + if( !attribute.empty() ) { - return false; + return IndexedName{ elixirAttributeDefName( attribute, id.name ), kind }; } - d.kind = elixirModuleKind( pass, m.roleNode, d.name ); - return true; + return IndexedName{ generatedModule ? std::move( module ) : defNameFromCapture( Lang::Elixir, id.name.text ), kind }; } -// The definition's name: the capture's (LB-E: a test title is a display string — see testMacroTitleOf), the file's stem for the -// module's own CommonJS export function (lane js-def-naming, ingest_names.h isCjsModuleExportsItself), Elixir's own. false: the -// capture mints no row (no stem to name an anonymous export by, as before; an unnamed Elixir module). -inline bool nameDefinition( const TagsPass& pass, RawDef& d, const TagsMatch& m, bool testMacroBlock ) +// The definition's index name and kind: the identity's name (LB-E: a test title is a display string — see testMacroTitleOf), the +// file's stem for the module's own CommonJS export function (lane js-def-naming, ingest_names.h isCjsModuleExportsItself; Drop when +// there is no stem to name it by, as before), Elixir's own (elixirIndexedName). +inline IndexedName indexedNameOf( const TagsFile& file, const TagsMatch& m, const DefIdentity& id, const DefCodeNodes& code, std::uint16_t params ) { - d.name = testMacroBlock ? std::string( m.name.text ) : defNameFromCapture( pass.le.lang, m.name.text ); - if( m.defCap == "definition.cjsexport" && isCjsModuleExportsItself( m.name.node, pass.src ) ) + if( file.le.lang == Lang::Elixir ) { - if( pass.fileStem.empty() ) - { - return false; - } - d.name = std::string( pass.fileStem ); + return elixirIndexedName( file, m, id, params ); + } + if( m.defCap == "definition.cjsexport" && isCjsModuleExportsItself( id.name.node, file.src ) ) + { + return file.fileStem.empty() ? IndexedName{ .fate = CaptureFate::Drop } : IndexedName{ std::string( file.fileStem ), id.kind }; + } + return IndexedName{ code.testMacroBlock ? std::string( id.name.text ) : defNameFromCapture( file.le.lang, id.name.text ), id.kind }; +} + +// L8: the in-file test-scope bit, for EVERY kind (a `#[cfg(test)] mod` and a `class TestFoo` are themselves symbols, and dropping +// the members while keeping the shell would be a worse answer than either). Read on defNode, whose ancestors are the enclosing +// scopes. LB-E: a test macro IS the in-file convention; so is an ExUnit `test`. +inline std::uint8_t definitionTestScope( const TagsFile& file, const TagsMatch& m, const DefCodeNodes& code ) +{ + if( code.testMacroBlock || isExUnitTest( file, m ) ) + { + return 1; } - return pass.le.lang != Lang::Elixir || nameElixirDefinition( pass, d, m ); + return std::uint8_t( inFileTestScope( code.defNode, file.src, file.le.lang ) ); } // A FUNCTION bound inside another function's body records that function's span (ingest_names.h enclosingFunctionScope): graph.h @@ -2574,197 +2650,198 @@ inline bool nameDefinition( const TagsPass& pass, RawDef& d, const TagsMatch& m, // defNode climbed from its declarator (the role node) to the function_definition, which must not read as the function enclosing // itself; a multi-name binding's defNode narrowed to one declarator, whose declaration (the role node) holds no scope node and is // not a 20k-child list to rescan per name. -inline void noteEnclosingFunctionScope( const TagsPass& pass, RawDef& d, const TagsMatch& m, TSNode defNode ) +inline void noteEnclosingFunctionScope( RawDef& d, const TagsFile& file, const TagsMatch& m, const DefIdentity& id, TSNode defNode ) { - if( !pass.full || m.kind != SymKind::Function || bindsOutsideItsFunction( m.roleNode, pass.le.lang ) ) + if( !file.full || id.kind != SymKind::Function || bindsOutsideItsFunction( m.roleNode, file.le.lang ) ) { return; } const bool defIsOuter = ts_node_start_byte( defNode ) <= ts_node_start_byte( m.roleNode ) && ts_node_end_byte( defNode ) >= ts_node_end_byte( m.roleNode ); - const FnScope fnScope = enclosingFunctionScope( pass.root, defIsOuter ? defNode : m.roleNode ); + const FnScope fnScope = enclosingFunctionScope( file.root, defIsOuter ? defNode : m.roleNode ); d.fnScopeStart = fnScope.start; d.fnScopeEnd = fnScope.end; } -// `defdelegate f(x), to: M, as: g`: the delegating clause calls M.g with its own arity. -inline void emitElixirDelegate( const TagsPass& pass, const RawDef& d, const TagsMatch& m ) +// A C++ definition's canonical scope (E#4): out-of-line `A::b` → "A" (`Box<T>::grow` (primary) → "Box"; a specialization keeps +// its id), else the enclosing class/namespace. +inline std::string cppDefinitionScope( TSNode nameNode, std::string_view src ) { - RawRef delegated; - delegated.fileId = pass.fileId; delegated.startByte = d.startByte; delegated.line = d.line; - delegated.lang = pass.le.lang; delegated.recv = RecvKind::ElixirModule; - delegated.qualifier = pass.elixir.moduleOf( elixirKeywordValue( m.roleNode, "to:", pass.src ), m.roleNode ); - const auto as = nodeTextOf( elixirKeywordValue( m.roleNode, "as:", pass.src ), pass.src ); - delegated.name = elixirFunctionName( as.starts_with( ":" ) ? as.substr( 1 ) : m.name.text, d.params ); - delegated.argCount = d.params; delegated.argCountKnown = true; - if( !delegated.qualifier.empty() ) { pass.refs.push_back( std::move( delegated ) ); } + std::string scope = qualifierOfDefinition( nameNode, src ); + return scope.empty() ? enclosingScopeOf( nameNode, src ) : scope; } -// An Elixir definition's scope, and for a def head (#355: the match's own @_keyword capture, decided by tags.scm, not a C++ keyword -// list) its arity-qualified name. B2.2 for Elixir: a clause's arity IS its parameter count (no variadic form), so `params` is -// call-comparable unless a `\\` default widens the callable to more than one arity. cc_paramShape's language gate leaves this at 0, -// which made every Elixir caller unflaggable by --edit-check (test/elixirnamearitycheck.sh arm C: run(x) -> run(x, y) must flag -// run(x) callers; run(x, y \\ 1) must flag none). -inline void scopeElixirDefinition( const TagsPass& pass, RawDef& d, const TagsMatch& m ) +// The definition's scope, per language ("" where the language records none). +inline std::string definitionScopeOf( const TagsFile& file, const TagsMatch& m, const DefIdentity& id ) { - d.scope = m.kind == SymKind::Other ? std::string{} : pass.elixir.scopeOf( m.roleNode ); - if( !m.keywordHead ) + const Lang lang = file.le.lang; + if( lang == Lang::Cpp ) { - return; + return cppDefinitionScope( id.name.node, file.src ); + } + if( enumTableAt( kDefScopeWalkerOfLang, lang, DefScopeWalker::None ) != DefScopeWalker::None ) + { // Python, Go, Rust, Kotlin: the language's row in ingest_names.h kDefScopeWalkerOfLang + return defScopeOf( lang, id.name.node, file.src ); } - d.name = elixirFunctionName( m.name.text, d.params ); - d.arityExact = elixirHeadDefaultCount( m.roleNode, pass.src ) == 0 ? std::uint8_t( 1 ) : std::uint8_t( 0 ); - elixirDefinitionFacts( d, m.roleNode, pass.src, pass.binds, pass.elixir.keywords ); - if( elixirTarget( m.roleNode, pass.src ) == "defdelegate" ) + if( lang == Lang::Elixir ) { - emitElixirDelegate( pass, d, m ); + return id.kind == SymKind::Other ? std::string{} : file.elixir.scopeOf( m.roleNode ); + } + if( lang == Lang::Ruby ) + { // enclosing class/module → id= addressability, per-class overload sets, editCheckImplicitReceiver + return rubyEnclosingScopeOf( id.name.node, file.src ); // (test/rubyscopecheck.sh) + } + if( ( lang == Lang::JavaScript || lang == Lang::TypeScript ) && m.defCap == "definition.protomethod" ) + { // only the five built-in ctors: every Foo.prototype.bar gaining sc= would mint a new + // canonical id and move quality baselines (node lib/ has ~163 anonymous protomethods) + const std::string_view ctor = prototypeCtorName( id.name.node, file.src ); + return isJsTsBuiltinCtor( ctor ) ? std::string( ctor ) : std::string{}; } + return std::string{}; } -// A C++ definition's canonical scope (E#4): out-of-line `A::b` → "A", else the enclosing class/namespace. -inline void scopeCppDefinition( RawDef& d, TSNode nameNode, std::string_view src ) +// `defdelegate f(x), to: M, as: g`: the delegating clause calls M.g with its own arity. +inline void emitElixirDelegate( const TagsFile& file, TagsSinks& sinks, const RawDef& d, const TagsMatch& m, const DefIdentity& id ) { - d.scope = qualifierOfDefinition( nameNode, src ); // `Box<T>::grow` (primary) → "Box"; a specialization keeps its id - if( d.scope.empty() ) - { - d.scope = enclosingScopeOf( nameNode, src ); - } - // #150: is this def genuinely INSIDE namespace std, at ANY nesting depth — not just a def - // whose immediate scope happens to spell a segment std also uses? See Symbol::scopeRootsStd. - d.scopeRootsStd = cppDefinitionRootsStd( nameNode, src ) ? std::uint8_t( 1 ) : std::uint8_t( 0 ); + RawRef delegated; + delegated.fileId = file.fileId; delegated.startByte = d.startByte; delegated.line = d.line; + delegated.lang = file.le.lang; delegated.recv = RecvKind::ElixirModule; + delegated.qualifier = file.elixir.moduleOf( elixirKeywordValue( m.roleNode, "to:", file.src ), m.roleNode ); + const auto as = nodeTextOf( elixirKeywordValue( m.roleNode, "as:", file.src ), file.src ); + delegated.name = elixirFunctionName( as.starts_with( ":" ) ? as.substr( 1 ) : id.name.text, d.params ); + delegated.argCount = d.params; delegated.argCountKnown = true; + if( !delegated.qualifier.empty() ) { sinks.refs.push_back( std::move( delegated ) ); } } -// The definition's scope, per language. -inline void scopeDefinition( const TagsPass& pass, RawDef& d, const TagsMatch& m, TSNode defNode ) +// An Elixir def head's own facts, read off the finished definition: its callable (and default-arity) binds, and a defdelegate's call. +inline void emitElixirHeadFacts( const TagsFile& file, TagsSinks& sinks, const RawDef& d, const TagsMatch& m, const DefIdentity& id ) { - const Lang lang = pass.le.lang; - if( lang == Lang::Cpp ) + if( file.le.lang != Lang::Elixir || !m.keywordHead ) { - scopeCppDefinition( d, m.name.node, pass.src ); - } - else if( enumTableAt( kDefScopeWalkerOfLang, lang, DefScopeWalker::None ) != DefScopeWalker::None ) - { // Python, Go, Rust, Kotlin: the language's row in ingest_names.h kDefScopeWalkerOfLang - d.scope = defScopeOf( lang, m.name.node, pass.src ); + return; } - else if( lang == Lang::Elixir ) + elixirDefinitionFacts( d, m.roleNode, file.src, sinks.binds, file.elixir.keywords ); + if( elixirTarget( m.roleNode, file.src ) == "defdelegate" ) { - scopeElixirDefinition( pass, d, m ); - } - else if( lang == Lang::Ruby ) - { // enclosing class/module → id= addressability, per-class overload sets, editCheckImplicitReceiver - d.scope = rubyEnclosingScopeOf( m.name.node, pass.src ); // (test/rubyscopecheck.sh) - if( m.kind == SymKind::Method || m.kind == SymKind::Function ) - { - rubyNoteClassSideDef( defNode, pass.fileId, d.name, pass.src, pass.binds ); // a class object's method (test/rubyclassrecvcheck.sh) - } + emitElixirDelegate( file, sinks, d, m, id ); } - else if( ( lang == Lang::JavaScript || lang == Lang::TypeScript ) && m.defCap == "definition.protomethod" ) - { // only the five built-in ctors: every Foo.prototype.bar gaining sc= would mint a new - // canonical id and move quality baselines (node lib/ has ~163 anonymous protomethods) - const std::string_view ctor = prototypeCtorName( m.name.node, pass.src ); - if( isJsTsBuiltinCtor( ctor ) ) - { - d.scope = std::string( ctor ); - } +} + +// A Ruby method defined on the class object (`def self.m`, `class << self`): its bind (test/rubyclassrecvcheck.sh). +inline void emitRubyClassSideBind( const TagsFile& file, TagsSinks& sinks, const RawDef& d, const DefIdentity& id, TSNode defNode ) +{ + if( file.le.lang == Lang::Ruby && isCallableKind( id.kind ) ) + { + rubyNoteClassSideDef( defNode, file.fileId, d.name, file.src, sinks.binds ); } } -// The reference edges a definition mints (TagsCapture::Full only): a type's IS-A and HAS-A edges, a macro's body calls. -inline void captureDefinitionEdges( const TagsPass& pass, const TagsMatch& m, TSNode defNode ) +// The reference edges a definition mints (TagsCapture::Full only): a type's IS-A and HAS-A edges, a macro's body calls. On the +// identity's kind — an Elixir module indexed as a Class/Struct/Interface is an Other capture here and mints none. +inline void captureDefinitionEdges( const TagsFile& file, TagsSinks& sinks, const TagsMatch& m, const DefIdentity& id, TSNode defNode ) { - const Lang lang = pass.le.lang; - if( m.kind == SymKind::Class || isStructOrNamedType( m.kind ) || m.kind == SymKind::Interface ) + const Lang lang = file.le.lang; + if( id.kind == SymKind::Class || isStructOrNamedType( id.kind ) || id.kind == SymKind::Interface ) { // #446: a language on the bases-as-captures port reads its bases through the // @reference.base reader (LangFacts::basesAsCaptures; C++ is the first). The // others keep the walk; C++'s own walk survives for captureSpecializationHeader. if( !langFacts( lang ).basesAsCaptures ) { - captureBases( defNode, pass.fileId, lang, pass.src, pass.refs ); // IS-A: inheritance edges (derived → base) + captureBases( defNode, file.fileId, lang, file.src, sinks.refs ); // IS-A: inheritance edges (derived → base) } if( m.defCap == "definition.classfactory" ) // lane lego-transitive (M2): the factory's receiver is the base { - emitBaseRef( jsClassFactoryReceiver( m.name.node, pass.src ), pass.fileId, lang, pass.src, pass.refs, defNode ); + emitBaseRef( jsClassFactoryReceiver( id.name.node, file.src ), file.fileId, lang, file.src, sinks.refs, defNode ); } - captureFields( defNode, pass.fileId, lang, pass.src, pass.refs ); // HAS-A: member-variable type edges (S5-E) + captureFields( defNode, file.fileId, lang, file.src, sinks.refs ); // HAS-A: member-variable type edges (S5-E) } - else if( m.kind == SymKind::Macro ) + else if( id.kind == SymKind::Macro ) { - captureMacroBodyCalls( m.roleNode, pass.fileId, lang, pass.src, pass.refs ); // macro-edges: the graph connects THROUGH the macro + captureMacroBodyCalls( m.roleNode, file.fileId, lang, file.src, sinks.refs ); // macro-edges: the graph connects THROUGH the macro if( langFacts( lang ).bangMacros ) // Rust: `$crate` exists only where `name!` macros do { - captureRustTranscriberMacroCalls( m.roleNode, pass.fileId, pass.src, pass.refs ); // RUST-MACRO-PATH: `$crate::m!` in a transcriber + captureRustTranscriberMacroCalls( m.roleNode, file.fileId, file.src, sinks.refs ); // RUST-MACRO-PATH: `$crate::m!` in a transcriber } } } -// The definition arm: span, extents, shape, name, linkage, function scope, scope and parse-recovery bits into one RawDef, then -// (Full) the edges it mints. `renamed`: MACRO-P1's annotation rename; `aliasTargetStart`: INDEX-ALIAS-CONST's written target. -void captureDefinition( const TagsPass& pass, TagsMatch& m, const AnnotationRename& renamed, std::uint32_t aliasTargetStart ) +// The definition arm: one RawDef, each field written by exactly one step — extent, complexity, parameters, name and kind, test scope, +// linkage, enclosing function, scope, parse-recovery bits — then its own binds and calls, the row, and (Full) the edges it mints. +// `aliasTargetStart`: INDEX-ALIAS-CONST's written target (aliasTargetStartOf). +inline void captureDefinition( const TagsFile& file, TagsSinks& sinks, const TagsMatch& m, const DefIdentity& id, std::uint32_t aliasTargetStart ) { - if( pass.le.lang == Lang::Elixir && m.defCap == "definition.attribute" ) { m.kind = SymKind::Var; } - const std::optional<DefCodeNodes> span = definitionSpanOf( pass, m ); - if( !span ) + const std::optional<DefCodeNodes> code = definitionCodeOf( file, m, id ); + if( !code ) { - return; + return; // a body-less C/C++ specifier in a function's signature: a type use, never a definition } RawDef d; - d.fileId = pass.fileId; - d.line = m.name.row + 1; // the identifier's line — most accurate, dedup-stable (a test macro block's: its title's, re-seated above) - fillDefinitionExtent( d, *span, m.name.byte, aliasTargetStart ); - fillDefinitionShape( pass, d, m, *span, renamed ); - if( !nameDefinition( pass, d, m, span->testMacroBlock ) ) + d.fileId = file.fileId; + d.lang = file.le.lang; + d.line = id.name.row + 1; // the identifier's line — most accurate, dedup-stable (a test macro block's: its title's) + fillDefinitionExtent( d, *code, id, aliasTargetStart ); + fillDefinitionComplexity( d, file, id, *code ); + fillDefinitionParameters( d, file, m, id, *code ); + IndexedName indexed = indexedNameOf( file, m, id, *code, d.params ); + if( indexed.fate != CaptureFate::Keep ) { return; } + d.name = std::move( indexed.name ); + d.kind = indexed.kind; + d.testScope = definitionTestScope( file, m, *code ); // Internal linkage (model.h Symbol::internalLinkage): C and C++ only, read off defNode — the node that owns // the storage class and whose ancestors are the enclosing namespaces (ingest_names.h::cppInternalLinkage). - d.internalLinkage = internalLinkageBit( pass.le.lang, span->defNode, pass.src ); - noteEnclosingFunctionScope( pass, d, m, span->defNode ); - scopeDefinition( pass, d, m, span->defNode ); + d.internalLinkage = internalLinkageBit( file.le.lang, code->defNode, file.src ); + noteEnclosingFunctionScope( d, file, m, id, code->defNode ); + d.scope = definitionScopeOf( file, m, id ); + // #150: is this def genuinely INSIDE namespace std, at ANY nesting depth — not just a def + // whose immediate scope happens to spell a segment std also uses? See Symbol::scopeRootsStd. + d.scopeRootsStd = file.le.lang == Lang::Cpp && cppDefinitionRootsStd( id.name.node, file.src ) ? std::uint8_t( 1 ) : std::uint8_t( 0 ); // extent honesty: did the parse RECOVER this def's container or kind? Only asked in a file whose root // holds an error (fileHasError, one O(1) flag test per file) — see parseRecoveredBits. - d.recovered = pass.fileHasError ? parseRecoveredBits( span->defNode, m.kind, pass.le.lang, d.scope.empty() ) : std::uint8_t( 0 ); - pass.defs.push_back( std::move( d ) ); - if( pass.full ) // TagsCapture::DefinitionsOnly: the reference edges feed no definition + d.recovered = file.fileHasError ? parseRecoveredBits( code->defNode, id.kind, file.le.lang, d.scope.empty() ) : std::uint8_t( 0 ); + emitRubyClassSideBind( file, sinks, d, id, code->defNode ); + emitElixirHeadFacts( file, sinks, d, m, id ); + sinks.defs.push_back( std::move( d ) ); + if( file.full ) // TagsCapture::DefinitionsOnly: the reference edges feed no definition { - captureDefinitionEdges( pass, m, span->defNode ); + captureDefinitionEdges( file, sinks, m, id, code->defNode ); } } -// The reference captures that are not a plain use-site. true: consumed here — emitted as their own fact, or dropped. -inline bool consumeSpecialReference( const TagsPass& pass, const TagsMatch& m ) +// The reference captures that are not a plain use-site, each ending the match: an element access names its receiver class's +// subscript operator, a Ruby mixin and a base-clause type are base edges (Emitted); a C++ cast keyword, an intrinsic JSX tag and a +// using-DIRECTIVE are no reference at all (Drop). Keep: a plain use-site. +inline CaptureFate specialReferenceFate( const TagsFile& file, TagsSinks& sinks, const TagsMatch& m ) { - const Lang lang = pass.le.lang; + const Lang lang = file.le.lang; // An element access: @name is its RECEIVER, and the site names the receiver class's subscript operator // method (ingest_binds.h subscriptOperatorRef) — never a call by itself (RefRole::Subscript). if( m.refCap == "reference.subscript" ) { - if( std::optional<RawRef> sub = subscriptOperatorRef( m.roleNode, m.name.node, pass.fileId, lang, pass.src ) ) + std::optional<RawRef> sub = subscriptOperatorRef( m.roleNode, m.name.node, file.fileId, lang, file.src ); + if( !sub ) { - pass.refs.push_back( std::move( *sub ) ); + return CaptureFate::Drop; } - return true; + sinks.refs.push_back( std::move( *sub ) ); + return CaptureFate::Emitted; } // H4: a C++ cast keyword is not a call — see isCppCastKeyword. Valid input, skipped, no alert. - if( lang == Lang::Cpp && isCppCastKeyword( m.name.text ) ) - { - return true; - } // #285: an intrinsic JSX tag (`<div>`, `<h1>`) is not a call — see isJsxIntrinsicTagIdentifier. // Valid input, skipped, no alert; a qualified (`<Foo.Bar />`) or namespaced (`<svg:rect />`) // tag never reaches this test (see that function's note for why). - if( ( lang == Lang::TypeScript || lang == Lang::JavaScript ) && isJsxIntrinsicTagIdentifier( m.roleNode, m.name.node, m.name.text ) ) - { - return true; - } // using-declaration re-exports (r9 loss bucket 1): @reference.import marks the C++ // `using ns::name;` tags pattern. The site becomes a role="import" use-site of the target // (never a call edge — graph.h admits Call+Macro only), and the grammar KEYWORD forms // (`using namespace ns;` / `using enum E;`) are dropped here at capture time, where the // query predicate a tags pattern cannot express IS enforceable (see the helper's note). - if( m.refCap == "reference.import" && usingDeclarationIsDirective( m.roleNode ) ) + if( ( lang == Lang::Cpp && isCppCastKeyword( m.name.text ) ) + || ( ( lang == Lang::TypeScript || lang == Lang::JavaScript ) && isJsxIntrinsicTagIdentifier( m.roleNode, m.name.node, m.name.text ) ) + || ( m.refCap == "reference.import" && usingDeclarationIsDirective( m.roleNode ) ) ) { - return true; + return CaptureFate::Drop; } // family 4 / slice 4a: a @reference.mixin capture is Ruby's `include`/`extend`/`prepend` — the shape // lives in queries/ruby/tags.scm, so the capture IS the language gate and no Lang:: branch is spent @@ -2775,8 +2852,8 @@ inline bool consumeSpecialReference( const TagsPass& pass, const TagsMatch& m ) // separate match. if( m.refCap == "reference.mixin" ) { - emitCapturedRubyMixinBase( m.roleNode, m.name.node, pass.fileId, lang, pass.src, pass.refs ); - return true; + emitCapturedRubyMixinBase( m.roleNode, m.name.node, file.fileId, lang, file.src, sinks.refs ); + return CaptureFate::Emitted; } // #446: a @reference.base capture is a base-clause type on the class-def path — // queries/<lang>/tags.scm names the clause's type node, so the capture IS the language @@ -2784,55 +2861,55 @@ inline bool consumeSpecialReference( const TagsPass& pass, const TagsMatch& m ) // the captureBases walk passed; C++ is the first language on this capture. if( m.refCap == "reference.base" ) { - emitBaseRef( m.name.node, pass.fileId, lang, pass.src, pass.refs, parentOf( m.roleNode ) ); - return true; + emitBaseRef( m.name.node, file.fileId, lang, file.src, sinks.refs, parentOf( m.roleNode ) ); + return CaptureFate::Emitted; } - return false; + return CaptureFate::Keep; } -// An Elixir reference's module, role and arity-qualified name. false: `r` is finished here — an attribute read pushed as its own -// fact, or a call whose module or arity is unknown (dropped). -inline bool qualifyElixirReference( const TagsPass& pass, const TagsMatch& m, RawRef& r ) +// An Elixir reference's module, role and arity-qualified name. Emitted: an attribute read, pushed as its own fact. Drop: a call +// whose module or arity is unknown. Keep: `r` is qualified and goes on. +inline CaptureFate qualifyElixirReference( const TagsFile& file, TagsSinks& sinks, const TagsMatch& m, RawRef& r ) { - r.qualifier = pass.elixir.scopeOf( m.roleNode ); + r.qualifier = file.elixir.scopeOf( m.roleNode ); if( m.refCap == "reference.attribute" ) { r.role = RefRole::Read; r.name = "@" + std::string( m.name.text ); - pass.refs.push_back( std::move( r ) ); - return false; + sinks.refs.push_back( std::move( r ) ); + return CaptureFate::Emitted; } const TSNode target = fieldChild( m.roleNode, NodeField::Target ); if( !ts_node_is_null( target ) && kindIs( ts_node_type( target ), "dot" ) ) { const TSNode receiver = fieldChild( target, NodeField::Left ); - r.qualifier = pass.elixir.moduleOf( receiver, m.roleNode ); - if( r.qualifier.empty() ) { return false; } + r.qualifier = file.elixir.moduleOf( receiver, m.roleNode ); + if( r.qualifier.empty() ) { return CaptureFate::Drop; } // `__MODULE__` spelled, or an alias of it (`alias __MODULE__, as: Current`): the receiver names the // enclosing module, and the reference is re-attributed per implementation of a multi-target defimpl - r.recv = nodeTextOf( receiver, pass.src ).starts_with( "__MODULE__" ) || pass.elixir.selfRelativeAlias( receiver, m.roleNode ) + r.recv = nodeTextOf( receiver, file.src ).starts_with( "__MODULE__" ) || file.elixir.selfRelativeAlias( receiver, m.roleNode ) ? RecvKind::ElixirSelfModule : RecvKind::ElixirModule; } - auto [ count, known ] = elixirCallArity( m.roleNode, m.name.node, pass.src ); + auto [ count, known ] = elixirCallArity( m.roleNode, m.name.node, file.src ); if( m.refCap == "reference.operator" ) { count = elixirNodeIs( m.roleNode, "binary_operator" ) ? 2 : 1; known = true; } - if( !known ) { return false; } + if( !known ) { return CaptureFate::Drop; } r.argCount = count; r.argCountKnown = true; r.name = elixirFunctionName( m.name.text, count ); - return true; + return CaptureFate::Keep; } // A C++ or Rust reference's qualifier as written. Returns RULE3-MEMBER-GUARD fix 4's Rust path-call qualifier as written, when // longer than one segment ("" otherwise) — set by readReceiverFacts once the receiver fields are. -inline std::string qualifyPathReference( const TagsPass& pass, const TagsMatch& m, RawRef& r ) +inline std::string qualifyPathReference( const TagsFile& file, const TagsMatch& m, RawRef& r ) { - const Lang lang = pass.le.lang; + const Lang lang = file.le.lang; std::string rustWritten; if( lang == Lang::Cpp ) { - r.qualifier = qualifierOf( m.name.node, pass.src ); // `A::b()` → "A" (E#4 canonical resolve) + r.qualifier = qualifierOf( m.name.node, file.src ); // `A::b()` → "A" (E#4 canonical resolve) // #150: the FULL written chain's root, BEFORE the H4 re-split below overwrites r.qualifier // with the immediate segment only (`std::ranges::move` loses "std", keeps "ranges") — see // Reference::qualifierRootsStd and graph.h::keepStdQualifiedCandidates. - r.qualifierRootsStd = cppQualifiedChainRootsStd( m.name.node, pass.src ); + r.qualifierRootsStd = cppQualifiedChainRootsStd( m.name.node, file.src ); cppResplitRefName( r, m.name.text ); // H4 RE-SPLIT at 3+ segments, operator tails, `template` disambiguator } else if( langFacts( lang ).bangMacros && r.role == RefRole::Macro ) @@ -2842,16 +2919,16 @@ inline std::string qualifyPathReference( const TagsPass& pass, const TagsMatch& if( !ts_node_is_null( parent ) && kindIs( ts_node_type( parent ), "scoped_identifier" ) ) { std::string qualifier; - rustMacroPathOf( nodeTextOf( fieldChild( parent, NodeField::Path ), pass.src ), qualifier, rustWritten ); + rustMacroPathOf( nodeTextOf( fieldChild( parent, NodeField::Path ), file.src ), qualifier, rustWritten ); r.qualifier = qualifier; } } else if( lang == Lang::Rust ) { - r.qualifier = rustQualifierOf( m.name.node, pass.src ); // H4: `Widget::new()` → "Widget" + r.qualifier = rustQualifierOf( m.name.node, file.src ); // H4: `Widget::new()` → "Widget" if( r.role == RefRole::Call ) { - rustWritten = rustWrittenQualifier( m.name.node, pass.src ); + rustWritten = rustWrittenQualifier( m.name.node, file.src ); } } return rustWritten; @@ -2859,15 +2936,15 @@ inline std::string qualifyPathReference( const TagsPass& pass, const TagsMatch& // A call site's receiver and argument facts (an import site has no receiver and no argument list — the defaults, // RecvKind::None and argCountKnown=false, are the truth there; Elixir's were read by qualifyElixirReference). -inline void readReceiverFacts( const TagsPass& pass, const TagsMatch& m, RawRef& r, std::string rustWritten ) +inline void readReceiverFacts( const TagsFile& file, const TagsMatch& m, RawRef& r, std::string rustWritten ) { - const Lang lang = pass.le.lang; + const Lang lang = file.le.lang; // FE-B: a Java method INVOCATION reads its receiver like every other language (a member call or a bare // implicit-this call); only a method REFERENCE (`T::m`) keeps issue #74's type-candidate shape. const bool javaMethodRef = lang == Lang::Java && !ts_node_is_null( m.roleNode ) && kindIs( ts_node_type( m.roleNode ), "method_reference" ); RecvShape rs = javaMethodRef - ? javaMethodReferenceReceiver( m.roleNode, pass.src ) - : receiverOf( m.name.node, lang, pass.src ); // P2-D: `this`/`self`/`x`/`base.field` shape + ? javaMethodReferenceReceiver( m.roleNode, file.src ) + : receiverOf( m.name.node, lang, file.src ); // P2-D: `this`/`self`/`x`/`base.field` shape r.recv = rs.kind; r.recvVar = rs.var; // → one-hop narrowing in resolve.h r.setFieldName( std::move( rs.field ) ); // depth-2 intermediate field; "" otherwise r.viaArrow = rs.viaArrow; // `p->m()`: Rule 2b's smart-pointer pointee needs it @@ -2875,9 +2952,9 @@ inline void readReceiverFacts( const TagsPass& pass, const TagsMatch& m, RawRef& r.setMemberPath( std::move( rs.path ) ); r.setMemberCtor( std::move( rs.ctor ) ); // FE-B: the rest of that receiver chain if( lang == Lang::Ruby && r.recv == RecvKind::NamedVar ) { - r.setFieldName( rubyReceiverWrittenPath( m.name.node, r.recvVar, pass.src ) ); // parser version 137: a constant's path as written + r.setFieldName( rubyReceiverWrittenPath( m.name.node, r.recvVar, file.src ) ); // parser version 137: a constant's path as written } - auto [ ac, ak ] = callArity( m.name.node, lang, pass.src ); // B2.2: call-site positional arg count + auto [ ac, ak ] = callArity( m.name.node, lang, file.src ); // B2.2: call-site positional arg count r.argCount = ac; r.argCountKnown = ak; // → arity filter in graph.h if( langFacts( lang ).trailingLambdaScopeFns ) { @@ -2889,7 +2966,7 @@ inline void readReceiverFacts( const TagsPass& pass, const TagsMatch& m, RawRef& } if( isQueueLang( lang ) && isQueueCallName( r.name ) ) { - if( const std::uint8_t kw = callKeywords( m.name.node, pass.src ); kw != 0 ) + if( const std::uint8_t kw = callKeywords( m.name.node, file.src ); kw != 0 ) { r.setComposeRel( pyKwTag( kw ) ); // a queue call's keywords, for QueueHops (model.h pyKwTag) } @@ -2897,16 +2974,16 @@ inline void readReceiverFacts( const TagsPass& pass, const TagsMatch& m, RawRef& } // The reference arm (TagsCapture::Full only): a use-site's role, name, qualifier and receiver facts into one RawRef. -void captureReference( const TagsPass& pass, const TagsMatch& m ) +inline void captureReference( const TagsFile& file, TagsSinks& sinks, const TagsMatch& m ) { - if( consumeSpecialReference( pass, m ) ) + if( specialReferenceFate( file, sinks, m ) != CaptureFate::Keep ) { return; } - const Lang lang = pass.le.lang; + const Lang lang = file.le.lang; const bool isImportRef = ( m.refCap == "reference.import" ); RawRef r; - r.fileId = pass.fileId; + r.fileId = file.fileId; r.startByte = ts_node_start_byte( m.roleNode ); r.line = ts_node_start_point( m.roleNode ).row + 1; // ABS-3: 1-based use-site line for --uses r.lang = lang; @@ -2916,11 +2993,11 @@ void captureReference( const TagsPass& pass, const TagsMatch& m ) r.name = finalSegment( m.name.text ); if( lang == Lang::Clojure ) { - r.qualifier = nodeFieldText( parentOf( m.name.node ), NodeField::Namespace, pass.src ); + r.qualifier = nodeFieldText( parentOf( m.name.node ), NodeField::Namespace, file.src ); } if( lang == Lang::Elixir ) { - if( !qualifyElixirReference( pass, m, r ) ) + if( qualifyElixirReference( file, sinks, m, r ) != CaptureFate::Keep ) { return; } @@ -2929,30 +3006,31 @@ void captureReference( const TagsPass& pass, const TagsMatch& m ) { r.name.push_back( '=' ); // `obj.name = v` calls `name=`, never the getter `name` (test/rubysettercheck.sh) } - std::string rustWritten = qualifyPathReference( pass, m, r ); + std::string rustWritten = qualifyPathReference( file, m, r ); if( !isImportRef && lang != Lang::Elixir ) { - readReceiverFacts( pass, m, r, std::move( rustWritten ) ); + readReceiverFacts( file, m, r, std::move( rustWritten ) ); } - pass.refs.push_back( std::move( r ) ); + sinks.refs.push_back( std::move( r ) ); } -// One match with a role and a name, through the capture-time drop decisions in their order, then into the definition or the -// reference arm. -void captureTagsMatch( const TagsPass& pass, TagsMatch& m ) +// One match with a role and a name, through the capture-time rules, then into the definition or the reference arm. The ORDER is +// load-bearing — each rule reads only facts decided before it, and an emitting step must stay on the same side of every drop: +// 1. a C++ specialization header emits its base clause and ends the match; it reads the @name AS CAPTURED (before the C1 re-seat); +// 2. drops that need no identity: a Swift function-local `let`/`var`, a function-local C++ alias; +// 3. a macro invocation's call site is emitted — AFTER (2), whose drops would otherwise leak it — then a definition that mints +// nothing (DefIdentity::fate) ends the match; +// 4. the gated capture classes (dropGatedCapture), on the name as declared; +// 5. the language filters (Elixir, Clojure), on the kind AS CAPTURED (Elixir's attribute→Var is the identity's, for the arm); +// 6. a capture in an inert quote region keeps its call candidates as declined facts and ends the match; +// 7. the definition arm, or (Full only) the reference arm. +inline void captureTagsMatch( const TagsFile& file, TagsSinks& sinks, const TagsMatch& m ) { - const Lang lang = pass.le.lang; - if( captureSpecializationHeader( m.isDef, lang, m.defCap, m.roleNode, m.name.node, pass.fileId, pass.src, pass.refs ) ) + const Lang lang = file.le.lang; + if( captureSpecializationHeader( m.isDef, lang, m.defCap, m.roleNode, m.name.node, file.fileId, file.src, sinks.refs ) ) { return; // a C++ specialization header: its base clause only, never a symbol } - - // C1 (memgraph F1) — see cppDefNameReseat. A null node is "nothing to re-seat". - if( const DefNameFacts reseated = cppDefNameReseat( m.isDef && lang == Lang::Cpp, m.name.node, pass.src ); !ts_node_is_null( reseated.node ) ) - { - m.name = reseated; - } - // F5: drop Swift function-local `let`/`var` bindings — they are not module symbols and, left in, // they steal the enclosing function's call edges (the last local binding above the call sites // becomes the nearest enclosing symbol). roleNode is the `property_declaration`; a `statements` @@ -2961,14 +3039,15 @@ void captureTagsMatch( const TagsPass& pass, TagsMatch& m ) { return; } - - const std::optional<AliasShape> aliasShape = aliasShapeOfCapture( lang, m ); - if( !aliasShape ) + // INDEX-ALIAS-CONST: a function-local alias is a local name (ingest_relations.h insideFunctionBody, the local-const rule) + if( isAliasDefinition( lang, m ) && insideFunctionBody( m.roleNode ) ) { return; } - AnnotationRename renamed {}; - if( !keepAfterMacroInvocation( pass, m, renamed ) ) + + const DefIdentity id = m.isDef ? definitionIdentityOf( file, m ) : DefIdentity{}; // a reference keeps its @name as captured + emitMacroInvocationCall( file, sinks, m, id ); + if( id.fate != CaptureFate::Keep ) { return; } @@ -2976,28 +3055,22 @@ void captureTagsMatch( const TagsPass& pass, TagsMatch& m ) // uninitialized C++ shape, which needs the captured declaration node), JS export/prototype // assignments — in one drop decision (see dropGatedCapture for the per-class rationale and why // none of this can live in the query as a #match?/#eq? predicate). - if( m.isDef && dropGatedCapture( m.defCap, lang, m.name.text, m.name.node, m.roleNode, pass.src ) ) - { - return; - } - const std::uint32_t aliasTargetStart = aliasShape->form != AliasForm::None ? aliasTargetStartOf( m.roleNode, *aliasShape ) : 0u; - - if( !keepLanguageCapture( pass, m ) ) + if( m.isDef && dropGatedCapture( m.defCap, lang, id.declarator.text, id.declarator.node, m.roleNode, file.src ) ) { return; } - if( consumeInertQuoteCapture( pass, m ) ) + if( languageFilterFate( file, m ) != CaptureFate::Keep || inertQuoteFate( file, sinks, m ) != CaptureFate::Keep ) { return; } if( m.isDef ) { - captureDefinition( pass, m, renamed, aliasTargetStart ); + captureDefinition( file, sinks, m, id, aliasTargetStartOf( file, m ) ); } - else if( m.isRef && pass.full ) + else if( m.isRef && file.full ) { - captureReference( pass, m ); + captureReference( file, sinks, m ); } } @@ -3014,22 +3087,22 @@ void captureTagsMatch( const TagsPass& pass, TagsMatch& m ) // methods — beside each singleton def, which the def capture notes. // Parser version 145 (test/rubyclassrecvcheck.sh): the mixins the class object's lookup reaches — an `extend`, an // `include` in `class << self` — into binds, beside the inherit reference each mixin already is. -inline void captureRubyFilePasses( const TagsPass& pass ) +inline void captureRubyFilePasses( const TagsFile& file, TagsSinks& sinks ) { - captureRubyDefs( pass.root, pass.fileId, pass.src, pass.defs ); // #339: the Definitions-only walker (attr defs + rendered db/schema.rb columns) - if( !pass.full ) + captureRubyDefs( file.root, file.fileId, file.src, sinks.defs ); // #339: the Definitions-only walker (attr defs + rendered db/schema.rb columns) + if( !file.full ) { return; // TagsCapture::DefinitionsOnly: the passes below write references and binds only } - captureRubyBareCalls( pass.root, pass.fileId, pass.src, pass.refs ); - captureRubyFactories( pass.root, pass.fileId, pass.src, pass.binds ); - captureRubyHelperMethods( pass.root, pass.fileId, pass.src, pass.binds ); - captureRubySingletonAccessors( pass.root, pass.fileId, pass.src, pass.binds ); - captureRubyClassMixins( pass.root, pass.fileId, pass.src, pass.binds ); - captureRubyMainMixins( pass.root, pass.fileId, pass.src, pass.binds ); - if( pass.le.ext == kJbuilderExt ) + captureRubyBareCalls( file.root, file.fileId, file.src, sinks.refs ); + captureRubyFactories( file.root, file.fileId, file.src, sinks.binds ); + captureRubyHelperMethods( file.root, file.fileId, file.src, sinks.binds ); + captureRubySingletonAccessors( file.root, file.fileId, file.src, sinks.binds ); + captureRubyClassMixins( file.root, file.fileId, file.src, sinks.binds ); + captureRubyMainMixins( file.root, file.fileId, file.src, sinks.binds ); + if( file.le.ext == kJbuilderExt ) { - typeRubyJbuilderLocal( pass.fileId, pass.refs ); + typeRubyJbuilderLocal( file.fileId, sinks.refs ); } } @@ -3073,9 +3146,9 @@ void captureTagsFacts( TSQueryCursor* cursor, const LangEntry& le, std::uint32_t elixir.shortfall = &shortfall; if( le.lang == Lang::Elixir ) { elixir.prepare( cursor, query, root, src, fileId, binds, includes, refs ); } - const TagsPass pass{ .le = le, .fileId = fileId, .src = src, .root = root, .defs = defs, .refs = refs, .binds = binds, .includes = includes, - .shortfall = shortfall, .elixir = elixir, .fileStem = fileStem, .full = mode == TagsCapture::Full, .shape = mode != TagsCapture::DefinitionsOnly, - .fileHasError = ts_node_has_error( root ) }; + const TagsFile file{ .le = le, .fileId = fileId, .src = src, .root = root, .elixir = elixir, .fileStem = fileStem, + .full = mode == TagsCapture::Full, .shape = mode != TagsCapture::DefinitionsOnly, .fileHasError = ts_node_has_error( root ) }; + TagsSinks sinks{ .defs = defs, .refs = refs, .binds = binds, .includes = includes, .shortfall = shortfall }; { PROFILE_SCOPE_DESCRIBE( "ingest/extractFile: tags query exec+captures" ); ts_query_cursor_exec( cursor, query, root ); @@ -3090,12 +3163,12 @@ void captureTagsFacts( TSQueryCursor* cursor, const LangEntry& le, std::uint32_t { continue; } - TagsMatch m = readTagsMatch( pass, query, match ); + const TagsMatch m = readTagsMatch( file, sinks, query, match ); // Some patterns (e.g. a bare (identifier) @name) carry no @definition/@reference wrapper: a name without a role is // skipped (avoids turning every identifier into an edge), and so is a role without a name. if( m.hasName() && m.hasRole() ) { - captureTagsMatch( pass, m ); + captureTagsMatch( file, sinks, m ); } } } @@ -3138,7 +3211,7 @@ void captureTagsFacts( TSQueryCursor* cursor, const LangEntry& le, std::uint32_t if( le.lang == Lang::Ruby ) { - captureRubyFilePasses( pass ); + captureRubyFilePasses( file, sinks ); } } From 1dc9c0ee9eb9977ea817227fea6261fbad6266fa Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:57:03 -0500 Subject: [PATCH 20/61] refactor(ingest): definition steps spell the callable test and the C++ scope inline (no new clones) qd_range flagged two one-line helpers from the previous commit as clones of existing predicates: isCallableKind (model.h isStructOrNamedType's shape) and cppDefinitionScope (graph.h resolveAllOrOwnerFitted's). Both are inlined at their call sites. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/ingest_sidecap.h | 27 ++++++++------------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/src/ingest_sidecap.h b/src/ingest_sidecap.h index 4a585990b..6c67b1004 100644 --- a/src/ingest_sidecap.h +++ b/src/ingest_sidecap.h @@ -2468,11 +2468,6 @@ inline void fillDefinitionExtent( RawDef& d, const DefCodeNodes& code, const Def d.loc = ( endRow >= startRow ) ? ( endRow - startRow + 1u ) : 1u; } -inline bool isCallableKind( SymKind kind ) noexcept -{ - return kind == SymKind::Function || kind == SymKind::Method; -} - // A callable's cc_walk facts (complexityOf) onto its definition. complexityOf runs on a callable only (and only with `shape`); off a // callable every fact is 0 — the zero Complexity below, which is what keeps ppAlt, maxNest, the nesting profile and ev absent on a // type. LB-E: a test macro block's body SIBLING is where the code lives — complexityOf walks INSIDE its root node, so handing it @@ -2485,8 +2480,9 @@ inline bool isCallableKind( SymKind kind ) noexcept inline void fillDefinitionComplexity( RawDef& d, const TagsFile& file, const DefIdentity& id, const DefCodeNodes& code ) { const TSNode measured = code.spanThroughBody ? code.body : ( ts_node_is_null( code.literal ) ? code.defNode : code.literal ); - const Complexity c = isCallableKind( id.kind ) && file.shape ? complexityOf( measured, file.src, file.le.lang ) - : Complexity{ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, {}, 0u, 0u, 0u }; + const bool callable = id.kind == SymKind::Function || id.kind == SymKind::Method; + const Complexity c = callable && file.shape ? complexityOf( measured, file.src, file.le.lang ) + : Complexity{ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, {}, 0u, 0u, 0u }; d.cx = c.cx; d.ccx = c.ccx; d.locals = c.locals; // Phase 1: floor count, C/C++ only (model.h localsCountedLang) — 0 elsewhere, never emitted there @@ -2529,7 +2525,7 @@ inline void fillDefinitionParameters( RawDef& d, const TagsFile& file, const Tag return; } const Lang lang = file.le.lang; - const bool callable = isCallableKind( id.kind ); + const bool callable = id.kind == SymKind::Function || id.kind == SymKind::Method; const bool literalBound = !ts_node_is_null( code.literal ); const TSNode metricNode = literalBound ? code.literal : code.defNode; const auto counted = callable ? definitionParamCount( lang, code.defNode, metricNode, literalBound, file.src ) : std::uint16_t( 0 ); @@ -2662,21 +2658,14 @@ inline void noteEnclosingFunctionScope( RawDef& d, const TagsFile& file, const T d.fnScopeEnd = fnScope.end; } -// A C++ definition's canonical scope (E#4): out-of-line `A::b` → "A" (`Box<T>::grow` (primary) → "Box"; a specialization keeps -// its id), else the enclosing class/namespace. -inline std::string cppDefinitionScope( TSNode nameNode, std::string_view src ) -{ - std::string scope = qualifierOfDefinition( nameNode, src ); - return scope.empty() ? enclosingScopeOf( nameNode, src ) : scope; -} - // The definition's scope, per language ("" where the language records none). inline std::string definitionScopeOf( const TagsFile& file, const TagsMatch& m, const DefIdentity& id ) { const Lang lang = file.le.lang; if( lang == Lang::Cpp ) - { - return cppDefinitionScope( id.name.node, file.src ); + { // E#4: out-of-line `A::b` → "A" (`Box<T>::grow` (primary) → "Box"; a specialization keeps its id), else the enclosing class/namespace + std::string qualifier = qualifierOfDefinition( id.name.node, file.src ); + return qualifier.empty() ? enclosingScopeOf( id.name.node, file.src ) : qualifier; } if( enumTableAt( kDefScopeWalkerOfLang, lang, DefScopeWalker::None ) != DefScopeWalker::None ) { // Python, Go, Rust, Kotlin: the language's row in ingest_names.h kDefScopeWalkerOfLang @@ -2729,7 +2718,7 @@ inline void emitElixirHeadFacts( const TagsFile& file, TagsSinks& sinks, const R // A Ruby method defined on the class object (`def self.m`, `class << self`): its bind (test/rubyclassrecvcheck.sh). inline void emitRubyClassSideBind( const TagsFile& file, TagsSinks& sinks, const RawDef& d, const DefIdentity& id, TSNode defNode ) { - if( file.le.lang == Lang::Ruby && isCallableKind( id.kind ) ) + if( file.le.lang == Lang::Ruby && ( id.kind == SymKind::Function || id.kind == SymKind::Method ) ) { rubyNoteClassSideDef( defNode, file.fileId, d.name, file.src, sinks.binds ); } From 8468dd848b39c21c543aaf5f39b56eb33512bb05 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:31:36 -0500 Subject: [PATCH 21/61] refactor(ingest): captureTagsFacts' language rules dispatch once; langidentity ceiling 317 -> 316 The round-2 identity step had added six shared-file language tests (323 > 317 ceiling). They are now asked once each: - DefIdentity carries exUnitTest, decided with the Elixir attribute kind. - languageFilterFate and emitLanguageDefinitionFacts each dispatch with one switch. - The Elixir def-head steps read @_keyword as their gate; queries/elixir/tags.scm is its only pattern. - definitionScopeOf returns DefScope, so C++'s std-rooted bit comes with the C++ scope. The count falls to 316, and the ceiling follows it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/ingest_sidecap.h | 107 +++++++++++++++++++++------------- test/langidentity/ratchet.tsv | 7 ++- 2 files changed, 72 insertions(+), 42 deletions(-) diff --git a/src/ingest_sidecap.h b/src/ingest_sidecap.h index 6c67b1004..b57f748a5 100644 --- a/src/ingest_sidecap.h +++ b/src/ingest_sidecap.h @@ -1922,7 +1922,8 @@ struct TagsMatch std::string_view refCap; // the @reference capture's name — "reference.import" routes the using-declaration role (r9 loss bucket 1) TSNode roleNode {}; DefNameFacts name {}; // the @name identifier as captured: its node, text, start byte and 0-based row - bool keywordHead = false; // #355: the pattern carried @_keyword, a head its tags.scm predicates accepted + bool keywordHead = false; // #355: the pattern carried @_keyword, a head its tags.scm predicates accepted — Elixir's + // def heads: queries/elixir/tags.scm is its only pattern, so the capture IS the language gate bool hasRole() const noexcept { return isDef || isRef; } bool hasName() const noexcept { return !ts_node_is_null( name.node ); } @@ -2066,6 +2067,7 @@ struct DefIdentity // only the index row of an Elixir defimpl/defprotocol module shows another (elixirIndexedName) AnnotationRename renamed {}; // MACRO-P1: the real function's name and start when a macro annotation hid it; null otherwise bool macroUse = false; // MACRO-P0: the declarator is a macro invocation — a call site of the macro (emitMacroInvocationCall) + bool exUnitTest = false; // an ExUnit `test "title"` block: indexed as `test <title>`, in the file's test scope CaptureFate fate = CaptureFate::Keep; // Drop: mints no definition — a macro use with no function behind it, a test macro // block without its parts (dropGatedCapture's own veto, guarded here, not asserted) }; @@ -2077,7 +2079,8 @@ struct DefIdentity // read the real function's own `f()` as a variable (annotationRenamedName), this definition is the only one f gets — it carries // f's name and kind (renamedAnnotationKind), from f's own start. // - LB-E testmacroblock: the def is TWO SIBLING nodes (testMacroBlockPartsOf); its name is the title literal (a display string). -// - Clojure: the kind is the head's shape (`defn`, `defmacro`, `defprotocol` …); Elixir: a module attribute (`@doc`, `@type`) is a Var. +// - Clojure: the kind is the head's shape (`defn`, `defmacro`, `defprotocol` …); Elixir: a module attribute (`@doc`, `@type`) is a +// Var, and an ExUnit `test` block is a test. // Pure: what a later step drops, it drops on these facts. inline DefIdentity definitionIdentityOf( const TagsFile& file, const TagsMatch& m ) { @@ -2113,9 +2116,10 @@ inline DefIdentity definitionIdentityOf( const TagsFile& file, const TagsMatch& { id.kind = clojureDefinitionShape( m.roleNode, file.src ).kind; } - else if( lang == Lang::Elixir && m.defCap == "definition.attribute" ) + else if( lang == Lang::Elixir ) { - id.kind = SymKind::Var; + id.kind = m.defCap == "definition.attribute" ? SymKind::Var : m.kind; + id.exUnitTest = elixirTarget( m.roleNode, file.src ) == "test"; } return id; } @@ -2204,15 +2208,17 @@ inline CaptureFate elixirFilterFate( const TagsFile& file, const TagsMatch& m ) // The per-language capture filters: Elixir's, and Clojure's (a definition needs a defining head, a reference must not be a special form). inline CaptureFate languageFilterFate( const TagsFile& file, const TagsMatch& m ) { - if( file.le.lang == Lang::Elixir ) + switch( file.le.lang ) { + case Lang::Elixir: return elixirFilterFate( file, m ); + + case Lang::Clojure: + return clojureKeepCapture( m.roleNode, m.isDef, file.src ) ? CaptureFate::Keep : CaptureFate::Drop; + + default: + return CaptureFate::Keep; } - if( file.le.lang == Lang::Clojure && !clojureKeepCapture( m.roleNode, m.isDef, file.src ) ) - { - return CaptureFate::Drop; - } - return CaptureFate::Keep; } // A capture inside an inert quote region ends here: call/operator/named-capture candidates are kept as declined facts, never edges @@ -2530,10 +2536,9 @@ inline void fillDefinitionParameters( RawDef& d, const TagsFile& file, const Tag const TSNode metricNode = literalBound ? code.literal : code.defNode; const auto counted = callable ? definitionParamCount( lang, code.defNode, metricNode, literalBound, file.src ) : std::uint16_t( 0 ); const ParamShape paramShape = ( callable && !code.testMacroBlock && lang != Lang::Clojure ) ? cc_paramShape( metricNode, lang, id.kind, file.src ) : ParamShape{}; - const bool elixirHead = lang == Lang::Elixir && m.keywordHead; d.params = counted; d.paramsMin = paramShape.minimum <= counted ? paramShape.minimum : std::uint16_t( 0 ); - d.arityExact = ( elixirHead ? elixirHeadDefaultCount( m.roleNode, file.src ) == 0 : paramShape.exact ) ? std::uint8_t( 1 ) : std::uint8_t( 0 ); + d.arityExact = ( m.keywordHead ? elixirHeadDefaultCount( m.roleNode, file.src ) == 0 : paramShape.exact ) ? std::uint8_t( 1 ) : std::uint8_t( 0 ); } // An Elixir module attribute's definition name: a typed attribute (@type/@callback and kin) is named with its arity, any other @@ -2569,11 +2574,6 @@ inline SymKind elixirModuleKind( const TagsFile& file, TSNode roleNode, const st return kind; } -inline bool isExUnitTest( const TagsFile& file, const TagsMatch& m ) -{ - return file.le.lang == Lang::Elixir && elixirTarget( m.roleNode, file.src ) == "test"; -} - // The name a definition is indexed under, and its kind there. Drop: the capture mints no row. struct IndexedName { @@ -2589,9 +2589,8 @@ struct IndexedName // elixirModuleKind's kind; Drop when it has no name). Anything else keeps the capture's name. inline IndexedName elixirIndexedName( const TagsFile& file, const TagsMatch& m, const DefIdentity& id, std::uint16_t params ) { - const bool exUnitTest = isExUnitTest( file, m ); - const std::string_view attribute = exUnitTest ? std::string_view{} : elixirAttribute( m.roleNode, file.src ); - const bool generatedModule = !exUnitTest && attribute.empty() && id.kind == SymKind::Other; + const std::string_view attribute = id.exUnitTest ? std::string_view{} : elixirAttribute( m.roleNode, file.src ); + const bool generatedModule = !id.exUnitTest && attribute.empty() && id.kind == SymKind::Other; std::string module = generatedModule ? file.elixir.moduleName( m.roleNode ) : std::string{}; if( generatedModule && module.empty() ) { @@ -2602,7 +2601,7 @@ inline IndexedName elixirIndexedName( const TagsFile& file, const TagsMatch& m, { return IndexedName{ elixirFunctionName( id.name.text, params ), kind }; } - if( exUnitTest ) + if( id.exUnitTest ) { return IndexedName{ "test " + std::string( id.name.text.substr( 1, id.name.text.size() - 2 ) ), kind }; } @@ -2632,9 +2631,9 @@ inline IndexedName indexedNameOf( const TagsFile& file, const TagsMatch& m, cons // L8: the in-file test-scope bit, for EVERY kind (a `#[cfg(test)] mod` and a `class TestFoo` are themselves symbols, and dropping // the members while keeping the shell would be a worse answer than either). Read on defNode, whose ancestors are the enclosing // scopes. LB-E: a test macro IS the in-file convention; so is an ExUnit `test`. -inline std::uint8_t definitionTestScope( const TagsFile& file, const TagsMatch& m, const DefCodeNodes& code ) +inline std::uint8_t definitionTestScope( const TagsFile& file, const DefIdentity& id, const DefCodeNodes& code ) { - if( code.testMacroBlock || isExUnitTest( file, m ) ) + if( code.testMacroBlock || id.exUnitTest ) { return 1; } @@ -2658,34 +2657,42 @@ inline void noteEnclosingFunctionScope( RawDef& d, const TagsFile& file, const T d.fnScopeEnd = fnScope.end; } -// The definition's scope, per language ("" where the language records none). -inline std::string definitionScopeOf( const TagsFile& file, const TagsMatch& m, const DefIdentity& id ) +// A definition's enclosing scope as the index records it, and (#150, C++ only) whether that scope chain roots at namespace std. +struct DefScope +{ + std::string name; // "" where the language records none + bool rootsStd = false; // genuinely INSIDE namespace std at ANY nesting depth — not just a scope whose immediate segment + // happens to spell one std also uses (model.h Symbol::scopeRootsStd) +}; + +// The definition's scope, per language. +inline DefScope definitionScopeOf( const TagsFile& file, const TagsMatch& m, const DefIdentity& id ) { const Lang lang = file.le.lang; if( lang == Lang::Cpp ) { // E#4: out-of-line `A::b` → "A" (`Box<T>::grow` (primary) → "Box"; a specialization keeps its id), else the enclosing class/namespace std::string qualifier = qualifierOfDefinition( id.name.node, file.src ); - return qualifier.empty() ? enclosingScopeOf( id.name.node, file.src ) : qualifier; + return DefScope{ qualifier.empty() ? enclosingScopeOf( id.name.node, file.src ) : std::move( qualifier ), cppDefinitionRootsStd( id.name.node, file.src ) }; } if( enumTableAt( kDefScopeWalkerOfLang, lang, DefScopeWalker::None ) != DefScopeWalker::None ) { // Python, Go, Rust, Kotlin: the language's row in ingest_names.h kDefScopeWalkerOfLang - return defScopeOf( lang, id.name.node, file.src ); + return DefScope{ defScopeOf( lang, id.name.node, file.src ) }; } if( lang == Lang::Elixir ) { - return id.kind == SymKind::Other ? std::string{} : file.elixir.scopeOf( m.roleNode ); + return DefScope{ id.kind == SymKind::Other ? std::string{} : file.elixir.scopeOf( m.roleNode ) }; } if( lang == Lang::Ruby ) { // enclosing class/module → id= addressability, per-class overload sets, editCheckImplicitReceiver - return rubyEnclosingScopeOf( id.name.node, file.src ); // (test/rubyscopecheck.sh) + return DefScope{ rubyEnclosingScopeOf( id.name.node, file.src ) }; // (test/rubyscopecheck.sh) } if( ( lang == Lang::JavaScript || lang == Lang::TypeScript ) && m.defCap == "definition.protomethod" ) { // only the five built-in ctors: every Foo.prototype.bar gaining sc= would mint a new // canonical id and move quality baselines (node lib/ has ~163 anonymous protomethods) const std::string_view ctor = prototypeCtorName( id.name.node, file.src ); - return isJsTsBuiltinCtor( ctor ) ? std::string( ctor ) : std::string{}; + return DefScope{ isJsTsBuiltinCtor( ctor ) ? std::string( ctor ) : std::string{} }; } - return std::string{}; + return DefScope{}; } // `defdelegate f(x), to: M, as: g`: the delegating clause calls M.g with its own arity. @@ -2704,7 +2711,7 @@ inline void emitElixirDelegate( const TagsFile& file, TagsSinks& sinks, const Ra // An Elixir def head's own facts, read off the finished definition: its callable (and default-arity) binds, and a defdelegate's call. inline void emitElixirHeadFacts( const TagsFile& file, TagsSinks& sinks, const RawDef& d, const TagsMatch& m, const DefIdentity& id ) { - if( file.le.lang != Lang::Elixir || !m.keywordHead ) + if( !m.keywordHead ) { return; } @@ -2718,12 +2725,34 @@ inline void emitElixirHeadFacts( const TagsFile& file, TagsSinks& sinks, const R // A Ruby method defined on the class object (`def self.m`, `class << self`): its bind (test/rubyclassrecvcheck.sh). inline void emitRubyClassSideBind( const TagsFile& file, TagsSinks& sinks, const RawDef& d, const DefIdentity& id, TSNode defNode ) { - if( file.le.lang == Lang::Ruby && ( id.kind == SymKind::Function || id.kind == SymKind::Method ) ) + if( id.kind == SymKind::Function || id.kind == SymKind::Method ) { rubyNoteClassSideDef( defNode, file.fileId, d.name, file.src, sinks.binds ); } } +// A definition's language-specific binds and calls, read off the finished row (Ruby's class-side methods, Elixir's def heads). +inline void emitLanguageDefinitionFacts( const TagsFile& file, TagsSinks& sinks, const RawDef& d, const TagsMatch& m, const DefIdentity& id, TSNode defNode ) +{ + switch( file.le.lang ) + { + case Lang::Ruby: + { + emitRubyClassSideBind( file, sinks, d, id, defNode ); + } + break; + + case Lang::Elixir: + { + emitElixirHeadFacts( file, sinks, d, m, id ); + } + break; + + default: + break; + } +} + // The reference edges a definition mints (TagsCapture::Full only): a type's IS-A and HAS-A edges, a macro's body calls. On the // identity's kind — an Elixir module indexed as a Class/Struct/Interface is an Other capture here and mints none. inline void captureDefinitionEdges( const TagsFile& file, TagsSinks& sinks, const TagsMatch& m, const DefIdentity& id, TSNode defNode ) @@ -2778,20 +2807,18 @@ inline void captureDefinition( const TagsFile& file, TagsSinks& sinks, const Tag } d.name = std::move( indexed.name ); d.kind = indexed.kind; - d.testScope = definitionTestScope( file, m, *code ); + d.testScope = definitionTestScope( file, id, *code ); // Internal linkage (model.h Symbol::internalLinkage): C and C++ only, read off defNode — the node that owns // the storage class and whose ancestors are the enclosing namespaces (ingest_names.h::cppInternalLinkage). d.internalLinkage = internalLinkageBit( file.le.lang, code->defNode, file.src ); noteEnclosingFunctionScope( d, file, m, id, code->defNode ); - d.scope = definitionScopeOf( file, m, id ); - // #150: is this def genuinely INSIDE namespace std, at ANY nesting depth — not just a def - // whose immediate scope happens to spell a segment std also uses? See Symbol::scopeRootsStd. - d.scopeRootsStd = file.le.lang == Lang::Cpp && cppDefinitionRootsStd( id.name.node, file.src ) ? std::uint8_t( 1 ) : std::uint8_t( 0 ); + DefScope scope = definitionScopeOf( file, m, id ); + d.scope = std::move( scope.name ); + d.scopeRootsStd = scope.rootsStd ? std::uint8_t( 1 ) : std::uint8_t( 0 ); // extent honesty: did the parse RECOVER this def's container or kind? Only asked in a file whose root // holds an error (fileHasError, one O(1) flag test per file) — see parseRecoveredBits. d.recovered = file.fileHasError ? parseRecoveredBits( code->defNode, id.kind, file.le.lang, d.scope.empty() ) : std::uint8_t( 0 ); - emitRubyClassSideBind( file, sinks, d, id, code->defNode ); - emitElixirHeadFacts( file, sinks, d, m, id ); + emitLanguageDefinitionFacts( file, sinks, d, m, id, code->defNode ); sinks.defs.push_back( std::move( d ) ); if( file.full ) // TagsCapture::DefinitionsOnly: the reference edges feed no definition { diff --git a/test/langidentity/ratchet.tsv b/test/langidentity/ratchet.tsv index d02d511df..0763ecd4f 100644 --- a/test/langidentity/ratchet.tsv +++ b/test/langidentity/ratchet.tsv @@ -37,8 +37,11 @@ # Cpp/C filter, the C scanner branch) and the composed tree counted 326; quality.h defectSitesOf and cFamilyEnumTable now read # langfacts.h's DefectScan column, so all six defect-shape language tests (four of them main's) left the count. # 321 -> 317 (GE-CAPTURETAGS): captureTagsFacts' three Elixir capture filters and its three Elixir definition-name arms each ask -# the language once, in a named step (ingest_sidecap.h keepLanguageCapture, nameDefinition). -ceiling 317 +# the language once, in a named step (ingest_sidecap.h languageFilterFate, indexedNameOf). +# 317 -> 316 (GE-CAPTURETAGS round 2): a definition's language rules are decided once (definitionIdentityOf), the language filters +# and the per-language binds dispatch by one switch each (languageFilterFate, emitLanguageDefinitionFacts), the Elixir def-head +# steps read @_keyword (queries/elixir/tags.scm's only) as their gate, and C++'s std-rooted scope comes with its scope (DefScope). +ceiling 316 perlang ingest_elixir.h perlang elixir_resolve.h perlang ingest_clojure.h From eb5b6bfc80f435bfaac86ddd76a45dde42c5c608 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:36:12 -0500 Subject: [PATCH 22/61] refactor(ingest): the Ruby class-side bind is inline in its language arm (no new clone) qd_range flagged emitRubyClassSideBind as a duplication of quality.h recordTangleOf's shape. The bind now sits inline in emitLanguageDefinitionFacts' Ruby case, its only caller. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/ingest_sidecap.h | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/src/ingest_sidecap.h b/src/ingest_sidecap.h index b57f748a5..89d0d7657 100644 --- a/src/ingest_sidecap.h +++ b/src/ingest_sidecap.h @@ -2722,15 +2722,6 @@ inline void emitElixirHeadFacts( const TagsFile& file, TagsSinks& sinks, const R } } -// A Ruby method defined on the class object (`def self.m`, `class << self`): its bind (test/rubyclassrecvcheck.sh). -inline void emitRubyClassSideBind( const TagsFile& file, TagsSinks& sinks, const RawDef& d, const DefIdentity& id, TSNode defNode ) -{ - if( id.kind == SymKind::Function || id.kind == SymKind::Method ) - { - rubyNoteClassSideDef( defNode, file.fileId, d.name, file.src, sinks.binds ); - } -} - // A definition's language-specific binds and calls, read off the finished row (Ruby's class-side methods, Elixir's def heads). inline void emitLanguageDefinitionFacts( const TagsFile& file, TagsSinks& sinks, const RawDef& d, const TagsMatch& m, const DefIdentity& id, TSNode defNode ) { @@ -2738,7 +2729,10 @@ inline void emitLanguageDefinitionFacts( const TagsFile& file, TagsSinks& sinks, { case Lang::Ruby: { - emitRubyClassSideBind( file, sinks, d, id, defNode ); + if( id.kind == SymKind::Function || id.kind == SymKind::Method ) + { // a method defined on the class object (`def self.m`, `class << self`): its bind (test/rubyclassrecvcheck.sh) + rubyNoteClassSideDef( defNode, file.fileId, d.name, file.src, sinks.binds ); + } } break; From ccb3ad88a6630b8a38e96400a7096162fb00bab7 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:05:49 -0500 Subject: [PATCH 23/61] refactor(ingest): pin the tags pass's three invariant-backed equivalences; test-macro parts read once Final round on the round-2 blind review: - The three equivalences with 5df5a26be that rest on an invariant are now written down: - dropGatedCapture judges the declarator: ASSUME that a macro use is a function/method capture, whose gate reads only the role node. - defBodyNodeOf may see a test macro's title node: DASSERT that a test macro is never in the fnLiteralBoundTo languages (a query-file fact, so it is not promised). - The keyword-head arityExact rule: a comment that @_keyword is captured by Elixir's query alone. - DefIdentity carries the test macro's body, so testMacroBlockPartsOf runs twice per capture, as before the refactor, not three times. - isCallable names the function/method test at its three sites. captureDefinition reads aliasTargetStartOf itself, so the parameter is gone. definitionCodeOf's type-use drop is a CaptureFate, the pass's one drop shape. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/ingest_sidecap.h | 82 ++++++++++++++++++++++++++++---------------- 1 file changed, 52 insertions(+), 30 deletions(-) diff --git a/src/ingest_sidecap.h b/src/ingest_sidecap.h index 89d0d7657..5cc3ac93f 100644 --- a/src/ingest_sidecap.h +++ b/src/ingest_sidecap.h @@ -2068,6 +2068,7 @@ struct DefIdentity AnnotationRename renamed {}; // MACRO-P1: the real function's name and start when a macro annotation hid it; null otherwise bool macroUse = false; // MACRO-P0: the declarator is a macro invocation — a call site of the macro (emitMacroInvocationCall) bool exUnitTest = false; // an ExUnit `test "title"` block: indexed as `test <title>`, in the file's test scope + TSNode testMacroBody {}; // LB-E: a test macro block's sibling block (its title is `name`); null otherwise CaptureFate fate = CaptureFate::Keep; // Drop: mints no definition — a macro use with no function behind it, a test macro // block without its parts (dropGatedCapture's own veto, guarded here, not asserted) }; @@ -2110,7 +2111,8 @@ inline DefIdentity definitionIdentityOf( const TagsFile& file, const TagsMatch& id.fate = CaptureFate::Drop; return id; } - id.name = nameFactsAt( parts.title, testMacroTitleOf( parts.title, file.src ) ); + id.name = nameFactsAt( parts.title, testMacroTitleOf( parts.title, file.src ) ); + id.testMacroBody = parts.body; } else if( lang == Lang::Clojure ) { @@ -2249,15 +2251,30 @@ inline CaptureFate inertQuoteFate( const TagsFile& file, TagsSinks& sinks, const return CaptureFate::Emitted; } +// A callable definition kind: what complexity, parameters and Ruby's class-side binds are read for. +inline bool isCallable( SymKind kind ) noexcept +{ + switch( kind ) + { + case SymKind::Function: + case SymKind::Method: + return true; + + default: + return false; + } +} + // Where a definition's code lives: the node its span covers, its body (null: a declaration), the function literal a name is bound // to (kFnLiteralBinding: params/cx/nest read from it), and whether the body is a SIBLING the span runs through. struct DefCodeNodes { - TSNode defNode {}; - TSNode body {}; - TSNode literal {}; - bool testMacroBlock = false; // LB-E: the def is TWO SIBLING nodes (testMacroBlockPartsOf): the macro statement and its block - bool spanThroughBody = false; // the code this symbol owns lives in a SIBLING node: byte/row extents and complexity run through it + TSNode defNode {}; + TSNode body {}; + TSNode literal {}; + bool testMacroBlock = false; // LB-E: the def is TWO SIBLING nodes (testMacroBlockPartsOf): the macro statement and its block + bool spanThroughBody = false; // the code this symbol owns lives in a SIBLING node: byte/row extents and complexity run through it + CaptureFate fate = CaptureFate::Keep; // Drop: no definition — a body-less C/C++ specifier in a function's signature is a type use }; // The declarator climb's STOP set: a type/namespace/file scope — a function's body never lives above one of these, so reaching @@ -2400,10 +2417,13 @@ inline TSNode positionalBodyOf( Lang lang, TSNode defNode ) // climb would hand the constant THE WHOLE CLASS — the exact Rust-method span bug the H4 W3 note describes). No-op for every // pre-existing Var capture (Swift/C#/Go/Python parents hit a scope-stop or the file root before any "body"-owning ancestor — // verified byte-identical on the gate corpora). A Field's span is its own field_declaration / defining assignment — the Var rule, -// same reason. std::nullopt: no definition — a body-less C/C++ specifier in a function's signature is a type use. -inline std::optional<DefCodeNodes> definitionCodeOf( const TagsFile& file, const TagsMatch& m, const DefIdentity& id ) +// same reason. Drop (DefCodeNodes::fate): a body-less C/C++ specifier in a function's signature is a type use. +inline DefCodeNodes definitionCodeOf( const TagsFile& file, const TagsMatch& m, const DefIdentity& id ) { const Lang lang = file.le.lang; + // defBodyNodeOf reads the name node only to find a literal a name is bound to (fnLiteralBoundTo); a test macro block, whose name + // node is its title, comes from queries/cpp/tags.scm alone, a language outside that walk. + DASSERT( m.defCap != "definition.testmacroblock" || !extent::inSet( kFnLiteralBinding.langs, lang ), "a test macro block is never literal-bound" ); const DefBodyNodes own = lang == Lang::Elixir ? DefBodyNodes{ elixirBody( m.roleNode, file.src ), {}, m.roleNode } : defBodyNodeOf( m.roleNode, id.name.node, id.kind, lang ); DefCodeNodes code; @@ -2413,14 +2433,14 @@ inline std::optional<DefCodeNodes> definitionCodeOf( const TagsFile& file, const code.testMacroBlock = m.defCap == "definition.testmacroblock"; if( code.testMacroBlock ) { - code.body = testMacroBlockPartsOf( m.roleNode, file.src ).body; // its parts were read whole: definitionIdentityOf + code.body = id.testMacroBody; // its parts were read once, by definitionIdentityOf } if( ts_node_is_null( code.body ) && id.kind != SymKind::Var && id.kind != SymKind::Field && lang != Lang::Elixir ) { const DeclaratorClimb climb = climbDeclaratorToDefinition( m.roleNode, isCFamilyTypeSpecifier( lang, m.roleNode ) ); if( climb.typeUseInSignature ) { - return std::nullopt; + return DefCodeNodes{ .fate = CaptureFate::Drop }; } code.defNode = ts_node_is_null( climb.span ) ? code.defNode : climb.span; code.body = climb.body; @@ -2486,8 +2506,7 @@ inline void fillDefinitionExtent( RawDef& d, const DefCodeNodes& code, const Def inline void fillDefinitionComplexity( RawDef& d, const TagsFile& file, const DefIdentity& id, const DefCodeNodes& code ) { const TSNode measured = code.spanThroughBody ? code.body : ( ts_node_is_null( code.literal ) ? code.defNode : code.literal ); - const bool callable = id.kind == SymKind::Function || id.kind == SymKind::Method; - const Complexity c = callable && file.shape ? complexityOf( measured, file.src, file.le.lang ) + const Complexity c = isCallable( id.kind ) && file.shape ? complexityOf( measured, file.src, file.le.lang ) : Complexity{ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, {}, 0u, 0u, 0u }; d.cx = c.cx; d.ccx = c.ccx; @@ -2531,13 +2550,14 @@ inline void fillDefinitionParameters( RawDef& d, const TagsFile& file, const Tag return; } const Lang lang = file.le.lang; - const bool callable = id.kind == SymKind::Function || id.kind == SymKind::Method; + const bool callable = isCallable( id.kind ); const bool literalBound = !ts_node_is_null( code.literal ); const TSNode metricNode = literalBound ? code.literal : code.defNode; const auto counted = callable ? definitionParamCount( lang, code.defNode, metricNode, literalBound, file.src ) : std::uint16_t( 0 ); const ParamShape paramShape = ( callable && !code.testMacroBlock && lang != Lang::Clojure ) ? cc_paramShape( metricNode, lang, id.kind, file.src ) : ParamShape{}; d.params = counted; d.paramsMin = paramShape.minimum <= counted ? paramShape.minimum : std::uint16_t( 0 ); + // m.keywordHead is an Elixir def head: @_keyword is captured by queries/elixir/tags.scm alone (TagsMatch::keywordHead) d.arityExact = ( m.keywordHead ? elixirHeadDefaultCount( m.roleNode, file.src ) == 0 : paramShape.exact ) ? std::uint8_t( 1 ) : std::uint8_t( 0 ); } @@ -2729,7 +2749,7 @@ inline void emitLanguageDefinitionFacts( const TagsFile& file, TagsSinks& sinks, { case Lang::Ruby: { - if( id.kind == SymKind::Function || id.kind == SymKind::Method ) + if( isCallable( id.kind ) ) { // a method defined on the class object (`def self.m`, `class << self`): its bind (test/rubyclassrecvcheck.sh) rubyNoteClassSideDef( defNode, file.fileId, d.name, file.src, sinks.binds ); } @@ -2779,44 +2799,43 @@ inline void captureDefinitionEdges( const TagsFile& file, TagsSinks& sinks, cons // The definition arm: one RawDef, each field written by exactly one step — extent, complexity, parameters, name and kind, test scope, // linkage, enclosing function, scope, parse-recovery bits — then its own binds and calls, the row, and (Full) the edges it mints. -// `aliasTargetStart`: INDEX-ALIAS-CONST's written target (aliasTargetStartOf). -inline void captureDefinition( const TagsFile& file, TagsSinks& sinks, const TagsMatch& m, const DefIdentity& id, std::uint32_t aliasTargetStart ) +inline void captureDefinition( const TagsFile& file, TagsSinks& sinks, const TagsMatch& m, const DefIdentity& id ) { - const std::optional<DefCodeNodes> code = definitionCodeOf( file, m, id ); - if( !code ) + const DefCodeNodes code = definitionCodeOf( file, m, id ); + if( code.fate != CaptureFate::Keep ) { - return; // a body-less C/C++ specifier in a function's signature: a type use, never a definition + return; } RawDef d; d.fileId = file.fileId; d.lang = file.le.lang; d.line = id.name.row + 1; // the identifier's line — most accurate, dedup-stable (a test macro block's: its title's) - fillDefinitionExtent( d, *code, id, aliasTargetStart ); - fillDefinitionComplexity( d, file, id, *code ); - fillDefinitionParameters( d, file, m, id, *code ); - IndexedName indexed = indexedNameOf( file, m, id, *code, d.params ); + fillDefinitionExtent( d, code, id, aliasTargetStartOf( file, m ) ); + fillDefinitionComplexity( d, file, id, code ); + fillDefinitionParameters( d, file, m, id, code ); + IndexedName indexed = indexedNameOf( file, m, id, code, d.params ); if( indexed.fate != CaptureFate::Keep ) { return; } d.name = std::move( indexed.name ); d.kind = indexed.kind; - d.testScope = definitionTestScope( file, id, *code ); + d.testScope = definitionTestScope( file, id, code ); // Internal linkage (model.h Symbol::internalLinkage): C and C++ only, read off defNode — the node that owns // the storage class and whose ancestors are the enclosing namespaces (ingest_names.h::cppInternalLinkage). - d.internalLinkage = internalLinkageBit( file.le.lang, code->defNode, file.src ); - noteEnclosingFunctionScope( d, file, m, id, code->defNode ); + d.internalLinkage = internalLinkageBit( file.le.lang, code.defNode, file.src ); + noteEnclosingFunctionScope( d, file, m, id, code.defNode ); DefScope scope = definitionScopeOf( file, m, id ); d.scope = std::move( scope.name ); d.scopeRootsStd = scope.rootsStd ? std::uint8_t( 1 ) : std::uint8_t( 0 ); // extent honesty: did the parse RECOVER this def's container or kind? Only asked in a file whose root // holds an error (fileHasError, one O(1) flag test per file) — see parseRecoveredBits. - d.recovered = file.fileHasError ? parseRecoveredBits( code->defNode, id.kind, file.le.lang, d.scope.empty() ) : std::uint8_t( 0 ); - emitLanguageDefinitionFacts( file, sinks, d, m, id, code->defNode ); + d.recovered = file.fileHasError ? parseRecoveredBits( code.defNode, id.kind, file.le.lang, d.scope.empty() ) : std::uint8_t( 0 ); + emitLanguageDefinitionFacts( file, sinks, d, m, id, code.defNode ); sinks.defs.push_back( std::move( d ) ); if( file.full ) // TagsCapture::DefinitionsOnly: the reference edges feed no definition { - captureDefinitionEdges( file, sinks, m, id, code->defNode ); + captureDefinitionEdges( file, sinks, m, id, code.defNode ); } } @@ -3065,6 +3084,9 @@ inline void captureTagsMatch( const TagsFile& file, TagsSinks& sinks, const Tags // uninitialized C++ shape, which needs the captured declaration node), JS export/prototype // assignments — in one drop decision (see dropGatedCapture for the per-class rationale and why // none of this can live in the query as a #match?/#eq? predicate). + // It judges the name AS DECLARED. Where identity re-named the definition (MACRO-P1) the capture is a function or method, whose + // gate reads the role node only (dropGatedCapture: definition.function's arm; definition.method has none). + ASSUME( !id.macroUse || m.defCap == "definition.function" || m.defCap == "definition.method", "cFamilyMacroInvocationCapture admits these two only" ); if( m.isDef && dropGatedCapture( m.defCap, lang, id.declarator.text, id.declarator.node, m.roleNode, file.src ) ) { return; @@ -3076,7 +3098,7 @@ inline void captureTagsMatch( const TagsFile& file, TagsSinks& sinks, const Tags if( m.isDef ) { - captureDefinition( file, sinks, m, id, aliasTargetStartOf( file, m ) ); + captureDefinition( file, sinks, m, id ); } else if( m.isRef && file.full ) { From 0358bc273115a39def87b9f123d9087e7e5d3505 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:54:40 -0500 Subject: [PATCH 24/61] =?UTF-8?q?refactor(serialize):=20the=20map=20as=20n?= =?UTF-8?q?amed=20steps=20=E2=80=94=20rows,=20order,=20groups,=20legend,?= =?UTF-8?q?=20head,=20rows=20written?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit rw::serialize was one ~1000-line body whose row loop sat six levels deep and whose selection logic (rank order, top-K cut, code-first pick, file buckets, stem rows, inventory, emit order, honesty gauges) was copied by hand into serializeJson. Both dialects now share the decisions about WHAT a map prints, each made once: mapKeepCount, rankMapRows, decideMapEmitOrder (one MapEmitOrder value read by the bucket order, order= and the inventory placement), groupMapRowsByFile and countMapHonestyGauges (one count decides a header gauge and its legend clause). The XML legend is an ordered list of named clause groups; the head is renderMapStats + renderMapRootTag; a row is writeMapSymbolRow with its attribute runs (rowGuessAttrs, rowRankAttr, BoundedAttrRun for the snprintf-exact truncation, rowEssentialComplexityAttrs). The est_tokens fixpoint is settleEstTokens. compressBody is its two phases, stripCommentsKeepLiterals (one step per token kind: copyStringLiteral / copyQuotedLiteral / skipLineComment / skipBlockComment) and collapseBlankLineRuns, whose first-line flag is now read off the output. Byte-identical: no answer changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/serialize.h | 2654 +++++++++++++++++++++++++---------------------- 1 file changed, 1426 insertions(+), 1228 deletions(-) diff --git a/src/serialize.h b/src/serialize.h index 863eda6d0..7dfeb6f03 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -3310,171 +3310,120 @@ inline void dropUnmappedRows( const IngestResult& ing, std::vector<NodeId>& orde std::erase_if( order, [ &ing ]( NodeId id ) noexcept { return ( ing.symbols[ id ].rankFlags & kRankFlagNotNamed ) != 0; } ); } -inline void serialize( std::FILE* out, const IngestResult& ing, const std::vector<float>& rank, - const std::vector<std::uint32_t>& outOff, const std::vector<NodeId>& outTargets, - int topK, bool mostImportantLast = false, - bool metrics = false, const std::vector<std::uint32_t>* fanIn = nullptr, - const std::vector<std::uint32_t>* ambOut = nullptr, bool stable = false, - const std::vector<std::uint8_t>* outProv = nullptr, - // Q-compute per-symbol metrics — surfaced on --metrics ONLY (descriptive facts, never gates). - // All optional (nullptr ⇒ that attribute is omitted); loc/params/nest live on Symbol itself. - const std::vector<std::uint32_t>* cbo = nullptr, // Q5a distinct in-repo dependency targets - const std::vector<std::uint8_t>* tested = nullptr, // Q2 referenced from a test-path file - const std::vector<std::uint32_t>* lcom4 = nullptr, // Q4 class cohesion (kLcom4NA ⇒ omit) - const std::vector<std::uint32_t>* amp = nullptr, // Q2 change-amplification (callers + co-change partners) - const std::vector<std::uint32_t>* unresolvedOut = nullptr, // honesty lever #2: per-symbol lang-filtered - // unresolved calls; summed into `unresolved=N` - const SparseLabels* bind = nullptr, // A4-R5 per-symbol cross-language binding - // label (graph.h g.bindLabel) — JNI decoded - // Java_pkg_Cls_method → "pkg.Cls.method". - // Emitted as bind="…" ONLY when non-empty - // (nullptr/empty-vector default ⇒ zero - // token cost, byte-identical golden map). - bool autoOrder = false, // T3: fill-aware auto important-last (see above) - std::size_t* outEstTokens = nullptr, // --token-budget: hand back the SAME est_tokens the - // header prints (no second counter) — nullptr ⇒ unused - std::size_t extraPayloadTokens = 0, // §H7 (was extraBodyTokens): tokens of - // EVERY block the caller appends after this map — - // <sigs>, <src>, <bodies>, <outline> — each MEASURED - // from its rendered bytes by the caller (main.cpp's - // renderMapPayload) and converted through - // tokensForEmittedBytes. The old name said "body" - // and only --expand ever filled it, which is - // precisely why the four siblings went uncharged. - const MapAnnotations& ann = {}, // how THIS map was produced (see MapAnnotations - // above); defaulted ⇒ byte-identical golden map. - // §B6 M10: keep the files=/symbols=/shown=/order= stanza on the FIRST SCREEN even under - // `stable`. --stable moves it to a TRAILING comment to protect the cacheable prefix, which is - // right for a CLI map a provider KV-caches and wrong for the MCP `analyze` verb, whose result - // is ONE tool payload an agent reads top-down: there the reader met 197 of 6368 symbols with - // no denominator and no order marker until the last line. The stanza is emitted ONCE either - // way (never both places), so no count is stated twice. Only the MCP analyze front door - // passes true; every CLI caller keeps the default and stays byte-identical. - bool statsFirstScreen = false, - // R-E (2026-08-17 harvest, report-memgraph §F6 seconded): the run's OWN root argument, - // single-root callers only (empty ⇒ multi-root — already carries the roots=/<root - // label=…> disclosure above and stays untouched — or a caller that never passes one, e.g. - // a pure sizing pass, where a root= attribute would add bytes nothing reads). Same fact - // --grep's root= states, same helper (sarif.h's rootPrefixOf/rootRelativeUri) — the two - // verbs must not diverge on what "root-relative" means. - std::string_view rootArg = {}, - // Phase 4: the S6-C locality-pin counter (graph.h g.locPinOut) → lpin="K" on the row, header - // locality_pinned=N — both absent when zero, so a pin-free corpus is byte-identical. - const std::vector<std::uint32_t>* locPinOut = nullptr, - // Phase 5: the external-name veto's refusal count (graph.h g.externalCalls) → header external=N, - // absent when zero, so a veto-free corpus is byte-identical. - std::size_t externalCalls = 0, - // Tier 3's per-caller declines (graph.h g.declinedOut) → header declined=N, absent when zero, so a - // corpus where no call reached tier 3 undecided stays byte-identical. - const std::vector<std::uint32_t>* declinedOut = nullptr, - // of those, the calls the builtin-method name gate declined (graph.h g.gateDeclinedCalls) → the - // kDeclinedGateMapLegend clause, absent when zero. - std::size_t gateDeclinedCalls = 0, - // FE-B: Graph::outNameOnly (parallel to outTargets) → via="name" on a <c> row and the via legend - // comment; nullptr/empty ⇒ every edge is evidence-bound and the map is byte-identical. - const std::vector<std::uint8_t>* outNameOnly = nullptr, - // of declined=, the calls the standard-member gate declined (graph.h g.stdMemberDeclinedCalls) → - // the kDeclinedStdMapLegend clause, absent when zero. - std::size_t stdMemberDeclinedCalls = 0, - // of declined=, the Elixir call candidates inside inert quote AST (g.inertDeclinedCalls, #380) → - // the kInertDeclinedMapLegend clause, absent when zero. - std::size_t inertDeclinedCalls = 0 ) -{ - const std::size_t* changedCount = ann.changedCount; - const std::string* mapAtStamp = ann.atStamp; - const std::string* churnWindow = ann.churnWindow; - const std::size_t S = ing.symbols.size(); - // R-E: normalize once, reuse at every <f p=…> row below — rootPrefixOf just strips a trailing '/', so - // this is O(1) work the loop below would otherwise repeat per row. - const std::string rootPrefix = rootArg.empty() ? std::string() : rw::sarif::rootPrefixOf( rootArg ); - const auto pathRel = [ & ]( std::uint32_t fileId ) -> std::string_view - { - return rootArg.empty() ? std::string_view( ing.files[ fileId ] ) : rw::sarif::rootRelativeUri( ing.files[ fileId ], rootPrefix ); - }; +// ── the map, as named steps ────────────────────────────────────────────────────────────────────────────────── +// serialize() (XML) and serializeJson() share the decisions about WHAT a map prints — the row cap, the rank order, the emit +// order, the file groups and the honesty gauges — so the two dialects cannot drift on them; each dialect then writes the +// same groups in its own spelling. Every step below is decided once and handed on as a const value. - // C1-b: `keep` is the row count the map WOULD print, and it depends on topK and S alone — never on the - // ranking. So under in=DIR's stub it is still the honest would_show=, and every step that exists only to - // ORDER and BUCKET rows nobody prints is skipped: the radix sort over S symbols, the files-sized bucket - // allocation, and the fill loop. (The <f> loop below already walked an empty order; this is the work that - // ran to feed it.) - const std::size_t mapS = mapSymbolCount( ing ); // the rows the map can print (dropUnmappedRows below) - const std::size_t keep = std::min<std::size_t>( topK > 0 ? std::size_t( topK ) : mapS, mapS ); - const bool stubbed = ann.stubSymbols; +// C1-b: the row count the map WOULD print. It depends on topK and the printable rows alone — never on the ranking — so under +// in=DIR's stub it is still the honest would_show=. +inline std::size_t mapKeepCount( const IngestResult& ing, int topK ) noexcept +{ + const std::size_t mapS = mapSymbolCount( ing ); // the rows the map can print (dropUnmappedRows) + return std::min<std::size_t>( topK > 0 ? std::size_t( topK ) : mapS, mapS ); +} - // rank order: (rank desc, id asc) — the id tie-break makes the top-K deterministic. +// The rank order the map's rows are drawn from: (rank desc, id asc) — the id tie-break makes the top-K deterministic — less +// the rows the map never prints, with the map scope's code-first pick (MapAnnotations::codeFirstRows) applied to the kept +// prefix; `dataSecCut` is that pick's disclosure. +struct RankedMapRows +{ std::vector<NodeId> order; - if( !stubbed ) + DataSectionsCut dataSecCut; + + // the rows inside the top-K cut: the first `keep` of the order, none under the stub (whose order is empty) + std::span<const NodeId> kept( std::size_t keep ) const noexcept { - order.resize( S ); - for( NodeId i = 0; i < S; ++i ) - { - order[i] = i; - } - sortutil::radixSortByScoreDescId( order, rank ); - dropUnmappedRows( ing, order ); + return { order.data(), std::min( keep, order.size() ) }; } - // The map scope's code-first row pick (MapAnnotations::codeFirstRows): rewrites the kept prefix, returns its disclosure. - const DataSectionsCut dataSecCut = ( ann.codeFirstRows && !stubbed ) ? codeFirstKeep( ing, order, keep ) : DataSectionsCut{}; - - // bucket the kept symbols by file, files ordered by their best (first-seen) rank. - std::vector<std::vector<NodeId>> buckets( stubbed ? 0 : ing.files.size() ); - std::vector<std::uint32_t> fileOrder; - std::vector<char> seen( stubbed ? 0 : ing.files.size(), 0 ); +}; - for( std::size_t k = 0; !stubbed && k < keep; ++k ) +// C1-b: under in=DIR's stub (`stubbed`) the map prints no symbol row, so every step that exists only to ORDER rows nobody +// prints is skipped — the radix sort over every symbol among them — and the order is empty. +inline RankedMapRows rankMapRows( const IngestResult& ing, const std::vector<float>& rank, const MapAnnotations& ann, std::size_t keep, + bool stubbed ) +{ + RankedMapRows ranked; + if( stubbed ) { - const NodeId id = order[k]; - const Symbol& s = ing.symbols[id]; - const std::uint32_t f = s.fileId; - if( !seen[f] ) { seen[f] = 1; fileOrder.push_back( f ); } - buckets[f].push_back( id ); - } - // MAP-STEM: the map scope's one reserved row per shown file (addMapStemRows above); added after the kept rows - const MapStemPick stemPick = stubbed ? MapStemPick{} : pickMapStemRows( ing, ann, buckets, fileOrder ); - const std::vector<NodeId>& stemRows = stemPick.rows; - // D7: the inventory over the files the kept rows did NOT reach (`seen` is exactly the printed <f> groups) - const MapInventory inventory = ( mapInventoryWanted( ing, ann ) && !stubbed ) - ? computeMapInventory( ing, outOff, outTargets, seen, pathRel ) : MapInventory{}; - - // T1/§H7: the byte MODEL. It keeps two jobs and loses one. It still decides the T3 emit order below - // (which has to be decided before any byte exists — see §H7 at estimateTokens) and it still supplies - // the language-weighted bytes/token RATE, the half of it that is actually measured. What it no longer - // does is REPORT the size: the reported est_tokens is computed from the document's emitted bytes in - // PHASE 2 below, because a model of the symbol set cannot see --metrics decoration or an appended - // payload, which is how four different documents came to report one number (§H7). - // T3 note: the auto-order decision keys off the MAP's own estimate, NOT the payload — the fill-order - // heuristic reasons about the map that gets reordered; the appended <bodies>/<sigs>/<src> blocks are - // emitted after and cannot be reordered, so they must not shift the map's primacy/recency decision. - // C1-b: under the stub the map prints NO symbol rows, so the estimate is taken over none of them. It used - // to be taken over `keep` rows the document does not contain, which put an est_tokens= in the header for a - // payload that was not there — and paid a per-symbol pass to compute it. - const TokenEstimate mapEst = estimateTokens( ing, order, stubbed ? 0 : keep, outOff, outTargets ); - const std::size_t mapEstTokens = mapEst.tokens; - - // T3: fill-aware auto important-last. A PURE function of estTokens (itself a pure function of the - // kept symbol set) → deterministic, byte-identical run-to-run. Only engages when the caller opted - // in (autoOrder) AND neither --stable nor an explicit --most-important-last already decided the - // order — an explicit flag always wins, auto-order never overrides a user's stated intent. Does - // NOT trigger on the small default map (test/fixture est_tokens=619, src/ ~10.6K — both far under - // the ~16K threshold) so the golden output is unchanged. - const bool autoFlip = autoOrder && !stable && !mostImportantLast && mapEstTokens > kFillOrderThreshold; - const bool effImportantLast = mostImportantLast || autoFlip; - - // --stable: emit in PATH / symbol-id order (not rank order) so re-running on a slowly-changing repo - // keeps a byte-identical PREFIX → free provider KV-cache hits. Selection stays rank-based (the top-K - // membership is unchanged); only the emit order is stabilized. Takes precedence over --most-important-last. + return ranked; + } + ranked.order.resize( ing.symbols.size() ); + for( NodeId i = 0; i < ranked.order.size(); ++i ) + { + ranked.order[ i ] = i; + } + sortutil::radixSortByScoreDescId( ranked.order, rank ); + dropUnmappedRows( ing, ranked.order ); + ASSUME( keep <= ranked.order.size(), "mapKeepCount caps keep at mapSymbolCount, the rows dropUnmappedRows leaves" ); + if( ann.codeFirstRows ) + { + ranked.dataSecCut = codeFirstKeep( ing, ranked.order, keep ); // rewrites the kept prefix; the size is unchanged + } + return ranked; +} + +// The order a map's rows are WRITTEN in. Selection is always rank-based (the top-K membership never changes); only the emit +// order moves. Decided once, and every order-dependent choice downstream — the bucket order, order=, where the inventory +// tier sits — reads this one value. +enum class MapEmitOrder : std::uint8_t +{ + ImportantFirst, // rank order (the default) + Stable, // --stable: PATH / symbol-id order, so re-running on a slowly-changing repo keeps a byte-identical + // PREFIX → free provider KV-cache hits. Takes precedence over --most-important-last. + ImportantLast, // --most-important-last: the highest-rank file/symbol LAST (some models weight end-of-context more) + ImportantLastAuto, // T3: the fill-aware auto flip to important-last +}; + +// T3: fill-aware auto important-last. A PURE function of the map's modelled tokens (itself a pure function of the kept symbol +// set) → deterministic, byte-identical run-to-run. Only engages when the caller opted in (autoOrder) AND neither --stable nor +// an explicit --most-important-last already decided the order — an explicit flag always wins, auto-order never overrides a +// user's stated intent. Does NOT trigger on the small default map (test/fixture est_tokens=619, src/ ~10.6K — both far under +// the ~16K threshold) so the golden output is unchanged. +// T3 note: the decision keys off the MAP's own estimate, NOT the payload — the fill-order heuristic reasons about the map that +// gets reordered; the appended <bodies>/<sigs>/<src> blocks are emitted after and cannot be reordered, so they must not shift +// the map's primacy/recency decision. +inline MapEmitOrder decideMapEmitOrder( bool stable, bool mostImportantLast, bool autoOrder, std::size_t mapEstTokens ) noexcept +{ if( stable ) { - std::sort( fileOrder.begin(), fileOrder.end(), - [ & ]( std::uint32_t a, std::uint32_t b ) { return ing.files[a] < ing.files[b]; } ); + return MapEmitOrder::Stable; + } + if( mostImportantLast ) + { + return MapEmitOrder::ImportantLast; + } + return ( autoOrder && mapEstTokens > kFillOrderThreshold ) ? MapEmitOrder::ImportantLastAuto : MapEmitOrder::ImportantFirst; +} + +inline bool isImportantLast( MapEmitOrder emitOrder ) noexcept +{ + return emitOrder == MapEmitOrder::ImportantLast || emitOrder == MapEmitOrder::ImportantLastAuto; +} + +// order= marker: T3's auto-flip must be OBSERVABLE, not a silent behaviour change — "important-last(auto:fill)" is distinct +// from the explicit "important-last" so a reader (or a diff) can tell the ordering was the fill-aware heuristic, not a +// requested flag. +inline const char* mapOrderAttr( MapEmitOrder emitOrder ) noexcept +{ + static constexpr const char* kNames[] = { "important-first", "stable", "important-last", "important-last(auto:fill)" }; + return kNames[ std::size_t( emitOrder ) ]; +} + +// Puts the rank-ordered file groups in the emit order: --stable sorts files by path and rows by symbol id (== file+line +// order); important-last reverses both. Order-only; the det-gate still holds. +inline void putMapGroupsInEmitOrder( const IngestResult& ing, MapEmitOrder emitOrder, std::vector<std::vector<NodeId>>& buckets, + std::vector<std::uint32_t>& fileOrder ) +{ + if( emitOrder == MapEmitOrder::Stable ) + { + std::sort( fileOrder.begin(), fileOrder.end(), [ & ]( std::uint32_t a, std::uint32_t b ) { return ing.files[ a ] < ing.files[ b ]; } ); for( std::vector<NodeId>& b : buckets ) { - std::sort( b.begin(), b.end() ); // by symbol id == file+line order (stable) + std::sort( b.begin(), b.end() ); } } - // --most-important-last (explicit) OR T3 auto-flip: emit highest-rank file/symbol LAST (some models - // weight end-of-context more heavily). Order-only; det-gate still holds. - else if( effImportantLast ) + else if( isImportantLast( emitOrder ) ) { std::reverse( fileOrder.begin(), fileOrder.end() ); for( std::vector<NodeId>& b : buckets ) @@ -3482,755 +3431,1108 @@ inline void serialize( std::FILE* out, const IngestResult& ing, const std::vecto std::reverse( b.begin(), b.end() ); } } +} - std::vector<char> esc; +// The printed rows grouped by file. Files are ordered by their best (first-seen) rank, and two row sets are decided over that +// rank-ordered grouping BEFORE it is put in the emit order: MAP-STEM's one reserved stem-namesake row per shown file (added +// to the buckets, after the kept rows) and the D7 inventory over the files the kept rows did NOT reach. Empty under the stub. +struct MapFileGroups +{ + std::vector<std::vector<NodeId>> buckets; // per file id: its printed rows, in emit order + std::vector<std::uint32_t> fileOrder; // the printed <f> groups, in emit order + MapStemPick stemPick; + MapInventory inventory; +}; - // The prov= legend is appended ONLY under --scip (outProv present) so the default header stays - // byte-identical to the pre-overlay output (no golden churn); prov="scip" marks a SCIP-pinned precise edge. - // §A8.7: shown= (in the `stats` comment below) counts overload-MERGED rows individually — rows + - // Σ(overloads-1) == shown — but overloads= itself (overloadsAttr(), above) was absent from this legend, - // the one clause that closes that arithmetic for a reader who has only the map, not the source. - // §H7: the legend is now COMPOSED into a string rather than streamed, because est_tokens can only be - // written once the document it describes has been measured (PHASE 2 below) and the legend's own bytes - // are part of what it describes. - std::string legend = outProv - ? "<!-- ripwire v1 t=fn|method|cls|struct|iface|var|sec|macro(#define;degraded:body-is-replacement-text,edges-cross-expansion) p=path layer=arch-layer(opt) n=name sc=enclosing-scope(absent-if-unscoped;the-full-id-is-p::sc::n-with-p=-from-the-enclosing-f,and-expand/callers/impact/uses-accept-it) k=rank c=call amb=ambiguous-calls(read-source) lpin=calls-pinned-by-locality-prior-alone(a-disclosed-guess;read-source;absent-if-0) overloads=N-same-name-defs-merged-into-this-row(absent-if-1;shown=counts-them-individually,so-rows+sum(overloads-1)=shown) prov=per-EDGE-confidence(orthogonal-to-k):scip(index-pinned;precise)|binding(cross-lang-FFI)|import(ES-named-import;module+export-named)|split(one-arm-of-a-k-way-pick;read-source;these-are-the-edges-amb=-counts)|final-segment(last-name-match;namespace-unchecked)(absent=uniquely-resolved-name-based) hdr:unresolved=calls-with-no-edge-and-no-proof-of-an-outside-target(every-same-named-def-lang-incompatible-or-out-of-the-language-lookup) (edges heuristic) hdr:locality_pinned=sum-of-lpin(absent-if-0) hdr:external=calls-refused-as-bound-outside-the-tree-ON-PROOF(builtin/global/predeclared/C-library-name-without-in-repo-evidence,outside-import/use,super-past-the-tree;no-edge;absent-if-0) r:est_tokens=hdr-copy(none-if-stable) -->" - : "<!-- ripwire v1 t=fn|method|cls|struct|iface|var|sec|macro(#define;degraded:body-is-replacement-text,edges-cross-expansion) p=path layer=arch-layer(opt) n=name sc=enclosing-scope(absent-if-unscoped;the-full-id-is-p::sc::n-with-p=-from-the-enclosing-f,and-expand/callers/impact/uses-accept-it) k=rank c=call amb=ambiguous-calls(read-source) lpin=calls-pinned-by-locality-prior-alone(a-disclosed-guess;read-source;absent-if-0) overloads=N-same-name-defs-merged-into-this-row(absent-if-1;shown=counts-them-individually,so-rows+sum(overloads-1)=shown) hdr:unresolved=calls-with-no-edge-and-no-proof-of-an-outside-target(every-same-named-def-lang-incompatible-or-out-of-the-language-lookup) (edges heuristic) hdr:locality_pinned=sum-of-lpin(absent-if-0) hdr:external=calls-refused-as-bound-outside-the-tree-ON-PROOF(builtin/global/predeclared/C-library-name-without-in-repo-evidence,outside-import/use,super-past-the-tree;no-edge;absent-if-0) r:est_tokens=hdr-copy(none-if-stable) -->"; - // EXTENT HONESTY (src/extentsuspect.h): how many definitions carry extent_suspect= corpus-wide — the header's - // extent_suspect_syms= — and the row + header readings, appended ONLY when that is non-zero, so a corpus with - // nothing flagged keeps every byte of this legend. - // MODULE-SCOPE OWNERS (issue #60): the t="modscope" kind's reading, appended ONLY when the corpus - // actually has one, under the same byte-identity rule as the two clauses below — a corpus with no - // file-scope call keeps every byte of this legend, which is what kept test/printf_parity.manifest's - // --pack-signatures and --around hashes and every est_tokens ceiling where they were. - bool hasModuleScope = false; - for( const Symbol& sym : ing.symbols ) +template <class PathRel> +inline MapFileGroups groupMapRowsByFile( const IngestResult& ing, const MapAnnotations& ann, std::span<const NodeId> kept, bool stubbed, + MapEmitOrder emitOrder, const std::vector<std::uint32_t>& outOff, + const std::vector<NodeId>& outTargets, const PathRel& pathRel ) +{ + MapFileGroups groups; + if( stubbed ) + { + return groups; // C1-b: no files-sized bucket allocation, no fill loop + } + groups.buckets.resize( ing.files.size() ); + std::vector<char> shownFile( ing.files.size(), 0 ); // exactly the printed <f> groups + for( const NodeId id : kept ) + { + const std::uint32_t f = ing.symbols[ id ].fileId; + if( !shownFile[ f ] ) + { + shownFile[ f ] = 1; + groups.fileOrder.push_back( f ); + } + groups.buckets[ f ].push_back( id ); + } + groups.stemPick = pickMapStemRows( ing, ann, groups.buckets, groups.fileOrder ); + if( mapInventoryWanted( ing, ann ) ) { - if( sym.kind == SymKind::ModuleScope ) { hasModuleScope = true; break; } + groups.inventory = computeMapInventory( ing, outOff, outTargets, shownFile, pathRel ); } - if( hasModuleScope ) + putMapGroupsInEmitOrder( ing, emitOrder, groups.buckets, groups.fileOrder ); + return groups; +} + +// The header's honesty gauges, counted once. Each one decides BOTH its header attribute (absent at 0) and, on the XML map, +// the legend clause that defines it — the two can no longer disagree on whether the gauge fired. +// ambiguous = the resolver guessed among >1 in-repo def (read source); unresolved = the callee name IS defined in-repo but +// EVERY def was language-filtered — a plausibly-internal, cross-language-filtered edge (NOT counted for genuine externals like +// stdlib/third-party, whose name has no in-repo def at all). +struct MapHonestyGauges +{ + std::size_t ambiguous = 0; // calls the resolver could not pin to one target + std::size_t unresolved = 0; // calls to an in-repo name, all defs lang-filtered + std::size_t localityPinned = 0; // Phase 4: calls the locality prior ALONE pinned + std::size_t external = 0; // Phase 5: calls refused as bound outside the tree + std::size_t declined = 0; // calls tier 3 declined: no edge, and no guess + std::size_t declinedByGate = 0; // of declined, the builtin-method name gate's + std::size_t declinedByStdMember = 0; // of declined, the standard-member gate's + std::size_t declinedInert = 0; // of declined, the Elixir call candidates inside inert quote AST (#380) + std::size_t extentSuspectSyms = 0; // definitions carrying extent_suspect= (src/extentsuspect.h) + std::size_t macroBlankedFiles = 0; // files whose symbols come from a member-macro re-parse (src/macroreparse.h) + std::size_t nestRefusedFiles = 0; // #157: files the nesting guard refused +}; + +// The graph's resolver counters as an emitter receives them (graph.h g.ambOut / unresolvedOut / locPinOut / declinedOut and +// the call totals); nullptr ⇒ never measured, which reads as zero (counterTotal). +struct MapResolverCounters +{ + const std::vector<std::uint32_t>* ambOut = nullptr; + const std::vector<std::uint32_t>* unresolvedOut = nullptr; + const std::vector<std::uint32_t>* locPinOut = nullptr; + const std::vector<std::uint32_t>* declinedOut = nullptr; + std::size_t externalCalls = 0; + std::size_t gateDeclinedCalls = 0; + std::size_t stdMemberDeclined = 0; + std::size_t inertDeclinedCalls = 0; +}; + +inline MapHonestyGauges countMapHonestyGauges( const IngestResult& ing, const MapResolverCounters& c ) +{ + std::size_t extentSuspect = 0; + for( const Symbol& sym : ing.symbols ) + { + extentSuspect += sym.extentSuspect != 0 ? 1u : 0u; + } + return MapHonestyGauges{ .ambiguous = counterTotal( c.ambOut ), + .unresolved = counterTotal( c.unresolvedOut ), + .localityPinned = counterTotal( c.locPinOut ), + .external = c.externalCalls, + .declined = counterTotal( c.declinedOut ), + .declinedByGate = c.gateDeclinedCalls, + .declinedByStdMember = c.stdMemberDeclined, + .declinedInert = c.inertDeclinedCalls, + .extentSuspectSyms = extentSuspect, + .macroBlankedFiles = macroBlankedFileCount( ing ), + .nestRefusedFiles = ing.crawlSkips.nestRefusedFiles }; +} + +// The per-symbol facts a map row may print, gathered once from the emitter's parameters. Read-only; a nullptr source means +// that attribute is never printed. +struct MapRowSources +{ + const std::vector<float>& rank; + const std::vector<std::uint32_t>& outOff; + const std::vector<NodeId>& outTargets; + const std::vector<std::uint8_t>* outProv; + const std::vector<std::uint8_t>* outNameOnly; + const std::vector<std::uint32_t>* ambOut; + const std::vector<std::uint32_t>* locPinOut; + const SparseLabels* bind; + bool stable; // --stable: no k= (PageRank is globally volatile) + bool metrics; // --metrics: the descriptive Q-compute attributes + const std::vector<std::uint32_t>* fanIn; + const std::vector<std::uint32_t>* cbo; + const std::vector<std::uint8_t>* tested; + const std::vector<std::uint32_t>* lcom4; + const std::vector<std::uint32_t>* amp; +}; + +// ── the XML map's legend, as its ordered clause groups ─────────────────────────────────────────────────────────────── +// §H7: the legend is COMPOSED into a string rather than streamed, because est_tokens can only be written once the document it +// describes has been measured (PHASE 2 in serialize()) and the legend's own bytes are part of what it describes. Every clause +// after the opening dictionary follows one rule: it is appended ONLY when the document carries what it defines, so a map with +// nothing to disclose keeps every byte of the legend. + +// The opening dictionary. The prov= clause is appended ONLY under --scip (outProv present) so the default header stays +// byte-identical to the pre-overlay output (no golden churn); prov="scip" marks a SCIP-pinned precise edge. +// §A8.7: shown= (in the stats comment) counts overload-MERGED rows individually — rows + Σ(overloads-1) == shown — and +// overloads= (overloadsAttr()) is defined here, the one clause that closes that arithmetic for a reader who has only the map. +inline std::string mapOpeningLegend( bool withProv ) +{ + return withProv + ? "<!-- ripwire v1 t=fn|method|cls|struct|iface|var|sec|macro(#define;degraded:body-is-replacement-text,edges-cross-expansion) p=path layer=arch-layer(opt) n=name sc=enclosing-scope(absent-if-unscoped;the-full-id-is-p::sc::n-with-p=-from-the-enclosing-f,and-expand/callers/impact/uses-accept-it) k=rank c=call amb=ambiguous-calls(read-source) lpin=calls-pinned-by-locality-prior-alone(a-disclosed-guess;read-source;absent-if-0) overloads=N-same-name-defs-merged-into-this-row(absent-if-1;shown=counts-them-individually,so-rows+sum(overloads-1)=shown) prov=per-EDGE-confidence(orthogonal-to-k):scip(index-pinned;precise)|binding(cross-lang-FFI)|import(ES-named-import;module+export-named)|split(one-arm-of-a-k-way-pick;read-source;these-are-the-edges-amb=-counts)|final-segment(last-name-match;namespace-unchecked)(absent=uniquely-resolved-name-based) hdr:unresolved=calls-with-no-edge-and-no-proof-of-an-outside-target(every-same-named-def-lang-incompatible-or-out-of-the-language-lookup) (edges heuristic) hdr:locality_pinned=sum-of-lpin(absent-if-0) hdr:external=calls-refused-as-bound-outside-the-tree-ON-PROOF(builtin/global/predeclared/C-library-name-without-in-repo-evidence,outside-import/use,super-past-the-tree;no-edge;absent-if-0) r:est_tokens=hdr-copy(none-if-stable) -->" + : "<!-- ripwire v1 t=fn|method|cls|struct|iface|var|sec|macro(#define;degraded:body-is-replacement-text,edges-cross-expansion) p=path layer=arch-layer(opt) n=name sc=enclosing-scope(absent-if-unscoped;the-full-id-is-p::sc::n-with-p=-from-the-enclosing-f,and-expand/callers/impact/uses-accept-it) k=rank c=call amb=ambiguous-calls(read-source) lpin=calls-pinned-by-locality-prior-alone(a-disclosed-guess;read-source;absent-if-0) overloads=N-same-name-defs-merged-into-this-row(absent-if-1;shown=counts-them-individually,so-rows+sum(overloads-1)=shown) hdr:unresolved=calls-with-no-edge-and-no-proof-of-an-outside-target(every-same-named-def-lang-incompatible-or-out-of-the-language-lookup) (edges heuristic) hdr:locality_pinned=sum-of-lpin(absent-if-0) hdr:external=calls-refused-as-bound-outside-the-tree-ON-PROOF(builtin/global/predeclared/C-library-name-without-in-repo-evidence,outside-import/use,super-past-the-tree;no-edge;absent-if-0) r:est_tokens=hdr-copy(none-if-stable) -->"; +} + +// MODULE-SCOPE OWNERS (issue #60): the t="modscope" kind's reading, ONLY when the corpus actually has one — a corpus with no +// file-scope call keeps every byte of this legend, which is what kept test/printf_parity.manifest's --pack-signatures and +// --around hashes and every est_tokens ceiling where they were. +inline std::string moduleScopeLegend( const IngestResult& ing ) +{ + const bool hasModuleScope = std::any_of( ing.symbols.begin(), ing.symbols.end(), []( const Symbol& sym ) { return sym.kind == SymKind::ModuleScope; } ); + return hasModuleScope ? std::string( kModScopeMapLegend ) : std::string(); +} + +// lane L6: a <c via="impl"> edge's reading, over the rows WRITTEN (fix round 1, N1): only when a kept row or an inventory entry +// has a one-implementor edge — never because one exists elsewhere in the graph. +inline std::string keptImplEdgeLegend( const std::vector<std::uint32_t>& outOff, const std::vector<std::uint8_t>* outProv, + std::span<const NodeId> kept, std::span<const NodeId> inventoryEntries ) +{ + if( outProv == nullptr ) { - legend += kModScopeMapLegend; + return {}; } - // lane L6: a <c via="impl"> edge's reading, under the same absent-at-zero rule over the rows WRITTEN (fix round 1, N1): only - // when a kept row or an inventory entry has a one-implementor edge — never because one exists elsewhere in the graph - if( outProv != nullptr && !stubbed - && ( markedOutAny( outOff, *outProv, std::span<const NodeId>( order.data(), std::min( keep, order.size() ) ), kProvImpl ) - || markedOutAny( outOff, *outProv, std::span<const NodeId>( inventory.entries.data(), inventory.entries.size() ), kProvImpl ) ) ) + if( markedOutAny( outOff, *outProv, kept, kProvImpl ) || markedOutAny( outOff, *outProv, inventoryEntries, kProvImpl ) ) { - legend += "<!-- c:via=impl:the-one-implementor-in-the-tree-of-the-receiver's-interface/trait/abstract-type-owns-the-callee(an-outside-or-macro-made-one-may-exist) -->"; + return "<!-- c:via=impl:the-one-implementor-in-the-tree-of-the-receiver's-interface/trait/abstract-type-owns-the-callee(an-outside-or-macro-made-one-may-exist) -->"; } - // honesty-small-068: the Go named-type kinds' clause, under the same absent-at-zero rule as modscope's above; index-alias-const: - // a C++ (and .h) alias or function-type row (LangFacts::aliasTargetDefs) reads its own clause, so neither language's row is - // explained by the other's + return {}; +} + +// honesty-small-068: the Go named-type kinds' clause; index-alias-const: a C++ (and .h) alias or function-type row +// (LangFacts::aliasTargetDefs) reads its own clause, so neither language's row is explained by the other's. Each only when +// the corpus has such a row. +inline std::string typeKindLegend( const IngestResult& ing ) +{ const auto namedTypeKind = []( const Symbol& sym ) { return sym.kind == SymKind::NamedType || sym.kind == SymKind::Alias || sym.kind == SymKind::FuncType; }; - if( std::any_of( ing.symbols.begin(), ing.symbols.end(), [&]( const Symbol& sym ) { return namedTypeKind( sym ) && !langFacts( sym.lang ).aliasTargetDefs; } ) ) + std::string clauses; + if( std::any_of( ing.symbols.begin(), ing.symbols.end(), [ & ]( const Symbol& sym ) { return namedTypeKind( sym ) && !langFacts( sym.lang ).aliasTargetDefs; } ) ) { - legend += kNamedTypeMapLegend; + clauses += kNamedTypeMapLegend; } - if( std::any_of( ing.symbols.begin(), ing.symbols.end(), [&]( const Symbol& sym ) { return namedTypeKind( sym ) && langFacts( sym.lang ).aliasTargetDefs; } ) ) + if( std::any_of( ing.symbols.begin(), ing.symbols.end(), [ & ]( const Symbol& sym ) { return namedTypeKind( sym ) && langFacts( sym.lang ).aliasTargetDefs; } ) ) { - legend += kCppAliasMapLegend; + clauses += kCppAliasMapLegend; } + return clauses; +} - std::size_t extentSuspectTotal = 0; - for( const Symbol& sym : ing.symbols ) +// The parse-honesty gauges' clauses, each charged only to the map whose header carries the gauge: EXTENT HONESTY +// (src/extentsuspect.h; the row and the header reading), MEMBER-MACRO RE-PARSE (src/macroreparse.h) and #157's nest_refused=. +inline std::string parseHonestyLegend( const MapHonestyGauges& gauges ) +{ + std::string clauses; + if( gauges.extentSuspectSyms > 0 ) { - extentSuspectTotal += sym.extentSuspect != 0 ? 1u : 0u; + clauses += kExtentSuspectRowLegend; + clauses += kExtentSuspectHdrLegend; } - if( extentSuspectTotal > 0 ) + if( gauges.macroBlankedFiles > 0 ) { - legend += kExtentSuspectRowLegend; - legend += kExtentSuspectHdrLegend; + clauses += kMacroBlankedHdrLegend; } - // MEMBER-MACRO RE-PARSE (src/macroreparse.h): files whose symbols come from a re-parse — the header's - // macro_blanked_files= — and its reading, appended ONLY when non-zero, under the same byte-identity rule. - const std::size_t macroBlankedFiles = macroBlankedFileCount( ing ); - if( macroBlankedFiles > 0 ) + if( gauges.nestRefusedFiles > 0 ) { - legend += kMacroBlankedHdrLegend; + clauses += kNestRefusedMapLegend; } - // #157: a file the nesting guard refused before this map was built — the header's nest_refused=, same - // absent-when-zero rule, charged only to the map that carries the attribute. - if( ing.crawlSkips.nestRefusedFiles > 0 ) + return clauses; +} + +// M20: the seeded-verb clause, emitted only on a seeded map (see MapAnnotations::SeedDisclosure). +inline std::string seedLegend( const MapAnnotations::SeedDisclosure& seed ) +{ + if( seed.of.empty() ) { - legend += kNestRefusedMapLegend; + return {}; } - // R-E fix (2026-08-19): root= was added to <r> with nothing defining it — legendcoveragecheck's arm (A) - // named it on nine roster verbs at once (the default map, --around, and every map-* variant share this - // legend). Spelled in THIS legend's own key=meaning dialect rather than as the prose sentence - // graphlegend.h's kRootRelPathsLegend carries: the map legend is the one first screen every run pays for, - // and its whole style is one compact token per attribute. Conditional, so a multi-root map — which emits - // no root= — stays byte-identical and no golden moves for a document the clause would not describe. + std::string clauses = "<!-- of= is the resolved SEED this neighbourhood is centred on; depth= call hops walked and fanout= " + "neighbours kept per hop are its whole boundary, so a row's absence means outside them, not nonexistent. " + "defs= (only when >1) = that NAME has N definitions and the most specific one was walked (a stated language first, else kind, the " + "repo's majority language on a kind tie, then path order: a CODE definition before a doc heading or config key, and a C/C++ declaration without a body yields to " + "the first bodied definition of its scope in that order); qualify with " + "file:name or @FILE:LINE to pick another. -->"; + if( seed.reflang != nullptr ) // D4: the FULL dialect's definition for the anchor pair — legendcoveragecheck (A) flags the --legend=full row when the seed stanza is silent, + { + clauses += std::string( "<!-- reflang=" ) + seed.reflang + ": the language this answer anchored to; reflang-origin=" + seed.reflangOrigin + + ": explicit (the @lang typed), context (the file asked from), client (the editor's languageId) or corpus (the repo's majority language " + "broke a same-kind tie for the front; next= lists every definition). -->"; // charged only when the row carries the attributes (seedBiteLegend's rule); kept short, the verb dict defines the pair in full + } + clauses += seedBiteLegend( seed ); // C2: charged only on a run whose root carries a bite attribute (the at= rule) + // H1: charged only on a run whose root carries unproven_defs= — the same rule, and part of the head est_tokens prices. + clauses += unprovenDefsVerbComment( UnprovenDefsVerb::Around, seed.unprovenDefs > 0, "<!-- ripwire around: " ); + return clauses; +} + +// How THIS map was produced (MapAnnotations and the run's flags), one clause per annotation the root or header carries. +inline std::string runAnnotationLegend( const IngestResult& ing, const MapAnnotations& ann, std::string_view rootArg, bool metrics ) +{ + std::string clauses; + // R-E fix (2026-08-19): root= was added to <r> with nothing defining it — legendcoveragecheck's arm (A) named it on nine + // roster verbs at once (the default map, --around, and every map-* variant share this legend). Spelled in THIS legend's + // own key=meaning dialect rather than as the prose sentence graphlegend.h's kRootRelPathsLegend carries: the map legend is + // the one first screen every run pays for, and its whole style is one compact token per attribute. Conditional, so a + // multi-root map — which emits no root= — stays byte-identical and no golden moves for a document the clause would not describe. if( !rootArg.empty() ) { - legend += "<!-- r:root=crawl-root-every-p=-is-relative-to(single-root-only;absent=>p=is-the-raw-ingest-path) -->"; + clauses += "<!-- r:root=crawl-root-every-p=-is-relative-to(single-root-only;absent=>p=is-the-raw-ingest-path) -->"; } - if( churnWindow != nullptr ) + if( ann.churnWindow != nullptr ) { - legend += churnRankLegendFor( ann.churnRankLabel ); // §A9.6 / P0-4, churn-only (see the constants) + clauses += churnRankLegendFor( ann.churnRankLabel ); // §A9.6 / P0-4, churn-only (see the constants) if( ann.scopedRecent != nullptr ) { - legend += kRecentScopeLegendOpen; // C1-b: in=DIR — the scoped block, its page, and the map stub (present-only) - legend += kNextLegendClause; - legend += kRecentScopeLegendClose; + clauses += kRecentScopeLegendOpen; // C1-b: in=DIR — the scoped block, its page, and the map stub (present-only) + clauses += kNextLegendClause; + clauses += kRecentScopeLegendClose; } } - // §B2.1: the same treatment for authority/hub/rrf. Mutually exclusive with the churn arm by construction - // (main.cpp fills exactly one of the two fields), and null on the default pagerank map ⇒ zero bytes there. + // §B2.1: the same treatment for authority/hub/rrf. Mutually exclusive with the churn arm by construction (main.cpp fills + // exactly one of the two fields), and null on the default pagerank map ⇒ zero bytes there. if( const char* rbLegend = rankByLegendFor( ann.rankByLabel ) ) { - legend += rbLegend; - } - // M20: the seeded-verb clause, emitted only on a seeded map (see MapAnnotations::SeedDisclosure). - if( !ann.seed.of.empty() ) - { - legend += "<!-- of= is the resolved SEED this neighbourhood is centred on; depth= call hops walked and fanout= " - "neighbours kept per hop are its whole boundary, so a row's absence means outside them, not nonexistent. " - "defs= (only when >1) = that NAME has N definitions and the most specific one was walked (a stated language first, else kind, the " - "repo's majority language on a kind tie, then path order: a CODE definition before a doc heading or config key, and a C/C++ declaration without a body yields to " - "the first bodied definition of its scope in that order); qualify with " - "file:name or @FILE:LINE to pick another. -->"; - if( ann.seed.reflang != nullptr ) // D4: the FULL dialect's definition for the anchor pair — legendcoveragecheck (A) flags the --legend=full row when the seed stanza is silent, - legend += std::string( "<!-- reflang=" ) + ann.seed.reflang + ": the language this answer anchored to; reflang-origin=" + ann.seed.reflangOrigin - + ": explicit (the @lang typed), context (the file asked from), client (the editor's languageId) or corpus (the repo's majority language " - "broke a same-kind tie for the front; next= lists every definition). -->"; // charged only when the row carries the attributes (seedBiteLegend's rule); kept short, the verb dict defines the pair in full - legend += seedBiteLegend( ann.seed ); // C2: charged only on a run whose root carries a bite attribute (the at= rule) - // H1: charged only on a run whose root carries unproven_defs= — the same rule, and part of the head est_tokens prices. - legend += unprovenDefsVerbComment( UnprovenDefsVerb::Around, ann.seed.unprovenDefs > 0, "<!-- ripwire around: " ); + clauses += rbLegend; } + clauses += seedLegend( ann.seed ); if( metrics ) { - legend += kMetricsLegend; // §B7.3, metrics-only (ditto) + clauses += kMetricsLegend; // §B7.3, metrics-only (ditto) } - // Beyond the brief, found by the CA4 legend-coverage sweep: `at=` is the ONE root attribute the map can - // emit that no map legend ever defined — §B7.1 fixed exactly this on the quality-delta screen and the map - // is the other surface that prints it. Emitted only on the runs that carry the stamp (map-diff / churn), - // so the default map is untouched and the clause is charged where the attribute is. - if( mapAtStamp != nullptr && !mapAtStamp->empty() ) + // Beyond the brief, found by the CA4 legend-coverage sweep: `at=` is the ONE root attribute the map can emit that no map + // legend ever defined — §B7.1 fixed exactly this on the quality-delta screen and the map is the other surface that prints + // it. Emitted only on the runs that carry the stamp (map-diff / churn), so the default map is untouched and the clause is + // charged where the attribute is. + if( ann.atStamp != nullptr && !ann.atStamp->empty() ) { - legend += kAtStampLegend; + clauses += kAtStampLegend; } if( ann.maxTokensFit != nullptr ) { - legend += kMaxTokensFitLegend; // §B13.4, --max-tokens-only (ditto) - legend += ann.maxTokensFit->isUnmeasured ? kMaxTokensUnmeasuredLegend : ""; // only on the degrade that sets it + clauses += kMaxTokensFitLegend; // §B13.4, --max-tokens-only (ditto) + if( ann.maxTokensFit->isUnmeasured ) + { + clauses += kMaxTokensUnmeasuredLegend; // only on the degrade that sets it + } + } + if( ing.crawlSkips.ignoredFiles > 0 || ing.crawlSkips.ignoredDirs > 0 ) + { + clauses += kIgnoredLegend; // §N6-C — charged to the map that carries it; see kIgnoredLegend } - const bool ignoreCut = ing.crawlSkips.ignoredFiles > 0 || ing.crawlSkips.ignoredDirs > 0; - legend += ignoreCut ? kIgnoredLegend : ""; // §N6-C — charged to the map that carries it; see kIgnoredLegend - // L3 follow-up (CodeRabbit 4053600616): notes.h's ONE marker, spelled identically on every notes-surfacing - // emitter — absent on a clean read (no sidecar, or every line parsed), so a map with nothing to disclose - // stays byte-identical to before this lane. + // L3 follow-up (CodeRabbit 4053600616): notes.h's ONE marker, spelled identically on every notes-surfacing emitter — absent + // on a clean read (no sidecar, or every line parsed), so a map with nothing to disclose stays byte-identical to before this lane. if( ann.notesDegraded ) { - legend += std::string( notes::kNotesDegradedComment ); + clauses += std::string( notes::kNotesDegradedComment ); } + return clauses; +} + +// The row-selection steps' clauses, each charged to the map whose root or rows carry the attribute: the code-first pick's +// data_sections_cut=, MAP-STEM's stem="1" (the rule the run selected) and stem_cut=, and D7's <inv>. +inline std::string rowSelectionLegend( const DataSectionsCut& dataSecCut, const MapFileGroups& groups ) +{ + std::string clauses; if( dataSecCut.cut > 0 ) { - legend += kDataSectionsCutLegend; // charged to the map that carries data_sections_cut= + clauses += kDataSectionsCutLegend; } - if( !stemRows.empty() ) + if( !groups.stemPick.rows.empty() ) { - legend += mapStemTightOn() ? kMapStemLegend : kMapStemLooseLegend; // MAP-STEM: charged to the map that carries stem="1"; the rule the run selected + clauses += mapStemTightOn() ? kMapStemLegend : kMapStemLooseLegend; } - if( stemPick.cut > 0 ) + if( groups.stemPick.cut > 0 ) { - legend += kMapStemCutLegend; // MAP-STEM: charged to the --max-tokens map that carries stem_cut= + clauses += kMapStemCutLegend; } - if( inventory.active ) + if( groups.inventory.active ) { - legend += kMapInventoryLegend; // D7: charged to the map that carries <inv> + clauses += kMapInventoryLegend; } - // W2-F: the pr_iters= / pr_converged= definition, charged to the maps that carry the attributes — empty - // for a lexical or HITS ordering, and the prose half only on the map whose iteration stopped short. - legend += renderDisclosure( ann.prDisclosure, DiscloseAs::LegendComment ); - // header honesty gauges: ambiguous=resolver guessed among >1 in-repo def (read source); unresolved=the callee - // name IS defined in-repo but EVERY def was language-filtered — a plausibly-internal, cross-language-filtered - // edge (NOT counted for genuine externals like stdlib/third-party, whose name has no in-repo def at all). - const std::size_t ambTotal = counterTotal( ambOut ); // calls the resolver could not pin to one target - const std::size_t unresolvedTotal = counterTotal( unresolvedOut ); // calls to an in-repo name, all defs lang-filtered - const std::size_t locPinTotal = counterTotal( locPinOut ); // Phase 4: calls the locality prior ALONE pinned - const std::size_t declinedTotal = counterTotal( declinedOut ); // calls tier 3 declined: no edge, and no guess - legend += declinedTotal > 0 ? kDeclinedMapLegend : ""; // charged to the map that carries declined= - legend += gateDeclinedCalls > 0 ? kDeclinedGateMapLegend : ""; // only where the builtin-method gate declined a call - legend += stdMemberDeclinedCalls > 0 ? kDeclinedStdMapLegend : ""; // only where the standard-member gate declined a call - legend += inertDeclinedCalls > 0 ? kInertDeclinedMapLegend : ""; // only where an Elixir quote declined a call candidate - if( outNameOnly && !stubbed && !ann.viaLegendStripped - && namesOnlyOutAny( outOff, *outNameOnly, std::span<const NodeId>( order.data(), std::min( keep, order.size() ) ) ) ) - { - // FE-B: the reading every other surface carries (graphlegend.h kViaNameLegend), in the map's short spelling — exactly - // when a kept row may print a via="name" <c> (over-approximated by merged overloads, which print one member's edges). - // It also defines a merged row's x=. Not written under the compact posture, whose rewrite strips it (compactlegend.h) - // and whose element-qualified via/x rows restate it: the --max-tokens fit then prices what is delivered. - legend += kMapViaNameLegend; - } - if( outNameOnly && !stubbed && !ann.viaLegendStripped - && markedOutAny( outOff, *outNameOnly, std::span<const NodeId>( order.data(), std::min( keep, order.size() ) ), kEdgeLink ) ) - { - legend += kMapViaLinkLegend; - } - if( outNameOnly && !stubbed && !ann.viaLegendStripped - && markedOutAny( outOff, *outNameOnly, std::span<const NodeId>( order.data(), std::min( keep, order.size() ) ), 0x80 ) ) - { - legend += kMapAnchorMissLegend; + return clauses; +} + +// The tier-3 decline clauses, each charged to the map that carries the count it explains. +inline std::string declineLegend( const MapHonestyGauges& gauges ) +{ + std::string clauses; + if( gauges.declined > 0 ) + { + clauses += kDeclinedMapLegend; // the map carries declined= } - // K51: history_unread='s definition, the LAST leading clause, so it stands right before the <r> root it marks and inside the - // leading block every reader (and legendcoveragecheck's full rows) meets first; absent unless the amp=/churn= walk was unread. - legend += renderHistoryUnread( DiscloseAs::LegendComment ); - // C1 DRIFT FIX (Round C lane B, found by re-reading this header's own output). `precise=` means "how many - // out-edges a SCIP index PINNED", and the emitter's own comment below says it is "emitted ONLY under - // --scip". Both were true when outProv held only {0, 1}. A4-R5 then added value 2 (an FFI binding edge) - // and this counter — `v ? 1 : 0` — silently began reporting binding edges as SCIP-precise: ripwire's own - // default map, with no --scip anywhere, printed `precise=3` for 3 FFI binding edges, which is the exact - // "a surface that quietly guesses" shape docs/ARCHITECTURE.md §4 forbids. It is load-bearing here because - // C1 adds value 3, which would have inflated the same number by every split edge in the corpus. - // The counter now names ONE value, and the attribute is absent at zero (the tool-wide absent-if-0 - // convention that lpin=/external=/locality_pinned= already follow) so a run with no overlay says nothing - // rather than saying `precise=0` about a measurement it never made. - std::size_t preciseTotal = 0; // how many out-edges the SCIP index pinned (value 1 ONLY) - if( outProv ) - { - for( std::uint8_t v : *outProv ) - { - preciseTotal += ( v == 1u ? 1u : 0u ); - } + if( gauges.declinedByGate > 0 ) + { + clauses += kDeclinedGateMapLegend; // the builtin-method gate declined a call } - char precAttr[ 40 ]; precAttr[ 0 ] = '\0'; // emitted only when a SCIP overlay pinned something - if( preciseTotal > 0 ) + if( gauges.declinedByStdMember > 0 ) { - rw::formatTo( precAttr, sizeof( precAttr ), " precise={}", preciseTotal ); + clauses += kDeclinedStdMapLegend; // the standard-member gate declined a call } - // Multi-root workspace (A13): `roots=N` joins the header gauges and a - // `<root l="LABEL" p="PATH"/>` prologue opens <r> — ONLY when N≥2 (single-root output byte-unchanged). - char rootsAttr[ 32 ]; rootsAttr[ 0 ] = '\0'; + if( gauges.declinedInert > 0 ) + { + clauses += kInertDeclinedMapLegend; // an Elixir quote declined a call candidate + } + return clauses; +} + +// FE-B: the readings of a <c> row's via="name", via="link" and anchor="missing", in the map's short spelling (graphlegend.h +// kViaNameLegend carries the long one) — each exactly when a kept row may print it (over-approximated by merged overloads, +// which print one member's edges). via="name"'s clause also defines a merged row's x=. None is written under the compact +// posture (viaLegendStripped), whose rewrite strips them (compactlegend.h) and whose element-qualified via/x rows restate +// them: the --max-tokens fit then prices what is delivered. +inline std::string keptNameEdgeLegend( const std::vector<std::uint32_t>& outOff, const std::vector<std::uint8_t>* outNameOnly, + std::span<const NodeId> kept, bool viaLegendStripped ) +{ + std::string clauses; + if( outNameOnly == nullptr || viaLegendStripped ) + { + return clauses; + } + if( namesOnlyOutAny( outOff, *outNameOnly, kept ) ) + { + clauses += kMapViaNameLegend; + } + if( markedOutAny( outOff, *outNameOnly, kept, kEdgeLink ) ) + { + clauses += kMapViaLinkLegend; + } + if( markedOutAny( outOff, *outNameOnly, kept, 0x80 ) ) + { + clauses += kMapAnchorMissLegend; + } + return clauses; +} + +// ── the XML map's header comment and root tag ──────────────────────────────────────────────────────────────────── + +// C1 DRIFT FIX (Round C lane B, found by re-reading this header's own output). `precise=` means "how many out-edges a SCIP +// index PINNED", emitted ONLY under --scip. Both were true when outProv held only {0, 1}. A4-R5 then added value 2 (an FFI +// binding edge) and a `v ? 1 : 0` counter silently began reporting binding edges as SCIP-precise: ripwire's own default map, +// with no --scip anywhere, printed `precise=3` for 3 FFI binding edges, which is the exact "a surface that quietly guesses" +// shape docs/ARCHITECTURE.md §4 forbids. It is load-bearing because C1 adds value 3, which would have inflated the same number +// by every split edge in the corpus. The counter names ONE value, and the attribute is absent at zero (the tool-wide +// absent-if-0 convention lpin=/external=/locality_pinned= follow) so a run with no overlay says nothing rather than saying +// `precise=0` about a measurement it never made. +inline std::size_t scipPinnedEdgeCount( const std::vector<std::uint8_t>* outProv ) noexcept +{ + return outProv ? std::size_t( std::count( outProv->begin(), outProv->end(), std::uint8_t( 1 ) ) ) : 0; +} + +// The header gauges after the parse-honesty run: what the run covered and what it left out. Each is absent unless its fact +// holds, so a default run over a tree with nothing to disclose stays byte-identical. Composed once per map. +inline std::string mapCoverageAttrs( const IngestResult& ing, const std::vector<std::uint8_t>* outProv, const MapAnnotations& ann ) +{ + std::string attrs; + char buf[ 96 ]; + if( const std::size_t precise = scipPinnedEdgeCount( outProv ); precise > 0 ) + { + rw::formatTo( buf, sizeof( buf ), " precise={}", precise ); // only when a SCIP overlay pinned something + attrs += buf; + } + // Multi-root workspace (A13): `roots=N` joins the header gauges and a `<root label= p=/>` prologue opens <r> — ONLY when + // N≥2 (single-root output byte-unchanged). if( ing.rootLabels.size() >= 2 ) { - rw::formatTo( rootsAttr, sizeof( rootsAttr ), " roots={}", ing.rootLabels.size() ); + rw::formatTo( buf, sizeof( buf ), " roots={}", ing.rootLabels.size() ); + attrs += buf; } - // D6: --map-diff's teleport-seed file count, ONLY when the caller passes changedCount - // (nullptr for every non-map-diff caller ⇒ zero token cost, byte-identical golden map). A clean - // tree reports "changed=0" so the caller can see the teleport degraded to uniform without shelling - // out to git a second time — that map is otherwise byte-identical to the plain default map. - char changedAttr[ 40 ]; changedAttr[ 0 ] = '\0'; - if( changedCount ) + // D6: --map-diff's teleport-seed file count, ONLY when the caller passes changedCount (nullptr for every non-map-diff + // caller ⇒ zero token cost, byte-identical golden map). A clean tree reports "changed=0" so the caller can see the + // teleport degraded to uniform without shelling out to git a second time — that map is otherwise byte-identical to the + // plain default map. + if( ann.changedCount ) { - rw::formatTo( changedAttr, sizeof( changedAttr ), " changed={}", *changedCount ); + rw::formatTo( buf, sizeof( buf ), " changed={}", *ann.changedCount ); + attrs += buf; } - // §P0.5d: how many otherwise-indexable files the crawl dropped for exceeding a per-file size ceiling — - // --max-file-size, or (§B13.1) the .json lane's fixed 256 KB config ceiling that --max-file-size does not - // raise. `--max-file-size=8K` dropped ~296 of ~759 files on this repo and files= reported the survivors as - // if they WERE the corpus. Emitted ONLY when non-zero, per the house rule — absent means nothing was - // skipped, so a default run over a tree with nothing oversized stays byte-identical. - char skippedAttr[ 48 ]; skippedAttr[ 0 ] = '\0'; + // §P0.5d: how many otherwise-indexable files the crawl dropped for exceeding a per-file size ceiling — --max-file-size, or + // (§B13.1) the .json lane's fixed 256 KB config ceiling that --max-file-size does not raise. `--max-file-size=8K` dropped + // ~296 of ~759 files on this repo and files= reported the survivors as if they WERE the corpus. if( !ing.skippedOversize.empty() ) { - rw::formatTo( skippedAttr, sizeof( skippedAttr ), " skipped_oversize={}", ing.skippedOversize.size() ); + rw::formatTo( buf, sizeof( buf ), " skipped_oversize={}", ing.skippedOversize.size() ); + attrs += buf; } - // §L1: the LANGUAGES this build could not read at all — buildUnindexedAttr carries the whole rule. - const std::string unindexedAttr = buildUnindexedAttr( ing.crawlSkips ); - const std::string ignoredAttr = buildIgnoredAttr( ing.crawlSkips ); // §N6-C, empty unless the ignore rules cut something - const std::string escapedAttr = buildEscapedRootAttr( ing.crawlSkips ); // §SEC1, empty unless a symlink left the root + attrs += buildMemoryStopAttr( ing, false ) + buildMemoryPeakAttr( ing, false ); // #350, empty unless the memory guard stopped the ingest or the peak passed the limit + attrs += buildUnindexedAttr( ing.crawlSkips ); // §L1: the LANGUAGES this build could not read at all + attrs += buildIgnoredAttr( ing.crawlSkips ); // §N6-C, empty unless the ignore rules cut something + attrs += buildEscapedRootAttr( ing.crawlSkips ); // §SEC1, empty unless a symlink left the root // M1 — the UNTRACKED files left out of a build/ the crawl entered because git tracks files under it (model.h - // CrawlSkips::untrackedBuild): on the default map for escaped_root='s reason, absent at zero for the same golden reason; - // defined in the --skipped legend (kUntrackedBuildLegend) and the compact legend, never in this header. - const std::string untrackedAttr = presentCountAttr( "untracked_build", ing.crawlSkips.untrackedBuildFiles ); - const std::string memoryAttr = buildMemoryStopAttr( ing, false ) + buildMemoryPeakAttr( ing, false ); // #350, empty unless the memory guard stopped the ingest or the peak passed the limit - // §B13.4: --max-tokens=N asked for a TOKEN count and got a BYTE ceiling. Both numbers, on the map that - // was shaped by them, so the ~10% the headroom leaves unused is a disclosed fact rather than a silent - // one. Emitted ONLY under --max-tokens (nullptr for every other caller ⇒ byte-identical default map). - // §F5: over_ceiling=1 rides the same attr — a cap that can be overshot is not a cap, so where the map's - // fixed floor cannot fit inside fit_bytes the map states that instead of quietly exceeding it. See - // MapAnnotations::MaxTokensFit for the four ways the cap was breached and why the label is monotone. - char fitAttr[ 96 ]; fitAttr[ 0 ] = '\0'; + // CrawlSkips::untrackedBuild): absent at zero; defined in the --skipped legend (kUntrackedBuildLegend) and the compact legend. + attrs += presentCountAttr( "untracked_build", ing.crawlSkips.untrackedBuildFiles ); + // §B13.4: --max-tokens=N asked for a TOKEN count and got a BYTE ceiling. Both numbers, on the map that was shaped by them, + // so the ~10% the headroom leaves unused is a disclosed fact rather than a silent one. §F5: over_ceiling=1 rides the same + // attr — a cap that can be overshot is not a cap, so where the map's fixed floor cannot fit inside fit_bytes the map states + // that instead of quietly exceeding it. See MapAnnotations::MaxTokensFit for the four ways the cap was breached and why + // the label is monotone. if( ann.maxTokensFit != nullptr ) { - rw::formatTo( fitAttr, sizeof( fitAttr ), " max_tokens={} fit_bytes={}{}{}", - ann.maxTokensFit->askedTokens, ann.maxTokensFit->ceilingBytes, - ann.maxTokensFit->isOverCeiling || ann.maxTokensFit->isUnmeasured ? " over_ceiling=1" : "", - ann.maxTokensFit->isUnmeasured ? " fit_unmeasured=1" : "" ); - } - // order= marker: T3's auto-flip must be OBSERVABLE, not a silent behaviour change — "important- - // last(auto:fill)" is distinct from the explicit "important-last" so a reader (or a diff) can tell - // the ordering was the fill-aware heuristic, not a requested flag. - const char* orderAttr = stable ? "stable" - : mostImportantLast ? "important-last" - : autoFlip ? "important-last(auto:fill)" - : "important-first"; - - // ── the HEAD and the TAIL, as BUILDERS ───────────────────────────────────────────────────────────── - // Both state est_tokens, and est_tokens describes the whole document including them, so the digit count - // feeds back into the number: PHASE 2 below iterates these to a fixpoint. buildRecall (recall.h) has the - // identical fixpoint for the identical reason — "the header, last: it REPORTS est_tokens, so it can only - // be written once the payload is measured". Pure functions of estTokens + the attrs computed above. - MapEstimate estimate{ ann.payloadUncharged }; // the est_tokens measurement's DISCLOSE sink — read by the head builders below - const auto buildStats = [ & ]( std::size_t estTokens ) -> std::string - { - // summary preamble: counts so the agent knows the map's scope + est size. §B14 — was `char stats[480]`, - // and the LATENT member of that class: every interpoland is bounded, but the worst-case format width - // is 80 literal bytes + 7×20 (%zu at UINT64_MAX) + 251 (precAttr 39 + rootsAttr 31 + changedAttr 39 + - // skippedAttr 47 + fitAttr 95, each buffer's max strlen) + 25 (`important-last(auto:fill)`) = **496 B**, - // 497 with the NUL, against a 480-byte buffer. It sat at 432/480 on this repo, so it was one new header - // attribute away from truncating — and a cut here deletes the trailing ` -->`, which turns the ENTIRE - // document into one unterminated comment. Composed on std::string, the margin question disappears. - std::string stats = "<!-- files="; - stats += std::to_string( ing.files.size() ); - stats += " symbols="; stats += std::to_string( mapSymbolCount( ing ) ); // the symbols the map ranks - stats += " edges="; stats += std::to_string( outTargets.size() ); - stats += " shown="; stats += std::to_string( ann.stubSymbols ? std::size_t( 0 ) : keep + stemRows.size() ); // C1-b: the stub prints no row - stats += " est_tokens="; stats += std::to_string( estTokens ); - if( estimate.isModelled ) - { - stats += " est_measured=0"; // the number beside it is the model (MapEstimate); absent ⇒ measured - } - stats += " ambiguous="; stats += std::to_string( ambTotal ); - stats += " unresolved="; stats += std::to_string( unresolvedTotal ); - if( locPinTotal > 0 ) // absent when 0 — zero bytes on a pin-free corpus - { - stats += " locality_pinned="; stats += std::to_string( locPinTotal ); - } - if( externalCalls > 0 ) // Phase 5: same absent-when-0 rule - { - stats += " external="; stats += std::to_string( externalCalls ); - } - if( declinedTotal > 0 ) // tier-3 declines: same rule, after external= so no adjacency moves - { - stats += " declined="; stats += std::to_string( declinedTotal ); - } - // The two parse-honesty gauges follow the call-resolution family (ambiguous= .. declined=), in this order, - // so declined= stays adjacent to external= and the resolver's gauges read as one contiguous run. - if( extentSuspectTotal > 0 ) // extent honesty: same absent-when-0 rule - { - stats += " extent_suspect_syms="; stats += std::to_string( extentSuspectTotal ); - } - if( macroBlankedFiles > 0 ) // member-macro re-parse: same absent-when-0 rule - { - stats += " macro_blanked_files="; stats += std::to_string( macroBlankedFiles ); - } - if( ing.crawlSkips.nestRefusedFiles > 0 ) // #157: same absent-when-0 rule, last of the parse-honesty gauges + rw::formatTo( buf, sizeof( buf ), " max_tokens={} fit_bytes={}{}{}", + ann.maxTokensFit->askedTokens, ann.maxTokensFit->ceilingBytes, + ann.maxTokensFit->isOverCeiling || ann.maxTokensFit->isUnmeasured ? " over_ceiling=1" : "", + ann.maxTokensFit->isUnmeasured ? " fit_unmeasured=1" : "" ); + attrs += buf; + } + return attrs; +} + +// The summary preamble: counts so the agent knows the map's scope + est size. §B14 — was `char stats[480]`, one new header +// attribute away from truncating (and a cut here deletes the trailing ` -->`, which turns the ENTIRE document into one +// unterminated comment). Composed on std::string, the margin question disappears. +struct MapStatsFacts +{ + std::size_t files; + std::size_t symbols; // the symbols the map ranks + std::size_t edges; + std::size_t shown; // C1-b: 0 under the stub, which prints no row + const MapHonestyGauges& gauges; + std::string_view coverageAttrs; + const char* orderAttr; +}; + +inline std::string renderMapStats( const MapStatsFacts& f, std::size_t estTokens, bool estModelled ) +{ + const auto gauge = []( std::string& out, std::string_view key, std::size_t value ) + { + if( value > 0 ) // absent when 0 — zero bytes on a corpus where the gauge never fired { - stats += " nest_refused="; stats += std::to_string( ing.crawlSkips.nestRefusedFiles ); + out += key; out += std::to_string( value ); } - stats += precAttr; stats += rootsAttr; stats += changedAttr; stats += skippedAttr; stats += memoryAttr; stats += unindexedAttr; - stats += ignoredAttr; stats += escapedAttr; stats += untrackedAttr; stats += fitAttr; - stats += " order="; stats += orderAttr; - stats += " -->"; - return stats; }; - // --stable: volatile counts move to a TRAILING comment (out of the cacheable prefix) — unless the caller - // asked for the first-screen placement (§B6 M10, the MCP analyze verb), in which case they stay here and - // the trailing copy is suppressed. Exactly one of the two builders emits `stats`. - const auto buildHead = [ & ]( std::size_t estTokens ) -> std::string + std::string stats = "<!-- files="; + stats += std::to_string( f.files ); + stats += " symbols="; stats += std::to_string( f.symbols ); + stats += " edges="; stats += std::to_string( f.edges ); + stats += " shown="; stats += std::to_string( f.shown ); + stats += " est_tokens="; stats += std::to_string( estTokens ); + if( estModelled ) + { + stats += " est_measured=0"; // the number beside it is the model (MapEstimate); absent ⇒ measured + } + stats += " ambiguous="; stats += std::to_string( f.gauges.ambiguous ); + stats += " unresolved="; stats += std::to_string( f.gauges.unresolved ); + gauge( stats, " locality_pinned=", f.gauges.localityPinned ); + gauge( stats, " external=", f.gauges.external ); // Phase 5 + gauge( stats, " declined=", f.gauges.declined ); // tier-3 declines, after external= so no adjacency moves + // The parse-honesty gauges follow the call-resolution family (ambiguous= .. declined=), in this order, so declined= stays + // adjacent to external= and the resolver's gauges read as one contiguous run. + gauge( stats, " extent_suspect_syms=", f.gauges.extentSuspectSyms ); + gauge( stats, " macro_blanked_files=", f.gauges.macroBlankedFiles ); + gauge( stats, " nest_refused=", f.gauges.nestRefusedFiles ); // #157: last of the parse-honesty gauges + stats += f.coverageAttrs; + stats += " order="; stats += f.orderAttr; + stats += " -->"; + return stats; +} + +// M20: the seeded-verb stanza on <r>, after root= and before the ranker attributes. Absent (and therefore byte-free) on every +// map that had no seed. +inline std::string seedRootAttrs( const MapAnnotations::SeedDisclosure& seed, std::vector<char>& esc ) +{ + if( seed.of.empty() ) { - std::string h = legend; - if( estimate.isModelled ) - { - h += kEstModelledLegend; + return {}; + } + std::string h; + h += " of=\""; h += escapeXml( seed.of, esc ); h += "\""; + h += " depth=\""; h += std::to_string( seed.depth ); h += "\""; + h += " fanout=\""; h += std::to_string( seed.fanout ); h += "\""; + if( seed.defs > 1 ) { h += " defs=\""; h += std::to_string( seed.defs ); h += "\""; } + h += unprovenDefsAttrXml( seed.unprovenDefs ); // H1: beside defs=, the rest of what the seed name resolved to + h += seedBiteAttrs( seed ); // C2: each bound's BITE, right after the bound it qualifies (empty when neither bit) + if( seed.reflang != nullptr ) // D4: after the bite pair, same slot logic — the anchor qualifies the whole seed stanza + { + h += " reflang=\""; h += seed.reflang; + h += "\" reflang-origin=\""; h += seed.reflangOrigin; h += "\""; + if( !seed.nextDefs.empty() ) // the corpus tie's pasteable follow-up, beside the disclosure it belongs to — + { // the ONE next= builder the house keeps (nextverb.h, darkflags/docdrift precedents) + h += nextAttrXml( nextFlag( "--defs=", seed.nextDefs ) ); } - if( !stable || statsFirstScreen ) - { - h += buildStats( estTokens ); - } - // r26-stamp Task A: ` at="..."` ONLY when the caller passed a non-empty stamp (--map-diff); every other - // caller passes nullptr, so the hot default-map path pays a pointer compare, not a git call. at= stays - // FIRST — the `<r at="<sha>` byte sequence gitstampcheck.sh pins is unchanged. - h += "<r"; - if( mapAtStamp != nullptr && !mapAtStamp->empty() ) { h += " at=\""; h += *mapAtStamp; h += "\""; } - // R-E: after at= (so gitstampcheck's `<r at="<sha>` byte sequence is unmoved), same slot --grep uses - // right after its own identifying attributes — the crawl root every <f p=…> below is now RELATIVE to. - if( !rootArg.empty() ) { h += " root=\""; h += escapeXml( rootArg, esc ); h += "\""; } - // M20: the seeded-verb stanza, after root= and before the ranker attributes. Absent (and therefore - // byte-free) on every map that had no seed. - if( !ann.seed.of.empty() ) - { - h += " of=\""; h += escapeXml( ann.seed.of, esc ); h += "\""; - h += " depth=\""; h += std::to_string( ann.seed.depth ); h += "\""; - h += " fanout=\""; h += std::to_string( ann.seed.fanout ); h += "\""; - if( ann.seed.defs > 1 ) { h += " defs=\""; h += std::to_string( ann.seed.defs ); h += "\""; } - h += unprovenDefsAttrXml( ann.seed.unprovenDefs ); // H1: beside defs=, the rest of what the seed name resolved to - h += seedBiteAttrs( ann.seed ); // C2: each bound's BITE, right after the bound it qualifies (empty when neither bit) - if( ann.seed.reflang != nullptr ) // D4: after the bite pair, same slot logic — the anchor qualifies the whole seed stanza - { - h += " reflang=\""; h += ann.seed.reflang; - h += "\" reflang-origin=\""; h += ann.seed.reflangOrigin; h += "\""; - if( !ann.seed.nextDefs.empty() ) // the corpus tie's pasteable follow-up, beside the disclosure it belongs to — - { // the ONE next= builder the house keeps (nextverb.h, darkflags/docdrift precedents) - h += nextAttrXml( nextFlag( "--defs=", ann.seed.nextDefs ) ); - } - } + } + return h; +} + +// What the <r> root tag states besides est_tokens: the provenance stamp in front, the row-selection disclosures behind. +struct MapRootFacts +{ + const MapAnnotations& ann; + std::string_view rootArg; + bool stable; + const DataSectionsCut& dataSecCut; + std::size_t stemCut; +}; + +inline std::string renderMapRootTag( const MapRootFacts& r, std::size_t estTokens, bool estModelled, std::vector<char>& esc ) +{ + const MapAnnotations& ann = r.ann; + // r26-stamp Task A: ` at="..."` ONLY when the caller passed a non-empty stamp (--map-diff); every other caller passes + // nullptr, so the hot default-map path pays a pointer compare, not a git call. at= stays FIRST — the `<r at="<sha>` byte + // sequence gitstampcheck.sh pins is unchanged. + std::string h = "<r"; + if( ann.atStamp != nullptr && !ann.atStamp->empty() ) { h += " at=\""; h += *ann.atStamp; h += "\""; } + // R-E: after at= (so gitstampcheck's `<r at="<sha>` byte sequence is unmoved), same slot --grep uses right after its own + // identifying attributes — the crawl root every <f p=…> below is now RELATIVE to. + if( !r.rootArg.empty() ) { h += " root=\""; h += escapeXml( r.rootArg, esc ); h += "\""; } + h += seedRootAttrs( ann.seed, esc ); + // §A9.6: after at= (so gitstampcheck's `<r at="<sha>` byte sequence is unmoved) — see MapAnnotations. + if( ann.churnWindow != nullptr ) { h += " rank_by=\""; h += ann.churnRankLabel; h += "\" window=\""; h += escapeXml( *ann.churnWindow, esc ); h += "\""; } + // §B2.1: the windowless rankers stamp the same attribute in the same slot. `else if` states the exclusivity the caller + // guarantees, so a future edit that fills both cannot emit rank_by= twice. + else if( ann.rankByLabel != nullptr ) { h += " rank_by=\""; h += ann.rankByLabel; h += "\""; } + // §P8: est_tokens as a MACHINE-READABLE root attribute — a conformant parser may discard comments, so the number a + // budget-aware caller most needs was unreachable from the comment alone. The SAME `estTokens` value (one estimator). + // --stable omits it on the precedent of the k= rank attribute: --stable buys a byte-stable PREFIX, the root element is + // that prefix, and est_tokens is globally volatile. + if( !r.stable ) { char estAttr[ 40 ]; rw::formatTo( estAttr, sizeof( estAttr ), " est_tokens=\"{}\"", estTokens ); h += estAttr; } + if( !r.stable && estModelled ) { h += " est_measured=\"0\""; } // beside the number it qualifies (MapEstimate) + // W2-F: LAST on the root, after est_tokens — the same placement rule counts_floor= follows, so no existing + // attribute-ADJACENCY assertion in test/ can break on it. NOT suppressed under --stable: the iteration count is a property + // of the CORPUS and the ranker, not of the run's size, and a byte-stable prefix that hides "this ranking is unfinished" + // would be a cache optimisation buying silence. + h += renderDisclosure( ann.prDisclosure, DiscloseAs::XmlAttrs ); + // H14 (capture-audit 2026-09-04): --stable's omissions, DECLARED. An agent reading a --stable map (which is what every MCP + // `analyze` call gets) saw rows with no rank attribute and nothing saying the score exists elsewhere. lens= names what is + // missing, so "absent" reads as "not served here", never as "not computed". Gate: test/mcpattrparitycheck.sh, whose lens= + // arm also fails on a stale name. + if( r.stable ) { h += " lens=\"k,est_tokens\""; } + // L3 follow-up (CodeRabbit 4053600616): TRULY last, past every pre-existing attribute — same placement rule as lens= just + // above, so no attribute-adjacency assertion in test/ can break on it. + if( ann.notesDegraded ) { h += notes::kNotesDegradedAttr; } + h += renderHistoryUnread( DiscloseAs::XmlAttrs ); // K51: absent unless the amp=/churn= walk could not be read + // The code-first pick's swaps, last of all (the same placement rule as the two above): absent when nothing was swapped. + if( r.dataSecCut.cut > 0 ) + { + h += " data_sections_cut=\""; h += std::to_string( r.dataSecCut.cut ); h += "\""; + h += nextAttrXml( dataSectionsNext( r.dataSecCut ) ); + } + if( r.stemCut > 0 ) + { + h += " stem_cut=\""; h += std::to_string( r.stemCut ); h += "\""; // MAP-STEM: absent unless a --max-tokens fit left stem rows out + } + h += ">"; // K51: history_unread='s definition rides the leading legend (HISTORY-UNREAD-LEGEND), not behind this tag + return h; +} + +// ── the XML map's rows ─────────────────────────────────────────────────────────────────────────────────────────── + +// amb= (≤ 17 B) then lpin= (≤ 18 B), each absent when 0: "fast guessed K of this symbol's call targets — read source", then +// the disclosed locality pin (Phase 4). The cursor is the OUT POINTER, never a would-have-written length: lpin= is written AT +// the offset the first write ended, so a count an implementation computed rather than wrote would place it inside the +// half-written amb= attribute. Same defect class as BoundedAttrRun below. +inline std::string rowGuessAttrs( const MapRowSources& src, NodeId id ) +{ + char ambs[ 48 ]; ambs[ 0 ] = '\0'; + char* ap = ambs; + char* const ae = ambs + sizeof( ambs ); + if( const std::uint32_t ambK = counterAt( src.ambOut, id ); ambK > 0 ) + { + ap = std::format_to_n( ap, ( ae - ap ) - 1, " amb=\"{}\"", ambK ).out; + *ap = '\0'; + } + if( const std::uint32_t lpinK = counterAt( src.locPinOut, id ); lpinK > 0 ) + { + ap = std::format_to_n( ap, ( ae - ap ) - 1, " lpin=\"{}\"", lpinK ).out; + *ap = '\0'; + } + return ambs; +} + +// PageRank k= is GLOBALLY volatile (any edit perturbs every rank) → omitted in --stable mode so the prefix stays byte-identical +// for unedited files (provider KV-cache hits). Default keeps k=. +inline std::string rowRankAttr( const MapRowSources& src, NodeId id ) +{ + char kbuf[ 24 ]; kbuf[ 0 ] = '\0'; + if( !src.stable ) + { + rw::formatTo( kbuf, sizeof( kbuf ), " k=\"{:.4f}\"", double( src.rank[ id ] ) ); + } + return kbuf; +} + +// A fixed attribute buffer that truncates the way snprintf did, byte for byte. A4-F8: snprintf returns the WOULD-HAVE-written +// length; on truncation `qp += ret` pushed qp PAST the end, then the next size_t(qe-qp) underflowed to a huge size → unbounded +// stack write. So every append is bound by the OUT POINTER, never by a would-have-written length: std::format_to_n's `out` is +// clamped to the n it was given on any implementation; its `size` is a would-have-written count an implementation can get +// wrong. n is (end-qp)-1 so the NUL always lands in bounds — snprintf's "at most S-1 characters plus a terminator". +// +// The obvious-looking rewrite — `qp = std::format_to_n( qp, qe - qp, ... ).out` — is WRONG, and wrong in a way no fixture +// catches: format_to_n( p, S, ... ) writes up to S and terminates nothing. It buys one extra byte of room and drops the +// terminator. Measured 2026-09-09: that version emitted a row carrying amp="1" where every previous release truncated it away, +// on test/ as the corpus — only a differential run against the pre-conversion binary on a REAL tree exposed it. +// std::format_string keeps -Wformat-security's compile-time checking through the member template. +// +// 96 -> 160 (Phase 1, local-variable-indexing, docs/LOCALS_INDEXING.md): the fn/method worst case grew by locals="4294967295" +// locals_floor="1" (38 B) on top of the pre-existing loc+params+nest+cbo+amp+tested run (~88 B) — 96 would silently TRUNCATE +// (safe from a buffer-overrun standpoint, but a truncated attr run is malformed XML, not a degrade worth shipping quietly). +// 160 -> 192 (ppalt disclosure): ppalt="65535" (+14 B) put the summed fn/method worst case within a rounding error of 160; 192 +// restores the same real headroom. The fn/method group and lcom4 are mutually exclusive, so the size covers ONE group's worst case. +class BoundedAttrRun +{ +public: + BoundedAttrRun() noexcept { buf_[ 0 ] = '\0'; } + BoundedAttrRun( const BoundedAttrRun& ) = delete; + BoundedAttrRun& operator=( const BoundedAttrRun& ) = delete; + + template <class... A> + void append( std::format_string<A...> fmt, A&&... args ) + { + char* const end = buf_ + sizeof( buf_ ); + if( at_ < end ) + { + at_ = std::format_to_n( at_, ( end - at_ ) - 1, fmt, std::forward<A>( args )... ).out; + *at_ = '\0'; } - // §A9.6: after at= (so gitstampcheck's `<r at="<sha>` byte sequence is unmoved) — see MapAnnotations. - if( churnWindow != nullptr ) { h += " rank_by=\""; h += ann.churnRankLabel; h += "\" window=\""; h += escapeXml( *churnWindow, esc ); h += "\""; } - // §B2.1: the windowless rankers stamp the same attribute in the same slot. `else if` states the - // exclusivity the caller guarantees, so a future edit that fills both cannot emit rank_by= twice. - else if( ann.rankByLabel != nullptr ) { h += " rank_by=\""; h += ann.rankByLabel; h += "\""; } - // §P8: est_tokens as a MACHINE-READABLE root attribute. The map reported its own size only inside the - // comment above, and a conformant parser may discard comments — so the number a budget-aware caller most - // needs was unreachable. Additive: the comment is kept, and this carries the SAME `estTokens` value - // (one estimator). --stable omits it on the precedent of the k= rank attribute below: --stable buys a - // byte-stable PREFIX, the root element is that prefix, and est_tokens is globally volatile. - if( !stable ) { char estAttr[ 40 ]; rw::formatTo( estAttr, sizeof( estAttr ), " est_tokens=\"{}\"", estTokens ); h += estAttr; } - if( !stable && estimate.isModelled ) { h += " est_measured=\"0\""; } // beside the number it qualifies (MapEstimate) - // W2-F: LAST on the root, after est_tokens — the same placement rule counts_floor= follows, so no - // existing attribute-ADJACENCY assertion in test/ can break on it. Unlike est_tokens this is NOT - // suppressed under --stable: the iteration count is a property of the CORPUS and the ranker, not of - // the run's size, so it does not move between two runs over the same tree, and a byte-stable prefix - // that hides "this ranking is unfinished" would be a cache optimisation buying silence. - h += renderDisclosure( ann.prDisclosure, DiscloseAs::XmlAttrs ); - // H14 (capture-audit 2026-09-04): --stable's omissions, DECLARED. Both are deliberate and both are - // argued for above — k= is globally volatile so dropping it is what buys the byte-stable prefix, and - // est_tokens= follows it for the same reason. But an agent reading a --stable map (which is what - // every MCP `analyze` call gets) saw 185 rows with no rank attribute and nothing saying the score - // exists elsewhere: membership is by PageRank, the emitted order is by file, and the score was - // simply gone. lens= names what is missing, so "absent" reads as "not served here", never as "not - // computed". Gate: test/mcpattrparitycheck.sh, whose lens= arm also fails on a stale name. - if( stable ) { h += " lens=\"k,est_tokens\""; } - // L3 follow-up (CodeRabbit 4053600616): TRULY last, past every pre-existing attribute — same placement - // rule as lens= just above, so no attribute-adjacency assertion in test/ can break on it. - if( ann.notesDegraded ) { h += notes::kNotesDegradedAttr; } - h += renderHistoryUnread( DiscloseAs::XmlAttrs ); // K51: absent unless the amp=/churn= walk could not be read - // The code-first pick's swaps, last of all (the same placement rule as the two above): absent when nothing was swapped. - if( dataSecCut.cut > 0 ) - { - h += " data_sections_cut=\""; h += std::to_string( dataSecCut.cut ); h += "\""; - h += nextAttrXml( dataSectionsNext( dataSecCut ) ); - } - if( stemPick.cut > 0 ) - { - h += " stem_cut=\""; h += std::to_string( stemPick.cut ); h += "\""; // MAP-STEM: absent unless a --max-tokens fit left stem rows out - } - h += ">"; // K51: history_unread='s definition rides the leading legend above (HISTORY-UNREAD-LEGEND), not behind this tag - return h; - }; - const auto buildTail = [ & ]( std::size_t estTokens ) -> std::string + } + const char* c_str() const noexcept { return buf_; } + +private: + char buf_[ 192 ]; + char* at_ = buf_; +}; + +// A function or method row's SHAPE attributes, --metrics only: params= (a floor when countParams saturated), nest= and its +// profile, steer=/tangle=, locals=, ppalt=. Only fns/methods carry them, so a class/sec never carries a 0 it can't have. +inline void appendFnShapeAttrs( BoundedAttrRun& run, const Symbol& s ) +{ + run.append( " params=\"{}\"", unsigned( s.params ) ); + if( s.params == std::numeric_limits<decltype( s.params )>::max() ) { - return ( stable && !statsFirstScreen ) ? buildStats( estTokens ) : std::string{}; - }; + run.append( " params_floor=\"1\"" ); // CR #586: countParams saturates at the field width, so this count is a floor + } + run.append( " nest=\"{}\"", unsigned( s.maxNest ) ); + // The nesting PROFILE beside the max (model.h Symbol::humps/deepLoc). nest= alone cannot distinguish a long run of shallow + // scoped steps from a body that sustains depth. Omitted, never a bare 0, when no region reached quality::kNestBar: that is + // exactly nest < kNestBar, which the row already carries, so absence is lossless rather than a truncation + // (test/nestprofilecheck.sh arm 5 pins the equivalence in both directions). + if( s.humps > 0 ) + { + run.append( " humps=\"{}\" deep=\"{}\" deep_floor=\"1\"", unsigned( s.humps ), unsigned( s.deepLoc ) ); + } + run.append( "{}", tangleMetricAttrs( s, /*json=*/false ) ); // QD-TANGLE: steer= / tangle=, each absent at 0 + // Phase 1 (local-variable-indexing, docs/LOCALS_INDEXING.md): locals= is ABSENT — never a bare "0" — for every def outside + // model.h's localsCountedLang (MVP: C/C++ only), so a reader never mistakes "not counted for this language" for "counted, + // and there are none". locals_floor="1" always rides alongside a present locals=: `int a,b;` counts as ONE + // declaration-statement, not two names (see cc_isCountableLocalDecl's own comment). + if( localsCountedLang( s.lang ) ) + { + run.append( " locals=\"{}\" locals_floor=\"1\"", unsigned( s.locals ) ); + } + // ppalt disclosure: the body carries preproc branches that never coexist at compile time, so this row's structural metrics + // are sums over ALL of them (model.h Symbol::ppAlt). ABSENT when 0 — presence itself is the signal. + if( s.ppAlt > 0 ) + { + run.append( " ppalt=\"{}\"", unsigned( s.ppAlt ) ); + } +} - // ── PHASE 1: render <r>'s CHILDREN into a buffer ──────────────────────────────────────────────────── - // §H7: est_tokens must charge the bytes the document actually carries, not a model of the symbol set — - // the model prices neither --metrics decoration nor an appended payload, which is how one number came to - // stand for five documents. So: measure, decide, then write (the order --recall's emitRecallBudgeted and - // the --for lens's pre-rendered sigs block already impose on themselves). - // - // DEGRADE: an open_memstream failure keeps the whole map — the head goes out FIRST carrying the MODELLED - // estimate (the pre-§H7 number, so this path is no worse than the old behaviour, never a fabricated one) - // and the children stream straight to `out` behind it. - rw::MemoryStream childStream; - std::FILE* const childMem = openChargeStream( childStream ); - if( !childMem ) +// The Q-compute descriptive attributes (loc/params/nest/locals/cbo/lcom4/amp/tested), --metrics only — facts, never gates. +// loc first (SIZE is the master variable); lcom4 only for class-kinds with methods (kLcom4NA = 0xFFFFFFFF omits); tested only +// when 1 (lean output). +inline void appendQMetricAttrs( BoundedAttrRun& run, const Symbol& s, NodeId id, const MapRowSources& src ) +{ + if( s.loc > 0 ) { - DISCLOSE( estimate, MapEstimate::DisclosureWhy::ChargeBufferFailed, "serialize: open_memstream failed — est_tokens reports the MODELLED bytes, not the emitted ones" ); + run.append( " loc=\"{}\"", s.loc ); + } + if( s.kind == SymKind::Function || s.kind == SymKind::Method ) + { + appendFnShapeAttrs( run, s ); + } + if( src.cbo && id < src.cbo->size() ) + { + run.append( " cbo=\"{}\"", ( *src.cbo )[ id ] ); + } + if( src.lcom4 && id < src.lcom4->size() && ( *src.lcom4 )[ id ] != 0xFFFFFFFFu ) + { + run.append( " lcom4=\"{}\"", ( *src.lcom4 )[ id ] ); + } + if( src.amp && id < src.amp->size() ) + { + run.append( " amp=\"{}\"", ( *src.amp )[ id ] ); + } + if( src.tested && id < src.tested->size() && ( *src.tested )[ id ] ) + { + run.append( " tested=\"1\"" ); } +} - const std::size_t modelledTokens = mapEstTokens + extraPayloadTokens; - // The children, as ONE renderer both paths call. This was inline code writing through a writer bound to "the buffer, - // or `out` when the buffer could not open". That serves a failed open, and cannot serve a buffer that opened and then - // lost a write: by then the children were already spent into it, and the only bytes left to print had a hole in them. - std::vector<std::uint32_t> hedgedScratch; // FE-B: writeMapCalleeRows' reused buffer - const auto writeChildren = [ & ]( XmlWriter& w ) +// The row's descriptive attributes as ONE run after its identity attributes: under --metrics with fan-in, in=/out=/cx=/ccx=, +// role="hub" at fan-in ≥ 8 and the Q-compute run first; then amb=/lpin= and k=. Composed in one fixed buffer, as always, so a +// run past its width truncates at the byte it always did. +inline std::string rowDescriptiveAttrs( const Symbol& s, NodeId id, const MapRowSources& src ) +{ + const std::uint32_t outDegree = src.outOff[ id + 1 ] - src.outOff[ id ]; + const std::string guesses = rowGuessAttrs( src, id ); + const std::string rankAttr = rowRankAttr( src, id ); + char attr[ 352 ]; + if( src.metrics && src.fanIn ) { - // §P8 collision: this prologue spelled its LABEL `l=`, the two characters 22 other sites use for a LINE - // NUMBER — including the <f p= …> rows just below. Renamed: the label had exactly two references in the - // tree (both updated here) against 15+ readers of the line-number meaning that must not move. - if( ing.rootLabels.size() >= 2 ) - { // A13 prologue: label → root path, canonical order - for( std::size_t r = 0; r < ing.rootLabels.size(); ++r ) - { - w.write( "<root label=\"" ); w.write( escapeXml( ing.rootLabels[r], esc ) ); - w.write( "\" p=\"" ); w.write( escapeXml( r < ing.rootPaths.size() ? ing.rootPaths[r] : std::string(), esc ) ); - w.write( "\"/>" ); - } - } - writeRecentRows( w, ann, pathRel, esc ); // F3: rank_by=churn-decay's file-level answer, before the symbol map - // C1-b: under in=DIR the symbol map is a DISCLOSED stub (docs/METHODOLOGY.md §9.3) — the caller asked for DIR's - // recent files, not the map. - // - // NOT total=/shown=, which is what this first shipped as. Under pageview.h's vocabulary total= is THE TOTAL - // (rule 2) and capped= always rides beside a shown= (rule 3), and the stub had neither property: it printed - // total="200" — the --top-k PAGE SIZE — on a document whose own header says symbols="18457", with no capped=, - // so the one number it carried was the one number it was not allowed to mean. The stub is not a page of the map - // and it must not borrow the page vocabulary to say so. It says what it IS instead: - // stubbed="1" the symbol map was not rendered at all (the <f> loop walks an empty order below) - // would_show="N" `keep` — the un-stubbed header's own shown=, and shown= counts symbol DEFINITIONS - // individually, not printed rows: the print loop runs collapseOverloadRows() per file - // bucket, so a const/non-const pair that both make the top-K cut prints ONE row carrying - // overloads=2. The row count therefore FOLLOWS from the identity the map legend already - // publishes for shown= — rows+sum(overloads-1)=shown — rather than being reported here. - // Measured on this repo 2026-09-14: shown=200, 193 <s> rows, 7 at overloads=2, 193+7=200. - // IT IS A DEFINITION COUNT AND NOT A CEILING, by owner decision 2026-09-14, and the - // reason is vocabulary: in this tool a floor/ceiling marker means "we could not see - // everything" (counts_floor=, _capped, the truncation disclosures). would_show is EXACT; - // what differs from a reader's guess is the UNIT. Spending an uncertainty marker on a - // unit difference would make "ceiling" mean "exact, but not in the unit you assumed" and - // weaken every honest use of the word elsewhere in the output. Naming the quantity is - // also the stronger claim: a ceiling cannot be inverted, while a definition count plus - // the published identity yields the rows. Reporting post-collapse rows instead — the - // review's original ask — is not available at this site for any price worth paying: - // which definitions survive the cut is a fact about the RANKING, and not ranking is the - // whole point of the stub (no pr_iters= rides its header). Not the corpus total either - // (that is symbols=), so the three cannot be read as each other. - // test/recentscopecheck.sh arms 14a/14b pin the arithmetic. - // Rule 3's own sentence sanctions the shape: "If a verb emits no shown=, it emits no capped= either." - if( ann.stubSymbols ) - { - std::string stub = "<symbols stubbed=\"1\" would_show=\""; // std::string, not a char[]: next= is already-markup (fixedbufsweep's rule) - stub += std::to_string( keep ); // `keep` is computed above from topK and S alone — the count with no ranking behind it - stub += "\""; - stub += nextAttrXml( ann.stubNext ); - stub += "/>"; - w.write( stub ); - } - // D7: the inventory tier rides the LOW-importance end of the document — after the rows, or before them when the - // map is emitted important-last (an explicit flag or the fill-aware auto flip), so the top-ranked rows keep the - // end position that order promises. - const auto writeInventory = [ & ]() - { - if( inventory.active ) - { - writeMapInventoryXml( w, ing, inventory, pathRel, outOff, outTargets, outProv, outNameOnly, esc, hedgedScratch ); - } - }; - const bool inventoryFirst = !stable && effImportantLast; // --stable's path order wins, as it does for the rows - if( inventoryFirst ) - { - writeInventory(); - } - static const std::vector<std::uint32_t> kNoFiles; - for( std::uint32_t f : ann.stubSymbols ? kNoFiles : fileOrder ) - { - w.write( "<f p=\"" ); w.write( escapeXml( pathRel( f ), esc ) ); w.write( "\"" ); - if( const char* fl = builtinLayer( rootRelPath( ing, f ) ); *fl ) { w.write( " layer=\"" ); w.write( fl ); w.write( "\"" ); } // P3 - w.write( ">" ); + BoundedAttrRun qmetrics; + appendQMetricAttrs( qmetrics, s, id, src ); + const std::uint32_t in = ( id < src.fanIn->size() ) ? ( *src.fanIn )[ id ] : 0u; + rw::formatTo( attr, sizeof( attr ), " in=\"{}\" out=\"{}\" cx=\"{}\" ccx=\"{}\"{}{}{}{}", + in, outDegree, s.cx, s.ccx, ( in >= 8 ? " role=\"hub\"" : "" ), qmetrics.c_str(), guesses, rankAttr ); + } + else + { + rw::formatTo( attr, sizeof( attr ), "{}{}", guesses, rankAttr ); + } + return attr; +} - // §P6.3: see collapseOverloadRows() above — const/non-const overload pairs are already folded to - // one representative row per (kind,id) before this loop runs, so the loop body below is unchanged - // shape (no added branch): it just iterates a shorter vector. - const OverloadRows rows = overloadRowsFor( ing, buckets[f], metrics ); // --metrics: one row per definition +// Essential complexity (model.h Symbol::ev), --metrics only. Emitted iff ev >= 2: ev >= 1 for any walked fn/method body, so on +// a row carrying cx= ABSENT means exactly ev == 1 — lossless, and never a bare ev="1" (G4 + the honesty contract point the +// same way). Routed through evCountedLang so an uncovered language (Bash) reads as "not counted", never "counted, 1". +// ev_floor="1" always rides along: noreturn calls, macro-hidden returns and unresolvable gotos are invisible to the syntactic +// walk and can only RAISE the true value. ev_why= is the reason breakdown that keeps §10.1-Option-A honest (a guard-heavy row +// is visibly not a knot). Composed on std::string: ev_why= is variable-length text (fixedbufsweep's rule). +inline std::string rowEssentialComplexityAttrs( const Symbol& s, bool metrics ) +{ + if( !metrics || !( s.kind == SymKind::Function || s.kind == SymKind::Method ) || !evCountedLang( s.lang ) || s.ev < 2u ) + { + return {}; + } + return " ev=\"" + std::to_string( s.ev ) + "\" ev_floor=\"1\" ev_why=\"" + evWhyString( s ) + "\""; +} - for( std::size_t i = 0; i < rows.id.size(); ++i ) - { - const NodeId id = rows.id[i]; - const Symbol& s = ing.symbols[id]; - const std::uint32_t out = outOff[id + 1] - outOff[id]; - w.write( "<s t=\"" ); w.write( symTag( s.kind ) ); - w.write( "\" n=\"" ); w.write( escapeXml( s.name, esc ) ); w.write( "\"" ); // close n="…" here so sc= can follow - - // S6-C / row 6 (2026-09-12): the SHORT id. The canonical SCIP-style id is `path::scope::name`, and - // on a map row the path is the enclosing <f p=> verbatim — 942 of 942 scoped rows on this tree - // repeated it, 11.2% of a flagless map. The row now prints ONLY the segment the wrapper does not - // carry: sc= the enclosing scope. The legend states the composition (id = p::sc::n), the selectors - // keep accepting the composed spelling, and test/scroundtripcheck.sh proves the composed multiset is - // byte-identical to the id= multiset this row used to print. Emitted ONLY when a scope exists — - // exactly when the canonical id differed from the bare name (canonicalId degrades to the name on an - // empty scope), so the row set that carries an identity attribute is unchanged. - writeScopeAttr( w, s, esc ); - if( !stemRows.empty() && std::ranges::binary_search( stemRows, id ) ) - { - w.write( " stem=\"1\"" ); // MAP-STEM: the file's stem-namesake type, added below the top-K cut - } +// One <s> row and its <c> callee rows. +inline void writeMapSymbolRow( XmlWriter& w, const IngestResult& ing, const OverloadRows& rows, std::size_t i, const std::vector<NodeId>& stemRows, + const MapRowSources& src, std::vector<char>& esc, std::vector<std::uint32_t>& scratch ) +{ + const NodeId id = rows.id[ i ]; + const Symbol& s = ing.symbols[ id ]; + w.write( "<s t=\"" ); w.write( symTag( s.kind ) ); + w.write( "\" n=\"" ); w.write( escapeXml( s.name, esc ) ); w.write( "\"" ); // close n="…" here so sc= can follow + // S6-C / row 6 (2026-09-12): the SHORT id. The canonical SCIP-style id is `path::scope::name`, and on a map row the path is + // the enclosing <f p=> verbatim. The row prints ONLY the segment the wrapper does not carry: sc= the enclosing scope. The + // legend states the composition (id = p::sc::n) and test/scroundtripcheck.sh proves the composed multiset is byte-identical + // to the id= multiset this row used to print. Emitted ONLY when a scope exists. + writeScopeAttr( w, s, esc ); + if( !stemRows.empty() && std::ranges::binary_search( stemRows, id ) ) + { + w.write( " stem=\"1\"" ); // MAP-STEM: the file's stem-namesake type, added below the top-K cut + } + w.write( overloadsAttr( rows.overloads[ i ] ) ); // see overloadsAttr() above — empty in the common case + w.write( splitLineAttr( rows, i, s ) ); // --metrics per-definition rows only + // A4-R5: bind="pkg.Cls.method" — the decoded JNI binding label (graph.h g.bindLabel), when this symbol has one. Not + // --metrics-gated: it is an identity fact like id=, not a descriptive stat. Omitted whenever bind is nullptr or the label is + // empty (the overwhelming common case) → zero token cost, byte-identical golden map on non-JNI corpora. + if( const std::string_view label = src.bind ? src.bind->labelOf( id ) : std::string_view{}; !label.empty() ) + { + w.write( " bind=\"" ); w.write( escapeXml( label, esc ) ); w.write( "\"" ); + } + w.write( rowDescriptiveAttrs( s, id, src ) ); + // EXTENT HONESTY (kExtentSuspectRowLegend): the containment checks this row's extent/scope/kind failed. After k= so every + // pre-existing adjacency holds; absent when every check held (clean corpora unchanged). + if( s.extentSuspect != 0 ) + { + w.write( " extent_suspect=\"" ); + w.write( extent::extentSuspectReasons( s.extentSuspect ) ); + w.write( "\"" ); + } + w.write( rowEssentialComplexityAttrs( s, src.metrics ) ); + w.write( ">" ); + writeMapCalleeRows( w, ing, src.outOff[ id ], src.outOff[ id + 1 ], src.outTargets, src.outProv, src.outNameOnly, esc, scratch ); + w.write( "</s>" ); +} - w.write( overloadsAttr( rows.overloads[i] ) ); // see overloadsAttr() above — empty in the common case - w.write( splitLineAttr( rows, i, s ) ); // --metrics per-definition rows only +// One <f> group: the file's path and arch layer (P3), then its rows. §P6.3: const/non-const overload pairs are folded to one +// representative row per (kind,id) by overloadRowsFor() before the rows are written (--metrics: one row per definition). +template <class PathRel> +inline void writeMapFileGroup( XmlWriter& w, const IngestResult& ing, std::uint32_t f, const MapFileGroups& groups, const MapRowSources& src, + const PathRel& pathRel, std::vector<char>& esc, std::vector<std::uint32_t>& scratch ) +{ + w.write( "<f p=\"" ); w.write( escapeXml( pathRel( f ), esc ) ); w.write( "\"" ); + if( const char* fl = builtinLayer( rootRelPath( ing, f ) ); *fl ) { w.write( " layer=\"" ); w.write( fl ); w.write( "\"" ); } // P3 + w.write( ">" ); + const OverloadRows rows = overloadRowsFor( ing, groups.buckets[ f ], src.metrics ); + for( std::size_t i = 0; i < rows.id.size(); ++i ) + { + writeMapSymbolRow( w, ing, rows, i, groups.stemPick.rows, src, esc, scratch ); + } + w.write( "</f>" ); +} - // A4-R5: bind="pkg.Cls.method" — the decoded JNI binding label (graph.h g.bindLabel), when this - // symbol has one. Unconditional (not --metrics-gated): it is an identity fact like id=, not a - // descriptive stat. Omitted whenever bind is nullptr or the per-symbol label is empty (the - // overwhelming common case) → zero token cost, byte-identical golden map on non-JNI corpora. - if( const std::string_view label = bind ? bind->labelOf( id ) : std::string_view{}; !label.empty() ) - { - w.write( " bind=\"" ); w.write( escapeXml( label, esc ) ); w.write( "\"" ); - } +// A13 prologue, multi-root only: label → root path, canonical order. §P8 collision: this prologue spelled its LABEL `l=`, the +// two characters 22 other sites use for a LINE NUMBER — including the <f p= …> rows. Renamed to label=. +inline void writeRootLabelPrologue( XmlWriter& w, const IngestResult& ing, std::vector<char>& esc ) +{ + if( ing.rootLabels.size() < 2 ) + { + return; + } + for( std::size_t r = 0; r < ing.rootLabels.size(); ++r ) + { + w.write( "<root label=\"" ); w.write( escapeXml( ing.rootLabels[r], esc ) ); + w.write( "\" p=\"" ); w.write( escapeXml( r < ing.rootPaths.size() ? ing.rootPaths[r] : std::string(), esc ) ); + w.write( "\"/>" ); + } +} - char ambs[ 48 ]; ambs[ 0 ] = '\0'; // "fast guessed K of this symbol's call targets — read source" - // amb= (≤ 17 B) then lpin= (≤ 18 B) in ONE buffer, each absent when 0. The cursor is the OUT - // POINTER, never a would-have-written length: lpin= is written AT the offset the first write - // ended, so a count an implementation computed rather than wrote would place it inside the - // half-written amb= attribute. Same defect class as the appendf clamps below. - char* ap = ambs; - char* const ae = ambs + sizeof( ambs ); - if( const std::uint32_t ambK = counterAt( ambOut, id ); ambK > 0 ) - { - ap = std::format_to_n( ap, ( ae - ap ) - 1, " amb=\"{}\"", ambK ).out; - *ap = '\0'; - } - if( const std::uint32_t lpinK = counterAt( locPinOut, id ); lpinK > 0 ) // Phase 4: the disclosed locality pin - { - ap = std::format_to_n( ap, ( ae - ap ) - 1, " lpin=\"{}\"", lpinK ).out; - *ap = '\0'; - } +// C1-b: under in=DIR the symbol map is a DISCLOSED stub (docs/METHODOLOGY.md §9.3) — the caller asked for DIR's recent files, +// not the map. +// +// NOT total=/shown=, which is what this first shipped as. Under pageview.h's vocabulary total= is THE TOTAL (rule 2) and +// capped= always rides beside a shown= (rule 3), and the stub had neither property: it printed total="200" — the --top-k PAGE +// SIZE — on a document whose own header says symbols="18457", with no capped=, so the one number it carried was the one +// number it was not allowed to mean. The stub is not a page of the map and it must not borrow the page vocabulary to say so. +// It says what it IS instead: +// stubbed="1" the symbol map was not rendered at all (the stub ranks and groups no row) +// would_show="N" `keep` — the un-stubbed header's own shown=, and shown= counts symbol DEFINITIONS individually, not +// printed rows: the print loop runs collapseOverloadRows() per file bucket, so a const/non-const pair that +// both make the top-K cut prints ONE row carrying overloads=2. The row count therefore FOLLOWS from the +// identity the map legend already publishes for shown= — rows+sum(overloads-1)=shown — rather than being +// reported here. Measured on this repo 2026-09-14: shown=200, 193 <s> rows, 7 at overloads=2, 193+7=200. +// IT IS A DEFINITION COUNT AND NOT A CEILING, by owner decision 2026-09-14, and the reason is vocabulary: +// in this tool a floor/ceiling marker means "we could not see everything" (counts_floor=, _capped, the +// truncation disclosures). would_show is EXACT; what differs from a reader's guess is the UNIT. Naming the +// quantity is also the stronger claim: a ceiling cannot be inverted, while a definition count plus the +// published identity yields the rows. Reporting post-collapse rows instead is not available at this site +// for any price worth paying: which definitions survive the cut is a fact about the RANKING, and not +// ranking is the whole point of the stub (no pr_iters= rides its header). Not the corpus total either +// (that is symbols=), so the three cannot be read as each other. +// test/recentscopecheck.sh arms 14a/14b pin the arithmetic. +// Rule 3's own sentence sanctions the shape: "If a verb emits no shown=, it emits no capped= either." +inline void writeSymbolMapStub( XmlWriter& w, std::size_t keep, std::string_view stubNext ) +{ + std::string stub = "<symbols stubbed=\"1\" would_show=\""; // std::string, not a char[]: next= is already-markup (fixedbufsweep's rule) + stub += std::to_string( keep ); // `keep` depends on topK and the printable rows alone — the count with no ranking behind it + stub += "\""; + stub += nextAttrXml( stubNext ); + stub += "/>"; + w.write( stub ); +} + +// <r>'s children, as ONE renderer serialize()'s measured path and its degrade path both call: the multi-root prologue, F3's +// recent files (rank_by=churn-decay's file-level answer, before the symbol map), the stub or the <f> groups, and the D7 +// inventory tier. The inventory rides the LOW-importance end of the document — after the rows, or before them when the map +// is emitted important-last, so the top-ranked rows keep the end position that order promises. +template <class PathRel> +inline void writeMapChildren( XmlWriter& w, const IngestResult& ing, const MapAnnotations& ann, std::size_t keep, const MapFileGroups& groups, + MapEmitOrder emitOrder, const MapRowSources& src, const PathRel& pathRel, std::vector<char>& esc, + std::vector<std::uint32_t>& scratch ) +{ + writeRootLabelPrologue( w, ing, esc ); + writeRecentRows( w, ann, pathRel, esc ); + if( ann.stubSymbols ) + { + writeSymbolMapStub( w, keep, ann.stubNext ); + } + const auto writeInventory = [ & ]() + { + if( groups.inventory.active ) + { + writeMapInventoryXml( w, ing, groups.inventory, pathRel, src.outOff, src.outTargets, src.outProv, src.outNameOnly, esc, scratch ); + } + }; + const bool inventoryFirst = isImportantLast( emitOrder ); // --stable's path order wins, as it does for the rows + if( inventoryFirst ) + { + writeInventory(); + } + for( const std::uint32_t f : groups.fileOrder ) + { + writeMapFileGroup( w, ing, f, groups, src, pathRel, esc, scratch ); + } + if( !inventoryFirst ) + { + writeInventory(); + } + w.write( "</r>" ); +} - // PageRank k= is GLOBALLY volatile (any edit perturbs every rank) → omit it in --stable mode - // so the prefix stays byte-identical for unedited files (provider KV-cache hits). Default keeps k=. - char kbuf[ 24 ]; kbuf[ 0 ] = '\0'; - if( !stable ) - { - rw::formatTo( kbuf, sizeof( kbuf ), " k=\"{:.4f}\"", double( rank[id] ) ); - } +// The fixpoint: est_tokens covers head + children + tail, and head/tail both PRINT est_tokens, so the digit count feeds back. +// Converges in ≤2 passes in practice (each extra digit moves the estimate by <1 token); the bound is 4, matching recall.h's. +// +// WHAT THE LOOP GUARANTEES (CA4 verifier L4): the LAST built pair is always the pair returned, and ON CONVERGENCE — the number +// stopped moving — that pair's own bytes are exactly the bytes `estTokens` was measured over, so the document's stated number +// describes the document. On the BOUND (4 passes without convergence, not observed on any measured corpus) the head/tail were +// rebuilt from the last `next` while `next` was measured over the PREVIOUS pair's widths, which differ only in the digit count +// of one field: at most a few bytes, i.e. a residual well under one token, and never a fabricated number. The honest statement +// is "converged ⇒ exact; bounded ⇒ within a digit's worth of bytes", not "always exact". +struct SettledHeadTail +{ + std::size_t estTokens = 0; + std::string head; + std::string tail; +}; - // Q-compute descriptive attrs (loc/params/nest/locals/cbo/lcom4/tested), built into a side buffer - // that is appended before the closing '>' of the metrics attr. ALL --metrics-only; absent by - // default so the golden map is byte-identical. params/nest/locals emitted only for fns/methods - // (kind guard) so a class/sec never carries a 0 it can't have; lcom4 only for class-kinds with - // methods (kLcom4NA sentinel omits) — mutually exclusive with the fn/method group, which is why - // the buffer sizing below only has to cover ONE of the two groups' worst case, not both summed. - // 96 -> 160 (Phase 1, local-variable-indexing, docs/LOCALS_INDEXING.md): the fn/method worst - // case grew by locals="4294967295" locals_floor="1" (38 B) on top of the pre-existing - // loc+params+nest+cbo+amp+tested run (~88 B) — 96 would silently TRUNCATE (appendf's qe-clamp - // makes truncation safe from a buffer-overrun standpoint, but a truncated attr run is malformed - // XML, not a degrade worth shipping quietly). 160 -> 192 (ppalt disclosure): ppalt="65535" - // (+14 B) put the summed fn/method worst case within a rounding error of 160; 192 restores the - // same real headroom over the recomputed worst case. - char qbuf[ 192 ]; qbuf[ 0 ] = '\0'; - if( metrics ) - { - char* qp = qbuf; char* const qe = qbuf + sizeof( qbuf ); - // A4-F8: snprintf returns the WOULD-HAVE-written length; on truncation `qp += ret` pushes qp - // PAST qe, then the next size_t(qe-qp) underflows to a huge size → unbounded stack write. Clamp - // qp to qe after every append (once full, further appends write nothing and stay clamped). - // fmt is always a string literal at every call site below — the non-literal warning is - // an artifact of routing it through the lambda parameter - // rw::formatTo reproduces snprintf's contract EXACTLY, so the A4-F8 clamp below is kept - // verbatim: it is applied to the same would-have-written length, and truncation therefore - // happens at the same byte it always did. - // - // The obvious-looking rewrite — `qp = std::format_to_n( qp, qe - qp, ... ).out` — is WRONG, - // and wrong in a way no fixture catches. snprintf( p, S, ... ) writes at most S-1 characters - // PLUS a NUL; format_to_n( p, S, ... ) writes up to S and terminates nothing. It buys one - // extra byte of room and drops the terminator. Measured 2026-09-09: that version emitted a - // row carrying amp="1" where every previous release truncated it away, on test/ as the - // corpus. The byte fence was green throughout — the fixture's attribute strings never reach - // this 80-byte buffer, so only a differential run against the pre-conversion binary on a - // REAL tree exposed it. - // - // What the conversion does keep: -Wformat-security is gone, because std::format_string - // preserves compile-time checking THROUGH the lambda parameter where a const char* fmt - // could not. - const auto appendf = [ & ]< class... A >( std::format_string<A...> fmt, A&&... args ) - { - // Bound by the OUT POINTER, never by a would-have-written length. std::format_to_n's - // `out` is clamped to the n it was given on any implementation; its `size` is a - // would-have-written count that an implementation can get wrong, and this clamp used - // to depend on it. n is (qe-qp)-1 so the NUL below always lands in bounds, which is - // snprintf's "at most S-1 characters plus a terminator", byte for byte. - if( qp < qe ) - { - const auto r = std::format_to_n( qp, ( qe - qp ) - 1, fmt, std::forward<A>( args )... ); - qp = r.out; - *qp = '\0'; - } - }; - // loc: physical line span — always meaningful (SIZE is the master variable — report it first). - if( s.loc > 0 ) - { - appendf( " loc=\"{}\"", s.loc ); - } - const bool isFn = ( s.kind == SymKind::Function || s.kind == SymKind::Method ); - if( isFn ) - { - appendf( " params=\"{}\"", unsigned( s.params ) ); - if( s.params == std::numeric_limits<decltype( s.params )>::max() ) - { - appendf( " params_floor=\"1\"" ); // CR #586: countParams saturates at the field width, so this count is a floor - } - appendf( " nest=\"{}\"", unsigned( s.maxNest ) ); - // The nesting PROFILE beside the max (model.h Symbol::humps/deepLoc). nest= alone cannot - // distinguish a long run of shallow scoped steps from a body that sustains depth — both - // report their deepest line and nothing about how much of the function is that deep. - // Omitted, never a bare 0, when no region reached quality::kNestBar: that is exactly - // nest < kNestBar, which the row already carries, so absence is lossless rather than a - // truncation (test/nestprofilecheck.sh arm 5 pins the equivalence in both directions). - if( s.humps > 0 ) - { - appendf( " humps=\"{}\" deep=\"{}\" deep_floor=\"1\"", unsigned( s.humps ), unsigned( s.deepLoc ) ); - } - appendf( "{}", tangleMetricAttrs( s, /*json=*/false ) ); // QD-TANGLE: steer= / tangle=, each absent at 0 - // Phase 1 (local-variable-indexing, docs/LOCALS_INDEXING.md): locals= is ABSENT — never - // a bare "0" — for every def outside model.h's localsCountedLang (MVP: C/C++ only), so a - // reader never mistakes "not counted for this language" for "counted, and there are none". - // locals_floor="1" always rides alongside a present locals=: `int a,b;` counts as ONE - // declaration-statement, not two names (see cc_isCountableLocalDecl's own comment). - if( localsCountedLang( s.lang ) ) - { - appendf( " locals=\"{}\" locals_floor=\"1\"", unsigned( s.locals ) ); - } - // ppalt disclosure: the body carries preproc branches that never coexist at compile - // time, so this row's structural metrics are sums over ALL of them (model.h Symbol:: - // ppAlt). ABSENT when 0 — presence itself is the signal. - if( s.ppAlt > 0 ) - { - appendf( " ppalt=\"{}\"", unsigned( s.ppAlt ) ); - } - } - if( cbo && id < cbo->size() ) - { - appendf( " cbo=\"{}\"", (*cbo)[id] ); - } - if( lcom4 && id < lcom4->size() && ( *lcom4 )[id] != 0xFFFFFFFFu ) - { // 0xFFFFFFFF = kLcom4NA (graph.h) ⇒ omit - appendf( " lcom4=\"{}\"", (*lcom4)[id] ); - } - if( amp && id < amp->size() ) - { - appendf( " amp=\"{}\"", (*amp)[id] ); - } - if( tested && id < tested->size() && ( *tested )[id] ) - { // omit when 0 (lean output) - appendf( " tested=\"1\"" ); - } - } +template <class BuildHead, class BuildTail> +inline SettledHeadTail settleEstTokens( std::size_t modelledTokens, std::size_t childBytes, double bytesPerToken, std::size_t extraPayloadTokens, + const BuildHead& buildHead, const BuildTail& buildTail ) +{ + SettledHeadTail s{ modelledTokens, buildHead( modelledTokens ), buildTail( modelledTokens ) }; + for( int pass = 0; pass < 4; ++pass ) + { + const std::size_t next = tokensForEmittedBytes( s.head.size() + childBytes + s.tail.size(), bytesPerToken ) + extraPayloadTokens; + if( next == s.estTokens ) + { + break; + } + s.estTokens = next; + s.head = buildHead( next ); + s.tail = buildTail( next ); + } + return s; +} - char attr[ 352 ]; // descriptive metric attrs (fan-in/out/cx/role/amb/lpin + Q-compute qbuf) — facts, never - // gates. The name quote + id= are already written above; this opens with a space. - // The closing '>' is written separately below so the ev run — composed on - // std::string, never a fixed char buffer (fixedbufsweep's own rule: ev_why= is - // variable-length text) — can sit inside the element. - if( metrics && fanIn ) - { - const std::uint32_t in = ( id < fanIn->size() ) ? (*fanIn)[id] : 0u; - rw::formatTo( attr, sizeof( attr ), " in=\"{}\" out=\"{}\" cx=\"{}\" ccx=\"{}\"{}{}{}{}", - in, out, s.cx, s.ccx, ( in >= 8 ? " role=\"hub\"" : "" ), rw::cstr( qbuf ), rw::cstr( ambs ), rw::cstr( kbuf ) ); - } - else - { - rw::formatTo( attr, sizeof( attr ), "{}{}", rw::cstr( ambs ), rw::cstr( kbuf ) ); - } - w.write( attr ); - // EXTENT HONESTY (kExtentSuspectRowLegend): the containment checks this row's extent/scope/kind failed. - // After k= so every pre-existing adjacency holds; absent when every check held (clean corpora unchanged). - if( s.extentSuspect != 0 ) - { - w.write( " extent_suspect=\"" ); - w.write( extent::extentSuspectReasons( s.extentSuspect ) ); - w.write( "\"" ); - } - // Essential complexity (model.h Symbol::ev), --metrics only. Emitted iff ev >= 2: ev >= 1 for any - // walked fn/method body, so on a row carrying cx= ABSENT means exactly ev == 1 — lossless in the - // strictest sense, and never a bare ev="1" (G4 + the honesty contract point the same way). Routed - // through evCountedLang so an uncovered language (Bash) reads as "not counted", never "counted, 1". - // ev_floor="1" always rides along: noreturn calls, macro-hidden returns and unresolvable gotos are - // invisible to the syntactic walk and can only RAISE the true value. ev_why= is the reason - // breakdown that keeps §10.1-Option-A honest (a guard-heavy row is visibly not a knot). - if( metrics && ( s.kind == SymKind::Function || s.kind == SymKind::Method ) && evCountedLang( s.lang ) && s.ev >= 2u ) - { - std::string evRun = " ev=\"" + std::to_string( s.ev ) + "\" ev_floor=\"1\" ev_why=\"" + evWhyString( s ) + "\""; - w.write( evRun ); - } - w.write( ">" ); +inline void serialize( std::FILE* out, const IngestResult& ing, const std::vector<float>& rank, + const std::vector<std::uint32_t>& outOff, const std::vector<NodeId>& outTargets, + int topK, bool mostImportantLast = false, + bool metrics = false, const std::vector<std::uint32_t>* fanIn = nullptr, + const std::vector<std::uint32_t>* ambOut = nullptr, bool stable = false, + const std::vector<std::uint8_t>* outProv = nullptr, + // Q-compute per-symbol metrics — surfaced on --metrics ONLY (descriptive facts, never gates). + // All optional (nullptr ⇒ that attribute is omitted); loc/params/nest live on Symbol itself. + const std::vector<std::uint32_t>* cbo = nullptr, // Q5a distinct in-repo dependency targets + const std::vector<std::uint8_t>* tested = nullptr, // Q2 referenced from a test-path file + const std::vector<std::uint32_t>* lcom4 = nullptr, // Q4 class cohesion (kLcom4NA ⇒ omit) + const std::vector<std::uint32_t>* amp = nullptr, // Q2 change-amplification (callers + co-change partners) + const std::vector<std::uint32_t>* unresolvedOut = nullptr, // honesty lever #2: per-symbol lang-filtered + // unresolved calls; summed into `unresolved=N` + const SparseLabels* bind = nullptr, // A4-R5 per-symbol cross-language binding + // label (graph.h g.bindLabel) — JNI decoded + // Java_pkg_Cls_method → "pkg.Cls.method". + // Emitted as bind="…" ONLY when non-empty + // (nullptr/empty-vector default ⇒ zero + // token cost, byte-identical golden map). + bool autoOrder = false, // T3: fill-aware auto important-last (see above) + std::size_t* outEstTokens = nullptr, // --token-budget: hand back the SAME est_tokens the + // header prints (no second counter) — nullptr ⇒ unused + std::size_t extraPayloadTokens = 0, // §H7 (was extraBodyTokens): tokens of + // EVERY block the caller appends after this map — + // <sigs>, <src>, <bodies>, <outline> — each MEASURED + // from its rendered bytes by the caller (main.cpp's + // renderMapPayload) and converted through + // tokensForEmittedBytes. The old name said "body" + // and only --expand ever filled it, which is + // precisely why the four siblings went uncharged. + const MapAnnotations& ann = {}, // how THIS map was produced (see MapAnnotations + // above); defaulted ⇒ byte-identical golden map. + // §B6 M10: keep the files=/symbols=/shown=/order= stanza on the FIRST SCREEN even under + // `stable`. --stable moves it to a TRAILING comment to protect the cacheable prefix, which is + // right for a CLI map a provider KV-caches and wrong for the MCP `analyze` verb, whose result + // is ONE tool payload an agent reads top-down: there the reader met 197 of 6368 symbols with + // no denominator and no order marker until the last line. The stanza is emitted ONCE either + // way (never both places), so no count is stated twice. Only the MCP analyze front door + // passes true; every CLI caller keeps the default and stays byte-identical. + bool statsFirstScreen = false, + // R-E (2026-08-17 harvest, report-memgraph §F6 seconded): the run's OWN root argument, + // single-root callers only (empty ⇒ multi-root — already carries the roots=/<root + // label=…> disclosure above and stays untouched — or a caller that never passes one, e.g. + // a pure sizing pass, where a root= attribute would add bytes nothing reads). Same fact + // --grep's root= states, same helper (sarif.h's rootPrefixOf/rootRelativeUri) — the two + // verbs must not diverge on what "root-relative" means. + std::string_view rootArg = {}, + // Phase 4: the S6-C locality-pin counter (graph.h g.locPinOut) → lpin="K" on the row, header + // locality_pinned=N — both absent when zero, so a pin-free corpus is byte-identical. + const std::vector<std::uint32_t>* locPinOut = nullptr, + // Phase 5: the external-name veto's refusal count (graph.h g.externalCalls) → header external=N, + // absent when zero, so a veto-free corpus is byte-identical. + std::size_t externalCalls = 0, + // Tier 3's per-caller declines (graph.h g.declinedOut) → header declined=N, absent when zero, so a + // corpus where no call reached tier 3 undecided stays byte-identical. + const std::vector<std::uint32_t>* declinedOut = nullptr, + // of those, the calls the builtin-method name gate declined (graph.h g.gateDeclinedCalls) → the + // kDeclinedGateMapLegend clause, absent when zero. + std::size_t gateDeclinedCalls = 0, + // FE-B: Graph::outNameOnly (parallel to outTargets) → via="name" on a <c> row and the via legend + // comment; nullptr/empty ⇒ every edge is evidence-bound and the map is byte-identical. + const std::vector<std::uint8_t>* outNameOnly = nullptr, + // of declined=, the calls the standard-member gate declined (graph.h g.stdMemberDeclinedCalls) → + // the kDeclinedStdMapLegend clause, absent when zero. + std::size_t stdMemberDeclinedCalls = 0, + // of declined=, the Elixir call candidates inside inert quote AST (g.inertDeclinedCalls, #380) → + // the kInertDeclinedMapLegend clause, absent when zero. + std::size_t inertDeclinedCalls = 0 ) +{ + // R-E: normalize once, reuse at every <f p=…> row — rootPrefixOf just strips a trailing '/'. + const std::string rootPrefix = rootArg.empty() ? std::string() : rw::sarif::rootPrefixOf( rootArg ); + const auto pathRel = [ & ]( std::uint32_t fileId ) -> std::string_view + { + return rootArg.empty() ? std::string_view( ing.files[ fileId ] ) : rw::sarif::rootRelativeUri( ing.files[ fileId ], rootPrefix ); + }; - writeMapCalleeRows( w, ing, outOff[id], outOff[id + 1], outTargets, outProv, outNameOnly, esc, hedgedScratch ); - w.write( "</s>" ); - } - w.write( "</f>" ); + // ── WHICH rows, in WHICH order ────────────────────────────────────────────────────────────────────────────────── + const bool stubbed = ann.stubSymbols; // C1-b: in=DIR's stub prints no symbol row + const std::size_t keep = mapKeepCount( ing, topK ); + const RankedMapRows ranked = rankMapRows( ing, rank, ann, keep, stubbed ); + const std::span<const NodeId> kept = ranked.kept( keep ); + // T1/§H7: the byte MODEL. It decides the T3 emit order (which has to be decided before any byte exists — see §H7 at + // estimateTokens) and supplies the language-weighted bytes/token RATE, the half of it that is actually measured. It no + // longer REPORTS the size: est_tokens is computed from the document's emitted bytes in PHASE 2 below, because a model of + // the symbol set cannot see --metrics decoration or an appended payload. C1-b: under the stub the estimate is taken over + // no rows, since the document contains none. + const TokenEstimate mapEst = estimateTokens( ing, ranked.order, kept.size(), outOff, outTargets ); + const MapEmitOrder emitOrder = decideMapEmitOrder( stable, mostImportantLast, autoOrder, mapEst.tokens ); + const MapFileGroups groups = groupMapRowsByFile( ing, ann, kept, stubbed, emitOrder, outOff, outTargets, pathRel ); + const MapHonestyGauges gauges = countMapHonestyGauges( ing, MapResolverCounters{ .ambOut = ambOut, .unresolvedOut = unresolvedOut, .locPinOut = locPinOut, + .declinedOut = declinedOut, .externalCalls = externalCalls, + .gateDeclinedCalls = gateDeclinedCalls, + .stdMemberDeclined = stdMemberDeclinedCalls, + .inertDeclinedCalls = inertDeclinedCalls } ); + ASSUME( !stubbed || ( kept.empty() && groups.fileOrder.empty() && groups.inventory.entries.empty() ), + "the stub ranks and groups no row, so no kept-row legend clause and no <f> group can fire under it" ); + std::vector<char> esc; + + // ── the legend, clause group by clause group, in the order the reader meets them ────────────────────────────── + std::string legend = mapOpeningLegend( outProv != nullptr ); + legend += moduleScopeLegend( ing ); + legend += keptImplEdgeLegend( outOff, outProv, kept, groups.inventory.entries ); + legend += typeKindLegend( ing ); + legend += parseHonestyLegend( gauges ); + legend += runAnnotationLegend( ing, ann, rootArg, metrics ); + legend += rowSelectionLegend( ranked.dataSecCut, groups ); + // W2-F: the pr_iters= / pr_converged= definition, charged to the maps that carry the attributes — empty for a lexical or + // HITS ordering, and the prose half only on the map whose iteration stopped short. + legend += renderDisclosure( ann.prDisclosure, DiscloseAs::LegendComment ); + legend += declineLegend( gauges ); + legend += keptNameEdgeLegend( outOff, outNameOnly, kept, ann.viaLegendStripped ); + // K51: history_unread='s definition, the LAST leading clause, so it stands right before the <r> root it marks and inside the + // leading block every reader (and legendcoveragecheck's full rows) meets first; absent unless the amp=/churn= walk was unread. + legend += renderHistoryUnread( DiscloseAs::LegendComment ); + + // ── the HEAD and the TAIL, as BUILDERS ───────────────────────────────────────────────────────────────────────── + // Both state est_tokens, and est_tokens describes the whole document including them, so the digit count feeds back into + // the number: PHASE 2 iterates these to a fixpoint (settleEstTokens). buildRecall (recall.h) has the identical fixpoint for + // the identical reason. Pure functions of estTokens, the values decided above and the estimate sink's state. + // --stable: the volatile counts move to a TRAILING comment (out of the cacheable prefix) — unless the caller asked for the + // first-screen placement (§B6 M10, the MCP analyze verb). Exactly one of the two builders emits the stats. + const bool statsTrail = stable && !statsFirstScreen; + const std::string coverageAttrs = mapCoverageAttrs( ing, outProv, ann ); + const MapStatsFacts statsFacts{ .files = ing.files.size(), .symbols = mapSymbolCount( ing ), .edges = outTargets.size(), + .shown = stubbed ? std::size_t( 0 ) : keep + groups.stemPick.rows.size(), + .gauges = gauges, .coverageAttrs = coverageAttrs, .orderAttr = mapOrderAttr( emitOrder ) }; + const MapRootFacts rootFacts{ .ann = ann, .rootArg = rootArg, .stable = stable, .dataSecCut = ranked.dataSecCut, .stemCut = groups.stemPick.cut }; + MapEstimate estimate{ ann.payloadUncharged }; // the est_tokens measurement's DISCLOSE sink — read by the builders + const auto buildHead = [ & ]( std::size_t estTokens ) -> std::string + { + std::string h = legend; + if( estimate.isModelled ) + { + h += kEstModelledLegend; } - if( !inventoryFirst ) + if( !statsTrail ) { - writeInventory(); + h += renderMapStats( statsFacts, estTokens, estimate.isModelled ); } - w.write( "</r>" ); + h += renderMapRootTag( rootFacts, estTokens, estimate.isModelled, esc ); + return h; + }; + const auto buildTail = [ & ]( std::size_t estTokens ) -> std::string + { + return statsTrail ? renderMapStats( statsFacts, estTokens, estimate.isModelled ) : std::string{}; + }; + + // ── PHASE 1: render <r>'s CHILDREN into a buffer ─────────────────────────────────────────────────────────────── + // §H7: est_tokens must charge the bytes the document actually carries, not a model of the symbol set — the model prices + // neither --metrics decoration nor an appended payload, which is how one number came to stand for five documents. So: + // measure, decide, then write (the order --recall's emitRecallBudgeted and the --for lens's pre-rendered sigs block + // already impose on themselves). + const MapRowSources rowSources{ .rank = rank, .outOff = outOff, .outTargets = outTargets, .outProv = outProv, .outNameOnly = outNameOnly, + .ambOut = ambOut, .locPinOut = locPinOut, .bind = bind, .stable = stable, .metrics = metrics, + .fanIn = fanIn, .cbo = cbo, .tested = tested, .lcom4 = lcom4, .amp = amp }; + std::vector<std::uint32_t> hedgedScratch; // FE-B: writeMapCalleeRows' reused buffer + const auto writeChildren = [ & ]( XmlWriter& w ) + { + writeMapChildren( w, ing, ann, keep, groups, emitOrder, rowSources, pathRel, esc, hedgedScratch ); }; - // DEGRADE, one path for both failures: the head goes out FIRST carrying the MODELLED estimate (the pre-§H7 number, so - // no worse than the old behaviour and never a fabricated one), the children stream straight to `out` behind it, then - // the trailing summary. The whole map, uncharged. + // DEGRADE, one path for both failures (a buffer that did not open, or one that opened and then lost a write — by then the + // children were already spent into it, so they are rendered again): the head goes out FIRST carrying the MODELLED estimate + // (the pre-§H7 number, so no worse than the old behaviour and never a fabricated one), the children stream straight to + // `out` behind it, then the trailing summary. The whole map, uncharged. + const std::size_t modelledTokens = mapEst.tokens + extraPayloadTokens; const auto emitModelled = [ & ]() { XmlWriter direct( out ); @@ -4243,17 +4545,19 @@ inline void serialize( std::FILE* out, const IngestResult& ing, const std::vecto *outEstTokens = modelledTokens; } }; + rw::MemoryStream childStream; + std::FILE* const childMem = openChargeStream( childStream ); if( !childMem ) { + DISCLOSE( estimate, MapEstimate::DisclosureWhy::ChargeBufferFailed, "serialize: open_memstream failed — est_tokens reports the MODELLED bytes, not the emitted ones" ); emitModelled(); return; } - // ── PHASE 2: measure, decide, then write ──────────────────────────────────────────────────────────── - // The children go into the buffer, and the writer flushes BEFORE the memstream is finished (its destructor flushes - // again at the end of the block, with nothing left to write). A buffer that did not finish whole means a write was - // lost INSIDE the children (rw::MemoryStream::finish), so those bytes are never printed: the map is rendered again, - // straight to `out`, on the modelled path a failed open takes. + // ── PHASE 2: measure, decide, then write ─────────────────────────────────────────────────────────────────────── + // The children go into the buffer, and the writer flushes BEFORE the memstream is finished (its destructor flushes again at + // the end of the block, with nothing left to write). A buffer that did not finish whole means a write was lost INSIDE the + // children (rw::MemoryStream::finish), so those bytes are never printed: the map is rendered again on the modelled path. { XmlWriter w( childMem ); writeChildren( w ); @@ -4268,44 +4572,16 @@ inline void serialize( std::FILE* out, const IngestResult& ing, const std::vecto return; } const std::string_view childrenStr = children.bytes; // owned by childStream, alive to the end of this function - - // The fixpoint: est_tokens covers head + children + tail, and head/tail both PRINT est_tokens, so the - // digit count feeds back. Converges in ≤2 passes in practice (each extra digit moves the estimate by - // <1 token); the bound is 4, matching recall.h's. - // - // WHAT THE LOOP GUARANTEES (CA4 verifier L4 — the previous wording claimed an equality this loop does not - // deliver): the LAST built pair is always the pair emitted, and ON CONVERGENCE — the `break`, i.e. the - // number stopped moving — that pair's own bytes are exactly the bytes `estTokens` was measured over, so the - // document's stated number describes the document. On the BOUND (4 passes without convergence, not observed - // on any measured corpus) the emitted head/tail were rebuilt from the last `next` while `next` was measured - // over the PREVIOUS pair's widths, which differ only in the digit count of one field: at most a few bytes, - // i.e. a residual well under one token, and never a fabricated number. The honest statement is "converged ⇒ - // exact; bounded ⇒ within a digit's worth of bytes", not "always exact". - std::size_t estTokens = modelledTokens; - std::string head = buildHead( estTokens ); - std::string tail = buildTail( estTokens ); - for( int pass = 0; pass < 4; ++pass ) - { - const std::size_t next = tokensForEmittedBytes( head.size() + childrenStr.size() + tail.size(), - mapEst.bytesPerToken() ) + extraPayloadTokens; - if( next == estTokens ) - { - break; - } - estTokens = next; - head = buildHead( estTokens ); - tail = buildTail( estTokens ); - } + const SettledHeadTail settled = settleEstTokens( modelledTokens, childrenStr.size(), mapEst.bytesPerToken(), extraPayloadTokens, buildHead, buildTail ); if( outEstTokens ) { - *outEstTokens = estTokens; // --token-budget reads THIS value — never a second counter + *outEstTokens = settled.estTokens; // --token-budget reads THIS value — never a second counter } - - std::fwrite( head.data(), 1, head.size(), out ); + std::fwrite( settled.head.data(), 1, settled.head.size(), out ); std::fwrite( childrenStr.data(), 1, childrenStr.size(), out ); - if( !tail.empty() ) + if( !settled.tail.empty() ) { - std::fwrite( tail.data(), 1, tail.size(), out ); + std::fwrite( settled.tail.data(), 1, settled.tail.size(), out ); } } @@ -4680,214 +4956,189 @@ inline std::string docCommentBefore( const std::string& src, std::size_t defStar // that follow stripping (i.e. lines that contained only a comment and are now empty). // // Correctness guarantee: a "//" or "/*" that appears inside a "…" or '…' literal is NEVER treated as -// a comment. We track the lexer state through the following states: -// NORMAL → default; comments and literals start here -// IN_STRING → inside "…"; ends at an unescaped " -// IN_CHAR → inside '…'; ends at an unescaped ' -// IN_RAW → inside R"delim(…)delim" (C++ raw string); ends at )delim" -// IN_LINE_CMT → inside // …; ends at the next \n (the \n is kept so line count is preserved) -// IN_BLK_CMT → inside /* … */; the entire span including markers is consumed +// a comment. The lexer below has one step per token kind it can start on: +// copyStringLiteral "…" (ends at an unescaped "), or a C++ raw string R"delim(…)delim" (ends at )delim") +// copyQuotedLiteral '…' (ends at an unescaped ') +// skipLineComment // … (ends at the next \n, which is kept so the line count is preserved) +// skipBlockComment /* … */ (the entire span including markers is consumed; its newlines are kept) +// and every other character is copied as-is. // // NOTE: does NOT strip the <doc> doc-comment field — that is emitted separately by the call site and // is never passed into this function (only the raw body bytes [sigStartByte, endByte) are compressed). -inline std::string compressBody( std::string_view src ) -{ - // Phase 1: lex out comments, preserving content inside string/char literals. - // - // output: the source with all comment content removed; literal content intact. - // We output character-by-character into `out` for simplicity (the budget-capped - // bodies are not huge — typically <200 KB — so quadratic string appending is fine). - std::string out; - out.reserve( src.size() ); +// Copies a `quote`-delimited literal starting at src[i] (the opening quote) through its closing quote; a backslash escapes +// the next character. Returns the index just past the closing quote (N + 1 when the literal runs off the end, which ends the +// caller's scan the same way). +inline std::size_t copyQuotedLiteral( std::string_view src, std::size_t i, char quote, std::string& out ) +{ const std::size_t N = src.size(); - std::size_t i = 0; - + out += src[ i ]; // the opening quote + ++i; while( i < N ) { - const char c = src[i]; - - // ── String literal "…" ──────────────────────────────────────────────────────────── - if( c == '"' ) + const char sc = src[ i ]; + out += sc; + if( sc == '\\' && i + 1 < N ) { - // Check for C++ raw string R"delim( - if( i >= 1 && src[i - 1] == 'R' && ( i < 2 || src[i - 2] != '\\' ) ) - { - // Raw string: collect delimiter between " and ( - std::size_t j = i + 1; - std::string delim; - while( j < N && src[j] != '(' && src[j] != '\n' ) - { - delim += src[j++]; - } - if( j < N && src[j] == '(' ) - { - // We're inside R"delim(...). Copy everything verbatim until )delim" - const std::string terminator = ")" + delim + "\""; - out += src.substr( i, j - i + 1 ); // R"delim( - i = j + 1; - const std::size_t termLen = terminator.size(); - while( i < N ) - { - if( i + termLen <= N && src.substr( i, termLen ) == terminator ) - { - out += terminator; - i += termLen; - break; - } - out += src[i++]; - } - continue; - } - // Not a raw string (malformed R"... without a paren) — fall through to - // regular string literal handling below. - } - - // Regular double-quoted string literal. - out += c; // emit the opening " - ++i; - while( i < N ) - { - const char sc = src[i]; - out += sc; - if( sc == '\\' && i + 1 < N ) { out += src[++i]; } // escape: skip next char - else if( sc == '"' ) - { - break; // end of string - } - ++i; - } - ++i; // step past the closing " - continue; + out += src[ ++i ]; // escape: copy the next char too } + else if( sc == quote ) + { + break; + } + ++i; + } + return i + 1; // step past the closing quote +} + +// A `"` at src[i] opens a C++ raw string when an unescaped `R` precedes it. +inline bool opensRawString( std::string_view src, std::size_t i ) noexcept +{ + return i >= 1 && src[ i - 1 ] == 'R' && ( i < 2 || src[ i - 2 ] != '\\' ); +} - // ── Char literal '…' ────────────────────────────────────────────────────────────── - if( c == '\'' ) +// Copies a raw string R"delim(…)delim" verbatim from its `"` at src[i]; the `R` was already copied. Returns the index past +// the terminator (or N when it never comes), or nullopt — copying nothing — when no `(` follows the delimiter on its line, +// which is a malformed R"… the caller reads as a regular string literal. +inline std::optional<std::size_t> copyRawStringLiteral( std::string_view src, std::size_t i, std::string& out ) +{ + const std::size_t N = src.size(); + std::size_t j = i + 1; + while( j < N && src[ j ] != '(' && src[ j ] != '\n' ) + { + ++j; + } + if( j >= N || src[ j ] != '(' ) + { + return std::nullopt; + } + const std::string terminator = ")" + std::string( src.substr( i + 1, j - i - 1 ) ) + "\""; + out += src.substr( i, j - i + 1 ); // "delim( + for( i = j + 1; i < N; ++i ) + { + if( src.substr( i, terminator.size() ) == terminator ) { - out += c; // opening ' - ++i; - while( i < N ) - { - const char sc = src[i]; - out += sc; - if( sc == '\\' && i + 1 < N ) { out += src[++i]; } - else if( sc == '\'' ) - { - break; - } - ++i; - } - ++i; - continue; + out += terminator; + return i + terminator.size(); } + out += src[ i ]; + } + return N; +} - // ── Comment detection (only reached OUTSIDE string/char literals) ───────────────── - if( c == '/' && i + 1 < N ) +// A "…" literal from its opening quote: a raw string when it opens one, else a regular escaped string. +inline std::size_t copyStringLiteral( std::string_view src, std::size_t i, std::string& out ) +{ + if( opensRawString( src, i ) ) + { + if( const std::optional<std::size_t> end = copyRawStringLiteral( src, i, out ) ) { - // Line comment: // … — consume to end of line, emit a newline to preserve line count. - if( src[i + 1] == '/' ) - { - while( i < N && src[i] != '\n' ) - { - ++i; - } - // leave the \n to be emitted in the NORMAL branch below - continue; - } - // Block comment: /* … */ — consume entirely (no newline kept; blank lines handle the gap) - if( src[i + 1] == '*' ) - { - i += 2; // skip /* - while( i + 1 < N && !( src[i] == '*' && src[i + 1] == '/' ) ) - { - if( src[i] == '\n' ) - { - out += '\n'; // preserve newlines so line numbers survive - } - ++i; - } - if( i + 1 < N ) - { - i += 2; // skip */ - } - continue; - } + return *end; } + } + return copyQuotedLiteral( src, i, '"', out ); +} - // ── Normal character — emit as-is ───────────────────────────────────────────────── - out += c; +// A // comment from its first slash: consumed up to (not including) the \n, which the caller then copies so the line count +// is preserved. +inline std::size_t skipLineComment( std::string_view src, std::size_t i ) noexcept +{ + while( i < src.size() && src[ i ] != '\n' ) + { ++i; } + return i; +} - // Phase 2: post-process the comment-stripped text: - // (a) Drop lines that are now whitespace-only (previously held only a comment). - // (b) Collapse runs of 3+ blank lines → a single blank line. - // - // "Blank line" = a line whose trimmed content is empty. We preserve lines that have ANY - // non-whitespace content after comment stripping (this keeps intentional blank lines between - // logical blocks — only the *excess* is collapsed). - std::string result; - result.reserve( out.size() ); - - std::size_t pos = 0; - int blanks = 0; // consecutive blank lines seen so far - bool firstLine = true; // suppress leading blanks at the very start of a body - - const std::size_t M = out.size(); - while( pos < M ) +// A /* … */ comment from its first slash: consumed entirely, markers included, but its newlines are kept so line numbers +// survive (the blank-line pass handles the gap). An unterminated comment runs to the last character. +inline std::size_t skipBlockComment( std::string_view src, std::size_t i, std::string& out ) +{ + const std::size_t N = src.size(); + i += 2; // skip /* + while( i + 1 < N && !( src[ i ] == '*' && src[ i + 1 ] == '/' ) ) { - // Find end of line. - std::size_t eol = out.find( '\n', pos ); - if( eol == std::string::npos ) + if( src[ i ] == '\n' ) { - eol = M; + out += '\n'; } + ++i; + } + return i + 1 < N ? i + 2 : i; // skip */ +} - const std::string_view line( out.data() + pos, eol - pos ); - - // Is this line blank (all whitespace)? - bool isBlank = true; - for( char ch : line ) +// Phase 1: the source with all comment content removed and literal content intact. +inline std::string stripCommentsKeepLiterals( std::string_view src ) +{ + std::string out; + out.reserve( src.size() ); + const std::size_t N = src.size(); + std::size_t i = 0; + while( i < N ) + { + const char c = src[ i ]; + const char d = i + 1 < N ? src[ i + 1 ] : '\0'; // the comment openers are read only OUTSIDE string/char literals + if( c == '"' ) { - if( ch != ' ' && ch != '\t' && ch != '\r' ) - { - isBlank = false; - break; - } + i = copyStringLiteral( src, i, out ); } - - if( isBlank ) + else if( c == '\'' ) { - // Suppress leading blank lines at the very start of a body (artifact of stripping - // the opening comment of a function body), and collapse 3+ consecutive blanks. - if( !firstLine ) - { - ++blanks; - } - // Emit at most one blank line (we allow up to 2 accumulated before we start collapsing; - // the spec says "runs of 3+ → single blank", so blanks==1 and blanks==2 are both fine). - if( !firstLine && blanks <= 2 ) - { - result += '\n'; // the blank line itself (the \n that terminated the previous line) - } - // If blanks > 2: suppress (collapse). + i = copyQuotedLiteral( src, i, '\'', out ); + } + else if( c == '/' && d == '/' ) + { + i = skipLineComment( src, i ); + } + else if( c == '/' && d == '*' ) + { + i = skipBlockComment( src, i, out ); } else { - // Non-blank line: reset counter, emit. - blanks = 0; - firstLine = false; - result.append( out.data() + pos, eol - pos ); - if( eol < M ) + out += c; + ++i; + } + } + return out; +} + +// A line whose content is only spaces, tabs and carriage returns. +inline bool isBlankLine( std::string_view line ) noexcept +{ + return std::all_of( line.begin(), line.end(), []( char ch ) { return ch == ' ' || ch == '\t' || ch == '\r'; } ); +} + +// Phase 2: the comment-stripped text's line layout. Lines that are now whitespace-only and come before the first content line +// are dropped (an artifact of stripping the opening comment of a body); after it, at most two consecutive blank lines are +// kept and the rest of a run is dropped. Every line with ANY non-whitespace content is kept, so intentional blank lines between +// logical blocks survive and only the excess is collapsed. Trailing newlines are trimmed (cosmetic). +inline std::string collapseBlankLineRuns( std::string_view text ) +{ + std::string result; + result.reserve( text.size() ); + std::size_t blanks = 0; // consecutive blank lines since the last content line + std::size_t pos = 0; + while( pos < text.size() ) + { + const std::size_t eol = std::min( text.find( '\n', pos ), text.size() ); + const std::string_view line = text.substr( pos, eol - pos ); + if( !isBlankLine( line ) ) + { + blanks = 0; + result.append( line ); + if( eol < text.size() ) { result += '\n'; } } - - pos = ( eol < M ) ? eol + 1 : M; + // `result` is empty exactly until the first content line is copied: a blank line is only ever written after one. + else if( !result.empty() && ++blanks <= 2 ) + { + result += '\n'; // the blank line itself (the \n that terminated the previous line) + } + pos = eol + 1; } - - // Trim a single trailing newline that may have been added (cosmetic). while( !result.empty() && result.back() == '\n' ) { result.pop_back(); @@ -4895,6 +5146,11 @@ inline std::string compressBody( std::string_view src ) return result; } +inline std::string compressBody( std::string_view src ) +{ + return collapseBlankLineRuns( stripCommentsKeepLiterals( src ) ); +} + // --pack-signatures: emit each top-N ranked definition's SIGNATURE (declaration up to // the body), bodies elided — ~70% fewer tokens than raw source while keeping the structural shape. // Grouped by file, capped at budgetBytes. Emitted AFTER </r>, like packSource. With L2: a <doc> child. @@ -11754,6 +12010,30 @@ inline void writeJsonMapHeader( JsonWriter& w, std::string& esc, const JsonMapHe w.write( "]" ); } +// One JSON row's "c" array members: the callee objects over out-edges [from, to), comma-separated. §A4d: prov mirrors the XML +// attribute 1:1 — "scip" for a SCIP-pinned edge, "binding" for a decoded FFI binding, "import" for an ES named-import edge, +// "split" (C1) for one arm of a k-way split the resolver could not choose between, "via":"impl" (L6) for the one implementor. +// outProv parallels outTargets exactly, so index `e` is the same edge. The two dialects MUST spell the same vocabulary: +// test/mcpclidiffcheck.sh is the gate that says so. The "r" rows and the inventory entries share this writer. +inline void writeJsonCalleeObjects( JsonWriter& w, const IngestResult& ing, std::uint32_t from, std::uint32_t to, const std::vector<NodeId>& outTargets, + const std::vector<std::uint8_t>* outProv, const std::vector<std::uint8_t>* outNameOnly, std::string& esc ) +{ + for( std::uint32_t e = from; e < to; ++e ) + { + w.write( e > from ? ",{\"n\":" : "{\"n\":" ); writeJsonStr( w, ing.symbols[ outTargets[ e ] ].name, esc ); + if( outProv && e < outProv->size() && ( *outProv )[ e ] ) + { + w.write( ",\"" ); w.write( provAttrName( ( *outProv )[ e ] ) ); w.write( "\":" ); writeJsonStr( w, provLabel( ( *outProv )[ e ] ), esc ); + } + if( outNameOnly && e < outNameOnly->size() ) + { + writeMapCalleeJsonKind( w, ( *outNameOnly )[ e ] ); + } + w.write( "}" ); + } +} + + // D7: the JSON twin of writeMapInventoryXml — `,"inv":{"listed":L,"unlisted":U,"entry":[{"p":…,"n":…,"c":[…]}], // "ls":[{"p":…,"n":N,"f":[…]}]}` after the "r" array. The callee objects spell exactly what a "r" row's "c" array does. template <class PathRel> @@ -11777,19 +12057,7 @@ inline void writeMapInventoryJson( JsonWriter& w, const IngestResult& ing, const w.write( i ? ",{\"p\":" : "{\"p\":" ); writeJsonStr( w, pathRel( s.fileId ), esc ); w.write( ",\"n\":" ); writeJsonStr( w, s.name, esc ); w.write( ",\"c\":[" ); - for( std::uint32_t e = outOff[ id ]; e < outOff[ id + 1 ]; ++e ) - { - w.write( e > outOff[ id ] ? ",{\"n\":" : "{\"n\":" ); writeJsonStr( w, ing.symbols[ outTargets[ e ] ].name, esc ); - if( outProv && e < outProv->size() && ( *outProv )[ e ] ) - { - w.write( ",\"" ); w.write( provAttrName( ( *outProv )[ e ] ) ); w.write( "\":" ); writeJsonStr( w, provLabel( ( *outProv )[ e ] ), esc ); // L6: "via":"impl" - } - if( outNameOnly && e < outNameOnly->size() ) - { - writeMapCalleeJsonKind( w, ( *outNameOnly )[ e ] ); - } - w.write( "}" ); - } + writeJsonCalleeObjects( w, ing, outOff[ id ], outOff[ id + 1 ], outTargets, outProv, outNameOnly, esc ); w.write( "]}" ); } w.write( "],\"ls\":[" ); @@ -11813,30 +12081,98 @@ inline void writeMapInventoryJson( JsonWriter& w, const IngestResult& ing, const w.write( "]}" ); } -// The default-map JSON sibling of serialize() — same rank/order/bucket logic (kept a deliberate, mechanical -// duplication per the L2 seam decision: a sibling emitter, not a shared-emission refactor of the XML path, -// so the G5 byte-identical-default contract carries zero risk from this addition). Scope: the common single- -// root invocation (metrics, fan-in, ambiguity, cbo/tested/lcom4/amp Q-metrics, stable/most-important-last/ -// auto-order, bind labels, est_tokens, per-edge provenance, the multi-root prologue, and — §B1.2 — the -// at/rank_by/window PROVENANCE STAMP a churn-ranked map carries. NOT covered (documented gap, refused -// upstream by jsonUnsupportedVerb before this is ever reached in those combinations): --map-diff -// (changed=), --expand's appended <bodies> token math (extraBodyTokens). +// One "s" row object: the XML <s> row's facts, key for attribute — the same presence rules (hasScopeAttr, stem rows, the +// overload collapse, absent-at-0 counters), then the "c" callee array. +inline void writeJsonMapRow( JsonWriter& w, const IngestResult& ing, const OverloadRows& rows, std::size_t rowIndex, const std::vector<NodeId>& stemRows, + const MapRowSources& src, std::string& esc ) +{ + char num[ 64 ]; + const NodeId id = rows.id[ rowIndex ]; + const Symbol& s = ing.symbols[ id ]; + w.write( "{\"t\":" ); writeJsonStr( w, symTag( s.kind ), esc ); + w.write( ",\"n\":" ); writeJsonStr( w, s.name, esc ); + if( hasScopeAttr( s ) ) { w.write( ",\"sc\":" ); writeJsonStr( w, s.scope, esc ); } // row 6: the XML sibling's sc=, one presence rule (hasScopeAttr) + if( !stemRows.empty() && std::ranges::binary_search( stemRows, id ) ) { w.write( ",\"stem\":1" ); } // MAP-STEM: the XML sibling's stem="1" + if( rows.overloads[ rowIndex ] > 1 ) + { + rw::formatTo( num, sizeof( num ), ",\"overloads\":{}", rows.overloads[ rowIndex ] ); w.write( num ); + } + w.write( splitLineJson( rows, rowIndex, s ) ); // the XML l= twin: a --metrics row split out of a same-name group + if( const std::string_view label = src.bind ? src.bind->labelOf( id ) : std::string_view{}; !label.empty() ) + { + w.write( ",\"bind\":" ); writeJsonStr( w, label, esc ); + } + if( const std::uint32_t ambK = counterAt( src.ambOut, id ); ambK > 0 ) + { + rw::formatTo( num, sizeof( num ), ",\"amb\":{}", ambK ); w.write( num ); + } + if( const std::uint32_t lpinK = counterAt( src.locPinOut, id ); lpinK > 0 ) // Phase 4: the XML lpin= twin + { + rw::formatTo( num, sizeof( num ), ",\"lpin\":{}", lpinK ); w.write( num ); + } + if( s.extentSuspect != 0 ) // extent honesty: the XML extent_suspect= twin, same reason spelling + { + w.write( ",\"extent_suspect\":" ); writeJsonStr( w, extent::extentSuspectReasons( s.extentSuspect ), esc ); + } + if( !src.stable ) + { + rw::formatTo( num, sizeof( num ), ",\"k\":{:.4f}", double( src.rank[ id ] ) ); w.write( num ); + } + if( src.metrics ) + { + const std::uint32_t outDegree = src.outOff[ id + 1 ] - src.outOff[ id ]; + writeJsonQMetrics( w, JsonQMetrics{ s, id, outDegree, src.fanIn, src.cbo, src.tested, src.lcom4, src.amp } ); + } + w.write( ",\"c\":[" ); + writeJsonCalleeObjects( w, ing, src.outOff[ id ], src.outOff[ id + 1 ], src.outTargets, src.outProv, src.outNameOnly, esc ); + w.write( "]}" ); +} + +// One "r" file object: its path and arch layer, then its rows. §P6.3 / §A4d: const/non-const overloads canonicalize to the +// SAME id, so a bucket straight from the rank order printed two byte-identical JSON objects and a consumer keying on "id" +// silently dropped one. Same collapse the XML path runs (overloadRowsFor), same "overloads" count. +template <class PathRel> +inline void writeJsonMapFileGroup( JsonWriter& w, const IngestResult& ing, std::uint32_t f, const MapFileGroups& groups, const MapRowSources& src, + const PathRel& pathRel, std::string& esc ) +{ + w.write( "{\"p\":" ); writeJsonStr( w, pathRel( f ), esc ); + if( const char* fl = builtinLayer( rootRelPath( ing, f ) ); *fl ) { w.write( ",\"layer\":" ); writeJsonStr( w, fl, esc ); } + w.write( ",\"s\":[" ); + const OverloadRows rows = overloadRowsFor( ing, groups.buckets[ f ], src.metrics ); + for( std::size_t rowIndex = 0; rowIndex < rows.id.size(); ++rowIndex ) + { + if( rowIndex > 0 ) + { + w.write( "," ); + } + writeJsonMapRow( w, ing, rows, rowIndex, groups.stemPick.rows, src, esc ); + } + w.write( "]}" ); +} + +// The default-map JSON sibling of serialize(). It shares serialize()'s decisions about WHAT the map prints — mapKeepCount, +// rankMapRows, decideMapEmitOrder, groupMapRowsByFile, countMapHonestyGauges — and writes the same groups in its own +// spelling, so a defect fixed in one dialect's selection cannot survive in the other's. Scope: the common single-root +// invocation (metrics, fan-in, ambiguity, cbo/tested/lcom4/amp Q-metrics, stable/most-important-last/auto-order, bind labels, +// est_tokens, per-edge provenance, the multi-root prologue, and — §B1.2 — the at/rank_by/window PROVENANCE STAMP a +// churn-ranked map carries. NOT covered (documented gap, refused upstream by jsonUnsupportedVerb before this is ever reached +// in those combinations): --map-diff (changed=), --expand's appended <bodies> token math (extraBodyTokens). // -// §B1.2 — churn was the third XML-only honesty fact this sibling dropped, and the enumeration above used to -// omit it entirely: it read as a complete coverage statement while `--rank-by=churn --json` and -// `--rank-by=pagerank --json` emitted keyset-identical headers. serializeJson now takes the same -// `MapAnnotations` the XML path takes and emits `at`/`rank_by`/`window` from it (writeJsonMapHeader). +// §B1.2 — churn was the third XML-only honesty fact this sibling dropped, and the enumeration above used to omit it entirely: +// it read as a complete coverage statement while `--rank-by=churn --json` and `--rank-by=pagerank --json` emitted +// keyset-identical headers. serializeJson now takes the same `MapAnnotations` the XML path takes and emits +// `at`/`rank_by`/`window` from it (writeJsonMapHeader). // // §A4b/§A4d closed three XML-only honesty attributes that this sibling used to drop SILENTLY: -// * multi-root: the header comment above claimed the combination was "refused upstream by -// jsonUnsupportedVerb" — it never was (no roots-count arm exists there), so a JSON consumer got -// `"p":"src/./svector.h"` with no label→path table and no signal the graph spanned several roots. -// `"roots"`/`"roots_count"` now mirror the XML `roots=` + `<root label= p=/>` prologue exactly. -// * overloads: this emitter never called collapseOverloadRows(), so a const/non-const pair printed TWO -// byte-identical rows and a consumer keying on "id" silently lost one. Collapsed here as in the XML, -// with the same `"overloads":N` (>1 only) discriminator. -// * prov/precise: an edge the SCIP overlay or an FFI binding actually PINNED read identical to a -// name-guessed one. Same absent-unless-present rule as the XML attribute. +// * multi-root: the header comment above claimed the combination was "refused upstream by jsonUnsupportedVerb" — it never +// was (no roots-count arm exists there), so a JSON consumer got `"p":"src/./svector.h"` with no label→path table and no +// signal the graph spanned several roots. `"roots"`/`"roots_count"` now mirror the XML `roots=` + `<root label= p=/>` +// prologue exactly. +// * overloads: this emitter never called collapseOverloadRows(), so a const/non-const pair printed TWO byte-identical rows +// and a consumer keying on "id" silently lost one. Collapsed here as in the XML, with the same `"overloads":N` (>1 only) +// discriminator. +// * prov/precise: an edge the SCIP overlay or an FFI binding actually PINNED read identical to a name-guessed one. Same +// absent-unless-present rule as the XML attribute. inline void serializeJson( std::FILE* out, const IngestResult& ing, const std::vector<float>& rank, const std::vector<std::uint32_t>& outOff, const std::vector<NodeId>& outTargets, int topK, bool mostImportantLast, bool metrics, @@ -11859,87 +12195,28 @@ inline void serializeJson( std::FILE* out, const IngestResult& ing, const std::v const std::vector<std::uint8_t>* outNameOnly = nullptr, // FE-B: same as serialize()'s → "via":"name" std::size_t /*stdMemberDeclinedCalls*/ = 0 ) // serialize()'s legend clause; JSON carries no legend, so unread here { - const std::size_t S = ing.symbols.size(); const std::string rootPrefix = rootArg.empty() ? std::string() : rw::sarif::rootPrefixOf( rootArg ); const auto pathRel = [ & ]( std::uint32_t fileId ) -> std::string_view { return rootArg.empty() ? std::string_view( ing.files[ fileId ] ) : rw::sarif::rootRelativeUri( ing.files[ fileId ], rootPrefix ); }; - std::vector<NodeId> order( S ); - for( NodeId i = 0; i < S; ++i ) - { - order[i] = i; - } - sortutil::radixSortByScoreDescId( order, rank ); - dropUnmappedRows( ing, order ); // serialize()'s rows, same rule - - const std::size_t mapS = mapSymbolCount( ing ); - const std::size_t keep = std::min<std::size_t>( topK > 0 ? std::size_t( topK ) : mapS, mapS ); - const DataSectionsCut dataSecCut = ann.codeFirstRows ? codeFirstKeep( ing, order, keep ) : DataSectionsCut{}; // serialize()'s pick, same rule - - std::vector<std::vector<NodeId>> buckets( ing.files.size() ); - std::vector<std::uint32_t> fileOrder; - std::vector<char> seen( ing.files.size(), 0 ); - for( std::size_t k = 0; k < keep; ++k ) - { - const NodeId id = order[k]; - const std::uint32_t f = ing.symbols[id].fileId; - if( !seen[f] ) { seen[f] = 1; fileOrder.push_back( f ); } - buckets[f].push_back( id ); - } - // MAP-STEM: the XML twin's reserved stem-namesake rows, the same rule over the same buckets - const MapStemPick stemPick = pickMapStemRows( ing, ann, buckets, fileOrder ); - const std::vector<NodeId>& stemRows = stemPick.rows; - // D7: the XML twin's inventory, the same selection (mapinventory.h) over the same printed-file set - const MapInventory inventory = mapInventoryWanted( ing, ann ) ? computeMapInventory( ing, outOff, outTargets, seen, pathRel ) - : MapInventory{}; - - // T1/§H7: SAME byte-model the XML sibling uses, in the same two roles — the fill-order oracle and the - // rate source. The REPORTED est_tokens is measured from the emitted bytes in PHASE 2 below, exactly as - // in serialize(): a defect fixed in one serialization and not the other is how the §H5 dialect - // divergences are born, and this emitter had the identical --metrics under-report (MEASURED: 1780 B - // reported as est_tokens=507, 3.51 B/tok). - const TokenEstimate mapEst = estimateTokens( ing, order, keep, outOff, outTargets ); - const std::size_t mapEstTokens = mapEst.tokens; - - const bool autoFlip = autoOrder && !stable && !mostImportantLast && mapEstTokens > kFillOrderThreshold; - const bool effImportantLast = mostImportantLast || autoFlip; - if( stable ) - { - std::sort( fileOrder.begin(), fileOrder.end(), - [ & ]( std::uint32_t a, std::uint32_t b ) { return ing.files[a] < ing.files[b]; } ); - for( std::vector<NodeId>& b : buckets ) - { - std::sort( b.begin(), b.end() ); - } - } - else if( effImportantLast ) - { - std::reverse( fileOrder.begin(), fileOrder.end() ); - for( std::vector<NodeId>& b : buckets ) - { - std::reverse( b.begin(), b.end() ); - } - } - - const std::size_t ambTotal = counterTotal( ambOut ); - const std::size_t unresolvedTotal = counterTotal( unresolvedOut ); - const std::size_t locPinTotal = counterTotal( locPinOut ); // Phase 4: Σ lpin, the JSON twin of locality_pinned= - const std::size_t declinedTotal = counterTotal( declinedOut ); // Σ declinedOut, the JSON twin of declined= - std::size_t extentSuspectTotal = 0; // extent honesty: the JSON twin of extent_suspect_syms= - for( const Symbol& sym : ing.symbols ) - { - extentSuspectTotal += sym.extentSuspect != 0 ? 1u : 0u; - } - const char* orderAttr = stable ? "stable" - : mostImportantLast ? "important-last" - : autoFlip ? "important-last(auto:fill)" - : "important-first"; - - // ── PHASE 1: render the "r" array into a buffer (§H7 — see serialize()'s PHASE 1 for the full reasoning: - // measure, decide, then write). DEGRADE: an open_memstream failure emits the header FIRST with the - // MODELLED estimate (the pre-§H7 number, never a fabricated one) and streams the array behind it. + // ── WHICH rows, in WHICH order: serialize()'s steps. This dialect has no in=DIR stub; it always prints its rows. ────────── + const std::size_t keep = mapKeepCount( ing, topK ); + const RankedMapRows ranked = rankMapRows( ing, rank, ann, keep, /*stubbed=*/false ); + const std::span<const NodeId> kept = ranked.kept( keep ); + // T1/§H7: SAME byte-model the XML sibling uses, in the same two roles — the fill-order oracle and the rate source. The + // REPORTED est_tokens is measured from the emitted bytes in PHASE 2 below, exactly as in serialize(): this emitter had the + // identical --metrics under-report (MEASURED: 1780 B reported as est_tokens=507, 3.51 B/tok). + const TokenEstimate mapEst = estimateTokens( ing, ranked.order, kept.size(), outOff, outTargets ); + const MapEmitOrder emitOrder = decideMapEmitOrder( stable, mostImportantLast, autoOrder, mapEst.tokens ); + const MapFileGroups groups = groupMapRowsByFile( ing, ann, kept, /*stubbed=*/false, emitOrder, outOff, outTargets, pathRel ); + const MapHonestyGauges gauges = countMapHonestyGauges( ing, MapResolverCounters{ .ambOut = ambOut, .unresolvedOut = unresolvedOut, .locPinOut = locPinOut, + .declinedOut = declinedOut, .externalCalls = externalCalls } ); + + // ── PHASE 1: render the "r" array into a buffer (§H7 — see serialize()'s PHASE 1 for the full reasoning: measure, decide, + // then write). DEGRADE: an open_memstream failure emits the header FIRST with the MODELLED estimate (the pre-§H7 number, + // never a fabricated one) and streams the array behind it. rw::MemoryStream rowsStream; std::FILE* const rowsMem = openChargeStream( rowsStream ); MapEstimate estimate{ ann.payloadUncharged }; @@ -11948,132 +12225,53 @@ inline void serializeJson( std::FILE* out, const IngestResult& ing, const std::v DISCLOSE( estimate, MapEstimate::DisclosureWhy::ChargeBufferFailed, "serializeJson: open_memstream failed — est_tokens reports the MODELLED bytes, not the emitted ones" ); } - // ONE header emitter, used by the degrade write, the size probe and the real write, so the three can - // never disagree on the header's shape. The peak attribute is read here once for all three: a second reading may - // pass the limit the first did not, and the probe would then have priced a shorter header than the one written. + // ONE header emitter, used by the degrade write, the size probe and the real write, so the three can never disagree on the + // header's shape. The peak attribute is read here once for all three: a second reading may pass the limit the first did + // not, and the probe would then have priced a shorter header than the one written. const std::string memoryPeakJson = buildMemoryPeakAttr( ing, true ); std::string esc; const auto emitHeader = [ & ]( std::FILE* dst, std::size_t estTokens ) { JsonWriter hw( dst ); - writeJsonMapHeader( hw, esc, JsonMapHeader{ ing, mapSymbolCount( ing ), outTargets.size(), keep + stemRows.size(), estTokens, ambTotal, - unresolvedTotal, orderAttr, outProv, &ann, rootArg, locPinTotal, externalCalls, declinedTotal, - extentSuspectTotal, macroBlankedFileCount( ing ), ing.crawlSkips.nestRefusedFiles, - estimate.isModelled, dataSecCut, stemPick.cut, memoryPeakJson } ); + writeJsonMapHeader( hw, esc, JsonMapHeader{ ing, mapSymbolCount( ing ), outTargets.size(), keep + groups.stemPick.rows.size(), estTokens, gauges.ambiguous, + gauges.unresolved, mapOrderAttr( emitOrder ), outProv, &ann, rootArg, gauges.localityPinned, gauges.external, + gauges.declined, gauges.extentSuspectSyms, gauges.macroBlankedFiles, gauges.nestRefusedFiles, + estimate.isModelled, ranked.dataSecCut, groups.stemPick.cut, memoryPeakJson } ); hw.write( ",\"r\":[" ); }; - // The "r" array, as ONE renderer both paths call — serialize()'s writeChildren above, for the same reason: a buffer - // that opened and then lost a write has already spent the rows, so the fallback must be able to write them again. + // The "r" array, as ONE renderer both paths call — serialize()'s writeChildren, for the same reason: a buffer that opened and + // then lost a write has already spent the rows, so the fallback must be able to write them again. + const MapRowSources rowSources{ .rank = rank, .outOff = outOff, .outTargets = outTargets, .outProv = outProv, .outNameOnly = outNameOnly, + .ambOut = ambOut, .locPinOut = locPinOut, .bind = bind, .stable = stable, .metrics = metrics, + .fanIn = fanIn, .cbo = cbo, .tested = tested, .lcom4 = lcom4, .amp = amp }; const auto writeRows = [ & ]( JsonWriter& w ) { - char num[ 64 ]; - - bool firstFile = true; - for( std::uint32_t f : fileOrder ) + for( std::size_t i = 0; i < groups.fileOrder.size(); ++i ) { - if( !firstFile ) + if( i > 0 ) { w.write( "," ); } - firstFile = false; - w.write( "{\"p\":" ); writeJsonStr( w, pathRel( f ), esc ); - if( const char* fl = builtinLayer( rootRelPath( ing, f ) ); *fl ) { w.write( ",\"layer\":" ); writeJsonStr( w, fl, esc ); } - w.write( ",\"s\":[" ); - - // §P6.3 / §A4d: const/non-const overloads canonicalize to the SAME id, so a bucket straight from - // `order` printed two byte-identical JSON objects and a consumer keying on "id" silently dropped - // one. Same collapse the XML path runs (collapseOverloadRows above), same "overloads" count. - const OverloadRows rows = overloadRowsFor( ing, buckets[f], metrics ); // the XML path's per-definition rule - - bool firstSym = true; - for( std::size_t rowIndex = 0; rowIndex < rows.id.size(); ++rowIndex ) - { - const NodeId id = rows.id[ rowIndex ]; - if( !firstSym ) - { - w.write( "," ); - } - firstSym = false; - const Symbol& s = ing.symbols[id]; - const std::uint32_t out2= outOff[id + 1] - outOff[id]; - - w.write( "{\"t\":" ); writeJsonStr( w, symTag( s.kind ), esc ); - w.write( ",\"n\":" ); writeJsonStr( w, s.name, esc ); - - if( hasScopeAttr( s ) ) { w.write( ",\"sc\":" ); writeJsonStr( w, s.scope, esc ); } // row 6: the XML sibling's sc=, one presence rule (hasScopeAttr) - if( !stemRows.empty() && std::ranges::binary_search( stemRows, id ) ) { w.write( ",\"stem\":1" ); } // MAP-STEM: the XML sibling's stem="1" - - if( rows.overloads[ rowIndex ] > 1 ) - { rw::formatTo( num, sizeof( num ), ",\"overloads\":{}", rows.overloads[ rowIndex ] ); w.write( num ); } - w.write( splitLineJson( rows, rowIndex, s ) ); // the XML l= twin: a --metrics row split out of a same-name group - - if( const std::string_view label = bind ? bind->labelOf( id ) : std::string_view{}; !label.empty() ) - { w.write( ",\"bind\":" ); writeJsonStr( w, label, esc ); } - - if( const std::uint32_t ambK = counterAt( ambOut, id ); ambK > 0 ) - { rw::formatTo( num, sizeof( num ), ",\"amb\":{}", ambK ); w.write( num ); } - - if( const std::uint32_t lpinK = counterAt( locPinOut, id ); lpinK > 0 ) // Phase 4: the XML lpin= twin - { rw::formatTo( num, sizeof( num ), ",\"lpin\":{}", lpinK ); w.write( num ); } - - if( s.extentSuspect != 0 ) // extent honesty: the XML extent_suspect= twin, same reason spelling - { w.write( ",\"extent_suspect\":" ); writeJsonStr( w, extent::extentSuspectReasons( s.extentSuspect ), esc ); } - - if( !stable ) - { rw::formatTo( num, sizeof( num ), ",\"k\":{:.4f}", double( rank[id] ) ); w.write( num ); } - - if( metrics ) - { - writeJsonQMetrics( w, JsonQMetrics{ s, id, out2, fanIn, cbo, tested, lcom4, amp } ); - } - - w.write( ",\"c\":[" ); - bool firstC = true; - for( std::uint32_t e = outOff[id]; e < outOff[id + 1]; ++e ) - { - if( !firstC ) - { - w.write( "," ); - } - firstC = false; - w.write( "{\"n\":" ); writeJsonStr( w, ing.symbols[ outTargets[e] ].name, esc ); - // §A4d: prov mirrors the XML attribute 1:1 — "scip" for a SCIP-pinned edge, "binding" for a - // decoded FFI binding, "import" for an ES named-import edge, "split" (C1) for one arm of a k-way - // split the resolver could not choose between. outProv parallels outTargets exactly, so index `e` - // is the same edge. The two dialects MUST spell the same vocabulary: test/mcpclidiffcheck.sh is - // the gate that says so. - if( outProv && e < outProv->size() && (*outProv)[e] ) - { - w.write( ",\"" ); w.write( provAttrName( (*outProv)[e] ) ); w.write( "\":" ); writeJsonStr( w, provLabel( (*outProv)[e] ), esc ); // L6: "via":"impl" - } - if( outNameOnly && e < outNameOnly->size() ) - { - writeMapCalleeJsonKind( w, ( *outNameOnly )[e] ); - } - w.write( "}" ); - } - w.write( "]}" ); - } - w.write( "]}" ); + writeJsonMapFileGroup( w, ing, groups.fileOrder[ i ], groups, rowSources, pathRel, esc ); } w.write( "]" ); - if( inventory.active ) + if( groups.inventory.active ) { - writeMapInventoryJson( w, ing, inventory, pathRel, outOff, outTargets, outProv, outNameOnly, esc ); + writeMapInventoryJson( w, ing, groups.inventory, pathRel, outOff, outTargets, outProv, outNameOnly, esc ); } w.write( "}" ); }; // DEGRADE, one path for both failures: the header FIRST with the MODELLED estimate, the array streamed behind it. const auto emitModelled = [ & ]() { - emitHeader( out, mapEstTokens ); + emitHeader( out, mapEst.tokens ); JsonWriter direct( out ); writeRows( direct ); direct.flush(); if( outEstTokens ) { - *outEstTokens = mapEstTokens; + *outEstTokens = mapEst.tokens; } }; if( !rowsMem ) @@ -12112,7 +12310,7 @@ inline void serializeJson( std::FILE* out, const IngestResult& ing, const std::v rw::MemoryStream probe; if( std::FILE* const pm = openChargeStream( probe ) ) { - emitHeader( pm, mapEstTokens ); + emitHeader( pm, mapEst.tokens ); if( const rw::MemoryStreamBytes header = probe.finish(); header.isWhole ) { headerBytes = header.bytes.size(); From 6f961f752d8f27b81b2709a2bf9f5cc18fd98b87 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:59:18 -0500 Subject: [PATCH 25/61] refactor(serialize): one writer for the roots table, the emit order and gauge clauses as data qd-range on the first commit gated five clone rows. The map's multi-root prologue was a copy of writeMultiRootTable; both now write writeRootLabelRows. The emit order's order= spelling and important-last flag are one traits table (kMapEmitOrderTraits) instead of a predicate shaped like four others. The gauge-to-legend-clause pairs are tables (kParseHonestyClauses, kDeclineClauses) read by gaugeLegend, and the corpus-kind clauses share corpusHasSymbol. The blank line test is find_first_not_of in place. Byte-identical: no answer changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/serialize.h | 198 +++++++++++++++++++++++------------------------- 1 file changed, 96 insertions(+), 102 deletions(-) diff --git a/src/serialize.h b/src/serialize.h index 7dfeb6f03..e90eda58a 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -224,29 +224,6 @@ inline std::string_view escapeXml( std::string_view s, std::vector<char>& out ) return std::string_view( out.data(), out.size() ); } -// M12 (capture-audit-2026-09-04, lane L9): under multi-root, every one of the graph-count verbs -// (--callers/--callees/--uses) drops root= (correctly — there IS no single root=) but discloses NOTHING in -// its place, so a reader of `ripwire src test --callers=SYM` has no way to learn what the `<label>/` prefix -// on every p=/id= MEANS. The default map's own prologue already prints exactly this table for exactly this -// reason (below, in serialize()); this is that same shape, factored out so the read verbs can reuse it -// instead of re-deriving it. Lives here (not graphlegend.h, which is included from ABOVE this point in this -// very file) because it needs escapeXml, and emits nothing at all under single-root (rootLabels.size() < 2) -// — this must never move a single byte of single-root output. -inline void writeMultiRootTable( std::FILE* out, const IngestResult& ing ) -{ - if( ing.rootLabels.size() < 2 ) - { - return; - } - std::vector<char> esc; - for( std::size_t r = 0; r < ing.rootLabels.size(); ++r ) - { - rw::emitTo( out, "<root label=\"{}\" p=\"{}\"/>", - std::string( escapeXml( ing.rootLabels[r], esc ) ).c_str(), - std::string( escapeXml( r < ing.rootPaths.size() ? ing.rootPaths[r] : std::string(), esc ) ).c_str() ); - } -} - // The legend clause defining the table above — appended ONLY when it actually rides (multiRoot), the same // presence-matches-emission discipline every other conditional clause in this file follows (and the same // SEPARATE-comment shape kRootRelPathsLegend uses — graphlegend.h — so a caller just concatenates it). @@ -518,6 +495,39 @@ class XmlWriter char m_buf[ kCap ]; }; +// The multi-root label → root path table, canonical order: `<root label= p=/>` per root, nothing under single-root. §P8 +// collision: this prologue spelled its LABEL `l=`, the two characters 22 other sites use for a LINE NUMBER — including the +// map's <f p= …> rows. Renamed to label=. +inline void writeRootLabelRows( XmlWriter& w, const IngestResult& ing, std::vector<char>& esc ) +{ + if( ing.rootLabels.size() < 2 ) + { + return; + } + for( std::size_t r = 0; r < ing.rootLabels.size(); ++r ) + { + w.write( "<root label=\"" ); w.write( escapeXml( ing.rootLabels[r], esc ) ); + w.write( "\" p=\"" ); w.write( escapeXml( r < ing.rootPaths.size() ? ing.rootPaths[r] : std::string(), esc ) ); + w.write( "\"/>" ); + } +} + +// M12 (capture-audit-2026-09-04, lane L9): under multi-root, every one of the graph-count verbs +// (--callers/--callees/--uses) drops root= (correctly — there IS no single root=) but discloses NOTHING in +// its place, so a reader of `ripwire src test --callers=SYM` has no way to learn what the `<label>/` prefix +// on every p=/id= MEANS. The default map's own prologue prints exactly this table for exactly this reason +// (serialize()'s writeMapChildren), and both write it with writeRootLabelRows. Lives here (not graphlegend.h, +// which is included from ABOVE this point in this very file) because it needs escapeXml and XmlWriter, and +// emits nothing at all under single-root (rootLabels.size() < 2) — this must never move a single byte of +// single-root output. +inline void writeMultiRootTable( std::FILE* out, const IngestResult& ing ) +{ + std::vector<char> esc; + XmlWriter w( out ); + writeRootLabelRows( w, ing, esc ); + w.flush(); +} + // L3 field-notes surfacing: attach `<note d="ISO-date"><![CDATA[text]]></note>` children for a symbol or file // `target` (a canonical id, or a path). INERT when `ni == nullptr` (no/empty notes file) → it writes ZERO // bytes, so the whole pipeline stays byte-identical to the pre-feature output on every verb (the L3 inertness @@ -3396,18 +3406,25 @@ inline MapEmitOrder decideMapEmitOrder( bool stable, bool mostImportantLast, boo return ( autoOrder && mapEstTokens > kFillOrderThreshold ) ? MapEmitOrder::ImportantLastAuto : MapEmitOrder::ImportantFirst; } -inline bool isImportantLast( MapEmitOrder emitOrder ) noexcept -{ - return emitOrder == MapEmitOrder::ImportantLast || emitOrder == MapEmitOrder::ImportantLastAuto; -} - +// What each emit order means downstream, as data: its order= spelling and whether the rank order is REVERSED (important-last). // order= marker: T3's auto-flip must be OBSERVABLE, not a silent behaviour change — "important-last(auto:fill)" is distinct // from the explicit "important-last" so a reader (or a diff) can tell the ordering was the fill-aware heuristic, not a // requested flag. -inline const char* mapOrderAttr( MapEmitOrder emitOrder ) noexcept +struct MapEmitOrderTraits +{ + const char* orderAttr; + bool importantLast; +}; +inline constexpr MapEmitOrderTraits kMapEmitOrderTraits[] = { + { "important-first", false }, // ImportantFirst + { "stable", false }, // Stable + { "important-last", true }, // ImportantLast + { "important-last(auto:fill)", true }, // ImportantLastAuto +}; + +inline const MapEmitOrderTraits& traitsOf( MapEmitOrder emitOrder ) noexcept { - static constexpr const char* kNames[] = { "important-first", "stable", "important-last", "important-last(auto:fill)" }; - return kNames[ std::size_t( emitOrder ) ]; + return kMapEmitOrderTraits[ std::size_t( emitOrder ) ]; } // Puts the rank-ordered file groups in the emit order: --stable sorts files by path and rows by symbol id (== file+line @@ -3423,7 +3440,7 @@ inline void putMapGroupsInEmitOrder( const IngestResult& ing, MapEmitOrder emitO std::sort( b.begin(), b.end() ); } } - else if( isImportantLast( emitOrder ) ) + else if( traitsOf( emitOrder ).importantLast ) { std::reverse( fileOrder.begin(), fileOrder.end() ); for( std::vector<NodeId>& b : buckets ) @@ -3567,13 +3584,19 @@ inline std::string mapOpeningLegend( bool withProv ) : "<!-- ripwire v1 t=fn|method|cls|struct|iface|var|sec|macro(#define;degraded:body-is-replacement-text,edges-cross-expansion) p=path layer=arch-layer(opt) n=name sc=enclosing-scope(absent-if-unscoped;the-full-id-is-p::sc::n-with-p=-from-the-enclosing-f,and-expand/callers/impact/uses-accept-it) k=rank c=call amb=ambiguous-calls(read-source) lpin=calls-pinned-by-locality-prior-alone(a-disclosed-guess;read-source;absent-if-0) overloads=N-same-name-defs-merged-into-this-row(absent-if-1;shown=counts-them-individually,so-rows+sum(overloads-1)=shown) hdr:unresolved=calls-with-no-edge-and-no-proof-of-an-outside-target(every-same-named-def-lang-incompatible-or-out-of-the-language-lookup) (edges heuristic) hdr:locality_pinned=sum-of-lpin(absent-if-0) hdr:external=calls-refused-as-bound-outside-the-tree-ON-PROOF(builtin/global/predeclared/C-library-name-without-in-repo-evidence,outside-import/use,super-past-the-tree;no-edge;absent-if-0) r:est_tokens=hdr-copy(none-if-stable) -->"; } +// Whether any symbol of the corpus satisfies `pred` — the presence test behind every corpus-kind legend clause. +template <class Pred> +inline bool corpusHasSymbol( const IngestResult& ing, const Pred& pred ) +{ + return std::any_of( ing.symbols.begin(), ing.symbols.end(), pred ); +} + // MODULE-SCOPE OWNERS (issue #60): the t="modscope" kind's reading, ONLY when the corpus actually has one — a corpus with no // file-scope call keeps every byte of this legend, which is what kept test/printf_parity.manifest's --pack-signatures and // --around hashes and every est_tokens ceiling where they were. inline std::string moduleScopeLegend( const IngestResult& ing ) { - const bool hasModuleScope = std::any_of( ing.symbols.begin(), ing.symbols.end(), []( const Symbol& sym ) { return sym.kind == SymKind::ModuleScope; } ); - return hasModuleScope ? std::string( kModScopeMapLegend ) : std::string(); + return corpusHasSymbol( ing, []( const Symbol& sym ) { return sym.kind == SymKind::ModuleScope; } ) ? std::string( kModScopeMapLegend ) : std::string(); } // lane L6: a <c via="impl"> edge's reading, over the rows WRITTEN (fix round 1, N1): only when a kept row or an inventory entry @@ -3599,38 +3622,54 @@ inline std::string typeKindLegend( const IngestResult& ing ) { const auto namedTypeKind = []( const Symbol& sym ) { return sym.kind == SymKind::NamedType || sym.kind == SymKind::Alias || sym.kind == SymKind::FuncType; }; std::string clauses; - if( std::any_of( ing.symbols.begin(), ing.symbols.end(), [ & ]( const Symbol& sym ) { return namedTypeKind( sym ) && !langFacts( sym.lang ).aliasTargetDefs; } ) ) + if( corpusHasSymbol( ing, [ & ]( const Symbol& sym ) { return namedTypeKind( sym ) && !langFacts( sym.lang ).aliasTargetDefs; } ) ) { clauses += kNamedTypeMapLegend; } - if( std::any_of( ing.symbols.begin(), ing.symbols.end(), [ & ]( const Symbol& sym ) { return namedTypeKind( sym ) && langFacts( sym.lang ).aliasTargetDefs; } ) ) + if( corpusHasSymbol( ing, [ & ]( const Symbol& sym ) { return namedTypeKind( sym ) && langFacts( sym.lang ).aliasTargetDefs; } ) ) { clauses += kCppAliasMapLegend; } return clauses; } -// The parse-honesty gauges' clauses, each charged only to the map whose header carries the gauge: EXTENT HONESTY -// (src/extentsuspect.h; the row and the header reading), MEMBER-MACRO RE-PARSE (src/macroreparse.h) and #157's nest_refused=. -inline std::string parseHonestyLegend( const MapHonestyGauges& gauges ) +// Which legend clause defines which gauge, as data: a clause is charged only to the map whose header carries its gauge (> 0). +struct GaugeClause +{ + std::size_t MapHonestyGauges::* gauge; + std::string_view clause; +}; + +inline std::string gaugeLegend( const MapHonestyGauges& gauges, std::span<const GaugeClause> table ) { std::string clauses; - if( gauges.extentSuspectSyms > 0 ) + for( const GaugeClause& row : table ) { - clauses += kExtentSuspectRowLegend; - clauses += kExtentSuspectHdrLegend; - } - if( gauges.macroBlankedFiles > 0 ) - { - clauses += kMacroBlankedHdrLegend; - } - if( gauges.nestRefusedFiles > 0 ) - { - clauses += kNestRefusedMapLegend; + if( gauges.*row.gauge > 0 ) + { + clauses += row.clause; + } } return clauses; } +// The parse-honesty gauges' clauses: EXTENT HONESTY (src/extentsuspect.h; the row and the header reading), MEMBER-MACRO +// RE-PARSE (src/macroreparse.h) and #157's nest_refused=. +inline constexpr GaugeClause kParseHonestyClauses[] = { + { &MapHonestyGauges::extentSuspectSyms, kExtentSuspectRowLegend }, + { &MapHonestyGauges::extentSuspectSyms, kExtentSuspectHdrLegend }, + { &MapHonestyGauges::macroBlankedFiles, kMacroBlankedHdrLegend }, + { &MapHonestyGauges::nestRefusedFiles, kNestRefusedMapLegend }, +}; + +// The tier-3 decline clauses: declined=, then the builtin-method gate's, the standard-member gate's and the Elixir quote's share. +inline constexpr GaugeClause kDeclineClauses[] = { + { &MapHonestyGauges::declined, kDeclinedMapLegend }, + { &MapHonestyGauges::declinedByGate, kDeclinedGateMapLegend }, + { &MapHonestyGauges::declinedByStdMember, kDeclinedStdMapLegend }, + { &MapHonestyGauges::declinedInert, kInertDeclinedMapLegend }, +}; + // M20: the seeded-verb clause, emitted only on a seeded map (see MapAnnotations::SeedDisclosure). inline std::string seedLegend( const MapAnnotations::SeedDisclosure& seed ) { @@ -3743,29 +3782,6 @@ inline std::string rowSelectionLegend( const DataSectionsCut& dataSecCut, const return clauses; } -// The tier-3 decline clauses, each charged to the map that carries the count it explains. -inline std::string declineLegend( const MapHonestyGauges& gauges ) -{ - std::string clauses; - if( gauges.declined > 0 ) - { - clauses += kDeclinedMapLegend; // the map carries declined= - } - if( gauges.declinedByGate > 0 ) - { - clauses += kDeclinedGateMapLegend; // the builtin-method gate declined a call - } - if( gauges.declinedByStdMember > 0 ) - { - clauses += kDeclinedStdMapLegend; // the standard-member gate declined a call - } - if( gauges.declinedInert > 0 ) - { - clauses += kInertDeclinedMapLegend; // an Elixir quote declined a call candidate - } - return clauses; -} - // FE-B: the readings of a <c> row's via="name", via="link" and anchor="missing", in the map's short spelling (graphlegend.h // kViaNameLegend carries the long one) — each exactly when a kept row may print it (over-approximated by merged overloads, // which print one member's edges). via="name"'s clause also defines a merged row's x=. None is written under the compact @@ -4244,22 +4260,6 @@ inline void writeMapFileGroup( XmlWriter& w, const IngestResult& ing, std::uint3 w.write( "</f>" ); } -// A13 prologue, multi-root only: label → root path, canonical order. §P8 collision: this prologue spelled its LABEL `l=`, the -// two characters 22 other sites use for a LINE NUMBER — including the <f p= …> rows. Renamed to label=. -inline void writeRootLabelPrologue( XmlWriter& w, const IngestResult& ing, std::vector<char>& esc ) -{ - if( ing.rootLabels.size() < 2 ) - { - return; - } - for( std::size_t r = 0; r < ing.rootLabels.size(); ++r ) - { - w.write( "<root label=\"" ); w.write( escapeXml( ing.rootLabels[r], esc ) ); - w.write( "\" p=\"" ); w.write( escapeXml( r < ing.rootPaths.size() ? ing.rootPaths[r] : std::string(), esc ) ); - w.write( "\"/>" ); - } -} - // C1-b: under in=DIR the symbol map is a DISCLOSED stub (docs/METHODOLOGY.md §9.3) — the caller asked for DIR's recent files, // not the map. // @@ -4303,7 +4303,7 @@ inline void writeMapChildren( XmlWriter& w, const IngestResult& ing, const MapAn MapEmitOrder emitOrder, const MapRowSources& src, const PathRel& pathRel, std::vector<char>& esc, std::vector<std::uint32_t>& scratch ) { - writeRootLabelPrologue( w, ing, esc ); + writeRootLabelRows( w, ing, esc ); // A13: the multi-root prologue writeRecentRows( w, ann, pathRel, esc ); if( ann.stubSymbols ) { @@ -4316,7 +4316,7 @@ inline void writeMapChildren( XmlWriter& w, const IngestResult& ing, const MapAn writeMapInventoryXml( w, ing, groups.inventory, pathRel, src.outOff, src.outTargets, src.outProv, src.outNameOnly, esc, scratch ); } }; - const bool inventoryFirst = isImportantLast( emitOrder ); // --stable's path order wins, as it does for the rows + const bool inventoryFirst = traitsOf( emitOrder ).importantLast; // --stable's path order wins, as it does for the rows if( inventoryFirst ) { writeInventory(); @@ -4471,13 +4471,13 @@ inline void serialize( std::FILE* out, const IngestResult& ing, const std::vecto legend += moduleScopeLegend( ing ); legend += keptImplEdgeLegend( outOff, outProv, kept, groups.inventory.entries ); legend += typeKindLegend( ing ); - legend += parseHonestyLegend( gauges ); + legend += gaugeLegend( gauges, kParseHonestyClauses ); legend += runAnnotationLegend( ing, ann, rootArg, metrics ); legend += rowSelectionLegend( ranked.dataSecCut, groups ); // W2-F: the pr_iters= / pr_converged= definition, charged to the maps that carry the attributes — empty for a lexical or // HITS ordering, and the prose half only on the map whose iteration stopped short. legend += renderDisclosure( ann.prDisclosure, DiscloseAs::LegendComment ); - legend += declineLegend( gauges ); + legend += gaugeLegend( gauges, kDeclineClauses ); legend += keptNameEdgeLegend( outOff, outNameOnly, kept, ann.viaLegendStripped ); // K51: history_unread='s definition, the LAST leading clause, so it stands right before the <r> root it marks and inside the // leading block every reader (and legendcoveragecheck's full rows) meets first; absent unless the amp=/churn= walk was unread. @@ -4493,7 +4493,7 @@ inline void serialize( std::FILE* out, const IngestResult& ing, const std::vecto const std::string coverageAttrs = mapCoverageAttrs( ing, outProv, ann ); const MapStatsFacts statsFacts{ .files = ing.files.size(), .symbols = mapSymbolCount( ing ), .edges = outTargets.size(), .shown = stubbed ? std::size_t( 0 ) : keep + groups.stemPick.rows.size(), - .gauges = gauges, .coverageAttrs = coverageAttrs, .orderAttr = mapOrderAttr( emitOrder ) }; + .gauges = gauges, .coverageAttrs = coverageAttrs, .orderAttr = traitsOf( emitOrder ).orderAttr }; const MapRootFacts rootFacts{ .ann = ann, .rootArg = rootArg, .stable = stable, .dataSecCut = ranked.dataSecCut, .stemCut = groups.stemPick.cut }; MapEstimate estimate{ ann.payloadUncharged }; // the est_tokens measurement's DISCLOSE sink — read by the builders const auto buildHead = [ & ]( std::size_t estTokens ) -> std::string @@ -5103,12 +5103,6 @@ inline std::string stripCommentsKeepLiterals( std::string_view src ) return out; } -// A line whose content is only spaces, tabs and carriage returns. -inline bool isBlankLine( std::string_view line ) noexcept -{ - return std::all_of( line.begin(), line.end(), []( char ch ) { return ch == ' ' || ch == '\t' || ch == '\r'; } ); -} - // Phase 2: the comment-stripped text's line layout. Lines that are now whitespace-only and come before the first content line // are dropped (an artifact of stripping the opening comment of a body); after it, at most two consecutive blank lines are // kept and the rest of a run is dropped. Every line with ANY non-whitespace content is kept, so intentional blank lines between @@ -5123,7 +5117,7 @@ inline std::string collapseBlankLineRuns( std::string_view text ) { const std::size_t eol = std::min( text.find( '\n', pos ), text.size() ); const std::string_view line = text.substr( pos, eol - pos ); - if( !isBlankLine( line ) ) + if( line.find_first_not_of( " \t\r" ) != std::string_view::npos ) // the line has content { blanks = 0; result.append( line ); @@ -12234,7 +12228,7 @@ inline void serializeJson( std::FILE* out, const IngestResult& ing, const std::v { JsonWriter hw( dst ); writeJsonMapHeader( hw, esc, JsonMapHeader{ ing, mapSymbolCount( ing ), outTargets.size(), keep + groups.stemPick.rows.size(), estTokens, gauges.ambiguous, - gauges.unresolved, mapOrderAttr( emitOrder ), outProv, &ann, rootArg, gauges.localityPinned, gauges.external, + gauges.unresolved, traitsOf( emitOrder ).orderAttr, outProv, &ann, rootArg, gauges.localityPinned, gauges.external, gauges.declined, gauges.extentSuspectSyms, gauges.macroBlankedFiles, gauges.nestRefusedFiles, estimate.isModelled, ranked.dataSecCut, groups.stemPick.cut, memoryPeakJson } ); hw.write( ",\"r\":[" ); From 7c116cd60c1e0faf36bd06db2e0a91cc138a1e24 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:03:16 -0500 Subject: [PATCH 26/61] refactor(serialize): the module-scope clause as its presence scan, no one-line any_of wrapper qd-range gated corpusHasSymbol as a clone of notes::sortNotes' one-call shape. The module-scope legend test is its own early-return scan again and the two type-kind tests call std::any_of directly. Byte-identical: no answer changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/serialize.h | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/serialize.h b/src/serialize.h index e90eda58a..ab7794e94 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -3584,19 +3584,19 @@ inline std::string mapOpeningLegend( bool withProv ) : "<!-- ripwire v1 t=fn|method|cls|struct|iface|var|sec|macro(#define;degraded:body-is-replacement-text,edges-cross-expansion) p=path layer=arch-layer(opt) n=name sc=enclosing-scope(absent-if-unscoped;the-full-id-is-p::sc::n-with-p=-from-the-enclosing-f,and-expand/callers/impact/uses-accept-it) k=rank c=call amb=ambiguous-calls(read-source) lpin=calls-pinned-by-locality-prior-alone(a-disclosed-guess;read-source;absent-if-0) overloads=N-same-name-defs-merged-into-this-row(absent-if-1;shown=counts-them-individually,so-rows+sum(overloads-1)=shown) hdr:unresolved=calls-with-no-edge-and-no-proof-of-an-outside-target(every-same-named-def-lang-incompatible-or-out-of-the-language-lookup) (edges heuristic) hdr:locality_pinned=sum-of-lpin(absent-if-0) hdr:external=calls-refused-as-bound-outside-the-tree-ON-PROOF(builtin/global/predeclared/C-library-name-without-in-repo-evidence,outside-import/use,super-past-the-tree;no-edge;absent-if-0) r:est_tokens=hdr-copy(none-if-stable) -->"; } -// Whether any symbol of the corpus satisfies `pred` — the presence test behind every corpus-kind legend clause. -template <class Pred> -inline bool corpusHasSymbol( const IngestResult& ing, const Pred& pred ) -{ - return std::any_of( ing.symbols.begin(), ing.symbols.end(), pred ); -} - // MODULE-SCOPE OWNERS (issue #60): the t="modscope" kind's reading, ONLY when the corpus actually has one — a corpus with no // file-scope call keeps every byte of this legend, which is what kept test/printf_parity.manifest's --pack-signatures and // --around hashes and every est_tokens ceiling where they were. -inline std::string moduleScopeLegend( const IngestResult& ing ) +inline std::string_view moduleScopeLegend( const IngestResult& ing ) noexcept { - return corpusHasSymbol( ing, []( const Symbol& sym ) { return sym.kind == SymKind::ModuleScope; } ) ? std::string( kModScopeMapLegend ) : std::string(); + for( const Symbol& sym : ing.symbols ) + { + if( sym.kind == SymKind::ModuleScope ) + { + return kModScopeMapLegend; + } + } + return {}; } // lane L6: a <c via="impl"> edge's reading, over the rows WRITTEN (fix round 1, N1): only when a kept row or an inventory entry @@ -3622,11 +3622,11 @@ inline std::string typeKindLegend( const IngestResult& ing ) { const auto namedTypeKind = []( const Symbol& sym ) { return sym.kind == SymKind::NamedType || sym.kind == SymKind::Alias || sym.kind == SymKind::FuncType; }; std::string clauses; - if( corpusHasSymbol( ing, [ & ]( const Symbol& sym ) { return namedTypeKind( sym ) && !langFacts( sym.lang ).aliasTargetDefs; } ) ) + if( std::any_of( ing.symbols.begin(), ing.symbols.end(), [ & ]( const Symbol& sym ) { return namedTypeKind( sym ) && !langFacts( sym.lang ).aliasTargetDefs; } ) ) { clauses += kNamedTypeMapLegend; } - if( corpusHasSymbol( ing, [ & ]( const Symbol& sym ) { return namedTypeKind( sym ) && langFacts( sym.lang ).aliasTargetDefs; } ) ) + if( std::any_of( ing.symbols.begin(), ing.symbols.end(), [ & ]( const Symbol& sym ) { return namedTypeKind( sym ) && langFacts( sym.lang ).aliasTargetDefs; } ) ) { clauses += kCppAliasMapLegend; } From 6fb8a8487511545ad9dfa14d8686165658ecbad2 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:00:05 -0500 Subject: [PATCH 27/61] refactor(serialize): the map header's coverage attributes composed on std::string fixedbufsweep re-derived the moved precise=/roots=/changed=/skipped_oversize=/ max_tokens= buffers as one unclassified `buf`. Every interpoland is an integer or a fixed literal, so mapCoverageAttrs now composes them on std::string and no fixed buffer is left; the five stale table rows go, and the `p` comment-mention row drops to the one remaining site. Byte-identical: no answer changes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/serialize.h | 29 ++++++++++++++--------------- test/fixedbufsweep.sh | 9 +++------ 2 files changed, 17 insertions(+), 21 deletions(-) diff --git a/src/serialize.h b/src/serialize.h index ab7794e94..cbe854a10 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -3830,18 +3830,15 @@ inline std::size_t scipPinnedEdgeCount( const std::vector<std::uint8_t>* outProv inline std::string mapCoverageAttrs( const IngestResult& ing, const std::vector<std::uint8_t>* outProv, const MapAnnotations& ann ) { std::string attrs; - char buf[ 96 ]; if( const std::size_t precise = scipPinnedEdgeCount( outProv ); precise > 0 ) { - rw::formatTo( buf, sizeof( buf ), " precise={}", precise ); // only when a SCIP overlay pinned something - attrs += buf; + attrs += " precise=" + std::to_string( precise ); // only when a SCIP overlay pinned something } // Multi-root workspace (A13): `roots=N` joins the header gauges and a `<root label= p=/>` prologue opens <r> — ONLY when // N≥2 (single-root output byte-unchanged). if( ing.rootLabels.size() >= 2 ) { - rw::formatTo( buf, sizeof( buf ), " roots={}", ing.rootLabels.size() ); - attrs += buf; + attrs += " roots=" + std::to_string( ing.rootLabels.size() ); } // D6: --map-diff's teleport-seed file count, ONLY when the caller passes changedCount (nullptr for every non-map-diff // caller ⇒ zero token cost, byte-identical golden map). A clean tree reports "changed=0" so the caller can see the @@ -3849,16 +3846,14 @@ inline std::string mapCoverageAttrs( const IngestResult& ing, const std::vector< // plain default map. if( ann.changedCount ) { - rw::formatTo( buf, sizeof( buf ), " changed={}", *ann.changedCount ); - attrs += buf; + attrs += " changed=" + std::to_string( *ann.changedCount ); } // §P0.5d: how many otherwise-indexable files the crawl dropped for exceeding a per-file size ceiling — --max-file-size, or // (§B13.1) the .json lane's fixed 256 KB config ceiling that --max-file-size does not raise. `--max-file-size=8K` dropped // ~296 of ~759 files on this repo and files= reported the survivors as if they WERE the corpus. if( !ing.skippedOversize.empty() ) { - rw::formatTo( buf, sizeof( buf ), " skipped_oversize={}", ing.skippedOversize.size() ); - attrs += buf; + attrs += " skipped_oversize=" + std::to_string( ing.skippedOversize.size() ); } attrs += buildMemoryStopAttr( ing, false ) + buildMemoryPeakAttr( ing, false ); // #350, empty unless the memory guard stopped the ingest or the peak passed the limit attrs += buildUnindexedAttr( ing.crawlSkips ); // §L1: the LANGUAGES this build could not read at all @@ -3872,13 +3867,17 @@ inline std::string mapCoverageAttrs( const IngestResult& ing, const std::vector< // attr — a cap that can be overshot is not a cap, so where the map's fixed floor cannot fit inside fit_bytes the map states // that instead of quietly exceeding it. See MapAnnotations::MaxTokensFit for the four ways the cap was breached and why // the label is monotone. - if( ann.maxTokensFit != nullptr ) + if( const MapAnnotations::MaxTokensFit* fit = ann.maxTokensFit ) { - rw::formatTo( buf, sizeof( buf ), " max_tokens={} fit_bytes={}{}{}", - ann.maxTokensFit->askedTokens, ann.maxTokensFit->ceilingBytes, - ann.maxTokensFit->isOverCeiling || ann.maxTokensFit->isUnmeasured ? " over_ceiling=1" : "", - ann.maxTokensFit->isUnmeasured ? " fit_unmeasured=1" : "" ); - attrs += buf; + attrs += " max_tokens=" + std::to_string( fit->askedTokens ) + " fit_bytes=" + std::to_string( fit->ceilingBytes ); + if( fit->isOverCeiling || fit->isUnmeasured ) + { + attrs += " over_ceiling=1"; + } + if( fit->isUnmeasured ) + { + attrs += " fit_unmeasured=1"; + } } return attrs; } diff --git a/test/fixedbufsweep.sh b/test/fixedbufsweep.sh index 9f4bcd9b1..4c1ab6783 100755 --- a/test/fixedbufsweep.sh +++ b/test/fixedbufsweep.sh @@ -187,7 +187,6 @@ TABLE = { ( "src/packtask.h", "bodylessAttr" ): ( 1, "safe", "bodylessAttr[40], ONE call site (PB1, 2026-11-19: it was two). The surviving site is the <bodies> open-tag restate (issue #60, integration/train-12). The second site, the bare-wrapper placeholder branch (t14-cleanup #6), is gone: PB1 emits that no-candidate tag as a fixed literal with no bodyless= at all, because a bundle with no body CANDIDATE has no bodyless owner to count. It formats ' bodyless=\"{}\"' — 12 B of literal (' bodyless=\"' 11 + '\"' 1) and ONE interpoland, a std::size_t: 20 digits at absolute most, so 32 B against 39 usable + NUL, 7 B of margin. No string interpolation at all — the count is a count, never caller text — so no escaper can sit on either side of the buffer. It is a TABLE row and not NUMERIC_ONLY for arch.h hex[17]'s reason: a buffer that never existed before the std::print conversion has no pre-conversion format to derive a class from. THE ORIGINAL BUFFER WAS DECLARED [32] WHEN IT ARRIVED, which is 1 B short of its own worst case (32 B of text needs 33 with the NUL); formatTo truncates rather than overruns, so the failure mode was a dropped closing quote and a document that stops being well-formed, not a memory breach. Widened to 40 in the same commit as that row; the second site was declared [160]/[40] correctly from the start." ), # ── src/serialize.h ────────────────────────────────────────────────────────────────────────────────── ( "src/serialize.h", "bodylessAttr" ): ( 1, "safe", "bodylessAttr[40] in packBodies (issue #60, integration/train-12): the exact twin of the packtask.h row above — same format, same 12 B of literal, one std::size_t (bodylessCount), 32 B against 39 usable + NUL, 7 B of margin, no string interpoland. Same [32]-on-arrival correction, widened in the same commit." ), - ( "src/serialize.h", "fitAttr" ): ( 1, "safe", "fitAttr[96]: two %zu plus the literal ' over_ceiling=1'." ), ( "src/serialize.h", "attr" ): ( 2, "safe", "attr[352] x2: the per-symbol metric attrs. Widest 26 lit + 4x10 digits + 11 role + qbuf(<=95) + ambs(<=35: amb= + lpin=) + kbuf(<=23) = 230 B." ), ( "src/serialize.h", "tail" ): ( 3, "safe", "tail[192] x3: the <d> row tail. Widest 34 lit+digits + inAttr(<=23) + lens(qbuf, <=79) + pure(9) = 145 B. The third (lane/lean-answers-068, sigRowTail's zero-elision branch) prints cxAttr/ccxAttr/inAttr pre-formatted, each omitted at 0 — never wider than the second." ), ( "src/serialize.h", "hdr" ): ( 15, "safe", "hdr[64] x2 (packBodies/packOutline) (15: the tracked-build crawl fix — writeJsonMapHeader's `\"untracked_build\":{},` formatTo into the EXISTING hdr[256], one unsigned long long and no string argument, 19 B of literal + 20 digits + NUL = 40 B, the `\"escaped_root\":{},` twin beside it; 14: arch-honest — packDeps' <f> row for a no-edge file writes includes= and a language tag, hdr[144], one integer + a label of at most 8 B: far under the buffer; 13: train 26b — count-floor-068 replaced the <lego> implementors= header writes, two hdr sites, with string appends): '<b t=\"%s\" l=\"%u\" p=\"' — symTag's fixed vocabulary + a line number. THE ESCAPED PATH IS APPENDED AFTER, on std::string. snprintf-then-append: textbook safe." ), @@ -218,7 +217,7 @@ TABLE = { # A NEW row here still fails the gate until someone adds it, which is the point. When you add one, say which # set it belongs in and why: a string argument makes it a TABLE row, with real prose. NUMERIC_ONLY = { - ( "src/serialize.h", "p" ): 2, + ( "src/serialize.h", "p" ): 1, # GE-SERIALIZE (2026-11-21): the map row's copy of the snprintf( p, S, ... ) comment became BoundedAttrRun's; one comment mention left (the --for lens qbuf) ( "src/degradedscan.h", "hit.errRatio" ): 1, ( "src/dmm.h", "value" ): 1, ( "src/editcheck.h", "callersOpen" ): 1, @@ -260,7 +259,6 @@ NUMERIC_ONLY = { ( "src/serialize.h", "callsHdr" ): 2, ( "src/serialize.h", "cb" ): 1, ( "src/serialize.h", "ccxAttr" ): 1, # lane/lean-answers-068: sigRowTail's zero elision, " ccx=\"{}\"" of one count (<= 17 B of 23) - ( "src/serialize.h", "changedAttr" ): 1, ( "src/serialize.h", "eAttr" ): 1, # lane/for-spine-span-068 (2026-10-04): writeSigHeadWithEnd's ' e="{}"' — 5 B literal + one # std::uint32_t (10 digits) = 15 B against 23 usable + NUL. A count, no %s, nothing escaped. ( "src/serialize.h", "cxAttr" ): 1, # lane/lean-answers-068: the same, " cx=\"{}\"" (<= 16 B of 23) @@ -291,12 +289,9 @@ NUMERIC_ONLY = { # digits = 35 B). A count, no %s, nothing escaped. # lane/hrr (2026-10-18): +1 in the same nb[96] — ' files_first="{}"' (15 B + 20 # digits = 35 B), the head round-robin's moved count. A count, no %s, nothing escaped. - ( "src/serialize.h", "precAttr" ): 1, ( "src/serialize.h", "rankAttr" ): 1, ( "src/serialize.h", "rc" ): 1, - ( "src/serialize.h", "rootsAttr" ): 1, ( "src/serialize.h", "sh" ): 1, - ( "src/serialize.h", "skippedAttr" ): 1, ( "src/serialize.h", "vb" ): 1, ( "src/testmap.h", "buf" ): 6, ( "src/verbs_report.h", "buf" ): 2, @@ -626,6 +621,8 @@ if not bad: # 2026-10-18 (lane/hrr): +1 call/+1 mention/+1 site, rows unchanged (363/248/248/109 -> 364/249/249/109): sigsOpenTag's # nb[96] ' files_first="{}"' (35 B worst case, one size_t, nothing escaped) — re-read and sized before this pin. EXPECTED = { "mentions": 366, "calls": 251, "sites": 251, "rows": 109, "widthforms": 0 } # lane/hrr: +1 nb site (files_first=); arch-honest: +2 (packDeps hb, hdr) +# 2026-11-21 (GE-SERIALIZE): -5 calls/-5 sites/-5 rows (precAttr, rootsAttr, changedAttr, skippedAttr, fitAttr): the map +# header's coverage attributes are composed on std::string in mapCoverageAttrs (serialize.h), no fixed buffer left. # 2026-11-12 (B43 PINNED-SELF-COUNTS): EXPECTED above is now HISTORY, not a pin -- it drifted on #619 (and on every # lane that added one site) while (S1)/(S2) already held the member set both ways: every derived site is a TABLE # row with its multiplicity, and no row is stale. An exact count on top of that only re-pins arithmetic. What (S1)/(S2) From ef4a92dee7ad1e879ad09e2021c9130e701ddf20 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:13:38 -0500 Subject: [PATCH 28/61] refactor(serialize): one MapPlan for both map dialects; the JSON header spells the plan planMap() decides what a map prints once for XML and JSON: symbols= (counted once), the top-K cut, the rank order, the byte model, the emit order, the file groups, the honesty gauges and shown=. The stub is one named MapStubPolicy at each call (XML honours in=DIR's stub, JSON always prints rows), so rankMapRows and groupMapRowsByFile lose their stubbed parameter. The JSON header takes the plan and MapCoverageFacts (precise= via scipPinnedEdgeCount, roots, skipped_oversize; each absent at 0 in both dialects) instead of 21 positional fields, and no longer recounts mapSymbolCount on every emitHeader call. mapCoverageAttrs splits into renderMapCoverageAttrs + mapFitAttrs. --stable's byte-stable prefix is a trait of the emit order (emitOrderTraits().stablePrefix): k= on both row dialects, est_tokens=/lens= on <r>, the trailing stats and the path sort read it, never the flag. emitOrderTraits is an exhaustive switch (-Werror=switch). rowDescriptiveAttrs splits into rowMetricsAttrs + rowResolverGuessAttrs + rowRankAttr, written in the same order (the shared buffer never truncated: 326 B worst case < 351). Byte-identical output. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/serialize.h | 551 ++++++++++++++++++++++-------------------- test/fixedbufsweep.sh | 4 +- 2 files changed, 297 insertions(+), 258 deletions(-) diff --git a/src/serialize.h b/src/serialize.h index cbe854a10..9c5009d7e 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -3325,12 +3325,11 @@ inline void dropUnmappedRows( const IngestResult& ing, std::vector<NodeId>& orde // order, the file groups and the honesty gauges — so the two dialects cannot drift on them; each dialect then writes the // same groups in its own spelling. Every step below is decided once and handed on as a const value. -// C1-b: the row count the map WOULD print. It depends on topK and the printable rows alone — never on the ranking — so under -// in=DIR's stub it is still the honest would_show=. -inline std::size_t mapKeepCount( const IngestResult& ing, int topK ) noexcept +// C1-b: the row count the map WOULD print. It depends on topK and the printable rows alone (`mapSymbols`, mapSymbolCount: the +// rows dropUnmappedRows leaves) — never on the ranking — so under in=DIR's stub it is still the honest would_show=. +inline std::size_t mapKeepCount( std::size_t mapSymbols, int topK ) noexcept { - const std::size_t mapS = mapSymbolCount( ing ); // the rows the map can print (dropUnmappedRows) - return std::min<std::size_t>( topK > 0 ? std::size_t( topK ) : mapS, mapS ); + return std::min<std::size_t>( topK > 0 ? std::size_t( topK ) : mapSymbols, mapSymbols ); } // The rank order the map's rows are drawn from: (rank desc, id asc) — the id tie-break makes the top-K deterministic — less @@ -3348,16 +3347,11 @@ struct RankedMapRows } }; -// C1-b: under in=DIR's stub (`stubbed`) the map prints no symbol row, so every step that exists only to ORDER rows nobody -// prints is skipped — the radix sort over every symbol among them — and the order is empty. -inline RankedMapRows rankMapRows( const IngestResult& ing, const std::vector<float>& rank, const MapAnnotations& ann, std::size_t keep, - bool stubbed ) +// Not run under in=DIR's stub (planMap): the stub prints no symbol row, so the radix sort over every symbol would order rows +// nobody prints, and the stub's order stays empty. +inline RankedMapRows rankMapRows( const IngestResult& ing, const std::vector<float>& rank, const MapAnnotations& ann, std::size_t keep ) { RankedMapRows ranked; - if( stubbed ) - { - return ranked; - } ranked.order.resize( ing.symbols.size() ); for( NodeId i = 0; i < ranked.order.size(); ++i ) { @@ -3393,20 +3387,30 @@ enum class MapEmitOrder : std::uint8_t // T3 note: the decision keys off the MAP's own estimate, NOT the payload — the fill-order heuristic reasons about the map that // gets reordered; the appended <bodies>/<sigs>/<src> blocks are emitted after and cannot be reordered, so they must not shift // the map's primacy/recency decision. -inline MapEmitOrder decideMapEmitOrder( bool stable, bool mostImportantLast, bool autoOrder, std::size_t mapEstTokens ) noexcept +// The caller's order flags, as asked; decideMapEmitOrder turns them into the one MapEmitOrder everything downstream reads. +struct MapOrderRequest +{ + bool stable = false; // --stable + bool mostImportantLast = false; // --most-important-last + bool autoOrder = false; // T3: the caller opted into the fill-aware flip +}; + +inline MapEmitOrder decideMapEmitOrder( const MapOrderRequest& asked, std::size_t mapEstTokens ) noexcept { - if( stable ) + if( asked.stable ) { return MapEmitOrder::Stable; } - if( mostImportantLast ) + if( asked.mostImportantLast ) { return MapEmitOrder::ImportantLast; } - return ( autoOrder && mapEstTokens > kFillOrderThreshold ) ? MapEmitOrder::ImportantLastAuto : MapEmitOrder::ImportantFirst; + return ( asked.autoOrder && mapEstTokens > kFillOrderThreshold ) ? MapEmitOrder::ImportantLastAuto : MapEmitOrder::ImportantFirst; } -// What each emit order means downstream, as data: its order= spelling and whether the rank order is REVERSED (important-last). +// What each emit order means downstream, as data: its order= spelling, whether the rank order is REVERSED (important-last), +// and whether the map is --stable's byte-stable PREFIX — path/id order, no k= on a row, lens= in place of est_tokens= on <r>, +// and the volatile stats moved to a trailing comment. Every one of those choices reads this trait, never the --stable flag. // order= marker: T3's auto-flip must be OBSERVABLE, not a silent behaviour change — "important-last(auto:fill)" is distinct // from the explicit "important-last" so a reader (or a diff) can tell the ordering was the fill-aware heuristic, not a // requested flag. @@ -3414,17 +3418,20 @@ struct MapEmitOrderTraits { const char* orderAttr; bool importantLast; -}; -inline constexpr MapEmitOrderTraits kMapEmitOrderTraits[] = { - { "important-first", false }, // ImportantFirst - { "stable", false }, // Stable - { "important-last", true }, // ImportantLast - { "important-last(auto:fill)", true }, // ImportantLastAuto + bool stablePrefix; }; -inline const MapEmitOrderTraits& traitsOf( MapEmitOrder emitOrder ) noexcept +// A switch with no default: -Werror=switch makes a new MapEmitOrder a compile error until it has its traits here. +inline MapEmitOrderTraits emitOrderTraits( MapEmitOrder emitOrder ) noexcept { - return kMapEmitOrderTraits[ std::size_t( emitOrder ) ]; + switch( emitOrder ) + { + case MapEmitOrder::ImportantFirst: return { .orderAttr = "important-first", .importantLast = false, .stablePrefix = false }; + case MapEmitOrder::Stable: return { .orderAttr = "stable", .importantLast = false, .stablePrefix = true }; + case MapEmitOrder::ImportantLast: return { .orderAttr = "important-last", .importantLast = true, .stablePrefix = false }; + case MapEmitOrder::ImportantLastAuto: return { .orderAttr = "important-last(auto:fill)", .importantLast = true, .stablePrefix = false }; + } + UNREACHABLE( "a MapEmitOrder outside its four enumerators" ); } // Puts the rank-ordered file groups in the emit order: --stable sorts files by path and rows by symbol id (== file+line @@ -3432,7 +3439,8 @@ inline const MapEmitOrderTraits& traitsOf( MapEmitOrder emitOrder ) noexcept inline void putMapGroupsInEmitOrder( const IngestResult& ing, MapEmitOrder emitOrder, std::vector<std::vector<NodeId>>& buckets, std::vector<std::uint32_t>& fileOrder ) { - if( emitOrder == MapEmitOrder::Stable ) + const MapEmitOrderTraits traits = emitOrderTraits( emitOrder ); + if( traits.stablePrefix ) { std::sort( fileOrder.begin(), fileOrder.end(), [ & ]( std::uint32_t a, std::uint32_t b ) { return ing.files[ a ] < ing.files[ b ]; } ); for( std::vector<NodeId>& b : buckets ) @@ -3440,7 +3448,7 @@ inline void putMapGroupsInEmitOrder( const IngestResult& ing, MapEmitOrder emitO std::sort( b.begin(), b.end() ); } } - else if( traitsOf( emitOrder ).importantLast ) + else if( traits.importantLast ) { std::reverse( fileOrder.begin(), fileOrder.end() ); for( std::vector<NodeId>& b : buckets ) @@ -3452,7 +3460,8 @@ inline void putMapGroupsInEmitOrder( const IngestResult& ing, MapEmitOrder emitO // The printed rows grouped by file. Files are ordered by their best (first-seen) rank, and two row sets are decided over that // rank-ordered grouping BEFORE it is put in the emit order: MAP-STEM's one reserved stem-namesake row per shown file (added -// to the buckets, after the kept rows) and the D7 inventory over the files the kept rows did NOT reach. Empty under the stub. +// to the buckets, after the kept rows) and the D7 inventory over the files the kept rows did NOT reach. Not run under the stub +// (planMap), whose groups stay empty: no files-sized bucket allocation, no fill loop. struct MapFileGroups { std::vector<std::vector<NodeId>> buckets; // per file id: its printed rows, in emit order @@ -3462,15 +3471,10 @@ struct MapFileGroups }; template <class PathRel> -inline MapFileGroups groupMapRowsByFile( const IngestResult& ing, const MapAnnotations& ann, std::span<const NodeId> kept, bool stubbed, - MapEmitOrder emitOrder, const std::vector<std::uint32_t>& outOff, - const std::vector<NodeId>& outTargets, const PathRel& pathRel ) +inline MapFileGroups groupMapRowsByFile( const IngestResult& ing, const MapAnnotations& ann, std::span<const NodeId> kept, MapEmitOrder emitOrder, + const std::vector<std::uint32_t>& outOff, const std::vector<NodeId>& outTargets, const PathRel& pathRel ) { MapFileGroups groups; - if( stubbed ) - { - return groups; // C1-b: no files-sized bucket allocation, no fill loop - } groups.buckets.resize( ing.files.size() ); std::vector<char> shownFile( ing.files.size(), 0 ); // exactly the printed <f> groups for( const NodeId id : kept ) @@ -3546,6 +3550,63 @@ inline MapHonestyGauges countMapHonestyGauges( const IngestResult& ing, const Ma .nestRefusedFiles = ing.crawlSkips.nestRefusedFiles }; } +// Whether in=DIR's stub (MapAnnotations::stubSymbols) replaces the symbol rows. The XML map honours it; the JSON map has no +// stub spelling and always prints its rows. Named once, at the planMap call, so neither dialect re-reads the flag. +enum class MapStubPolicy : std::uint8_t +{ + HonourAnnotation, + AlwaysPrintRows, +}; + +// WHAT a map prints, decided once for both dialects (planMap): the row cap, the rank order, the byte model, the emit order, +// the file groups, the honesty gauges and the shown= count. Each dialect then only spells the plan. +struct MapPlan +{ + bool stubbed = false; // C1-b: in=DIR's stub prints no symbol row (MapStubPolicy) + std::size_t symbolCount = 0; // symbols=: the symbols the map ranks (mapSymbolCount), counted once per map + std::size_t keep = 0; // the top-K cut; under the stub, the would_show= it would have printed + RankedMapRows ranked; // empty under the stub + TokenEstimate mapEst; // the byte MODEL: the T3 order oracle and the bytes/token rate (§H7) + MapEmitOrder emitOrder = MapEmitOrder::ImportantFirst; + MapFileGroups groups; // empty under the stub + MapHonestyGauges gauges; + std::size_t shown = 0; // shown=: the kept rows plus the stem rows; 0 under the stub + + // the rows inside the top-K cut (none under the stub) + std::span<const NodeId> kept() const noexcept { return ranked.kept( keep ); } +}; + +template <class PathRel> +inline MapPlan planMap( const IngestResult& ing, const std::vector<float>& rank, const std::vector<std::uint32_t>& outOff, const std::vector<NodeId>& outTargets, + const MapAnnotations& ann, int topK, const MapOrderRequest& asked, const MapResolverCounters& counters, MapStubPolicy stubPolicy, + const PathRel& pathRel ) +{ + MapPlan plan; + plan.stubbed = stubPolicy == MapStubPolicy::HonourAnnotation && ann.stubSymbols; + plan.symbolCount = mapSymbolCount( ing ); + plan.keep = mapKeepCount( plan.symbolCount, topK ); + if( !plan.stubbed ) + { + plan.ranked = rankMapRows( ing, rank, ann, plan.keep ); + } + // T1/§H7: the byte MODEL. It decides the T3 emit order (which has to be decided before any byte exists — see §H7 at + // estimateTokens) and supplies the language-weighted bytes/token RATE, the half of it that is actually measured. It no + // longer REPORTS the size: each dialect measures est_tokens from its emitted bytes, because a model of the symbol set cannot + // see --metrics decoration or an appended payload. C1-b: under the stub the estimate is taken over no rows. + plan.mapEst = estimateTokens( ing, plan.ranked.order, plan.kept().size(), outOff, outTargets ); + plan.emitOrder = decideMapEmitOrder( asked, plan.mapEst.tokens ); + ASSUME( emitOrderTraits( plan.emitOrder ).stablePrefix == asked.stable, "decideMapEmitOrder returns Stable exactly when --stable was asked" ); + if( !plan.stubbed ) + { + plan.groups = groupMapRowsByFile( ing, ann, plan.kept(), plan.emitOrder, outOff, outTargets, pathRel ); + } + plan.gauges = countMapHonestyGauges( ing, counters ); + plan.shown = plan.stubbed ? 0 : plan.keep + plan.groups.stemPick.rows.size(); + ASSUME( !plan.stubbed || ( plan.kept().empty() && plan.groups.fileOrder.empty() && plan.groups.inventory.entries.empty() ), + "the stub ranks and groups no row, so no kept-row legend clause and no <f> group can fire under it" ); + return plan; +} + // The per-symbol facts a map row may print, gathered once from the emitter's parameters. Read-only; a nullptr source means // that attribute is never printed. struct MapRowSources @@ -3558,8 +3619,8 @@ struct MapRowSources const std::vector<std::uint32_t>* ambOut; const std::vector<std::uint32_t>* locPinOut; const SparseLabels* bind; - bool stable; // --stable: no k= (PageRank is globally volatile) - bool metrics; // --metrics: the descriptive Q-compute attributes + MapEmitOrder emitOrder; // k= is absent on --stable's byte-stable prefix (emitOrderTraits().stablePrefix) + bool metrics; // --metrics: the descriptive Q-compute attributes const std::vector<std::uint32_t>* fanIn; const std::vector<std::uint32_t>* cbo; const std::vector<std::uint8_t>* tested; @@ -3825,20 +3886,35 @@ inline std::size_t scipPinnedEdgeCount( const std::vector<std::uint8_t>* outProv return outProv ? std::size_t( std::count( outProv->begin(), outProv->end(), std::uint8_t( 1 ) ) ) : 0; } -// The header gauges after the parse-honesty run: what the run covered and what it left out. Each is absent unless its fact -// holds, so a default run over a tree with nothing to disclose stays byte-identical. Composed once per map. -inline std::string mapCoverageAttrs( const IngestResult& ing, const std::vector<std::uint8_t>* outProv, const MapAnnotations& ann ) +// What the run covered and what it left out, as the counts both dialects' headers state. Every one is ABSENT at 0 in both +// spellings, so a default run over a tree with nothing to disclose stays byte-identical; each count's presence rule is decided +// here, once, and the renderers only test > 0. +struct MapCoverageFacts +{ + std::size_t scipPinnedEdges = 0; // precise=: the out-edges a SCIP overlay pinned (scipPinnedEdgeCount) + std::size_t multiRootCount = 0; // roots=: the workspace's roots — 0 on a single root (A13: only N≥2 is stated) + std::size_t skippedOversize = 0; // skipped_oversize=: files the crawl dropped for a per-file size ceiling (§P0.5d) +}; + +inline MapCoverageFacts mapCoverageFacts( const IngestResult& ing, const std::vector<std::uint8_t>* outProv ) noexcept +{ + return MapCoverageFacts{ .scipPinnedEdges = scipPinnedEdgeCount( outProv ), + .multiRootCount = ing.rootLabels.size() >= 2 ? ing.rootLabels.size() : 0, + .skippedOversize = ing.skippedOversize.size() }; +} + +// The XML header's coverage attributes after the parse-honesty gauges, composed once per map. +inline std::string renderMapCoverageAttrs( const IngestResult& ing, const MapCoverageFacts& c, const MapAnnotations& ann ) { std::string attrs; - if( const std::size_t precise = scipPinnedEdgeCount( outProv ); precise > 0 ) + if( c.scipPinnedEdges > 0 ) { - attrs += " precise=" + std::to_string( precise ); // only when a SCIP overlay pinned something + attrs += " precise=" + std::to_string( c.scipPinnedEdges ); // only when a SCIP overlay pinned something } - // Multi-root workspace (A13): `roots=N` joins the header gauges and a `<root label= p=/>` prologue opens <r> — ONLY when - // N≥2 (single-root output byte-unchanged). - if( ing.rootLabels.size() >= 2 ) + // Multi-root workspace (A13): `roots=N` joins the header gauges and a `<root label= p=/>` prologue opens <r>. + if( c.multiRootCount > 0 ) { - attrs += " roots=" + std::to_string( ing.rootLabels.size() ); + attrs += " roots=" + std::to_string( c.multiRootCount ); } // D6: --map-diff's teleport-seed file count, ONLY when the caller passes changedCount (nullptr for every non-map-diff // caller ⇒ zero token cost, byte-identical golden map). A clean tree reports "changed=0" so the caller can see the @@ -3851,9 +3927,9 @@ inline std::string mapCoverageAttrs( const IngestResult& ing, const std::vector< // §P0.5d: how many otherwise-indexable files the crawl dropped for exceeding a per-file size ceiling — --max-file-size, or // (§B13.1) the .json lane's fixed 256 KB config ceiling that --max-file-size does not raise. `--max-file-size=8K` dropped // ~296 of ~759 files on this repo and files= reported the survivors as if they WERE the corpus. - if( !ing.skippedOversize.empty() ) + if( c.skippedOversize > 0 ) { - attrs += " skipped_oversize=" + std::to_string( ing.skippedOversize.size() ); + attrs += " skipped_oversize=" + std::to_string( c.skippedOversize ); } attrs += buildMemoryStopAttr( ing, false ) + buildMemoryPeakAttr( ing, false ); // #350, empty unless the memory guard stopped the ingest or the peak passed the limit attrs += buildUnindexedAttr( ing.crawlSkips ); // §L1: the LANGUAGES this build could not read at all @@ -3862,6 +3938,13 @@ inline std::string mapCoverageAttrs( const IngestResult& ing, const std::vector< // M1 — the UNTRACKED files left out of a build/ the crawl entered because git tracks files under it (model.h // CrawlSkips::untrackedBuild): absent at zero; defined in the --skipped legend (kUntrackedBuildLegend) and the compact legend. attrs += presentCountAttr( "untracked_build", ing.crawlSkips.untrackedBuildFiles ); + return attrs; +} + +// The XML header's budget attributes, right after the coverage ones: --max-tokens' asked count and the byte ceiling it became. +inline std::string mapFitAttrs( const MapAnnotations& ann ) +{ + std::string attrs; // §B13.4: --max-tokens=N asked for a TOKEN count and got a BYTE ceiling. Both numbers, on the map that was shaped by them, // so the ~10% the headroom leaves unused is a disclosed fact rather than a silent one. §F5: over_ceiling=1 rides the same // attr — a cap that can be overshot is not a cap, so where the map's fixed floor cannot fit inside fit_bytes the map states @@ -3887,13 +3970,10 @@ inline std::string mapCoverageAttrs( const IngestResult& ing, const std::vector< // unterminated comment). Composed on std::string, the margin question disappears. struct MapStatsFacts { - std::size_t files; - std::size_t symbols; // the symbols the map ranks - std::size_t edges; - std::size_t shown; // C1-b: 0 under the stub, which prints no row - const MapHonestyGauges& gauges; - std::string_view coverageAttrs; - const char* orderAttr; + const MapPlan& plan; // symbols=, shown=, the honesty gauges and order= + std::size_t files; + std::size_t edges; + std::string_view coverageAttrs; // renderMapCoverageAttrs + mapFitAttrs }; inline std::string renderMapStats( const MapStatsFacts& f, std::size_t estTokens, bool estModelled ) @@ -3905,28 +3985,29 @@ inline std::string renderMapStats( const MapStatsFacts& f, std::size_t estTokens out += key; out += std::to_string( value ); } }; + const MapHonestyGauges& g = f.plan.gauges; std::string stats = "<!-- files="; stats += std::to_string( f.files ); - stats += " symbols="; stats += std::to_string( f.symbols ); + stats += " symbols="; stats += std::to_string( f.plan.symbolCount ); stats += " edges="; stats += std::to_string( f.edges ); - stats += " shown="; stats += std::to_string( f.shown ); + stats += " shown="; stats += std::to_string( f.plan.shown ); stats += " est_tokens="; stats += std::to_string( estTokens ); if( estModelled ) { stats += " est_measured=0"; // the number beside it is the model (MapEstimate); absent ⇒ measured } - stats += " ambiguous="; stats += std::to_string( f.gauges.ambiguous ); - stats += " unresolved="; stats += std::to_string( f.gauges.unresolved ); - gauge( stats, " locality_pinned=", f.gauges.localityPinned ); - gauge( stats, " external=", f.gauges.external ); // Phase 5 - gauge( stats, " declined=", f.gauges.declined ); // tier-3 declines, after external= so no adjacency moves + stats += " ambiguous="; stats += std::to_string( g.ambiguous ); + stats += " unresolved="; stats += std::to_string( g.unresolved ); + gauge( stats, " locality_pinned=", g.localityPinned ); + gauge( stats, " external=", g.external ); // Phase 5 + gauge( stats, " declined=", g.declined ); // tier-3 declines, after external= so no adjacency moves // The parse-honesty gauges follow the call-resolution family (ambiguous= .. declined=), in this order, so declined= stays // adjacent to external= and the resolver's gauges read as one contiguous run. - gauge( stats, " extent_suspect_syms=", f.gauges.extentSuspectSyms ); - gauge( stats, " macro_blanked_files=", f.gauges.macroBlankedFiles ); - gauge( stats, " nest_refused=", f.gauges.nestRefusedFiles ); // #157: last of the parse-honesty gauges + gauge( stats, " extent_suspect_syms=", g.extentSuspectSyms ); + gauge( stats, " macro_blanked_files=", g.macroBlankedFiles ); + gauge( stats, " nest_refused=", g.nestRefusedFiles ); // #157: last of the parse-honesty gauges stats += f.coverageAttrs; - stats += " order="; stats += f.orderAttr; + stats += " order="; stats += emitOrderTraits( f.plan.emitOrder ).orderAttr; stats += " -->"; return stats; } @@ -3963,14 +4044,13 @@ struct MapRootFacts { const MapAnnotations& ann; std::string_view rootArg; - bool stable; - const DataSectionsCut& dataSecCut; - std::size_t stemCut; + const MapPlan& plan; // the byte-stable prefix (emit order), data_sections_cut= and stem_cut= }; inline std::string renderMapRootTag( const MapRootFacts& r, std::size_t estTokens, bool estModelled, std::vector<char>& esc ) { - const MapAnnotations& ann = r.ann; + const MapAnnotations& ann = r.ann; + const bool stablePrefix = emitOrderTraits( r.plan.emitOrder ).stablePrefix; // r26-stamp Task A: ` at="..."` ONLY when the caller passed a non-empty stamp (--map-diff); every other caller passes // nullptr, so the hot default-map path pays a pointer compare, not a git call. at= stays FIRST — the `<r at="<sha>` byte // sequence gitstampcheck.sh pins is unchanged. @@ -3989,8 +4069,8 @@ inline std::string renderMapRootTag( const MapRootFacts& r, std::size_t estToken // budget-aware caller most needs was unreachable from the comment alone. The SAME `estTokens` value (one estimator). // --stable omits it on the precedent of the k= rank attribute: --stable buys a byte-stable PREFIX, the root element is // that prefix, and est_tokens is globally volatile. - if( !r.stable ) { char estAttr[ 40 ]; rw::formatTo( estAttr, sizeof( estAttr ), " est_tokens=\"{}\"", estTokens ); h += estAttr; } - if( !r.stable && estModelled ) { h += " est_measured=\"0\""; } // beside the number it qualifies (MapEstimate) + if( !stablePrefix ) { char estAttr[ 40 ]; rw::formatTo( estAttr, sizeof( estAttr ), " est_tokens=\"{}\"", estTokens ); h += estAttr; } + if( !stablePrefix && estModelled ) { h += " est_measured=\"0\""; } // beside the number it qualifies (MapEstimate) // W2-F: LAST on the root, after est_tokens — the same placement rule counts_floor= follows, so no existing // attribute-ADJACENCY assertion in test/ can break on it. NOT suppressed under --stable: the iteration count is a property // of the CORPUS and the ranker, not of the run's size, and a byte-stable prefix that hides "this ranking is unfinished" @@ -4000,20 +4080,20 @@ inline std::string renderMapRootTag( const MapRootFacts& r, std::size_t estToken // `analyze` call gets) saw rows with no rank attribute and nothing saying the score exists elsewhere. lens= names what is // missing, so "absent" reads as "not served here", never as "not computed". Gate: test/mcpattrparitycheck.sh, whose lens= // arm also fails on a stale name. - if( r.stable ) { h += " lens=\"k,est_tokens\""; } + if( stablePrefix ) { h += " lens=\"k,est_tokens\""; } // L3 follow-up (CodeRabbit 4053600616): TRULY last, past every pre-existing attribute — same placement rule as lens= just // above, so no attribute-adjacency assertion in test/ can break on it. if( ann.notesDegraded ) { h += notes::kNotesDegradedAttr; } h += renderHistoryUnread( DiscloseAs::XmlAttrs ); // K51: absent unless the amp=/churn= walk could not be read // The code-first pick's swaps, last of all (the same placement rule as the two above): absent when nothing was swapped. - if( r.dataSecCut.cut > 0 ) + if( const DataSectionsCut& cut = r.plan.ranked.dataSecCut; cut.cut > 0 ) { - h += " data_sections_cut=\""; h += std::to_string( r.dataSecCut.cut ); h += "\""; - h += nextAttrXml( dataSectionsNext( r.dataSecCut ) ); + h += " data_sections_cut=\""; h += std::to_string( cut.cut ); h += "\""; + h += nextAttrXml( dataSectionsNext( cut ) ); } - if( r.stemCut > 0 ) + if( const std::size_t stemCut = r.plan.groups.stemPick.cut; stemCut > 0 ) { - h += " stem_cut=\""; h += std::to_string( r.stemCut ); h += "\""; // MAP-STEM: absent unless a --max-tokens fit left stem rows out + h += " stem_cut=\""; h += std::to_string( stemCut ); h += "\""; // MAP-STEM: absent unless a --max-tokens fit left stem rows out } h += ">"; // K51: history_unread='s definition rides the leading legend (HISTORY-UNREAD-LEGEND), not behind this tag return h; @@ -4025,7 +4105,7 @@ inline std::string renderMapRootTag( const MapRootFacts& r, std::size_t estToken // the disclosed locality pin (Phase 4). The cursor is the OUT POINTER, never a would-have-written length: lpin= is written AT // the offset the first write ended, so a count an implementation computed rather than wrote would place it inside the // half-written amb= attribute. Same defect class as BoundedAttrRun below. -inline std::string rowGuessAttrs( const MapRowSources& src, NodeId id ) +inline std::string rowResolverGuessAttrs( const MapRowSources& src, NodeId id ) { char ambs[ 48 ]; ambs[ 0 ] = '\0'; char* ap = ambs; @@ -4043,12 +4123,12 @@ inline std::string rowGuessAttrs( const MapRowSources& src, NodeId id ) return ambs; } -// PageRank k= is GLOBALLY volatile (any edit perturbs every rank) → omitted in --stable mode so the prefix stays byte-identical -// for unedited files (provider KV-cache hits). Default keeps k=. +// PageRank k= is GLOBALLY volatile (any edit perturbs every rank) → omitted on --stable's byte-stable prefix so the prefix stays +// byte-identical for unedited files (provider KV-cache hits). Default keeps k=. inline std::string rowRankAttr( const MapRowSources& src, NodeId id ) { char kbuf[ 24 ]; kbuf[ 0 ] = '\0'; - if( !src.stable ) + if( !emitOrderTraits( src.emitOrder ).stablePrefix ) { rw::formatTo( kbuf, sizeof( kbuf ), " k=\"{:.4f}\"", double( src.rank[ id ] ) ); } @@ -4162,27 +4242,24 @@ inline void appendQMetricAttrs( BoundedAttrRun& run, const Symbol& s, NodeId id, } } -// The row's descriptive attributes as ONE run after its identity attributes: under --metrics with fan-in, in=/out=/cx=/ccx=, -// role="hub" at fan-in ≥ 8 and the Q-compute run first; then amb=/lpin= and k=. Composed in one fixed buffer, as always, so a -// run past its width truncates at the byte it always did. -inline std::string rowDescriptiveAttrs( const Symbol& s, NodeId id, const MapRowSources& src ) +// The row's --metrics run (only with fan-in): in=/out=/cx=/ccx=, role="hub" at fan-in ≥ 8, then the Q-compute run. +// EQUIVALENCE (GE-SERIALIZE round 2): this run, amb=/lpin= and k= used to share one attr[352] buffer, so a run past its width +// would have truncated across all three. None ever did: the widest is 26 B of literal + 4 × 10 digits + 11 B role + the +// BoundedAttrRun's 191 + amb=/lpin=' 35 + k=' 23 = 326 B < 351 (test/fixedbufsweep.sh's attr row), so writing the three as +// separate writes is byte-identical — and this buffer alone now has 83 B of headroom. +inline std::string rowMetricsAttrs( const Symbol& s, NodeId id, const MapRowSources& src ) { - const std::uint32_t outDegree = src.outOff[ id + 1 ] - src.outOff[ id ]; - const std::string guesses = rowGuessAttrs( src, id ); - const std::string rankAttr = rowRankAttr( src, id ); - char attr[ 352 ]; - if( src.metrics && src.fanIn ) + if( !src.metrics || !src.fanIn ) { - BoundedAttrRun qmetrics; - appendQMetricAttrs( qmetrics, s, id, src ); - const std::uint32_t in = ( id < src.fanIn->size() ) ? ( *src.fanIn )[ id ] : 0u; - rw::formatTo( attr, sizeof( attr ), " in=\"{}\" out=\"{}\" cx=\"{}\" ccx=\"{}\"{}{}{}{}", - in, outDegree, s.cx, s.ccx, ( in >= 8 ? " role=\"hub\"" : "" ), qmetrics.c_str(), guesses, rankAttr ); - } - else - { - rw::formatTo( attr, sizeof( attr ), "{}{}", guesses, rankAttr ); + return {}; } + BoundedAttrRun qmetrics; + appendQMetricAttrs( qmetrics, s, id, src ); + const std::uint32_t in = ( id < src.fanIn->size() ) ? ( *src.fanIn )[ id ] : 0u; + const std::uint32_t outDegree = src.outOff[ id + 1 ] - src.outOff[ id ]; + char attr[ 352 ]; + rw::formatTo( attr, sizeof( attr ), " in=\"{}\" out=\"{}\" cx=\"{}\" ccx=\"{}\"{}{}", + in, outDegree, s.cx, s.ccx, ( in >= 8 ? " role=\"hub\"" : "" ), qmetrics.c_str() ); return attr; } @@ -4227,7 +4304,9 @@ inline void writeMapSymbolRow( XmlWriter& w, const IngestResult& ing, const Over { w.write( " bind=\"" ); w.write( escapeXml( label, esc ) ); w.write( "\"" ); } - w.write( rowDescriptiveAttrs( s, id, src ) ); + w.write( rowMetricsAttrs( s, id, src ) ); // --metrics: in=/out=/cx=/ccx=/role= and the Q-compute run + w.write( rowResolverGuessAttrs( src, id ) ); // amb= / lpin=, each absent at 0 + w.write( rowRankAttr( src, id ) ); // k=, absent on --stable's byte-stable prefix // EXTENT HONESTY (kExtentSuspectRowLegend): the containment checks this row's extent/scope/kind failed. After k= so every // pre-existing adjacency holds; absent when every check held (clean corpora unchanged). if( s.extentSuspect != 0 ) @@ -4296,17 +4375,19 @@ inline void writeSymbolMapStub( XmlWriter& w, std::size_t keep, std::string_view // <r>'s children, as ONE renderer serialize()'s measured path and its degrade path both call: the multi-root prologue, F3's // recent files (rank_by=churn-decay's file-level answer, before the symbol map), the stub or the <f> groups, and the D7 // inventory tier. The inventory rides the LOW-importance end of the document — after the rows, or before them when the map -// is emitted important-last, so the top-ranked rows keep the end position that order promises. +// is emitted important-last, so the top-ranked rows keep the end position that order promises. That placement is the XML +// document's own: <r>'s children are a sequence a reader meets in order, while the JSON map's "inv" is a key of one object, +// where a position carries nothing — so it stays here rather than in MapPlan (moving it would also move JSON bytes). template <class PathRel> -inline void writeMapChildren( XmlWriter& w, const IngestResult& ing, const MapAnnotations& ann, std::size_t keep, const MapFileGroups& groups, - MapEmitOrder emitOrder, const MapRowSources& src, const PathRel& pathRel, std::vector<char>& esc, - std::vector<std::uint32_t>& scratch ) +inline void writeMapChildren( XmlWriter& w, const IngestResult& ing, const MapAnnotations& ann, const MapPlan& plan, const MapRowSources& src, + const PathRel& pathRel, std::vector<char>& esc, std::vector<std::uint32_t>& scratch ) { + const MapFileGroups& groups = plan.groups; writeRootLabelRows( w, ing, esc ); // A13: the multi-root prologue writeRecentRows( w, ann, pathRel, esc ); - if( ann.stubSymbols ) + if( plan.stubbed ) { - writeSymbolMapStub( w, keep, ann.stubNext ); + writeSymbolMapStub( w, plan.keep, ann.stubNext ); } const auto writeInventory = [ & ]() { @@ -4315,7 +4396,7 @@ inline void writeMapChildren( XmlWriter& w, const IngestResult& ing, const MapAn writeMapInventoryXml( w, ing, groups.inventory, pathRel, src.outOff, src.outTargets, src.outProv, src.outNameOnly, esc, scratch ); } }; - const bool inventoryFirst = traitsOf( emitOrder ).importantLast; // --stable's path order wins, as it does for the rows + const bool inventoryFirst = emitOrderTraits( plan.emitOrder ).importantLast; // --stable's path order wins, as it does for the rows if( inventoryFirst ) { writeInventory(); @@ -4443,41 +4524,29 @@ inline void serialize( std::FILE* out, const IngestResult& ing, const std::vecto return rootArg.empty() ? std::string_view( ing.files[ fileId ] ) : rw::sarif::rootRelativeUri( ing.files[ fileId ], rootPrefix ); }; - // ── WHICH rows, in WHICH order ────────────────────────────────────────────────────────────────────────────────── - const bool stubbed = ann.stubSymbols; // C1-b: in=DIR's stub prints no symbol row - const std::size_t keep = mapKeepCount( ing, topK ); - const RankedMapRows ranked = rankMapRows( ing, rank, ann, keep, stubbed ); - const std::span<const NodeId> kept = ranked.kept( keep ); - // T1/§H7: the byte MODEL. It decides the T3 emit order (which has to be decided before any byte exists — see §H7 at - // estimateTokens) and supplies the language-weighted bytes/token RATE, the half of it that is actually measured. It no - // longer REPORTS the size: est_tokens is computed from the document's emitted bytes in PHASE 2 below, because a model of - // the symbol set cannot see --metrics decoration or an appended payload. C1-b: under the stub the estimate is taken over - // no rows, since the document contains none. - const TokenEstimate mapEst = estimateTokens( ing, ranked.order, kept.size(), outOff, outTargets ); - const MapEmitOrder emitOrder = decideMapEmitOrder( stable, mostImportantLast, autoOrder, mapEst.tokens ); - const MapFileGroups groups = groupMapRowsByFile( ing, ann, kept, stubbed, emitOrder, outOff, outTargets, pathRel ); - const MapHonestyGauges gauges = countMapHonestyGauges( ing, MapResolverCounters{ .ambOut = ambOut, .unresolvedOut = unresolvedOut, .locPinOut = locPinOut, - .declinedOut = declinedOut, .externalCalls = externalCalls, - .gateDeclinedCalls = gateDeclinedCalls, - .stdMemberDeclined = stdMemberDeclinedCalls, - .inertDeclinedCalls = inertDeclinedCalls } ); - ASSUME( !stubbed || ( kept.empty() && groups.fileOrder.empty() && groups.inventory.entries.empty() ), - "the stub ranks and groups no row, so no kept-row legend clause and no <f> group can fire under it" ); + // ── WHICH rows, in WHICH order: the plan both dialects share; the XML map honours in=DIR's stub ───────────────────── + const MapPlan plan = planMap( ing, rank, outOff, outTargets, ann, topK, + MapOrderRequest{ .stable = stable, .mostImportantLast = mostImportantLast, .autoOrder = autoOrder }, + MapResolverCounters{ .ambOut = ambOut, .unresolvedOut = unresolvedOut, .locPinOut = locPinOut, + .declinedOut = declinedOut, .externalCalls = externalCalls, + .gateDeclinedCalls = gateDeclinedCalls, .stdMemberDeclined = stdMemberDeclinedCalls, + .inertDeclinedCalls = inertDeclinedCalls }, + MapStubPolicy::HonourAnnotation, pathRel ); std::vector<char> esc; // ── the legend, clause group by clause group, in the order the reader meets them ────────────────────────────── std::string legend = mapOpeningLegend( outProv != nullptr ); legend += moduleScopeLegend( ing ); - legend += keptImplEdgeLegend( outOff, outProv, kept, groups.inventory.entries ); + legend += keptImplEdgeLegend( outOff, outProv, plan.kept(), plan.groups.inventory.entries ); legend += typeKindLegend( ing ); - legend += gaugeLegend( gauges, kParseHonestyClauses ); + legend += gaugeLegend( plan.gauges, kParseHonestyClauses ); legend += runAnnotationLegend( ing, ann, rootArg, metrics ); - legend += rowSelectionLegend( ranked.dataSecCut, groups ); + legend += rowSelectionLegend( plan.ranked.dataSecCut, plan.groups ); // W2-F: the pr_iters= / pr_converged= definition, charged to the maps that carry the attributes — empty for a lexical or // HITS ordering, and the prose half only on the map whose iteration stopped short. legend += renderDisclosure( ann.prDisclosure, DiscloseAs::LegendComment ); - legend += gaugeLegend( gauges, kDeclineClauses ); - legend += keptNameEdgeLegend( outOff, outNameOnly, kept, ann.viaLegendStripped ); + legend += gaugeLegend( plan.gauges, kDeclineClauses ); + legend += keptNameEdgeLegend( outOff, outNameOnly, plan.kept(), ann.viaLegendStripped ); // K51: history_unread='s definition, the LAST leading clause, so it stands right before the <r> root it marks and inside the // leading block every reader (and legendcoveragecheck's full rows) meets first; absent unless the amp=/churn= walk was unread. legend += renderHistoryUnread( DiscloseAs::LegendComment ); @@ -4488,12 +4557,10 @@ inline void serialize( std::FILE* out, const IngestResult& ing, const std::vecto // the identical reason. Pure functions of estTokens, the values decided above and the estimate sink's state. // --stable: the volatile counts move to a TRAILING comment (out of the cacheable prefix) — unless the caller asked for the // first-screen placement (§B6 M10, the MCP analyze verb). Exactly one of the two builders emits the stats. - const bool statsTrail = stable && !statsFirstScreen; - const std::string coverageAttrs = mapCoverageAttrs( ing, outProv, ann ); - const MapStatsFacts statsFacts{ .files = ing.files.size(), .symbols = mapSymbolCount( ing ), .edges = outTargets.size(), - .shown = stubbed ? std::size_t( 0 ) : keep + groups.stemPick.rows.size(), - .gauges = gauges, .coverageAttrs = coverageAttrs, .orderAttr = traitsOf( emitOrder ).orderAttr }; - const MapRootFacts rootFacts{ .ann = ann, .rootArg = rootArg, .stable = stable, .dataSecCut = ranked.dataSecCut, .stemCut = groups.stemPick.cut }; + const bool statsTrail = emitOrderTraits( plan.emitOrder ).stablePrefix && !statsFirstScreen; + const std::string coverageAttrs = renderMapCoverageAttrs( ing, mapCoverageFacts( ing, outProv ), ann ) + mapFitAttrs( ann ); + const MapStatsFacts statsFacts{ .plan = plan, .files = ing.files.size(), .edges = outTargets.size(), .coverageAttrs = coverageAttrs }; + const MapRootFacts rootFacts{ .ann = ann, .rootArg = rootArg, .plan = plan }; MapEstimate estimate{ ann.payloadUncharged }; // the est_tokens measurement's DISCLOSE sink — read by the builders const auto buildHead = [ & ]( std::size_t estTokens ) -> std::string { @@ -4520,18 +4587,18 @@ inline void serialize( std::FILE* out, const IngestResult& ing, const std::vecto // measure, decide, then write (the order --recall's emitRecallBudgeted and the --for lens's pre-rendered sigs block // already impose on themselves). const MapRowSources rowSources{ .rank = rank, .outOff = outOff, .outTargets = outTargets, .outProv = outProv, .outNameOnly = outNameOnly, - .ambOut = ambOut, .locPinOut = locPinOut, .bind = bind, .stable = stable, .metrics = metrics, + .ambOut = ambOut, .locPinOut = locPinOut, .bind = bind, .emitOrder = plan.emitOrder, .metrics = metrics, .fanIn = fanIn, .cbo = cbo, .tested = tested, .lcom4 = lcom4, .amp = amp }; std::vector<std::uint32_t> hedgedScratch; // FE-B: writeMapCalleeRows' reused buffer const auto writeChildren = [ & ]( XmlWriter& w ) { - writeMapChildren( w, ing, ann, keep, groups, emitOrder, rowSources, pathRel, esc, hedgedScratch ); + writeMapChildren( w, ing, ann, plan, rowSources, pathRel, esc, hedgedScratch ); }; // DEGRADE, one path for both failures (a buffer that did not open, or one that opened and then lost a write — by then the // children were already spent into it, so they are rendered again): the head goes out FIRST carrying the MODELLED estimate // (the pre-§H7 number, so no worse than the old behaviour and never a fabricated one), the children stream straight to // `out` behind it, then the trailing summary. The whole map, uncharged. - const std::size_t modelledTokens = mapEst.tokens + extraPayloadTokens; + const std::size_t modelledTokens = plan.mapEst.tokens + extraPayloadTokens; const auto emitModelled = [ & ]() { XmlWriter direct( out ); @@ -4571,7 +4638,7 @@ inline void serialize( std::FILE* out, const IngestResult& ing, const std::vecto return; } const std::string_view childrenStr = children.bytes; // owned by childStream, alive to the end of this function - const SettledHeadTail settled = settleEstTokens( modelledTokens, childrenStr.size(), mapEst.bytesPerToken(), extraPayloadTokens, buildHead, buildTail ); + const SettledHeadTail settled = settleEstTokens( modelledTokens, childrenStr.size(), plan.mapEst.bytesPerToken(), extraPayloadTokens, buildHead, buildTail ); if( outEstTokens ) { *outEstTokens = settled.estTokens; // --token-budget reads THIS value — never a second counter @@ -11710,35 +11777,24 @@ inline void writeJsonQMetrics( JsonWriter& w, const JsonQMetrics& q ) } // The default map's JSON header — the gauge block plus the two prologues that ride on it, in one place so -// "which gauge, in which order, on which condition" is stated once rather than smeared through the emitter. -// The XML sibling states the same set through its `stats` snprintf + the <root> prologue in serialize(). +// "which gauge, in which order, on which condition" is stated once rather than smeared through the emitter. Its counts are the +// plan's and the coverage facts' — the same values the XML header spells (renderMapStats, renderMapCoverageAttrs, +// renderMapRootTag), never a second count. struct JsonMapHeader { - const IngestResult& ing; - std::size_t symbolCount; - std::size_t edgeCount; - std::size_t shownCount; - std::size_t estTokens; - std::size_t ambiguousCount; - std::size_t unresolvedCount; - const char* orderAttr; - const std::vector<std::uint8_t>* outProv; // nullptr ⇒ no precise= (nothing was measured) - const MapAnnotations* ann; // §B1.2: how THIS map was produced — the same at/rank_by/window - // stamp the XML `<r>` element carries. nullptr ⇒ no stamp emitted. - std::string_view rootArg; // R-E: the JSON twin of the XML `<r root="…">` — empty for - // multi-root (its own roots_count/roots table below already - // names every root) or a caller that never passes one. - std::size_t localityPinnedCount = 0; // Phase 4: Σ lpin — "locality_pinned":N, absent when 0 - std::size_t externalCount = 0; // Phase 5: the veto's refusals — "external":N, absent when 0 - std::size_t declinedCount = 0; // tier 3's declines — "declined":N, absent when 0 - std::size_t extentSuspectCount = 0; // extent honesty: "extent_suspect_syms":N, absent when 0 - std::size_t macroBlankedCount = 0; // member-macro re-parse: "macro_blanked_files":N, absent when 0 - std::size_t nestRefusedCount = 0; // #157: "nest_refused":N, the JSON twin of the XML nest_refused=, absent when 0 - bool isEstModelled = false; // MapEstimate: "est_measured":false, absent when measured - DataSectionsCut dataSectionsCut = {}; // the code-first pick's swaps: "data_sections_cut":N + "next", absent at N=0 - std::size_t stemCut = 0; // MAP-STEM: "stem_cut":N, the XML stem_cut=, absent at N=0 - std::string_view memoryPeakJson = {}; // buildMemoryPeakAttr( ing, true ), read ONCE per serializeJson call (the - // peak reading only rises and the seam counts calls); kept last, the struct is filled positionally + const IngestResult& ing; + const MapPlan& plan; // symbols, shown, the honesty gauges, order, data_sections_cut, stem_cut + const MapCoverageFacts& coverage; // precise, skipped_oversize, roots_count + std::size_t edgeCount; + std::size_t estTokens; + bool isEstModelled; // MapEstimate: "est_measured":false, absent when measured + const MapAnnotations& ann; // §B1.2: how THIS map was produced — the same at/rank_by/window stamp the XML `<r>` + // element carries + std::string_view rootArg; // R-E: the JSON twin of the XML `<r root="…">` — empty for multi-root (its own + // roots_count/roots table below already names every root) or a caller that never + // passes one. + std::string_view memoryPeakJson; // buildMemoryPeakAttr( ing, true ), read ONCE per serializeJson call (the peak + // reading only rises and the seam counts calls) }; // §B1.2: the PROVENANCE stamp — the JSON half of the XML `<r at= rank_by= window=>` attributes. Without it @@ -11748,13 +11804,8 @@ struct JsonMapHeader // Same absent-unless-produced rule as the XML: a default map passes no annotations ⇒ zero bytes, byte- // identical output. `changed` (--map-diff) has no arm here on purpose — see the coverage note above // serializeJson: jsonUnsupportedVerb refuses --map-diff before this emitter is ever reached. -inline void writeJsonMapStamp( JsonWriter& w, std::string& esc, const MapAnnotations* ann ) +inline void writeJsonMapStamp( JsonWriter& w, std::string& esc, const MapAnnotations& ann ) { - if( !ann ) - { - return; - } - // §B12.6 (CA4): `at`'s ABSENCE had two meanings inside one dialect. Five JSON emitters (quality-delta, // test-gate, cochange, plan-lanes, the MCP quality_delta twin) write `"at":null` when the root has no // HEAD to anchor to — "we tried, there is nothing" — while this one OMITTED the key in the same state, @@ -11767,32 +11818,32 @@ inline void writeJsonMapStamp( JsonWriter& w, std::string& esc, const MapAnnotat // no churn ranking) emits no key, which is also what the XML does, so the 1:1 attr/key correspondence // holds in every state. The windowless rank_by= stamps (authority/hub/rrf) attempt no anchor and are // deliberately outside the predicate, exactly as they are on the XML side. - const bool didAttemptAtStamp = ( ann->changedCount != nullptr ) || ( ann->churnWindow != nullptr ); + const bool didAttemptAtStamp = ( ann.changedCount != nullptr ) || ( ann.churnWindow != nullptr ); if( didAttemptAtStamp ) { w.write( ",\"at\":" ); - if( ann->atStamp != nullptr && !ann->atStamp->empty() ) + if( ann.atStamp != nullptr && !ann.atStamp->empty() ) { - writeJsonStr( w, *ann->atStamp, esc ); + writeJsonStr( w, *ann.atStamp, esc ); } else { w.write( "null" ); } } - if( ann->churnWindow != nullptr ) + if( ann.churnWindow != nullptr ) { w.write( ",\"rank_by\":" ); // P0-4: which churn ranker — "churn" or "churn-decay" - writeJsonStr( w, ann->churnRankLabel, esc ); + writeJsonStr( w, ann.churnRankLabel, esc ); w.write( ",\"window\":" ); - writeJsonStr( w, *ann->churnWindow, esc ); + writeJsonStr( w, *ann.churnWindow, esc ); } // §B2.1: authority/hub/rrf carry no window, so they stamp rank_by alone — the JSON half of the XML arm // above, symmetric with it, so the two dialects still cannot disagree about how a map was produced. - else if( ann->rankByLabel != nullptr ) + else if( ann.rankByLabel != nullptr ) { w.write( ",\"rank_by\":" ); - writeJsonStr( w, std::string_view( ann->rankByLabel ), esc ); + writeJsonStr( w, std::string_view( ann.rankByLabel ), esc ); } // §C4 — the --max-tokens fit, in the dialect that was missing it. `--max-tokens=N --json` shaped the map and @@ -11809,13 +11860,13 @@ inline void writeJsonMapStamp( JsonWriter& w, std::string& esc, const MapAnnotat // without naming the dialect it was measured against would replace one silence with a false implication. // The XML needs no such key because the XML is the measured dialect. Fixing the SEARCH to measure the // emitted dialect is a main.cpp change and is recorded as a residual, not smuggled in here. - if( ann->maxTokensFit != nullptr ) + if( ann.maxTokensFit != nullptr ) { char fit[ 160 ]; rw::formatTo( fit, sizeof( fit ), ",\"max_tokens\":{},\"fit_bytes\":{},\"fit_measured_in\":\"xml\"{}{}", - ann->maxTokensFit->askedTokens, ann->maxTokensFit->ceilingBytes, - ann->maxTokensFit->isOverCeiling || ann->maxTokensFit->isUnmeasured ? ",\"over_ceiling\":true" : "", - ann->maxTokensFit->isUnmeasured ? ",\"fit_unmeasured\":true" : "" ); + ann.maxTokensFit->askedTokens, ann.maxTokensFit->ceilingBytes, + ann.maxTokensFit->isOverCeiling || ann.maxTokensFit->isUnmeasured ? ",\"over_ceiling\":true" : "", + ann.maxTokensFit->isUnmeasured ? ",\"fit_unmeasured\":true" : "" ); w.write( fit ); } } @@ -11861,55 +11912,56 @@ inline void writeJsonUnindexed( JsonWriter& w, std::string& esc, const CrawlSkip inline void writeJsonMapHeader( JsonWriter& w, std::string& esc, const JsonMapHeader& h ) { + const MapHonestyGauges& g = h.plan.gauges; char hdr[ 256 ]; // the gauge line has 7 size_t fields — wider than the per-symbol scratch rw::formatTo( hdr, sizeof( hdr ), "{{\"files\":{},\"symbols\":{},\"edges\":{},\"shown\":{},\"est_tokens\":{},\"ambiguous\":{},\"unresolved\":{},", - h.ing.files.size(), h.symbolCount, h.edgeCount, h.shownCount, h.estTokens, h.ambiguousCount, h.unresolvedCount ); + h.ing.files.size(), h.plan.symbolCount, h.edgeCount, h.plan.shown, h.estTokens, g.ambiguous, g.unresolved ); w.write( hdr ); if( h.isEstModelled ) { w.write( "\"est_measured\":false," ); // the XML est_measured="0" twin: est_tokens above is the model } // Phase 4: the S6-C locality-pin gauge — same absent-when-zero rule as the XML `locality_pinned=`. - if( h.localityPinnedCount > 0 ) + if( g.localityPinned > 0 ) { - rw::formatTo( hdr, sizeof( hdr ), "\"locality_pinned\":{},", h.localityPinnedCount ); + rw::formatTo( hdr, sizeof( hdr ), "\"locality_pinned\":{},", g.localityPinned ); w.write( hdr ); } // Phase 5: the external-name veto gauge — the JSON twin of the XML `external=`, same absent-when-zero rule. - if( h.externalCount > 0 ) + if( g.external > 0 ) { - rw::formatTo( hdr, sizeof( hdr ), "\"external\":{},", h.externalCount ); + rw::formatTo( hdr, sizeof( hdr ), "\"external\":{},", g.external ); w.write( hdr ); } // tier 3's declines — the JSON twin of the XML `declined=`, same absent-when-zero rule. - if( h.declinedCount > 0 ) + if( g.declined > 0 ) { - rw::formatTo( hdr, sizeof( hdr ), "\"declined\":{},", h.declinedCount ); + rw::formatTo( hdr, sizeof( hdr ), "\"declined\":{},", g.declined ); w.write( hdr ); } // extent honesty: the JSON twin of the XML header's extent_suspect_syms=, same absent-when-zero rule and the // XML header's order (after the call-resolution family, declined included). - if( h.extentSuspectCount > 0 ) + if( g.extentSuspectSyms > 0 ) { - w.write( "\"extent_suspect_syms\":" + std::to_string( h.extentSuspectCount ) + "," ); // composed, not a fixed buffer + w.write( "\"extent_suspect_syms\":" + std::to_string( g.extentSuspectSyms ) + "," ); // composed, not a fixed buffer } // member-macro re-parse: the JSON twin of the XML header's macro_blanked_files=, same absent-when-zero rule. - if( h.macroBlankedCount > 0 ) + if( g.macroBlankedFiles > 0 ) { - w.write( "\"macro_blanked_files\":" + std::to_string( h.macroBlankedCount ) + "," ); + w.write( "\"macro_blanked_files\":" + std::to_string( g.macroBlankedFiles ) + "," ); } // #157: the JSON twin of the XML header's nest_refused=, same absent-when-zero rule. - if( h.nestRefusedCount > 0 ) + if( g.nestRefusedFiles > 0 ) { - w.write( "\"nest_refused\":" + std::to_string( h.nestRefusedCount ) + "," ); + w.write( "\"nest_refused\":" + std::to_string( g.nestRefusedFiles ) + "," ); } // §P0.5d, JSON lane: the size-ceiling disclosure must reach --json consumers too — the XML header // gained skipped_oversize= and a JSON reader (MCP clients most of all) must not be the one audience // still shown the survivors as if they were the corpus. Same absent-when-zero rule as the XML side. - if( !h.ing.skippedOversize.empty() ) + if( h.coverage.skippedOversize > 0 ) { - rw::formatTo( hdr, sizeof( hdr ), "\"skipped_oversize\":{},", h.ing.skippedOversize.size() ); + rw::formatTo( hdr, sizeof( hdr ), "\"skipped_oversize\":{},", h.coverage.skippedOversize ); w.write( hdr ); } w.write( buildMemoryStopAttr( h.ing, true ) ); // #350, JSON lane: empty unless the memory guard stopped the ingest @@ -11930,25 +11982,16 @@ inline void writeJsonMapHeader( JsonWriter& w, std::string& esc, const JsonMapHe } writeJsonUnindexed( w, esc, h.ing.crawlSkips ); // §L1, JSON lane — see its own header - // §A4d: `precise=N` — how many out-edges the SCIP overlay actually pinned. C1 drift fix, the JSON half of - // the XML fix above and by the same argument: this counted every NONZERO provenance value, so an FFI - // binding (2) and now a k-way split arm (3) were both reported as SCIP-precise. Emitted only when the - // count is non-zero (absent ⇒ nothing was pinned, never a fabricated 0 nor a borrowed one). - if( h.outProv ) + // §A4d: `precise=N` — how many out-edges the SCIP overlay actually pinned: the ONE count both dialects state + // (scipPinnedEdgeCount, whose C1 drift note says why it names value 1 alone). Absent at 0 — nothing was pinned, never a + // fabricated 0 nor a borrowed one. + if( h.coverage.scipPinnedEdges > 0 ) { - std::size_t preciseTotal = 0; - for( std::uint8_t v : *h.outProv ) - { - preciseTotal += ( v == 1u ? 1u : 0u ); - } - if( preciseTotal > 0 ) - { - rw::formatTo( hdr, sizeof( hdr ), "\"precise\":{},", preciseTotal ); - w.write( hdr ); - } + rw::formatTo( hdr, sizeof( hdr ), "\"precise\":{},", h.coverage.scipPinnedEdges ); + w.write( hdr ); } w.write( "\"order\":" ); - writeJsonStr( w, h.orderAttr, esc ); + writeJsonStr( w, emitOrderTraits( h.plan.emitOrder ).orderAttr, esc ); // R-E (2026-08-17 harvest): the JSON twin of the XML `<r root="…">` — same condition (single-root only, // multi-root's own roots_count/roots table below already names every root), right after order= like the @@ -11965,29 +12008,29 @@ inline void writeJsonMapHeader( JsonWriter& w, std::string& esc, const JsonMapHe // headers carry the SAME KEYSET for the same run, so this is not an XML-side courtesy — a JSON consumer // (every MCP client) reading a truncated ranking with no key to tell it so is the exact defect the XML // side just closed. Same slot, same absent-means-converged rule. - w.write( renderDisclosure( h.ann->prDisclosure, DiscloseAs::JsonKeys ) ); + w.write( renderDisclosure( h.ann.prDisclosure, DiscloseAs::JsonKeys ) ); w.write( renderHistoryUnread( DiscloseAs::JsonKeys ) ); // K51: the JSON twin of the root's history_unread= (absent unless the amp= walk was unread) // The JSON twin of the XML root's data_sections_cut= / next= (codeFirstKeep): same keys, same absent-at-zero rule. - if( h.dataSectionsCut.cut > 0 ) + if( const DataSectionsCut& cut = h.plan.ranked.dataSecCut; cut.cut > 0 ) { - w.write( ",\"data_sections_cut\":" + std::to_string( h.dataSectionsCut.cut ) + ",\"next\":" ); // composed, not a fixed buffer - writeJsonStr( w, dataSectionsNext( h.dataSectionsCut ), esc ); + w.write( ",\"data_sections_cut\":" + std::to_string( cut.cut ) + ",\"next\":" ); // composed, not a fixed buffer + writeJsonStr( w, dataSectionsNext( cut ), esc ); } - if( h.stemCut > 0 ) + if( const std::size_t stemCut = h.plan.groups.stemPick.cut; stemCut > 0 ) { - w.write( ",\"stem_cut\":" + std::to_string( h.stemCut ) ); // the JSON twin of the XML root's stem_cut= + w.write( ",\"stem_cut\":" + std::to_string( stemCut ) ); // the JSON twin of the XML root's stem_cut= } // §A4b: the multi-root prologue (A13) — `roots_count` joins the header gauges and a // `roots` table maps each label to its root path, ONLY when N≥2 (single-root output byte-unchanged). // Without it every `"p"` in the payload is an unresolvable root-relative fragment. - if( h.ing.rootLabels.size() < 2 ) + if( h.coverage.multiRootCount == 0 ) { return; } - rw::formatTo( hdr, sizeof( hdr ), ",\"roots_count\":{},\"roots\":[", h.ing.rootLabels.size() ); + rw::formatTo( hdr, sizeof( hdr ), ",\"roots_count\":{},\"roots\":[", h.coverage.multiRootCount ); w.write( hdr ); for( std::size_t r = 0; r < h.ing.rootLabels.size(); ++r ) { @@ -12107,7 +12150,7 @@ inline void writeJsonMapRow( JsonWriter& w, const IngestResult& ing, const Overl { w.write( ",\"extent_suspect\":" ); writeJsonStr( w, extent::extentSuspectReasons( s.extentSuspect ), esc ); } - if( !src.stable ) + if( !emitOrderTraits( src.emitOrder ).stablePrefix ) { rw::formatTo( num, sizeof( num ), ",\"k\":{:.4f}", double( src.rank[ id ] ) ); w.write( num ); } @@ -12143,8 +12186,8 @@ inline void writeJsonMapFileGroup( JsonWriter& w, const IngestResult& ing, std:: w.write( "]}" ); } -// The default-map JSON sibling of serialize(). It shares serialize()'s decisions about WHAT the map prints — mapKeepCount, -// rankMapRows, decideMapEmitOrder, groupMapRowsByFile, countMapHonestyGauges — and writes the same groups in its own +// The default-map JSON sibling of serialize(). It shares serialize()'s decisions about WHAT the map prints — one MapPlan +// (planMap) and the same MapCoverageFacts — and writes the same groups in its own // spelling, so a defect fixed in one dialect's selection cannot survive in the other's. Scope: the common single-root // invocation (metrics, fan-in, ambiguity, cbo/tested/lcom4/amp Q-metrics, stable/most-important-last/auto-order, bind labels, // est_tokens, per-edge provenance, the multi-root prologue, and — §B1.2 — the at/rank_by/window PROVENANCE STAMP a @@ -12194,18 +12237,16 @@ inline void serializeJson( std::FILE* out, const IngestResult& ing, const std::v return rootArg.empty() ? std::string_view( ing.files[ fileId ] ) : rw::sarif::rootRelativeUri( ing.files[ fileId ], rootPrefix ); }; - // ── WHICH rows, in WHICH order: serialize()'s steps. This dialect has no in=DIR stub; it always prints its rows. ────────── - const std::size_t keep = mapKeepCount( ing, topK ); - const RankedMapRows ranked = rankMapRows( ing, rank, ann, keep, /*stubbed=*/false ); - const std::span<const NodeId> kept = ranked.kept( keep ); - // T1/§H7: SAME byte-model the XML sibling uses, in the same two roles — the fill-order oracle and the rate source. The - // REPORTED est_tokens is measured from the emitted bytes in PHASE 2 below, exactly as in serialize(): this emitter had the - // identical --metrics under-report (MEASURED: 1780 B reported as est_tokens=507, 3.51 B/tok). - const TokenEstimate mapEst = estimateTokens( ing, ranked.order, kept.size(), outOff, outTargets ); - const MapEmitOrder emitOrder = decideMapEmitOrder( stable, mostImportantLast, autoOrder, mapEst.tokens ); - const MapFileGroups groups = groupMapRowsByFile( ing, ann, kept, /*stubbed=*/false, emitOrder, outOff, outTargets, pathRel ); - const MapHonestyGauges gauges = countMapHonestyGauges( ing, MapResolverCounters{ .ambOut = ambOut, .unresolvedOut = unresolvedOut, .locPinOut = locPinOut, - .declinedOut = declinedOut, .externalCalls = externalCalls } ); + // ── WHICH rows, in WHICH order: serialize()'s plan. This dialect has no in=DIR stub spelling; it always prints its rows. ──── + // The byte model in the plan plays the same two roles as in serialize() — the fill-order oracle and the rate source; the + // REPORTED est_tokens is measured from the emitted bytes in PHASE 2 below (this emitter had the identical --metrics + // under-report: MEASURED 1780 B reported as est_tokens=507, 3.51 B/tok). + const MapPlan plan = planMap( ing, rank, outOff, outTargets, ann, topK, + MapOrderRequest{ .stable = stable, .mostImportantLast = mostImportantLast, .autoOrder = autoOrder }, + MapResolverCounters{ .ambOut = ambOut, .unresolvedOut = unresolvedOut, .locPinOut = locPinOut, + .declinedOut = declinedOut, .externalCalls = externalCalls }, + MapStubPolicy::AlwaysPrintRows, pathRel ); + const MapCoverageFacts coverage = mapCoverageFacts( ing, outProv ); // ── PHASE 1: render the "r" array into a buffer (§H7 — see serialize()'s PHASE 1 for the full reasoning: measure, decide, // then write). DEGRADE: an open_memstream failure emits the header FIRST with the MODELLED estimate (the pre-§H7 number, @@ -12226,45 +12267,43 @@ inline void serializeJson( std::FILE* out, const IngestResult& ing, const std::v const auto emitHeader = [ & ]( std::FILE* dst, std::size_t estTokens ) { JsonWriter hw( dst ); - writeJsonMapHeader( hw, esc, JsonMapHeader{ ing, mapSymbolCount( ing ), outTargets.size(), keep + groups.stemPick.rows.size(), estTokens, gauges.ambiguous, - gauges.unresolved, traitsOf( emitOrder ).orderAttr, outProv, &ann, rootArg, gauges.localityPinned, gauges.external, - gauges.declined, gauges.extentSuspectSyms, gauges.macroBlankedFiles, gauges.nestRefusedFiles, - estimate.isModelled, ranked.dataSecCut, groups.stemPick.cut, memoryPeakJson } ); + writeJsonMapHeader( hw, esc, JsonMapHeader{ .ing = ing, .plan = plan, .coverage = coverage, .edgeCount = outTargets.size(), .estTokens = estTokens, + .isEstModelled = estimate.isModelled, .ann = ann, .rootArg = rootArg, .memoryPeakJson = memoryPeakJson } ); hw.write( ",\"r\":[" ); }; // The "r" array, as ONE renderer both paths call — serialize()'s writeChildren, for the same reason: a buffer that opened and // then lost a write has already spent the rows, so the fallback must be able to write them again. const MapRowSources rowSources{ .rank = rank, .outOff = outOff, .outTargets = outTargets, .outProv = outProv, .outNameOnly = outNameOnly, - .ambOut = ambOut, .locPinOut = locPinOut, .bind = bind, .stable = stable, .metrics = metrics, + .ambOut = ambOut, .locPinOut = locPinOut, .bind = bind, .emitOrder = plan.emitOrder, .metrics = metrics, .fanIn = fanIn, .cbo = cbo, .tested = tested, .lcom4 = lcom4, .amp = amp }; const auto writeRows = [ & ]( JsonWriter& w ) { - for( std::size_t i = 0; i < groups.fileOrder.size(); ++i ) + for( std::size_t i = 0; i < plan.groups.fileOrder.size(); ++i ) { if( i > 0 ) { w.write( "," ); } - writeJsonMapFileGroup( w, ing, groups.fileOrder[ i ], groups, rowSources, pathRel, esc ); + writeJsonMapFileGroup( w, ing, plan.groups.fileOrder[ i ], plan.groups, rowSources, pathRel, esc ); } w.write( "]" ); - if( groups.inventory.active ) + if( plan.groups.inventory.active ) // after "r", always: a key of one object (see writeMapChildren on the XML placement) { - writeMapInventoryJson( w, ing, groups.inventory, pathRel, outOff, outTargets, outProv, outNameOnly, esc ); + writeMapInventoryJson( w, ing, plan.groups.inventory, pathRel, outOff, outTargets, outProv, outNameOnly, esc ); } w.write( "}" ); }; // DEGRADE, one path for both failures: the header FIRST with the MODELLED estimate, the array streamed behind it. const auto emitModelled = [ & ]() { - emitHeader( out, mapEst.tokens ); + emitHeader( out, plan.mapEst.tokens ); JsonWriter direct( out ); writeRows( direct ); direct.flush(); if( outEstTokens ) { - *outEstTokens = mapEst.tokens; + *outEstTokens = plan.mapEst.tokens; } }; if( !rowsMem ) @@ -12303,7 +12342,7 @@ inline void serializeJson( std::FILE* out, const IngestResult& ing, const std::v rw::MemoryStream probe; if( std::FILE* const pm = openChargeStream( probe ) ) { - emitHeader( pm, mapEst.tokens ); + emitHeader( pm, plan.mapEst.tokens ); if( const rw::MemoryStreamBytes header = probe.finish(); header.isWhole ) { headerBytes = header.bytes.size(); @@ -12322,7 +12361,7 @@ inline void serializeJson( std::FILE* out, const IngestResult& ing, const std::v } const std::size_t estTokens = tokensForEmittedBytes( headerBytes + kEstTokensFieldReserve + rowsStr.size(), - mapEst.bytesPerToken() ); + plan.mapEst.bytesPerToken() ); if( outEstTokens ) { *outEstTokens = estTokens; diff --git a/test/fixedbufsweep.sh b/test/fixedbufsweep.sh index 4c1ab6783..2713b0daf 100755 --- a/test/fixedbufsweep.sh +++ b/test/fixedbufsweep.sh @@ -187,7 +187,7 @@ TABLE = { ( "src/packtask.h", "bodylessAttr" ): ( 1, "safe", "bodylessAttr[40], ONE call site (PB1, 2026-11-19: it was two). The surviving site is the <bodies> open-tag restate (issue #60, integration/train-12). The second site, the bare-wrapper placeholder branch (t14-cleanup #6), is gone: PB1 emits that no-candidate tag as a fixed literal with no bodyless= at all, because a bundle with no body CANDIDATE has no bodyless owner to count. It formats ' bodyless=\"{}\"' — 12 B of literal (' bodyless=\"' 11 + '\"' 1) and ONE interpoland, a std::size_t: 20 digits at absolute most, so 32 B against 39 usable + NUL, 7 B of margin. No string interpolation at all — the count is a count, never caller text — so no escaper can sit on either side of the buffer. It is a TABLE row and not NUMERIC_ONLY for arch.h hex[17]'s reason: a buffer that never existed before the std::print conversion has no pre-conversion format to derive a class from. THE ORIGINAL BUFFER WAS DECLARED [32] WHEN IT ARRIVED, which is 1 B short of its own worst case (32 B of text needs 33 with the NUL); formatTo truncates rather than overruns, so the failure mode was a dropped closing quote and a document that stops being well-formed, not a memory breach. Widened to 40 in the same commit as that row; the second site was declared [160]/[40] correctly from the start." ), # ── src/serialize.h ────────────────────────────────────────────────────────────────────────────────── ( "src/serialize.h", "bodylessAttr" ): ( 1, "safe", "bodylessAttr[40] in packBodies (issue #60, integration/train-12): the exact twin of the packtask.h row above — same format, same 12 B of literal, one std::size_t (bodylessCount), 32 B against 39 usable + NUL, 7 B of margin, no string interpoland. Same [32]-on-arrival correction, widened in the same commit." ), - ( "src/serialize.h", "attr" ): ( 2, "safe", "attr[352] x2: the per-symbol metric attrs. Widest 26 lit + 4x10 digits + 11 role + qbuf(<=95) + ambs(<=35: amb= + lpin=) + kbuf(<=23) = 230 B." ), + ( "src/serialize.h", "attr" ): ( 1, "safe", "attr[352]: the per-symbol --metrics run (rowMetricsAttrs). Widest 26 lit + 4x10 digits + 11 role + the BoundedAttrRun (<=191) = 268 B. GE-SERIALIZE round 2 (2026-11-22): was x2 with ambs(<=35) + kbuf(<=23) folded into the same buffer (326 B worst case, never truncated), now written as their own attributes beside it." ), ( "src/serialize.h", "tail" ): ( 3, "safe", "tail[192] x3: the <d> row tail. Widest 34 lit+digits + inAttr(<=23) + lens(qbuf, <=79) + pure(9) = 145 B. The third (lane/lean-answers-068, sigRowTail's zero-elision branch) prints cxAttr/ccxAttr/inAttr pre-formatted, each omitted at 0 — never wider than the second." ), ( "src/serialize.h", "hdr" ): ( 15, "safe", "hdr[64] x2 (packBodies/packOutline) (15: the tracked-build crawl fix — writeJsonMapHeader's `\"untracked_build\":{},` formatTo into the EXISTING hdr[256], one unsigned long long and no string argument, 19 B of literal + 20 digits + NUL = 40 B, the `\"escaped_root\":{},` twin beside it; 14: arch-honest — packDeps' <f> row for a no-edge file writes includes= and a language tag, hdr[144], one integer + a label of at most 8 B: far under the buffer; 13: train 26b — count-floor-068 replaced the <lego> implementors= header writes, two hdr sites, with string appends): '<b t=\"%s\" l=\"%u\" p=\"' — symTag's fixed vocabulary + a line number. THE ESCAPED PATH IS APPENDED AFTER, on std::string. snprintf-then-append: textbook safe." ), ( "src/serialize.h", "db" ): ( 1, "safe", "db[64 + kPageDisclosureCap]: <deps files=...> plus pageDisclosure's own capped buffer, sized against that cap by construction." ), @@ -622,7 +622,7 @@ if not bad: # nb[96] ' files_first="{}"' (35 B worst case, one size_t, nothing escaped) — re-read and sized before this pin. EXPECTED = { "mentions": 366, "calls": 251, "sites": 251, "rows": 109, "widthforms": 0 } # lane/hrr: +1 nb site (files_first=); arch-honest: +2 (packDeps hb, hdr) # 2026-11-21 (GE-SERIALIZE): -5 calls/-5 sites/-5 rows (precAttr, rootsAttr, changedAttr, skippedAttr, fitAttr): the map -# header's coverage attributes are composed on std::string in mapCoverageAttrs (serialize.h), no fixed buffer left. +# header's coverage attributes are composed on std::string in renderMapCoverageAttrs / mapFitAttrs (serialize.h), no fixed buffer left. # 2026-11-12 (B43 PINNED-SELF-COUNTS): EXPECTED above is now HISTORY, not a pin -- it drifted on #619 (and on every # lane that added one site) while (S1)/(S2) already held the member set both ways: every derived site is a TABLE # row with its multiplicity, and no row is stale. An exact count on top of that only re-pins arithmetic. What (S1)/(S2) From a365f33a5ca00c260160f9332541a46d02bb297b Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:06:52 -0500 Subject: [PATCH 29/61] refactor(serialize): planMap's two equivalence pins read fields, not calls selfcheckcheck (C) admits only accessor calls inside an ASSUME: the --stable pin compares the decided MapEmitOrder with the flag directly, and the stub pin reads the ranked order itself. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/serialize.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/serialize.h b/src/serialize.h index 9c5009d7e..23a5a33c9 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -3595,14 +3595,16 @@ inline MapPlan planMap( const IngestResult& ing, const std::vector<float>& rank, // see --metrics decoration or an appended payload. C1-b: under the stub the estimate is taken over no rows. plan.mapEst = estimateTokens( ing, plan.ranked.order, plan.kept().size(), outOff, outTargets ); plan.emitOrder = decideMapEmitOrder( asked, plan.mapEst.tokens ); - ASSUME( emitOrderTraits( plan.emitOrder ).stablePrefix == asked.stable, "decideMapEmitOrder returns Stable exactly when --stable was asked" ); + // Stable is the one order whose traits carry stablePrefix (emitOrderTraits), so every downstream --stable choice that reads + // the trait reads exactly the flag the caller passed. + ASSUME( ( plan.emitOrder == MapEmitOrder::Stable ) == asked.stable, "decideMapEmitOrder returns Stable exactly when --stable was asked" ); if( !plan.stubbed ) { plan.groups = groupMapRowsByFile( ing, ann, plan.kept(), plan.emitOrder, outOff, outTargets, pathRel ); } plan.gauges = countMapHonestyGauges( ing, counters ); plan.shown = plan.stubbed ? 0 : plan.keep + plan.groups.stemPick.rows.size(); - ASSUME( !plan.stubbed || ( plan.kept().empty() && plan.groups.fileOrder.empty() && plan.groups.inventory.entries.empty() ), + ASSUME( !plan.stubbed || ( plan.ranked.order.empty() && plan.groups.fileOrder.empty() && plan.groups.inventory.entries.empty() ), "the stub ranks and groups no row, so no kept-row legend clause and no <f> group can fire under it" ); return plan; } From ca702e7c6b1129a36f9d9adb404781184d11a994 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:30:25 -0500 Subject: [PATCH 30/61] refactor(lexical): lexicalScoresTiered reads as its named BM25 steps lexicalScoresTiered was one 1045-line body (nest 6, 151 deep lines) whose corpus-statistics membership (statsS / allS / statsOut / unranked) was set at the top and steered branches 800 lines later. It is now an ordered list of steps, each making one named decision: - assignLexCorpusRoles: each unit is counted, statsOut or unranked, decided once (LexCorpusRoles); every later step asks the role instead of combining two masks and a merged copy. - buildLexMatchTable + lightStemVariantsOf: exact terms, then the armed RIPWIRE_QSTEM variants (suffix rules flattened, first-wins dedupe kept). - LexTfTable: the dl/tf accumulator; every write goes through its add/fold members and one field scanner. - addNameAndCalleeFields / addPathField / addBasenameField, then pass 2 from addDocBodyFromPersistedStats or scanDocBodyFields (now on symbolsByFileInIdOrder instead of a hand-rolled CSR). - admitRareStemVariants: the R3 admission decided once (was re-evaluated in three loops); foldAdmittedVariants / foldAdmittedNameDf apply it. - judgeTermMargins: one TermMarginVerdict per term; termKept and the debug lines both read it instead of re-deriving the reason. - tallyBm25Stats + LexTopKPruner + scoreLexCandidates: one scoring loop over the candidates; exhaustive scoring is the same loop with a pruner that never skips (non-candidates keep +0.0f, as before; DASSERT on the tier multiplier range that equivalence rests on). The per-doc BM25 expression is unchanged text (the idf log stays inside the loop: hoisting it would let -ffast-math vectorize and reassociate the sum). Answers are byte-identical (stdout, stderr, rc) on plain builds. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/lexical.h | 1771 +++++++++++++++++++++++++------------------------ 1 file changed, 896 insertions(+), 875 deletions(-) diff --git a/src/lexical.h b/src/lexical.h index 02cb2906c..a41063bca 100644 --- a/src/lexical.h +++ b/src/lexical.h @@ -159,7 +159,7 @@ struct LexTermEvidence const std::uint64_t* anyMaskOf( std::size_t sym ) const noexcept { return anyMask.data() + sym * maskWords; } static bool hasBit( const std::uint64_t* mask, std::size_t u ) noexcept { return ( mask[ u / 64 ] >> ( u % 64 ) ) & 1u; } - // BM25's own idf for term u over the `statsCount` symbols the statistics count — the exact expression both scoring branches use, + // BM25's own idf for term u over the `statsCount` symbols the statistics count — the exact expression scoreLexCandidates uses, // so an absent term (df 0) weighs as the rarest possible term and never as nothing. double idf( std::size_t u ) const noexcept { @@ -266,7 +266,7 @@ inline Bm25Params resolveBm25Params() noexcept // The provably-safe per-term impact bound (MaxScore "max contribution"), derived from the SAME (k1,b) the // exact scoring loop uses. idf: this term's IDF. T: the largest weighted tf of this term anywhere in the -// corpus (tfMaxOf[u] at the call site). See lexicalScoresTiered's pruned branch for the full monotonicity +// corpus (tfMaxOf[u] at the call site). See LexTopKPruner for the full monotonicity // proof this bound relies on — it holds for ANY k1 > 0 and ANY b in [0,1], not just the shipped defaults. inline double bm25ImpactBound( double idf, double T, const Bm25Params& p ) noexcept { @@ -551,208 +551,200 @@ inline std::vector<char> notLexRankedMask( const IngestResult& ing ) return mask; } -inline std::vector<float> lexicalScoresTiered( const IngestResult& ing, const std::vector<std::uint32_t>& outOff, - const std::vector<NodeId>& outTargets, std::string_view query, - std::size_t pruneTopK, const std::vector<char>* alwaysExact, - const std::vector<float>* symbolScoreMul, int pathFieldDefaultW = 0, - int basenameFieldDefaultW = 0, std::string_view pathRootPrefix = {}, - LexTermEvidence* evidenceOut = nullptr, // L-W: the term evidence, read back out (see the struct) - const std::vector<char>* statsOut = nullptr ) // units scored but kept OUT of the corpus statistics +// ─── lexicalScoresTiered's steps, in the order it runs them ───────────────────────────────────────────── +// lexicalScoresTiered (below) reads as the list of these steps. Each one makes ONE decision and names it: +// which units the corpus statistics count, which tokens a corpus subtoken can match, what each field adds, +// which stem variants are rare enough to keep, which query terms separate, and which units are scored. + +// TIER STEP — which units the BM25 corpus statistics count. Decided ONCE per call, per unit, as one of three roles: +// kCounted scored, and counted in the statistics: the symbol count, every document frequency, the average length +// kStatsOut scored like any other unit but kept OUT of the statistics (the caller's statsOut — filter.h +// sphinxTxtStatsExclusion). It scores against the whole ranked corpus instead: rankedCount units, its +// term's counted df plus the statsOut df, and the ranked average length. +// kUnranked a kRankFlagNotLexRanked unit (model.h): never scored (0), and no document in either corpus — so a +// Sphinx .txt section scores as it did before HTML units existed. +// An unranked unit that the caller also lists in statsOut is kUnranked: unranked wins. roleOf is EMPTY when every unit +// is kCounted, so a corpus with neither kind pays no per-unit lookup and runs the historical pass byte-for-byte. +struct LexCorpusRoles +{ + enum Role : std::uint8_t + { + kCounted = 0, + kStatsOut = 1, + kUnranked = 2, + }; + + std::vector<std::uint8_t> roleOf; // per unit; empty = every unit kCounted + std::size_t countedCount = 0; // the units the statistics count (the BM25 N of a counted unit) + std::size_t rankedCount = 0; // counted + statsOut: the corpus a statsOut unit scores against + + Role role( std::size_t i ) const noexcept { return roleOf.empty() ? kCounted : Role( roleOf[i] ); } + bool isUnranked( std::size_t i ) const noexcept { return role( i ) == kUnranked; } + bool isStatsOut( std::size_t i ) const noexcept { return role( i ) == kStatsOut; } + // a unit's weight in every corpus statistic: 1 counted, 0 otherwise (statsOut and unranked alike) + int statsWeight( std::size_t i ) const noexcept { return role( i ) == kCounted ? 1 : 0; } +}; + +inline LexCorpusRoles assignLexCorpusRoles( const IngestResult& ing, const std::vector<char>* statsOut ) { - PROFILE_SCOPE_DESCRIBE( "lexical: lexicalScores (BM25 over symbols)" ); const std::size_t S = ing.symbols.size(); - // kRankFlagNotLexRanked units (model.h): out of the statistics like a statsOut unit, and never scored (0 below) - const std::vector<char> unranked = notLexRankedMask( ing ); - std::vector<char> statsOutMerged; - if( !unranked.empty() ) + LexCorpusRoles roles; + for( std::size_t i = 0; i < S; ++i ) { - statsOutMerged = unranked; - for( std::size_t i = 0; statsOut != nullptr && i < statsOut->size() && i < S; ++i ) + const bool listedOut = statsOut != nullptr && i < statsOut->size() && ( *statsOut )[i] != 0; + const auto role = notLexRanked( ing.symbols[i] ) ? LexCorpusRoles::kUnranked + : listedOut ? LexCorpusRoles::kStatsOut + : LexCorpusRoles::kCounted; + if( role != LexCorpusRoles::kCounted && roles.roleOf.empty() ) { - statsOutMerged[i] = char( statsOutMerged[i] | ( *statsOut )[i] ); + roles.roleOf.assign( S, LexCorpusRoles::kCounted ); } - statsOut = &statsOutMerged; - } - const auto isUnranked = [ &unranked ]( std::size_t i ) noexcept { return !unranked.empty() && unranked[i] != 0; }; - // the WHOLE corpus an OUT unit scores against (avgdlAll, allS, dfOut below) is the ranked one: a kRankFlagNotLexRanked - // unit is no document there either, so a Sphinx .txt section scores as it did before HTML units existed - const std::size_t allS = S - std::size_t( std::count( unranked.begin(), unranked.end(), char( 1 ) ) ); - // statsOut (filter.h sphinxTxtStatsExclusion): units SCORED like any other but kept out of the corpus statistics — - // the symbol count, every document frequency and the average length. Null: every unit counts, the historical pass. - const auto statsWeight = [ statsOut ]( std::size_t i ) noexcept -> int - { return ( statsOut != nullptr && i < statsOut->size() && ( *statsOut )[i] != 0 ) ? 0 : 1; }; - std::size_t statsS = S; - if( statsOut != nullptr ) - { - statsS = 0; - for( std::size_t i = 0; i < S; ++i ) + if( role != LexCorpusRoles::kCounted ) { - statsS += std::size_t( statsWeight( i ) ); + roles.roleOf[i] = role; } + roles.countedCount += role == LexCorpusRoles::kCounted ? 1 : 0; + roles.rankedCount += role != LexCorpusRoles::kUnranked ? 1 : 0; } + return roles; +} - // query subtokens — occurrence order preserved (BM25 adds one contribution PER occurrence, as before); - // an empty query scores exactly 0 everywhere (0.0 survives the Section down-weight unchanged) - std::vector<std::string> qToks; - subtokens( query, qToks ); - if( qToks.empty() ) +// One row of a query's match table: a token a corpus subtoken is compared against, and the unique query term whose +// tf/idf row it scores into — itself for an exact term (row m == u), the original term for an LB-3 stem variant. +struct LexMatchTok +{ + std::string tok; + std::uint32_t u; +}; + +// The LB-3 arm S suffix rules for ONE query term, in the order the match table admits them (first-wins): a +// plural/participle query token ("splits", "resolved", "hoisting") cannot exact-match the singular subtoken a +// compound name carries (SplitChunksPlugin → split; resolve.h → resolve) — the measured LB-3 anatomy (bench/r7 + r8, +// three independent confirmations). Candidates only: the 3-byte floor and the first-wins dedupe are the table's. +inline std::vector<std::string> lightStemVariantsOf( const std::string& t ) +{ + const auto isConsonant = []( char c ) { - if( evidenceOut ) - { - *evidenceOut = LexTermEvidence{}; - evidenceOut->symbolCount = S; - evidenceOut->statsCount = S; - } - return std::vector<float>( S, 0.f ); + return c >= 'a' && c <= 'z' && c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u'; + }; + const std::size_t L = t.size(); + const auto ends = [ & ]( std::string_view suf ) { return L >= suf.size() && t.compare( L - suf.size(), suf.size(), suf ) == 0; }; + // a doubled final consonant before the suffix ("flagged", "running"): the undoubled stem is a variant too + const auto doubledBefore = [ & ]( std::size_t suffixLen ) { return t[L - suffixLen - 1] == t[L - suffixLen - 2] && isConsonant( t[L - suffixLen - 1] ); }; + std::vector<std::string> variants; + if( ends( "s" ) && !ends( "ss" ) && L >= 4 ) + { + variants.push_back( t.substr( 0, L - 1 ) ); // splits → split + } + if( ends( "es" ) && L >= 5 ) + { + variants.push_back( t.substr( 0, L - 2 ) ); // classes → class + } + if( ends( "ed" ) && L >= 5 ) + { + variants.push_back( t.substr( 0, L - 1 ) ); // resolved → resolve + variants.push_back( t.substr( 0, L - 2 ) ); // parsed → pars (rarely useful, harmless) + } + if( ends( "ed" ) && L >= 6 && doubledBefore( 2 ) ) + { + variants.push_back( t.substr( 0, L - 3 ) ); // flagged → flag + } + if( ends( "ing" ) && L >= 6 ) + { + variants.push_back( t.substr( 0, L - 3 ) ); // hoisting → hoist + variants.push_back( t.substr( 0, L - 3 ) + "e" ); // caching → cache } + if( ends( "ing" ) && L >= 7 && doubledBefore( 3 ) ) + { + variants.push_back( t.substr( 0, L - 4 ) ); // running → run + } + return variants; +} - // dedupe to the unique terms whose statistics we need — a duplicated query word must not double-count - // tf, but still contributes once PER OCCURRENCE in the scoring loop (uniqueIndexOfQtok maps back) — - // capped (see dedupeQueryTerms above) so a pathologically term-rich query cannot blow up tfFlat's S×terms - // allocation below. - DedupedQueryTerms dedup = dedupeQueryTerms( qToks, kMaxUniqueQueryTerms ); - std::vector<std::string>& uniqueToks = dedup.uniqueToks; - std::vector<std::size_t>& uniqueIndexOfQtok = dedup.uniqueIndexOfQtok; - const std::size_t uniqueCount = uniqueToks.size(); - - // ── LB-3 arm S: conservative query-side stem variants ───────────────────────────────────────────── - // A plural/participle query token ("splits", "resolved", "hoisting") cannot exact-match the singular - // subtoken a compound name carries (SplitChunksPlugin → split; resolve.h → resolve) — the measured - // LB-3 anatomy (bench/r7 + r8, three independent confirmations). Variants are QUERY-side only and - // score into the ORIGINAL token's tf/idf row, so corpus stats and the cache format are untouched. - // ONE shared table drives the scan branch, the persisted-stats branch, and every field pass — - // parity by construction (test/postingscheck.sh; armed arm in test/lb3namecheck.sh). A variant - // string already claimed by an earlier token (or equal to any exact token) is dropped, first-wins, - // so a doc token maps to exactly one row in either branch. RIPWIRE_QSTEM=1 arms it; the shipped - // default stays OFF until the LB-3 acceptance verdict (scratchpad lb3/preregistration.md) lands. - struct LexMatchTok - { - std::string tok; - std::uint32_t u; - }; - std::vector<LexMatchTok> matchToks; - matchToks.reserve( uniqueCount * 2 ); +// THE query's match table: one row per unique exact term (rows 0..uniqueCount, m == u), then — only when RIPWIRE_QSTEM=1 +// arms LB-3 arm S — the terms' light-stem variants as PROVISIONAL rows (m ≥ uniqueCount), each owning its own tf column. +// Variants are QUERY-side only and score into the ORIGINAL token's tf/idf row, so corpus stats and the cache format are +// untouched. ONE shared table drives the scan branch, the persisted-stats branch, and every field pass — parity by +// construction (test/postingscheck.sh; armed arm in test/lb3namecheck.sh). A variant string already claimed by an +// earlier token (or equal to any exact token) is dropped, first-wins, so a doc token maps to exactly one row in either +// branch. The shipped default stays OFF until the LB-3 acceptance verdict (scratchpad lb3/preregistration.md) lands. +// +// IDF guard, rung R3 (LB-3 retry, scratchpad lb3retry/preregistration.md): the un-guarded round measured the failure: +// a corpus-common variant ("split" on webpack) hands its term-frequency mass to every competitor whose doc/body rides +// the same subtoken, displacing currently-hit truths (EVALS §7) — and the mass is BODY frequency (`.split()` call +// sites), which is why the name-carrier bound (rungs R1/R2) measured too low to catch it. So a variant enters the table +// PROVISIONALLY; admission is decided after pass 2 (admitRareStemVariants), when both pass-2 sources have measured +// its doc/body document frequency as the SAME integers. The guard never sees a user's EXACT query token — only derived +// variants — so it structurally cannot drop a truth's own carrier (the LB-1 IDF-floor failure). +inline std::vector<LexMatchTok> buildLexMatchTable( const std::vector<std::string>& uniqueToks ) +{ + const std::size_t uniqueCount = uniqueToks.size(); + std::vector<LexMatchTok> rows; + rows.reserve( uniqueCount * 2 ); for( std::size_t u = 0; u < uniqueCount; ++u ) { - matchToks.push_back( { uniqueToks[u], std::uint32_t( u ) } ); + rows.push_back( { uniqueToks[u], std::uint32_t( u ) } ); } + const char* qstemEnv = std::getenv( "RIPWIRE_QSTEM" ); + if( qstemEnv == nullptr || *qstemEnv != '1' ) { - const char* qstemEnv = std::getenv( "RIPWIRE_QSTEM" ); - const bool qstemOn = qstemEnv != nullptr && *qstemEnv == '1'; - // derived variants are CANDIDATES first: admission into the match table happens only after the - // IDF guard below — the guard sees the deduped candidate set, never the user's exact tokens - std::vector<LexMatchTok> stemCandidates; - const auto pushVariant = [ & ]( std::string v, std::uint32_t u ) - { - if( v.size() < 3 ) - { - return; // sub-3-byte stems are noise, frozen rule - } - for( const LexMatchTok& mt : matchToks ) - { - if( mt.tok == v ) - { - return; // first-wins: string already claimed - } - } - for( const LexMatchTok& cand : stemCandidates ) - { - if( cand.tok == v ) - { - return; // first-wins among candidates too - } - } - stemCandidates.push_back( { std::move( v ), u } ); - }; - const auto isConsonant = []( char c ) - { - return c >= 'a' && c <= 'z' && c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u'; - }; - if( qstemOn ) + return rows; + } + const auto alreadyClaimed = [ &rows ]( const std::string& v ) + { return std::ranges::any_of( rows, [ & ]( const LexMatchTok& row ) { return row.tok == v; } ); }; + for( std::size_t u = 0; u < uniqueCount; ++u ) + { + for( std::string& v : lightStemVariantsOf( uniqueToks[u] ) ) { - for( std::size_t u = 0; u < uniqueCount; ++u ) + if( v.size() >= 3 && !alreadyClaimed( v ) ) // sub-3-byte stems are noise, frozen rule; first-wins { - const std::string& t = uniqueToks[u]; - const std::size_t L = t.size(); - const auto ends = [ & ]( std::string_view suf ) - { return L >= suf.size() && t.compare( L - suf.size(), suf.size(), suf ) == 0; }; - if( ends( "s" ) && !ends( "ss" ) && L >= 4 ) - { - pushVariant( t.substr( 0, L - 1 ), std::uint32_t( u ) ); // splits → split - if( ends( "es" ) && L >= 5 ) - { - pushVariant( t.substr( 0, L - 2 ), std::uint32_t( u ) ); // classes → class - } - } - if( ends( "ed" ) && L >= 5 ) - { - pushVariant( t.substr( 0, L - 1 ), std::uint32_t( u ) ); // resolved → resolve - pushVariant( t.substr( 0, L - 2 ), std::uint32_t( u ) ); // parsed → pars (rarely useful, harmless) - if( L >= 6 && t[L - 3] == t[L - 4] && isConsonant( t[L - 3] ) ) - { - pushVariant( t.substr( 0, L - 3 ), std::uint32_t( u ) ); // flagged → flag - } - } - if( ends( "ing" ) && L >= 6 ) - { - pushVariant( t.substr( 0, L - 3 ), std::uint32_t( u ) ); // hoisting → hoist - pushVariant( t.substr( 0, L - 3 ) + "e", std::uint32_t( u ) ); // caching → cache - if( L >= 7 && t[L - 4] == t[L - 5] && isConsonant( t[L - 4] ) ) - { - pushVariant( t.substr( 0, L - 4 ), std::uint32_t( u ) ); // running → run - } - } + rows.push_back( { std::move( v ), std::uint32_t( u ) } ); } } - // ── IDF guard, rung R3 (LB-3 retry, scratchpad lb3retry/preregistration.md) ────────────────── - // The un-guarded round measured the failure: a corpus-common variant ("split" on webpack) hands - // its term-frequency mass to every competitor whose doc/body rides the same subtoken, displacing - // currently-hit truths (EVALS §7) — and the mass is BODY frequency (`.split()` call sites), which - // is why the name-carrier bound (rungs R1/R2) measured too low to catch it. So every candidate - // enters the match table PROVISIONALLY, owning its own tf column (m ≥ uniqueCount); admission is - // decided AFTER pass 2, when both scoring branches have measured the variant's doc/body document - // frequency as the SAME integers (postings rows on the rich path, the scan's own counts on the - // lean path — parity by construction), and only a corpus-rare variant (df ≤ max(8, S/64)) is - // folded into its original token's row; a common one is discarded untouched. The guard never - // sees a user's EXACT query token — only derived variants — so it structurally cannot drop a - // truth's own carrier (the LB-1 IDF-floor failure). - for( LexMatchTok& cand : stemCandidates ) - { - matchToks.push_back( std::move( cand ) ); - } - } - const std::size_t matchCount = matchToks.size(); - - // P2-3: build the head mask + length buckets for THIS query's match table (see LexHeadIndex above). - const auto matchTokOf = [ & ]( std::size_t m ) -> const std::string& { return matchToks[m].tok; }; - const LexHeadIndex headIndex = buildLexHeadIndex( matchCount, matchTokOf ); - - // per-doc integer stats (SoA): dl[i] = weighted subtoken count, tfFlat[i*matchCount+m] = weighted term - // frequency of match-table row m in doc i. Disarmed, matchCount == uniqueCount and the layout is the - // historical one byte-for-byte; armed, provisional variant columns sit at m ≥ uniqueCount until the - // post-pass-2 guard folds the admitted ones and the array shrinks back to uniqueCount stride. - std::vector<int> dl( S, 0 ); - std::vector<int> tfFlat( S * matchCount, 0 ); - - // Field weights: a query term in a symbol's NAME outranks one in its DOC-COMMENT, which outranks one - // buried in its BODY — so an exactly-named function beats a struct that merely mentions the word, and an - // algorithm beats a comment-dense enum (the "keyword magnet" the review flagged). BM25 tf accumulates - // these weighted contributions; dl is weighted to match, so length normalization stays consistent. - // Doc/body weights are the SHARED constants (lexindex.h) — the index-time stats builder must weigh - // those two fields identically or the postings path would diverge from this scan. - constexpr int kwName = 3, kwCallee = 1, kwDoc = kLexWeightDoc, kwBody = kLexWeightBody; - - // stream one field through the ONE shared state machine (lexindex.h forEachLexSubtoken — the same - // tokenizer subtokens() mirrors and the B0.2 index-time builder uses): a token is a maximal - // alphanumeric run between separators, cut at a lower/digit → Upper transition and at the ACRONYMWord - // seam. Tokens shorter than 2 bytes are dropped, exactly like subtokens(). - // No strings, no maps — just in-place span-vs-query compares. Since 2026-08-19 an all-caps run survives - // as ONE token, so a span's INTERIOR bytes can be uppercase and memcmp alone would miss it; the memcmp - // stays as the fast path (it resolves every ordinary identifier token) and only a span already agreeing - // on length AND head falls through to lexTokenEqualsLowered — the rare acronym case, arm D's seam. - const auto scanTextInto = [ & ]( int* tfRow, int& wtAccum, std::string_view text, int w ) - { - int fieldTokenWt = 0; + } + return rows; +} + +// The per-query BM25 term table every field pass adds into (SoA): dl[i] = doc i's weighted subtoken count (the BM25 +// document length) and tf[i * stride + m] = the weighted term frequency of match-table row m in doc i. Integer counts are +// exact, so fill order is free and the float scoring later runs in strict doc order with the historical expressions. +// Until the stem-variant fold, stride == matchCount and provisional variant columns sit at m ≥ uniqueCount; the fold +// (foldAdmittedVariants) shrinks it back to uniqueCount, the historical layout byte-for-byte. Disarmed, the two are equal. +// +// Every write goes through the four add/fold members below, and every field's evidence through ONE tokenizer: +// scanTextInto streams a field through lexindex.h forEachLexSubtoken (the same state machine subtokens() mirrors and the +// B0.2 index-time builder uses): a token is a maximal alphanumeric run between separators, cut at a lower/digit → Upper +// transition and at the ACRONYMWord seam. Tokens shorter than 2 bytes are dropped, exactly like subtokens(). No strings, +// no maps — just in-place span-vs-query compares through the P2-3 head index (LexHeadIndex above). Since 2026-08-19 an +// all-caps run survives as ONE token, so a span's INTERIOR bytes can be uppercase and memcmp alone would miss it; the +// memcmp stays as the fast path and only a span already agreeing on length AND head falls through to +// lexTokenEqualsLowered — the rare acronym case, arm D's seam. +struct LexTfTable +{ + const std::vector<LexMatchTok>& matchToks; + std::size_t uniqueCount; // rows 0..uniqueCount are the exact query terms + std::size_t stride; // matchToks.size() until the fold, uniqueCount after it + LexHeadIndex headIndex; + std::vector<int> dl; + std::vector<int> tf; + + LexTfTable( std::size_t docCount, const std::vector<LexMatchTok>& rows, std::size_t exactCount ) + : matchToks( rows ), uniqueCount( exactCount ), stride( rows.size() ), + headIndex( buildLexHeadIndex( rows.size(), [ &rows ]( std::size_t m ) -> const std::string& { return rows[m].tok; } ) ), + dl( docCount, 0 ), tf( docCount * rows.size(), 0 ) + { + } + + std::size_t variantCount() const noexcept { return matchToks.size() - uniqueCount; } + int* row( std::size_t doc ) noexcept { return tf.data() + doc * stride; } + const int* row( std::size_t doc ) const noexcept { return tf.data() + doc * stride; } + + // Streams `text` at weight w into a caller-owned tf row and length accumulator (the per-file basename rows use it + // directly; addField is the per-doc form). Exact tokens own rows 0..uniqueCount (m == u there). + void scanTextInto( int* tfRow, int& wtAccum, std::string_view text, int w ) const + { + const auto tokOf = [ this ]( std::size_t m ) -> const std::string& { return matchToks[m].tok; }; + int fieldTokenWt = 0; forEachLexSubtoken( text, [ & ]( std::size_t tokStartByte, std::size_t tokEndByte ) { const std::size_t tokLen = tokEndByte - tokStartByte; @@ -761,825 +753,791 @@ inline std::vector<float> lexicalScoresTiered( const IngestResult& ing, const st return; } fieldTokenWt += w; - const std::size_t m = headIndex.matchRow( text.data() + tokStartByte, tokLen, matchTokOf ); - if( m != LexHeadIndex::kNoRow ) + if( const std::size_t m = headIndex.matchRow( text.data() + tokStartByte, tokLen, tokOf ); m != LexHeadIndex::kNoRow ) { - tfRow[m] += w; // exact tokens own rows 0..uniqueCount (m == u there) + tfRow[m] += w; } } ); wtAccum += fieldTokenWt; - }; - const auto scanField = [ & ]( std::size_t docIndex, std::string_view text, int w ) + } + + void addField( std::size_t doc, std::string_view text, int w ) { scanTextInto( row( doc ), dl[doc], text, w ); } + + // a field scanned once per FILE and shared by every doc in it (pass 1.6): its tf row and its length, added + void addFileField( std::size_t doc, const int* fileRow, int fileWt ) { - scanTextInto( tfFlat.data() + docIndex * matchCount, dl[ docIndex ], text, w ); - }; + int* const tfRow = row( doc ); + for( std::size_t m = 0; m < stride; ++m ) + { + tfRow[m] += fileRow[m]; + } + dl[doc] += fileWt; + } + + // the persisted-stats branch's exact stored integers (B0.2): a doc's doc/body length, and one term's tf + void addStoredLength( std::size_t doc, int length ) { dl[doc] += length; } + void addStoredTf( std::size_t doc, std::size_t m, int count ) { row( doc )[m] += count; } + + // The R3 fold: an admitted variant's column adds into its original term's row, a rejected one's is dropped (its + // evidence — name, callee, path, basename, doc, body — vanishes without touching dl: document length counts all + // subtokens scanned, never matches). The table then has the historical uniqueCount stride. + void foldAdmittedVariants( const std::vector<char>& admitted ) + { + if( variantCount() == 0 ) + { + return; // disarmed: already the historical layout + } + const std::size_t docCount = dl.size(); + std::vector<int> folded( docCount * uniqueCount, 0 ); + for( std::size_t i = 0; i < docCount; ++i ) + { + const int* const src = row( i ); + int* const dst = folded.data() + i * uniqueCount; + std::copy( src, src + uniqueCount, dst ); + for( std::size_t v = 0; v < admitted.size(); ++v ) + { + dst[ matchToks[ uniqueCount + v ].u ] += admitted[v] != 0 ? src[ uniqueCount + v ] : 0; + } + } + tf = std::move( folded ); + stride = uniqueCount; + } +}; + +// ── SIRA term margin (docs/EVALS.md "Corpus-statistics term margin", PRE-REGISTERED 2026-09-05) — the arming ── +// The decision itself needs corpus statistics that do not exist until after pass 2 (judgeTermMargins); all that is +// read here is whether it is armed and at which rung. The result is the k of "a term separates iff idf_u >= k * ln 2", +// k = 1 being the shipped rule and the only rung this round may ship (the ladder is frozen in the registration). +// 0 = disarmed: every step that reads it skips its margin work and the scorer is the historical one byte-for-byte. +inline int termMarginBitsFromEnv() +{ + const char* env = std::getenv( "RIPWIRE_TERMMARGIN" ); + if( env == nullptr || *env == '0' ) + { + return 0; + } + const std::optional<int> bits = envKnob<int>( "RIPWIRE_TERMMARGIN_BITS" ); + return bits ? std::clamp( *bits, 1, 8 ) : 1; +} + +// A field's weight: the caller's lens default, or the RIPWIRE_* calibration knob (clamped 0..8) when set. 0 = the +// field is not scanned at all. +inline int fieldWeightOrEnv( int lensDefaultW, const char* envName ) +{ + if( const std::optional<int> knob = envKnob<int>( envName ) ) + { + return std::clamp( *knob, 0, 8 ); + } + return lensDefaultW; +} - // ── SIRA term margin (docs/EVALS.md "Corpus-statistics term margin", PRE-REGISTERED 2026-09-05) ── - // Arming only. The decision itself needs corpus statistics that do not exist until after pass 2, so - // it lives below the fold; all that happens here is the extra field statistic the decision reads. - // marginBits is the k of "a term separates iff idf_u >= k * ln 2", k = 1 being the shipped rule and - // the only rung this round may ship (the ladder is frozen in the registration). Disarmed, every - // branch this flag guards is skipped and the scorer is the historical one byte-for-byte. - const int marginBits = [] - { - const char* env = std::getenv( "RIPWIRE_TERMMARGIN" ); - if( env == nullptr || *env == '0' ) - { - return 0; - } - const std::optional<int> bits = envKnob<int>( "RIPWIRE_TERMMARGIN_BITS" ); - return bits ? std::clamp( *bits, 1, 8 ) : 1; - }(); - const bool marginArmed = marginBits > 0; - - // nameDf[m] = symbols whose NAME FIELD ALONE carries match-table row m. This is the statistic the - // LB-1 negative is the reason for: that round's IDF floor read document frequency only, and so - // deleted `module` — the truth's OWN name carrier — on a corpus where `module` is everywhere in - // bodies. A term that names between 1 and S/2 symbols separates on the field ripwire weights - // highest (×3) whatever its body mass says, and is kept. Measured HERE, inside pass 1, because - // this is the only point at which the name field's contribution is separable from the callee, doc, - // body, path and basename fields that follow — and because pass 1 runs before the pass-2 branch - // split, so the scan and persisted-stats paths read the identical integers. - std::vector<int> nameDf( marginArmed ? matchCount : 0, 0 ); - // L-W: the name-field mask is separable ONLY here — the callee, path, doc and body fields land in the - // same tf row from the next statement on (the nameDf comment below says the same thing for its count). +// Field weights: a query term in a symbol's NAME outranks one in its DOC-COMMENT, which outranks one buried in its +// BODY — so an exactly-named function beats a struct that merely mentions the word, and an algorithm beats a +// comment-dense enum (the "keyword magnet" the review flagged). BM25 tf accumulates these weighted contributions; dl is +// weighted to match, so length normalization stays consistent. Doc/body weights are the SHARED constants (lexindex.h) — +// the index-time stats builder must weigh those two fields identically or the postings path would diverge from the scan. +inline constexpr int kLexWeightName = 3, kLexWeightCallee = 1; + +// pass 1 — name (×kLexWeightName) + callee-name (×kLexWeightCallee) fields, which need no file text. Two per-unit facts +// are separable ONLY here, after a unit's name field and before its callee, path, doc and body fields land in the same +// tf row, so they are captured here: +// L-W evidenceOut->nameMask, bit u set iff the NAME field alone carried terms[u] (with maskWords; skipped when null) +// SIRA the returned nameDf[m] = ranked units whose NAME FIELD ALONE carries match-table row m (empty when the margin is +// disarmed). This is the statistic the LB-1 negative is the reason for: that round's IDF floor read document +// frequency only, and so deleted `module` — the truth's OWN name carrier — on a corpus where `module` is +// everywhere in bodies. A term that names between 1 and S/2 symbols separates on the field ripwire weights highest +// (×3) whatever its body mass says, and is kept. Pass 1 runs before the pass-2 branch split, so the scan and +// persisted-stats paths read the identical integers. +inline std::vector<int> addNameAndCalleeFields( LexTfTable& table, const IngestResult& ing, const std::vector<std::uint32_t>& outOff, + const std::vector<NodeId>& outTargets, const LexCorpusRoles& roles, bool countNameDf, + LexTermEvidence* evidenceOut ) +{ + const std::size_t S = ing.symbols.size(); + const std::size_t uniqueCount = table.uniqueCount; const std::size_t evidenceWords = ( uniqueCount + 63 ) / 64; if( evidenceOut ) { evidenceOut->maskWords = evidenceWords; evidenceOut->nameMask.assign( S * evidenceWords, 0u ); } - - // pass 1 — name (×kwName) + callee-name (×kwCallee) fields need no file text + std::vector<int> nameDf( countNameDf ? table.stride : 0, 0 ); for( std::size_t i = 0; i < S; ++i ) { - scanField( i, ing.symbols[i].name, kwName ); - if( evidenceOut && !isUnranked( i ) ) + table.addField( i, ing.symbols[i].name, kLexWeightName ); + const int* const nameRow = table.row( i ); // name field only: nothing else has run for this unit yet + if( evidenceOut && !roles.isUnranked( i ) ) { - const int* const nameRow = tfFlat.data() + i * matchCount; // name field only: nothing else has run - std::uint64_t* words = evidenceOut->nameMask.data() + i * evidenceWords; + std::uint64_t* words = evidenceOut->nameMask.data() + i * evidenceWords; for( std::size_t u = 0; u < uniqueCount; ++u ) { - if( nameRow[u] > 0 ) - { - words[ u / 64 ] |= std::uint64_t( 1 ) << ( u % 64 ); - } + words[ u / 64 ] |= nameRow[u] > 0 ? std::uint64_t( 1 ) << ( u % 64 ) : 0u; } } - if( marginArmed ) + for( std::size_t m = 0; m < nameDf.size() && !roles.isUnranked( i ); ++m ) { - const int* const nameRow = tfFlat.data() + i * matchCount; // name field only: nothing else has run - for( std::size_t m = 0; m < matchCount && !isUnranked( i ); ++m ) - { - nameDf[m] += nameRow[m] > 0 ? 1 : 0; - } + nameDf[m] += nameRow[m] > 0 ? 1 : 0; } for( std::uint32_t e = outOff[i]; e < outOff[i + 1]; ++e ) { - scanField( i, ing.symbols[ outTargets[e] ].name, kwCallee ); + table.addField( i, ing.symbols[ outTargets[e] ].name, kLexWeightCallee ); } } + return nameDf; +} - // pass 1.5 — path field (×kwPath): the symbol's file path scanned through the SAME state machine. - // pathFieldDefaultW is the CALLER's lens decision: the RECALL lens (docs) passes 1 — a query naming a - // "readme" / "report" / "paired table" should be able to hit the doc whose PATH says exactly that, and - // bench/recalleval/ is the instrument that measured the +0.03 lenient-MRR / doc-sibling recovery this - // buys (2026-08-03, gate: test/recallevalcheck.sh). The CODE lenses (--for and friends) still pass 0: - // a nonzero default THERE requires the pre-registered locbench acceptance gate - // (bench/locbench/results/r3_pathtok/PREREG.md), unchanged. RIPWIRE_PATHTOK_W overrides either default - // for calibration sweeps only. Paths need no file text, so the pass sits before the branch below and - // runs identically over the scan and persisted-stats paths — postings parity holds by construction and - // the cache format is untouched. - // - // R-R RANKING (2026-08-25): the scanned string is the ROOT-RELATIVE VIEW, never ing.files[f] itself, - // which stays absolute because the emission lane proved it must (g.canonId, Regression::key, every - // pathQualifiedKey and the ingest cache's relForHash compare all key off it). Scanning it verbatim indexed - // every directory ABOVE the corpus as corpus vocabulary — and a directory that spelled a query word - // then matched EVERY document and collapsed that word's idf — so two clones of ONE commit at different - // checkout depths ranked --recall differently: 11 of 42 frozen queries reordered, 5 of them returning a - // different SET of documents (registered + measured in docs/EVALS.md; test/recallrankdepthcheck.sh). - // - // A VIEW, not a move — and the same helper recall.h PRINTS the separator path with, so the scored and - // the printed spelling of a file cannot disagree. rootRelativeUri(p, "") returns p bar a leading "./", - // exactly what a relative-root run already scanned, which is why this is a CONVERGENCE onto the - // already-invariant `ripwire .` rather than a new ranking opinion. Multi-root passes no prefix: - // ing.files already hold "<label>/<root-relative>". +// pass 1.5 — path field (×kwPath): the symbol's file path scanned through the SAME state machine. +// pathFieldDefaultW is the CALLER's lens decision: the RECALL lens (docs) passes 1 — a query naming a +// "readme" / "report" / "paired table" should be able to hit the doc whose PATH says exactly that, and +// bench/recalleval/ is the instrument that measured the +0.03 lenient-MRR / doc-sibling recovery this +// buys (2026-08-03, gate: test/recallevalcheck.sh). The CODE lenses (--for and friends) still pass 0: +// a nonzero default THERE requires the pre-registered locbench acceptance gate +// (bench/locbench/results/r3_pathtok/PREREG.md), unchanged. RIPWIRE_PATHTOK_W overrides either default +// for calibration sweeps only. Paths need no file text, so the pass sits before the pass-2 branch split and +// runs identically over the scan and persisted-stats paths — postings parity holds by construction and +// the cache format is untouched. +// +// R-R RANKING (2026-08-25): the scanned string is the ROOT-RELATIVE VIEW, never ing.files[f] itself, +// which stays absolute because the emission lane proved it must (g.canonId, Regression::key, every +// pathQualifiedKey and the ingest cache's relForHash compare all key off it). Scanning it verbatim indexed +// every directory ABOVE the corpus as corpus vocabulary — and a directory that spelled a query word +// then matched EVERY document and collapsed that word's idf — so two clones of ONE commit at different +// checkout depths ranked --recall differently: 11 of 42 frozen queries reordered, 5 of them returning a +// different SET of documents (registered + measured in docs/EVALS.md; test/recallrankdepthcheck.sh). +// +// A VIEW, not a move — and the same helper recall.h PRINTS the separator path with, so the scored and +// the printed spelling of a file cannot disagree. rootRelativeUri(p, "") returns p bar a leading "./", +// exactly what a relative-root run already scanned, which is why this is a CONVERGENCE onto the +// already-invariant `ripwire .` rather than a new ranking opinion. Multi-root passes no prefix: +// ing.files already hold "<label>/<root-relative>". +inline void addPathField( LexTfTable& table, const IngestResult& ing, int kwPath, std::string_view pathRootPrefix ) +{ + if( kwPath <= 0 ) { - int kwPath = pathFieldDefaultW; - if( const std::optional<int> pathTokW = envKnob<int>( "RIPWIRE_PATHTOK_W" ) ) - { - kwPath = std::clamp( *pathTokW, 0, 8 ); - } - if( kwPath > 0 ) + return; + } + for( std::size_t i = 0; i < ing.symbols.size(); ++i ) + { + if( const std::uint32_t f = ing.symbols[i].fileId; f < ing.files.size() ) { - for( std::size_t i = 0; i < S; ++i ) - { - if( const std::uint32_t f = ing.symbols[i].fileId; f < ing.files.size() ) - { - scanField( i, rw::sarif::rootRelativeUri( ing.files[f], pathRootPrefix ), kwPath ); - } - } + table.addField( i, rw::sarif::rootRelativeUri( ing.files[f], pathRootPrefix ), kwPath ); } } +} - // pass 1.6 — LB-3 arm B: basename-only field (×kwBase). The r3_pathtok retry, narrowed per that - // round's own rejection note (bench/locbench/results/r3_pathtok/PREREG.md): FULL paths lost - // held-out to generic-directory noise, so only the basename is scanned, and the scan is amortized - // per FILE (each basename tokenized once, its row added per symbol) honoring r3's "amortize - // first". Needs no file text → runs before the pass-2 branch split; parity and the cache format - // untouched. RIPWIRE_BASENAME_W (0..8) overrides basenameFieldDefaultW; a nonzero shipped default - // requires the LB-3 acceptance verdict (gate: test/lb3namecheck.sh). The code lens now passes - // kForBasenameFieldW (above) on GA1 DEV evidence only — the acceptance verdict is still owed. - // - // R-R: takes the same root-relative view as pass 1.5. PROVABLY a no-op here — the basename is whatever - // follows the last '/', which the root prefix cannot change — and applied anyway so the two path passes - // cannot drift apart. One reading of ing.files[f], one rule; a future reader who changes one pass finds - // the other already agreeing rather than discovering half the path tokenization was still absolute. +// pass 1.6 — LB-3 arm B: basename-only field (×kwBase). The r3_pathtok retry, narrowed per that +// round's own rejection note (bench/locbench/results/r3_pathtok/PREREG.md): FULL paths lost +// held-out to generic-directory noise, so only the basename is scanned, and the scan is amortized +// per FILE (each basename tokenized once, its row added per symbol) honoring r3's "amortize +// first". Needs no file text → runs before the pass-2 branch split; parity and the cache format +// untouched. RIPWIRE_BASENAME_W (0..8) overrides basenameFieldDefaultW; a nonzero shipped default +// requires the LB-3 acceptance verdict (gate: test/lb3namecheck.sh). The code lens now passes +// kForBasenameFieldW (above) on GA1 DEV evidence only — the acceptance verdict is still owed. +// +// R-R: takes the same root-relative view as pass 1.5. PROVABLY a no-op here — the basename is whatever +// follows the last '/', which the root prefix cannot change — and applied anyway so the two path passes +// cannot drift apart. One reading of ing.files[f], one rule; a future reader who changes one pass finds +// the other already agreeing rather than discovering half the path tokenization was still absolute. +inline void addBasenameField( LexTfTable& table, const IngestResult& ing, int kwBase, std::string_view pathRootPrefix ) +{ + if( kwBase <= 0 ) { - int kwBase = basenameFieldDefaultW; - if( const std::optional<int> baseW = envKnob<int>( "RIPWIRE_BASENAME_W" ) ) - { - kwBase = std::clamp( *baseW, 0, 8 ); - } - if( kwBase > 0 ) + return; + } + const std::size_t fileCount = ing.files.size(); + std::vector<int> fileTf( fileCount * table.stride, 0 ); + std::vector<int> fileWt( fileCount, 0 ); + for( std::size_t f = 0; f < fileCount; ++f ) + { + const std::string_view path = rw::sarif::rootRelativeUri( ing.files[f], pathRootPrefix ); + const std::size_t cut = path.find_last_of( '/' ); + const std::string_view base = cut == std::string_view::npos ? path : path.substr( cut + 1 ); + table.scanTextInto( fileTf.data() + f * table.stride, fileWt[f], base, kwBase ); + } + for( std::size_t i = 0; i < ing.symbols.size(); ++i ) + { + if( const std::uint32_t f = ing.symbols[i].fileId; f < fileCount && fileWt[f] != 0 ) { - const std::size_t fileCount = ing.files.size(); - std::vector<int> fileTf( fileCount * matchCount, 0 ); - std::vector<int> fileWt( fileCount, 0 ); - for( std::size_t f = 0; f < fileCount; ++f ) - { - const std::string_view path = rw::sarif::rootRelativeUri( ing.files[f], pathRootPrefix ); - const std::size_t cut = path.find_last_of( '/' ); - const std::string_view base = cut == std::string_view::npos ? path : path.substr( cut + 1 ); - scanTextInto( fileTf.data() + f * matchCount, fileWt[f], base, kwBase ); - } - for( std::size_t i = 0; i < S; ++i ) - { - const std::uint32_t f = ing.symbols[i].fileId; - if( f >= fileCount || fileWt[f] == 0 ) - { - continue; - } - int* const tfRow = tfFlat.data() + i * matchCount; - const int* const fRow = fileTf.data() + std::size_t( f ) * matchCount; - for( std::size_t m = 0; m < matchCount; ++m ) - { - tfRow[m] += fRow[m]; - } - dl[i] += fileWt[f]; - } + table.addFileField( i, fileTf.data() + std::size_t( f ) * table.stride, fileWt[f] ); } } +} - // per-variant doc/body document frequency, measured by whichever pass-2 branch runs — the guard's - // admission signal (rung R3). Both branches accumulate the same integers, so admission is identical. - const std::size_t variantCount = matchCount - uniqueCount; - std::vector<std::uint32_t> dfVariant( variantCount, 0u ); - - // pass 2 — doc-comment (×kwDoc) + body (×kwBody) evidence. - // - // B0.2 (R1 hypothesis #1): a RICH ingest carries per-symbol weighted subtoken statistics built ONCE at - // parse/cache time — from the SAME byte spans through the SAME state machine — so the per-query work - // here is pure lookups: no file re-read, no corpus re-tokenize (the O(corpus-bytes) per-query term is - // gone). The stored dl/tf values are the exact integers the scan branch would accumulate, and the float - // scoring loop below is shared, so the two branches are byte-identical (test/postingscheck.sh). - if( ing.hasLexStats && ing.lexTokenRowOffsets.size() == S + 1 && ing.lexDocBodyDl.size() == S ) - { - PROFILE_SCOPE_DESCRIBE( "lexical: pass 2 via persisted subtoken stats (cached tf/dl, no corpus re-tokenize)" ); - - // dl first: BM25 length normalization needs EVERY doc's weighted length whether or not it matches - // the query (avgdl sums them all), so this runs unconditionally — exact stored integers. - for( std::size_t i = 0; i < S; ++i ) - { - dl[i] += int( ing.lexDocBodyDl[i] ); - } - - // query-token hashes — the same normalized-lowercase hash index time used, over the FULL match - // table (exact tokens + LB-3 stem variants), each hash mapped to its own tf ROW (a variant's tf - // lands in its provisional column; the post-pass-2 guard decides whether it folds into the - // original token's row) — the same row targeting the scan branch's table walk applies. - // try_emplace keeps the FIRST entry on the astronomically-unlikely 64-bit collision between two - // DISTINCT table strings, so both transfer strategies below agree deterministically. - std::vector<std::uint64_t> matchHash( matchCount ); - HashMap<std::uint64_t, std::uint32_t> rowIndexOfHash; - rowIndexOfHash.reserve( matchCount ); - for( std::size_t m = 0; m < matchCount; ++m ) - { - matchHash[m] = lexSubtokenHash( matchToks[m].tok.data(), matchToks[m].tok.size() ); - rowIndexOfHash.try_emplace( matchHash[m], std::uint32_t( m ) ); - } - - // B0.1 per-file pre-filter: skip a whole file's tf walks when its 512-bit signature excludes every - // query subtoken — no false negatives (dl above is already complete; tf for such a file is provably - // zero), and a false positive just walks the cheap stats rows. Symbol ids are file-contiguous - // (assigned in fileId,line,name order), so the test amortizes to one signature check per file. - const bool useFileSig = ing.lexFileSig.size() == ing.files.size() * kLexFileSigWords; - std::uint32_t lastFileId = kNoNode; - bool lastFileMayMatch = true; - for( std::size_t i = 0; i < S; ++i ) - { - const std::uint32_t rowBegin = ing.lexTokenRowOffsets[i]; - const std::uint32_t rowEnd = ing.lexTokenRowOffsets[ i + 1 ]; - if( rowBegin == rowEnd ) - { - continue; // no doc/body tokens → nothing to transfer - } +// Which pass-2 source an ingest offers: B0.2 (R1 hypothesis #1) — a RICH ingest carries per-symbol weighted subtoken +// statistics built ONCE at parse/cache time, from the SAME byte spans through the SAME state machine, so the per-query +// work is pure lookups: no file re-read, no corpus re-tokenize. The stored dl/tf values are the exact integers the scan +// would accumulate, and the float scoring is shared, so the two sources are byte-identical (test/postingscheck.sh). +inline bool hasPersistedLexStats( const IngestResult& ing ) noexcept +{ + const std::size_t S = ing.symbols.size(); + return ing.hasLexStats && ing.lexTokenRowOffsets.size() == S + 1 && ing.lexDocBodyDl.size() == S; +} - // one membership probe per FILE against the query's subtoken bits (B0.1) - if( const std::uint32_t f = ing.symbols[i].fileId; useFileSig && f < ing.files.size() ) - { - if( f != lastFileId ) - { - lastFileId = f; - lastFileMayMatch = false; - const std::uint64_t* sig = ing.lexFileSig.data() + std::size_t( f ) * kLexFileSigWords; - for( std::size_t m = 0; m < matchCount && !lastFileMayMatch; ++m ) - { - if( sig[lexSigWord( matchHash[m] )] & lexSigBit( matchHash[m] ) ) - { - lastFileMayMatch = true; - } - } - } - if( !lastFileMayMatch ) - { - continue; - } - } +// pass 2 from persisted stats — doc-comment + body evidence as stored integers. Returns, per stem variant, the units +// whose stored doc/body rows carry it (the R3 guard's admission signal; stored rows hold each hash once → one bump per +// unit). The match rows are reached by the same normalized-lowercase hash index time used, over the FULL match table +// (exact tokens + LB-3 stem variants), each hash mapped to its own tf ROW — the same row targeting the scan applies. +// try_emplace keeps the FIRST entry on the astronomically-unlikely 64-bit collision between two DISTINCT table strings, +// so both transfer strategies agree deterministically. +inline std::vector<std::uint32_t> addDocBodyFromPersistedStats( LexTfTable& table, const IngestResult& ing ) +{ + PROFILE_SCOPE_DESCRIBE( "lexical: pass 2 via persisted subtoken stats (cached tf/dl, no corpus re-tokenize)" ); + const std::size_t S = ing.symbols.size(); + const std::size_t matchCount = table.stride; + const std::size_t uniqueCount = table.uniqueCount; + std::vector<std::uint32_t> dfVariant( table.variantCount(), 0u ); + + // dl first: BM25 length normalization needs EVERY doc's weighted length whether or not it matches + // the query (avgdl sums them all), so this runs unconditionally — exact stored integers. + for( std::size_t i = 0; i < S; ++i ) + { + table.addStoredLength( i, int( ing.lexDocBodyDl[i] ) ); + } - // exact tf transfer — walk whichever side is smaller: probe the query map per stored token, or - // binary-search each DISTINCT query hash in the symbol's sorted row. Identical sums either way - // (the map dedupes hash-colliding query tokens for both strategies). - int* const tfRow = tfFlat.data() + i * matchCount; - const std::uint64_t* rowHash = ing.lexTokenHashes.data(); - if( std::size_t( rowEnd - rowBegin ) <= matchCount * 8 ) // ~log2(row) probes vs one map probe per entry - { - for( std::uint32_t e = rowBegin; e < rowEnd; ++e ) - { - if( const auto it = rowIndexOfHash.find( rowHash[e] ); it != rowIndexOfHash.end() ) - { - tfRow[ it->second ] += int( ing.lexTokenTfs[e] ); - if( it->second >= uniqueCount ) - { - ++dfVariant[ it->second - uniqueCount ]; // stored rows hold each hash once → one df bump per symbol - } - } - } - } - else - { - for( const auto& [ hash, m ] : rowIndexOfHash ) // iteration order is score-irrelevant: rows are disjoint per HASH (+= commutes) - { - const std::uint64_t* lo = rowHash + rowBegin; - const std::uint64_t* hi = rowHash + rowEnd; - if( const std::uint64_t* it = std::lower_bound( lo, hi, hash ); it != hi && *it == hash ) - { - tfRow[m] += int( ing.lexTokenTfs[ std::size_t( it - rowHash ) ] ); - if( m >= uniqueCount ) - { - ++dfVariant[ m - uniqueCount ]; - } - } - } - } - } + std::vector<std::uint64_t> matchHash( matchCount ); + HashMap<std::uint64_t, std::uint32_t> rowIndexOfHash; + rowIndexOfHash.reserve( matchCount ); + for( std::size_t m = 0; m < matchCount; ++m ) + { + matchHash[m] = lexSubtokenHash( table.matchToks[m].tok.data(), table.matchToks[m].tok.size() ); + rowIndexOfHash.try_emplace( matchHash[m], std::uint32_t( m ) ); } - else + const auto addStoredTerm = [ & ]( std::size_t i, std::uint32_t m, std::uint32_t storedTf ) { - // scan branch (lean ingests, --no-cache lean verbs, multi-root merges, stubs): CSR file→symbol - // index, then stream ONE file at a time touching only that file's symbols — peak memory is a single - // file's text, not the whole corpus held at once (symbol order within a file is irrelevant: integer - // counts commute exactly). - const std::size_t fileCount = ing.files.size(); - std::vector<std::uint32_t> fileRowOffsets( fileCount + 1, 0 ); - for( std::size_t i = 0; i < S; ++i ) + table.addStoredTf( i, m, int( storedTf ) ); + if( m >= uniqueCount ) { - if( ing.symbols[i].fileId < fileCount ) - { - ++fileRowOffsets[ing.symbols[i].fileId + 1]; - } + ++dfVariant[ m - uniqueCount ]; // stored rows hold each hash once → one df bump per symbol } - for( std::size_t f = 0; f < fileCount; ++f ) + }; + + // B0.1 per-file pre-filter: skip a whole file's tf walks when its 512-bit signature excludes every + // query subtoken — no false negatives (dl above is already complete; tf for such a file is provably + // zero), and a false positive just walks the cheap stats rows. Symbol ids are file-contiguous + // (assigned in fileId,line,name order), so the test amortizes to one signature check per file. + const bool useFileSig = ing.lexFileSig.size() == ing.files.size() * kLexFileSigWords; + const auto fileMayHoldTerm = [ & ]( std::uint32_t f ) + { + const std::uint64_t* sig = ing.lexFileSig.data() + std::size_t( f ) * kLexFileSigWords; + return std::ranges::any_of( matchHash, [ sig ]( std::uint64_t h ) { return ( sig[ lexSigWord( h ) ] & lexSigBit( h ) ) != 0; } ); + }; + std::uint32_t lastFileId = kNoNode; + bool lastFileMayMatch = true; + for( std::size_t i = 0; i < S; ++i ) + { + const std::uint32_t rowBegin = ing.lexTokenRowOffsets[i]; + const std::uint32_t rowEnd = ing.lexTokenRowOffsets[ i + 1 ]; + const std::uint32_t f = ing.symbols[i].fileId; + const bool sigTests = useFileSig && f < ing.files.size(); + if( rowBegin == rowEnd ) { - fileRowOffsets[f + 1] += fileRowOffsets[f]; + continue; // no doc/body tokens → nothing to transfer } - std::vector<std::uint32_t> fileSymbolIds( fileRowOffsets[ fileCount ] ); + if( sigTests && f != lastFileId ) { - std::vector<std::uint32_t> writeCursor( fileRowOffsets.begin(), fileRowOffsets.end() - 1 ); - for( std::size_t i = 0; i < S; ++i ) - { - if( ing.symbols[i].fileId < fileCount ) - { - fileSymbolIds[writeCursor[ing.symbols[i].fileId]++] = std::uint32_t( i ); - } - } + lastFileId = f; // one membership probe per FILE (B0.1) + lastFileMayMatch = fileMayHoldTerm( f ); } - // Files stream across a small worker pool: each worker holds ONE file's text at a time, and a file's - // symbols are touched only by the worker that claimed the file — every dl[i] / tfFlat row has exactly - // ONE writer (no locks needed). Determinism: all pooled writes are exact integer counts and the float - // scoring below stays single-threaded in doc order, so worker scheduling cannot change a byte of - // output (no cross-doc float reductions — the det-gate rule). - // per-(file, variant) doc/body df tallies — a file's tally has exactly ONE writer (the worker - // that claimed the file), merged single-threaded below in file order; integer sums commute, so - // worker scheduling cannot change the totals (the det-gate rule). Sized only when armed. - std::vector<std::uint32_t> dfPerFile( variantCount > 0 ? fileCount * variantCount : 0, 0u ); - const auto scanFileSymbols = [ & ]( std::size_t f, const std::string& src ) - { - const std::string_view sv = src; - std::vector<int> variantTfBefore( variantCount ); - for( std::uint32_t r = fileRowOffsets[f]; r < fileRowOffsets[ f + 1 ]; ++r ) - { - const std::size_t i = fileSymbolIds[r]; - const Symbol& s = ing.symbols[i]; - const std::size_t bodyStart = std::min<std::size_t>( s.sigStartByte, src.size() ); - const std::size_t end = std::min<std::size_t>( s.endByte, src.size() ); - const std::size_t docStart = docCommentStart( src, bodyStart ); - if( variantCount > 0 ) // snapshot the variant columns: df must count ONLY - { // pass-2 (doc/body) growth, never pass-1 name/callee tf - const int* tfRow = tfFlat.data() + i * matchCount + uniqueCount; - std::copy( tfRow, tfRow + variantCount, variantTfBefore.begin() ); - } - if( bodyStart > docStart ) - { - scanField( i, sv.substr( docStart, bodyStart - docStart ), kwDoc ); - } - if( end > bodyStart ) - { - scanField( i, sv.substr( bodyStart, end - bodyStart ), kwBody ); - } - if( variantCount > 0 ) - { - const int* tfRow = tfFlat.data() + i * matchCount + uniqueCount; - for( std::size_t v = 0; v < variantCount; ++v ) - { - if( tfRow[v] > variantTfBefore[v] ) - { - ++dfPerFile[ f * variantCount + v ]; - } - } - } - } - }; - std::atomic<std::size_t> nextFileIndex { 0 }; - const auto fileWorker = [ & ]() noexcept - { - try - { - std::string loadedText; - for( std::size_t f = nextFileIndex.fetch_add( 1 ); f < fileCount; f = nextFileIndex.fetch_add( 1 ) ) - { - if( fileRowOffsets[f] == fileRowOffsets[f + 1] ) - { - continue; // no symbols in this file → skip - } - const std::string* src = lexicalScanText( ing, f, loadedText ); - if( src != nullptr && !src->empty() ) - { - scanFileSymbols( f, *src ); // unreadable/empty → degrade (skip), as before - } - } - } - catch( ... ) // a throw escaping a worker thread is std::terminate — degrade to partial counts instead - { - rw::emitRaw( stderr, "ripwire: lexical scan worker degraded (exception swallowed)\n" ); - } - }; - const std::size_t hwThreadCount = std::thread::hardware_concurrency(); - const std::size_t workerCount = std::min( { hwThreadCount ? hwThreadCount : 1, fileCount ? fileCount : 1, std::size_t( 16 ) } ); - if( workerCount <= 1 ) + if( sigTests && !lastFileMayMatch ) { - fileWorker(); + continue; } - else + + // exact tf transfer — walk whichever side is smaller: probe the query map per stored token, or + // binary-search each DISTINCT query hash in the symbol's sorted row. Identical sums either way + // (the map dedupes hash-colliding query tokens for both strategies). + const std::uint64_t* rowHash = ing.lexTokenHashes.data(); + if( std::size_t( rowEnd - rowBegin ) <= matchCount * 8 ) // ~log2(row) probes vs one map probe per entry { - // symmetric bare scope: workers live exactly as long as the pooled scan - std::vector<std::thread> workers; - workers.reserve( workerCount ); - for( std::size_t w = 0; w < workerCount; ++w ) - { - workers.emplace_back( fileWorker ); - } - for( std::thread& worker : workers ) + for( std::uint32_t e = rowBegin; e < rowEnd; ++e ) { - worker.join(); + if( const auto it = rowIndexOfHash.find( rowHash[e] ); it != rowIndexOfHash.end() ) + { + addStoredTerm( i, it->second, ing.lexTokenTfs[e] ); + } } + continue; } - for( std::size_t f = 0; f < fileCount && variantCount > 0; ++f ) // deterministic df merge, file order + for( const auto& [ hash, m ] : rowIndexOfHash ) // iteration order is score-irrelevant: rows are disjoint per HASH (+= commutes) { - for( std::size_t v = 0; v < variantCount; ++v ) + const std::uint64_t* lo = rowHash + rowBegin; + const std::uint64_t* hi = rowHash + rowEnd; + if( const std::uint64_t* it = std::lower_bound( lo, hi, hash ); it != hi && *it == hash ) { - dfVariant[v] += dfPerFile[ f * variantCount + v ]; + addStoredTerm( i, m, ing.lexTokenTfs[ std::size_t( it - rowHash ) ] ); } } } + return dfVariant; +} + +// pass 2 by scanning (lean ingests, --no-cache lean verbs, multi-root merges, stubs) — doc-comment (×kLexWeightDoc) + +// body (×kLexWeightBody) evidence, streamed ONE file at a time touching only that file's symbols: peak memory is a single +// file's text, not the whole corpus held at once (symbol order within a file is irrelevant: integer counts commute +// exactly). Returns the same per-variant doc/body df the persisted branch returns, from the scan's own counts. +// +// Files stream across a small worker pool: each worker holds ONE file's text at a time, and a file's symbols are touched +// only by the worker that claimed the file — every dl[i] / tf row has exactly ONE writer (no locks needed). Determinism: +// all pooled writes are exact integer counts and the float scoring stays single-threaded in doc order, so worker +// scheduling cannot change a byte of output (no cross-doc float reductions — the det-gate rule). The per-(file, variant) +// df tallies likewise have ONE writer each and merge single-threaded in file order. +inline std::vector<std::uint32_t> scanDocBodyFields( LexTfTable& table, const IngestResult& ing ) +{ + const std::size_t fileCount = ing.files.size(); + const std::size_t variantCount = table.variantCount(); - // ── IDF-guard admission + fold (rung R3) — runs identically after EITHER pass-2 branch ────────── - // A variant whose doc/body document frequency is corpus-common (df > max(8, S/64)) is discarded: - // its provisional column is simply never folded, so its evidence — name, callee, path, basename, - // doc, body — vanishes without touching dl (document length counts all subtokens scanned, never - // matches). An admitted (corpus-rare) variant folds its column into the original token's row, the - // exact integers the un-guarded arm would have accumulated there. The array then shrinks back to - // uniqueCount stride, and everything below — corpus stats, both scoring branches — is untouched - // code operating on the historical layout. - if( variantCount > 0 ) + const SymbolsByFile symbolsOfFile = symbolsByFileInIdOrder( ing, []( const Symbol& ) { return true; } ); + + std::vector<std::uint32_t> dfPerFile( variantCount > 0 ? fileCount * variantCount : 0, 0u ); // sized only when armed + const auto scanFileSymbols = [ & ]( std::size_t f, const std::string& src ) { - const std::uint32_t sOver64 = std::uint32_t( allS / 64 ); // the ranked corpus: an unranked unit does not widen the cap - const std::uint32_t variantCap = sOver64 > 8u ? sOver64 : 8u; - if( std::getenv( "RIPWIRE_QSTEM_DEBUG" ) != nullptr ) + const std::string_view sv = src; + std::vector<int> variantTfBefore( variantCount ); + for( const NodeId i : symbolsOfFile[f] ) { - for( std::size_t v = 0; v < variantCount; ++v ) + const Symbol& s = ing.symbols[i]; + const std::size_t bodyStart = std::min<std::size_t>( s.sigStartByte, src.size() ); + const std::size_t end = std::min<std::size_t>( s.endByte, src.size() ); + const std::size_t docStart = docCommentStart( src, bodyStart ); + const int* const variantTf = table.row( i ) + table.uniqueCount; + // snapshot the variant columns: df must count ONLY pass-2 (doc/body) growth, never pass-1 name/callee tf + std::copy( variantTf, variantTf + variantCount, variantTfBefore.begin() ); + if( bodyStart > docStart ) { - rw::emitTo( stderr, "qstem-guard: \"{}\" df={} cap={} {}\n", - matchToks[ uniqueCount + v ].tok.c_str(), dfVariant[v], variantCap, - dfVariant[v] <= variantCap ? "admitted" : "rejected" ); + table.addField( i, sv.substr( docStart, bodyStart - docStart ), kLexWeightDoc ); } - } - std::vector<int> tfFolded( S * uniqueCount, 0 ); - for( std::size_t i = 0; i < S; ++i ) - { - const int* const src = tfFlat.data() + i * matchCount; - int* const dst = tfFolded.data() + i * uniqueCount; - for( std::size_t u = 0; u < uniqueCount; ++u ) + if( end > bodyStart ) { - dst[u] = src[u]; + table.addField( i, sv.substr( bodyStart, end - bodyStart ), kLexWeightBody ); } for( std::size_t v = 0; v < variantCount; ++v ) { - if( dfVariant[v] <= variantCap ) - { - dst[ matchToks[ uniqueCount + v ].u ] += src[ uniqueCount + v ]; - } + dfPerFile[ f * variantCount + v ] += variantTf[v] > variantTfBefore[v] ? 1u : 0u; } } - tfFlat = std::move( tfFolded ); - if( marginArmed ) + }; + std::atomic<std::size_t> nextFileIndex { 0 }; + const auto fileWorker = [ & ]() noexcept + { + try { - // fold nameDf the SAME way tf just folded, so the margin test below sees one row per unique - // token on either arm. A doc carrying both the exact token and an admitted variant in its - // name is counted twice, so a folded nameDf is a CEILING, not a count — stated rather than - // hidden. It matters only when RIPWIRE_QSTEM is also armed, which ships off. - for( std::size_t v = 0; v < variantCount; ++v ) + std::string loadedText; + for( std::size_t f = nextFileIndex.fetch_add( 1 ); f < fileCount; f = nextFileIndex.fetch_add( 1 ) ) { - if( dfVariant[v] <= variantCap ) + if( symbolsOfFile[f].empty() ) { - nameDf[ matchToks[ uniqueCount + v ].u ] += nameDf[ uniqueCount + v ]; + continue; // no symbols in this file → skip + } + const std::string* src = lexicalScanText( ing, f, loadedText ); + if( src != nullptr && !src->empty() ) + { + scanFileSymbols( f, *src ); // unreadable/empty → degrade (skip), as before } } } + catch( ... ) // a throw escaping a worker thread is std::terminate — degrade to partial counts instead + { + rw::emitRaw( stderr, "ripwire: lexical scan worker degraded (exception swallowed)\n" ); + } + }; + const std::size_t hwThreadCount = std::thread::hardware_concurrency(); + const std::size_t workerCount = std::min( { hwThreadCount ? hwThreadCount : 1, fileCount ? fileCount : 1, std::size_t( 16 ) } ); + if( workerCount <= 1 ) + { + fileWorker(); + } + else + { + // symmetric bare scope: workers live exactly as long as the pooled scan + std::vector<std::thread> workers; + workers.reserve( workerCount ); + for( std::size_t w = 0; w < workerCount; ++w ) + { + workers.emplace_back( fileWorker ); + } + for( std::thread& worker : workers ) + { + worker.join(); + } } - // ── L-W: the term evidence, read off the FINAL tf rows (uniqueCount stride, every field, the fold applied) - // — one S×U integer scan, the same "tf > 0" fact dfreq counts in both scoring branches below. - if( evidenceOut ) + std::vector<std::uint32_t> dfVariant( variantCount, 0u ); + for( std::size_t f = 0; f < fileCount && variantCount > 0; ++f ) // deterministic df merge, file order { - evidenceOut->termsSeenTotal = dedup.uniqueSeenTotal; - evidenceOut->termsCapped = dedup.capped; - evidenceOut->terms.assign( uniqueToks.begin(), uniqueToks.end() ); - evidenceOut->df.assign( uniqueCount, 0u ); - evidenceOut->anyMask.assign( S * evidenceWords, 0u ); - evidenceOut->symbolCount = S; - evidenceOut->statsCount = statsS; - for( std::size_t i = 0; i < S; ++i ) - { - const int* const row = tfFlat.data() + i * uniqueCount; - std::uint64_t* words = evidenceOut->anyMask.data() + i * evidenceWords; - const int w = statsWeight( i ); - for( std::size_t u = 0; u < uniqueCount && !isUnranked( i ); ++u ) - { - if( row[u] > 0 ) - { - evidenceOut->df[u] += std::uint32_t( w ); - words[ u / 64 ] |= std::uint64_t( 1 ) << ( u % 64 ); - } - } + for( std::size_t v = 0; v < variantCount; ++v ) + { + dfVariant[v] += dfPerFile[ f * variantCount + v ]; } } + return dfVariant; +} + +// ── IDF-guard admission (rung R3) — the same decision after EITHER pass-2 source ───────────────────────── +// A variant whose doc/body document frequency is corpus-common (df > max(8, rankedCount/64)) is rejected; a corpus-rare +// one is admitted and folds into its original token's row — the exact integers the un-guarded arm would have +// accumulated there. The cap reads the ranked corpus: an unranked unit does not widen it. Returns one flag per variant +// (empty when disarmed); RIPWIRE_QSTEM_DEBUG prints each verdict on stderr. +inline std::vector<char> admitRareStemVariants( const std::vector<std::uint32_t>& dfVariant, std::size_t rankedCount, + const LexTfTable& table ) +{ + const std::uint32_t sOver64 = std::uint32_t( rankedCount / 64 ); + const std::uint32_t variantCap = sOver64 > 8u ? sOver64 : 8u; + std::vector<char> admitted( dfVariant.size(), 0 ); + for( std::size_t v = 0; v < dfVariant.size(); ++v ) + { + admitted[v] = dfVariant[v] <= variantCap ? 1 : 0; + } + const bool debug = !dfVariant.empty() && std::getenv( "RIPWIRE_QSTEM_DEBUG" ) != nullptr; + for( std::size_t v = 0; v < dfVariant.size() && debug; ++v ) + { + rw::emitTo( stderr, "qstem-guard: \"{}\" df={} cap={} {}\n", table.matchToks[ table.uniqueCount + v ].tok.c_str(), dfVariant[v], + variantCap, admitted[v] != 0 ? "admitted" : "rejected" ); + } + return admitted; +} - // ── SIRA term margin — the decision (docs/EVALS.md, PRE-REGISTERED 2026-09-05) ──────────────────── - // A query term earns its contribution by SEPARATING the target from corpus-level confusers, not by - // looking relevant. BM25's own idf says when that stops being true: at df = S/2, - // idf = ln( (S-n+0.5)/(n+0.5) + 1 ) is exactly ln 2 — one bit, the point at which observing the term - // halves the candidate space. Above it the term carries less than a bit and hands its tf mass to - // whichever document recites it most, which on a natural-language query ("how does the csrf token - // get validated") is the prose, not the answer. This ranker has no query-side stopword list, and a - // corpus-statistics margin test is that idea derived from the tree in front of it rather than - // written down in English — a Rust corpus's `mut` and a Python corpus's `self` are caught by the - // same arithmetic that catches `the`, with nothing language-specific anywhere. - // - // TWO FIELDS, because ONE field is how the LB-1 negative happened. That round's IDF floor read - // document frequency alone and deleted `module` — the truth's own name carrier — flipping a hit to - // a miss (docs/EVALS.md §7). A term that names between 1 and S/2 symbols separates on the field - // this scorer weights highest, whatever its body mass says, so `separatesName` keeps it. A term - // naming NOTHING has no name margin to appeal to; a term naming MORE than half the corpus has no - // margin there either. - // - // THE SOLE-ANCHOR GUARD, and the trap inside it. Suppression is skipped entirely unless a PRESENT, - // non-suppressed term survives it — otherwise a query whose every term is corpus-saturating scores - // zero everywhere, which is the catastrophic shape, not a ranking. "Present" is load-bearing and is - // the subtle half: an ABSENT term (df = 0) has the LARGEST idf in the whole scheme, - // ln( (S+0.5)/0.5 + 1 ), so an implementation that asks "did a higher-idf term survive?" without - // excluding absent terms reads a typo beside the anchor as excellent evidence and drops the anchor. - // Gated: test/termmargincheck.sh arms (b), (c) and (d), each red before this code existed. - // - // KEPT OR DROPPED, never fractionally weighted. A kept term's contribution is the historical - // expression evaluated in the historical order — bit-identical, not merely close — and a dropped - // term's impact cap is 0, so the MaxScore bound stays a valid bound and the pruned and exhaustive - // branches stay byte-identical to each other. `dl` is untouched: a suppressed term's EVIDENCE - // vanishes, the document's length does not, exactly the posture the R3 variant guard already takes. - std::vector<char> termKept( uniqueCount, 1 ); - if( marginArmed ) +// fold nameDf the SAME way the tf table folds, so the margin test sees one row per unique token on either arm. A doc +// carrying both the exact token and an admitted variant in its name is counted twice, so a folded nameDf is a CEILING, +// not a count — stated rather than hidden. It matters only when RIPWIRE_QSTEM is also armed, which ships off. +inline void foldAdmittedNameDf( std::vector<int>& nameDf, const std::vector<char>& admitted, const LexTfTable& table ) +{ + for( std::size_t v = 0; v < admitted.size() && !nameDf.empty(); ++v ) + { + nameDf[ table.matchToks[ table.uniqueCount + v ].u ] += admitted[v] != 0 ? nameDf[ table.uniqueCount + v ] : 0; + } +} + +// ── L-W: the term evidence, read off the FINAL tf rows (uniqueCount stride, every field, the fold applied) — one S×U +// integer scan, the same "tf > 0" fact the document frequency counts when scoring. (nameMask was captured in pass 1.) +inline void recordTermEvidence( LexTermEvidence& evidence, const LexTfTable& table, const LexCorpusRoles& roles, const DedupedQueryTerms& dedup ) +{ + const std::size_t S = table.dl.size(); + const std::size_t uniqueCount = table.uniqueCount; + const std::size_t evidenceWords = evidence.maskWords; + evidence.termsSeenTotal = dedup.uniqueSeenTotal; + evidence.termsCapped = dedup.capped; + evidence.terms.assign( dedup.uniqueToks.begin(), dedup.uniqueToks.end() ); + evidence.df.assign( uniqueCount, 0u ); + evidence.anyMask.assign( S * evidenceWords, 0u ); + evidence.symbolCount = S; + evidence.statsCount = roles.countedCount; + for( std::size_t i = 0; i < S; ++i ) { - // df in fixed doc order over the folded rows — the same integers both pass-2 branches produced - std::vector<int> dfMargin( uniqueCount, 0 ); - for( std::size_t i = 0; i < S; ++i ) + const int* const row = table.row( i ); + std::uint64_t* words = evidence.anyMask.data() + i * evidenceWords; + const int w = roles.statsWeight( i ); + for( std::size_t u = 0; u < uniqueCount && !roles.isUnranked( i ); ++u ) { - const int* const tfRow = tfFlat.data() + i * uniqueCount; - const int w = statsWeight( i ); - for( std::size_t u = 0; u < uniqueCount; ++u ) - { - dfMargin[u] += tfRow[u] > 0 ? w : 0; - } + evidence.df[u] += row[u] > 0 ? std::uint32_t( w ) : 0u; + words[ u / 64 ] |= row[u] > 0 ? std::uint64_t( 1 ) << ( u % 64 ) : 0u; } - // "separates" at k bits: idf_u >= k*ln2 ⇔ (S-n+0.5)/(n+0.5) + 1 >= 2^k ⇔ n <= (S+0.5)/2^k - 0.5, - // which at k = 1 is exactly n <= S/2. Evaluated in doubles from integer inputs, so it is a pure - // function of (S, n, k) and cannot vary run to run. - const double separationCut = ( double( statsS ) + 0.5 ) / std::exp2( double( marginBits ) ) - 0.5; - std::vector<char> suppressible( uniqueCount, 0 ); - std::size_t presentCount = 0, survivorCount = 0; + } +} + +// ── SIRA term margin — the decision (docs/EVALS.md, PRE-REGISTERED 2026-09-05) ──────────────────── +// A query term earns its contribution by SEPARATING the target from corpus-level confusers, not by +// looking relevant. BM25's own idf says when that stops being true: at df = S/2, +// idf = ln( (S-n+0.5)/(n+0.5) + 1 ) is exactly ln 2 — one bit, the point at which observing the term +// halves the candidate space. Above it the term carries less than a bit and hands its tf mass to +// whichever document recites it most, which on a natural-language query ("how does the csrf token +// get validated") is the prose, not the answer. This ranker has no query-side stopword list, and a +// corpus-statistics margin test is that idea derived from the tree in front of it rather than +// written down in English — a Rust corpus's `mut` and a Python corpus's `self` are caught by the +// same arithmetic that catches `the`, with nothing language-specific anywhere. +// +// TWO FIELDS, because ONE field is how the LB-1 negative happened. That round's IDF floor read +// document frequency alone and deleted `module` — the truth's own name carrier — flipping a hit to +// a miss (docs/EVALS.md §7). A term that names between 1 and S/2 symbols separates on the field +// this scorer weights highest, whatever its body mass says, so the name margin keeps it. A term +// naming NOTHING has no name margin to appeal to; a term naming MORE than half the corpus has no +// margin there either. +// +// THE SOLE-ANCHOR GUARD, and the trap inside it. Suppression is skipped entirely unless a PRESENT, +// non-suppressed term survives it — otherwise a query whose every term is corpus-saturating scores +// zero everywhere, which is the catastrophic shape, not a ranking. "Present" is load-bearing and is +// the subtle half: an ABSENT term (df = 0) has the LARGEST idf in the whole scheme, +// ln( (S+0.5)/0.5 + 1 ), so an implementation that asks "did a higher-idf term survive?" without +// excluding absent terms reads a typo beside the anchor as excellent evidence and drops the anchor. +// Gated: test/termmargincheck.sh arms (b), (c) and (d), each red before this code existed. +// +// KEPT OR DROPPED, never fractionally weighted. A kept term's contribution is the historical +// expression evaluated in the historical order — bit-identical, not merely close — and a dropped +// term's impact cap is 0, so the MaxScore bound stays a valid bound and the pruned and exhaustive +// modes stay byte-identical to each other. `dl` is untouched: a suppressed term's EVIDENCE +// vanishes, the document's length does not, exactly the posture the R3 variant guard already takes. +// +// Each present term gets ONE verdict, decided here; termKept and the RIPWIRE_TERMMARGIN_DEBUG lines both read it. +enum class TermMarginVerdict : std::uint8_t +{ + kAbsent, // df 0: contributes nothing, survives nothing + kDocSeparates, // kept: its document frequency alone is under the cut + kNameSeparates, // kept: it names between 1 and cut units (the LB-1 protection) + kSoleAnchor, // would be suppressed, but no present term survives — suppression withheld for the whole query + kSuppressed, +}; + +// Returns termKept per unique term: all 1 when the margin is disarmed (marginBits 0). +inline std::vector<char> judgeTermMargins( const LexTfTable& table, const LexCorpusRoles& roles, const std::vector<int>& nameDf, int marginBits, + const std::vector<std::string>& uniqueToks ) +{ + const std::size_t uniqueCount = table.uniqueCount; + std::vector<char> termKept( uniqueCount, 1 ); + if( marginBits <= 0 ) + { + return termKept; + } + // df in fixed doc order over the folded rows — the same integers both pass-2 sources produced + std::vector<int> dfMargin( uniqueCount, 0 ); + for( std::size_t i = 0; i < table.dl.size(); ++i ) + { + const int* const tfRow = table.row( i ); + const int w = roles.statsWeight( i ); for( std::size_t u = 0; u < uniqueCount; ++u ) { - if( dfMargin[u] == 0 ) - { - continue; // absent: contributes nothing, survives nothing - } - ++presentCount; - const bool separatesDoc = double( dfMargin[u] ) <= separationCut; - const bool separatesName = nameDf[u] > 0 && double( nameDf[u] ) <= separationCut; - suppressible[u] = ( !separatesDoc && !separatesName ) ? 1 : 0; - survivorCount += suppressible[u] == 0 ? 1 : 0; + dfMargin[u] += tfRow[u] > 0 ? w : 0; } - const bool applySuppression = survivorCount > 0; // the sole-anchor guard - for( std::size_t u = 0; u < uniqueCount; ++u ) + } + // "separates" at k bits: idf_u >= k*ln2 ⇔ (S-n+0.5)/(n+0.5) + 1 >= 2^k ⇔ n <= (S+0.5)/2^k - 0.5, + // which at k = 1 is exactly n <= S/2. Evaluated in doubles from integer inputs, so it is a pure + // function of (S, n, k) and cannot vary run to run. + const double separationCut = ( double( roles.countedCount ) + 0.5 ) / std::exp2( double( marginBits ) ) - 0.5; + std::vector<TermMarginVerdict> verdict( uniqueCount, TermMarginVerdict::kAbsent ); + std::size_t presentCount = 0, survivorCount = 0; + for( std::size_t u = 0; u < uniqueCount; ++u ) + { + const bool separatesDoc = double( dfMargin[u] ) <= separationCut; + const bool separatesName = nameDf[u] > 0 && double( nameDf[u] ) <= separationCut; + verdict[u] = dfMargin[u] == 0 ? TermMarginVerdict::kAbsent + : separatesDoc ? TermMarginVerdict::kDocSeparates + : separatesName ? TermMarginVerdict::kNameSeparates + : TermMarginVerdict::kSuppressed; + presentCount += dfMargin[u] > 0 ? 1 : 0; + survivorCount += verdict[u] == TermMarginVerdict::kDocSeparates || verdict[u] == TermMarginVerdict::kNameSeparates ? 1 : 0; + } + const bool applySuppression = survivorCount > 0; // the sole-anchor guard + for( std::size_t u = 0; u < uniqueCount; ++u ) + { + if( verdict[u] == TermMarginVerdict::kSuppressed && !applySuppression ) { - termKept[u] = ( applySuppression && suppressible[u] != 0 ) ? 0 : 1; + verdict[u] = TermMarginVerdict::kSoleAnchor; } - if( std::getenv( "RIPWIRE_TERMMARGIN_DEBUG" ) != nullptr ) + termKept[u] = verdict[u] == TermMarginVerdict::kSuppressed ? 0 : 1; + } + if( std::getenv( "RIPWIRE_TERMMARGIN_DEBUG" ) != nullptr ) + { + static constexpr const char* kVerdictText[] = { "absent", "kept (doc-separates)", "kept (name-separates)", "kept (sole-anchor)", + "SUPPRESSED" }; + for( std::size_t u = 0; u < uniqueCount; ++u ) { - for( std::size_t u = 0; u < uniqueCount; ++u ) - { - const char* verdict = "absent"; - if( dfMargin[u] > 0 ) - { - if( termKept[u] == 0 ) - { - verdict = "SUPPRESSED"; - } - else if( !applySuppression && suppressible[u] != 0 ) - { - verdict = "kept (sole-anchor)"; - } - else if( double( dfMargin[u] ) <= separationCut ) - { - verdict = "kept (doc-separates)"; - } - else - { - verdict = "kept (name-separates)"; - } - } - rw::emitTo( stderr, "term-margin: \"{}\" df={}/{} nameDf={} bits={} {}\n", - uniqueToks[u].c_str(), dfMargin[u], statsS, nameDf[u], marginBits, verdict ); - } - rw::emitTo( stderr, "term-margin: {} present, {} survive, suppression {}\n", - presentCount, survivorCount, applySuppression ? "applied" : "withheld (sole-anchor)" ); + rw::emitTo( stderr, "term-margin: \"{}\" df={}/{} nameDf={} bits={} {}\n", uniqueToks[u].c_str(), dfMargin[u], roles.countedCount, + nameDf[u], marginBits, kVerdictText[ std::size_t( verdict[u] ) ] ); } + rw::emitTo( stderr, "term-margin: {} present, {} survive, suppression {}\n", presentCount, survivorCount, + applySuppression ? "applied" : "withheld (sole-anchor)" ); } + return termKept; +} - // corpus stats — avgdl accumulates in the SAME doc order as before (identical doubles); dfreq[u] = - // number of docs containing unique query token u (w ≥ 1, so tf > 0 ⇔ the old docs[i] contained it) - // statsOut: the counted units' average (the same doc order: identical doubles when every unit counts) scores the - // counted units; an OUT unit scores against the whole corpus (avgdlAll, S, its df plus dfOut), as with no statsOut. - double avgdl = 0, avgdlAll = 0; +// The corpus statistics BM25 scores against, tallied in ONE pass over the final tf rows in ascending doc id. +// avgdl accumulates in the historical doc order (integer sums: exact in any order anyway). dfreq[u] = COUNTED units +// containing unique query token u (w ≥ 1, so tf > 0 ⇔ the old docs[i] contained it); dfOut[u] = statsOut units carrying +// it (all 0 with no statsOut). A counted unit scores with (countedCount, dfreq, avgdlCounted); a statsOut unit against +// the whole ranked corpus (rankedCount, dfreq + dfOut, avgdlRanked), as with no statsOut. +struct LexBm25Stats +{ + std::vector<int> dfreq; + std::vector<int> dfOut; + std::vector<int> tfMaxOf; // per term, its largest weighted tf anywhere — the MaxScore bound's T + std::vector<std::uint32_t> candidateIds; // ascending: every unit with any tf > 0 + double avgdlCounted = 0; + double avgdlRanked = 0; +}; + +inline LexBm25Stats tallyBm25Stats( const LexTfTable& table, const LexCorpusRoles& roles ) +{ + const std::size_t S = table.dl.size(); + const std::size_t uniqueCount = table.uniqueCount; + LexBm25Stats st; + st.dfreq.assign( uniqueCount, 0 ); + st.dfOut.assign( uniqueCount, 0 ); + st.tfMaxOf.assign( uniqueCount, 0 ); + st.candidateIds.reserve( 1024 ); for( std::size_t i = 0; i < S; ++i ) { - avgdl += statsWeight( i ) != 0 ? dl[i] : 0; - avgdlAll += isUnranked( i ) ? 0 : dl[i]; - } - avgdl /= double( statsS ? statsS : 1 ); - avgdlAll /= double( allS ? allS : 1 ); - std::vector<int> dfOut( uniqueCount, 0 ); // per term, the OUT units carrying it (all 0 with no statsOut) - const auto countOut = [ & ]( const int* tfRow ) - { + st.avgdlCounted += roles.statsWeight( i ) != 0 ? table.dl[i] : 0; + st.avgdlRanked += roles.isUnranked( i ) ? 0 : table.dl[i]; + const int* const tfRow = table.row( i ); + const int w = roles.statsWeight( i ); + const int out = roles.isStatsOut( i ) ? 1 : 0; + bool any = false; for( std::size_t u = 0; u < uniqueCount; ++u ) { - dfOut[u] += tfRow[u] > 0 ? 1 : 0; + const bool carries = tfRow[u] > 0; + st.dfreq[u] += carries ? w : 0; + st.dfOut[u] += carries ? out : 0; + st.tfMaxOf[u] = std::max( st.tfMaxOf[u], tfRow[u] ); + any = any || carries; } - }; - - const Bm25Params bm25Params = resolveBm25Params(); // A4: the ONE definition — see above - const double k1 = bm25Params.k1, b = bm25Params.b; - std::vector<float> score( S, 0.f ); - - // ── H2 (B0 round 2): MaxScore-style safe pruning — only when the caller opted in AND the env - // escape hatch is off. The exhaustive branch below is the pre-H2 code, byte-for-byte. - const bool pruneActive = pruneTopK > 0 && std::getenv( "RIPWIRE_NO_PRUNE" ) == nullptr; - if( pruneActive ) - { - // one pass: candidates (any tf > 0 — every other doc scores EXACTLY the same +0.0f either way), - // exact dfreq, and the per-term max weighted tf the impact bound needs. Ascending doc id. - std::vector<int> dfreq( uniqueCount, 0 ); - std::vector<int> tfMaxOf( uniqueCount, 0 ); - std::vector<std::uint32_t> candidateIds; - candidateIds.reserve( 1024 ); - for( std::size_t i = 0; i < S; ++i ) - { - const int* tfRow = tfFlat.data() + i * uniqueCount; - bool any = false; - const int w = statsWeight( i ); - if( w == 0 && !isUnranked( i ) ) - { - countOut( tfRow ); - } - for( std::size_t u = 0; u < uniqueCount; ++u ) - { - if( tfRow[u] > 0 ) - { - dfreq[u] += w; - if( tfRow[u] > tfMaxOf[u] ) - { - tfMaxOf[u] = tfRow[u]; - } - any = true; - } - } - if( any ) - { - candidateIds.push_back( std::uint32_t( i ) ); - } + if( any ) + { + st.candidateIds.push_back( std::uint32_t( i ) ); } + } + st.avgdlCounted /= double( roles.countedCount ? roles.countedCount : 1 ); + st.avgdlRanked /= double( roles.rankedCount ? roles.rankedCount : 1 ); + return st; +} - // ── the PROVABLY-SAFE per-term impact bound (the MaxScore "max contribution") ──────────────── - // A term u's contribution to any doc is idf_u × tf(k1+1)/(tf + k1(1−b+b·dl/avgdl)). Two exact - // monotonicities bound it: it INCREASES in tf (so tf ≤ T := tfMaxOf[u], the largest weighted tf - // of u anywhere in the corpus) and DECREASES in dl (dl ≥ 0 ⇒ the mixed factor ≥ 1−b), giving - // contribution ≤ idf_u × T(k1+1)/(T + k1(1−b)) in REAL arithmetic. - // In IEEE doubles each side is computed with ≤ 7 rounded ops (relative error ≤ 7·2⁻⁵³ ≈ 8e-16), - // so the ×(1+1e-9) slack — six orders of magnitude above the worst accumulated rounding, and - // likewise above the U·2⁻⁵³ summation error of the per-doc bound sum below — makes the COMPUTED - // cap strictly ≥ the COMPUTED contribution. The Section ×0.30 down-weight and the §P4 tier - // multiplier (both (0,1], shrink-only) only shrink a real score, never the bound. - // Hence: bound < θ ⇒ computed score < θ, unconditionally. - // capOcc folds in the query-occurrence multiplicity (BM25 adds one contribution PER occurrence). - std::vector<double> capOcc( uniqueCount, 0.0 ); - { - std::vector<int> occCount( uniqueCount, 0 ); - for( std::size_t qi = 0; qi < qToks.size(); ++qi ) - { - if( uniqueIndexOfQtok[qi] == DedupedQueryTerms::kDroppedTerm ) - { - continue; // capped past kMaxUniqueQueryTerms — owns no row, no contribution - } - ++occCount[uniqueIndexOfQtok[qi]]; - } - for( std::size_t u = 0; u < uniqueCount; ++u ) - { - if( dfreq[u] + dfOut[u] == 0 || termKept[u] == 0 ) - { - continue; // never contributes anywhere — a suppressed term's cap stays 0, and a cap of - // 0 bounds a contribution of 0, so the MaxScore proof below is unchanged - } - const int n = dfreq[u]; - const int nAll = n + dfOut[u]; // an OUT unit's idf: the larger of the two bounds the contribution - const double idfIn = n > 0 ? std::log( ( double( statsS ) - n + 0.5 ) / ( n + 0.5 ) + 1.0 ) : 0.0; - const double idfAll = dfOut[u] > 0 ? std::log( ( double( allS ) - nAll + 0.5 ) / ( nAll + 0.5 ) + 1.0 ) : 0.0; - const double idf = std::max( idfIn, idfAll ); - const double T = double( tfMaxOf[u] ); - const double cap1 = bm25ImpactBound( idf, T, bm25Params ); // A4: shared bound, same (k1,b) - capOcc[u] = cap1 * double( occCount[u] ); - } +// ── H2 (B0 round 2): MaxScore-style SAFE early termination, decided once ──────────────────────────────── +// Armed only when the caller opted in (pruneTopK > 0: it consumes only the top-pruneTopK ranked units, plus +// `alwaysExact` — e.g. every interface packLego may surface) AND the RIPWIRE_NO_PRUNE escape hatch is off (the +// postingscheck equivalence gate flips it). Disarmed, skips() is always false and the scorer is exhaustive. +// +// The PROVABLY-SAFE per-term impact bound (the MaxScore "max contribution"): a term u's contribution to any doc is +// idf_u × tf(k1+1)/(tf + k1(1−b+b·dl/avgdl)). Two exact monotonicities bound it: it INCREASES in tf (so tf ≤ T := +// tfMaxOf[u], the largest weighted tf of u anywhere in the corpus) and DECREASES in dl (dl ≥ 0 ⇒ the mixed factor +// ≥ 1−b), giving +// contribution ≤ idf_u × T(k1+1)/(T + k1(1−b)) in REAL arithmetic. +// In IEEE doubles each side is computed with ≤ 7 rounded ops (relative error ≤ 7·2⁻⁵³ ≈ 8e-16), so the ×(1+1e-9) +// slack — six orders of magnitude above the worst accumulated rounding, and likewise above the U·2⁻⁵³ summation +// error of the per-doc bound sum — makes the COMPUTED cap strictly ≥ the COMPUTED contribution. The Section ×0.30 +// down-weight and the §P4 tier multiplier (both (0,1], shrink-only) only shrink a real score, never the bound. +// Hence: bound < θ ⇒ computed score < θ, unconditionally. capOcc folds in the query-occurrence multiplicity (BM25 +// adds one contribution PER occurrence). +// +// θ = K-th best exact score seen so far (min-heap; grows monotonically). θ at skip time ≤ final θ ≤ the true K-th +// best overall, and skipping needs bound < θ STRICTLY, so a skipped doc's true score is strictly below the final +// K-th score — it cannot enter the top-K even via the (score desc, id asc) tie-break. Docs are visited in ascending id +// (determinism). Safety is absolute, not approximate: the emitted top-K set, their EXACT scores, and their +// (score desc, id asc) order are byte-identical to exhaustive scoring. +class LexTopKPruner +{ +public: + LexTopKPruner( std::size_t pruneTopK, const std::vector<char>* alwaysExact, const LexBm25Stats& st, const LexCorpusRoles& roles, + const DedupedQueryTerms& dedup, const std::vector<char>& termKept, const Bm25Params& bm25Params ) + : topK_( std::getenv( "RIPWIRE_NO_PRUNE" ) == nullptr ? pruneTopK : 0 ), alwaysExact_( alwaysExact ) + { + if( topK_ == 0 ) + { + return; } - - // top-K threshold θ = K-th best exact score seen so far (min-heap; grows monotonically). θ at - // skip time ≤ final θ ≤ the true K-th best overall, and skipping needs bound < θ STRICTLY, so a - // skipped doc's true score is strictly below the final K-th score — it cannot enter the top-K - // even via the (score desc, id asc) tie-break. Docs are processed in ascending id (determinism). - std::vector<double> heap; // min-heap over exact final scores - heap.reserve( pruneTopK ); - double theta = -1.0; // scores are ≥ 0 ⇒ no skips until K docs scored - for( const std::uint32_t i : candidateIds ) + heap_.reserve( topK_ ); + const std::size_t uniqueCount = st.dfreq.size(); + std::vector<int> occCount( uniqueCount, 0 ); + for( const std::size_t u : dedup.uniqueIndexOfQtok ) { - const int* tfRow = tfFlat.data() + std::size_t( i ) * uniqueCount; - - // cheap upper bound: adds only, fixed u-ascending order (deterministic) - double ub = 0.0; - for( std::size_t u = 0; u < uniqueCount; ++u ) - { - if( tfRow[u] > 0 ) - { - ub += capOcc[u]; - } - } - if( isUnranked( i ) ) - { - continue; // a kRankFlagNotLexRanked unit scores 0, the value a skipped symbol keeps - } - const bool mustScore = alwaysExact && i < alwaysExact->size() && (*alwaysExact)[i] != 0; - if( !mustScore && ub < theta ) - { - continue; // provably cannot enter the top-K → skip - } - - // exact score — the IDENTICAL expressions, in the IDENTICAL order, as the exhaustive branch - const bool outI = statsWeight( i ) == 0; - const double Si = outI ? double( allS ) : double( statsS ); - const double avgI = outI ? avgdlAll : avgdl; - double sc = 0; - for( std::size_t qi = 0; qi < qToks.size(); ++qi ) - { - const std::size_t u = uniqueIndexOfQtok[qi]; - if( u == DedupedQueryTerms::kDroppedTerm ) - { - continue; // capped past kMaxUniqueQueryTerms — owns no row, no contribution - } - const int tf = tfRow[u]; - if( tf == 0 || termKept[u] == 0 ) - { - continue; // termKept is all-1 disarmed, so this reads as the historical `tf == 0` - } - const int n = dfreq[u] + ( outI ? dfOut[u] : 0 ); - const double idf = std::log( ( Si - n + 0.5 ) / ( n + 0.5 ) + 1.0 ); - sc += idf * ( tf * ( k1 + 1.0 ) ) / ( tf + k1 * ( 1.0 - b + b * dl[i] / ( avgI > 0 ? avgI : 1.0 ) ) ); - } - if( ing.symbols[i].kind == SymKind::Section ) - { - sc *= 0.30; - } - if( symbolScoreMul && i < symbolScoreMul->size() ) + if( u != DedupedQueryTerms::kDroppedTerm ) // capped past kMaxUniqueQueryTerms — owns no row, no contribution { - sc *= double( ( *symbolScoreMul )[i] ); // §P4 tier down-weight — shrink-only, bound-safe + ++occCount[u]; } - score[i] = float( sc ); - - if( heap.size() < pruneTopK ) - { - heap.push_back( sc ); - std::push_heap( heap.begin(), heap.end(), std::greater<double>{} ); - if( heap.size() == pruneTopK ) - { - theta = heap.front(); - } - } - else if( sc > heap.front() ) + } + capOcc_.assign( uniqueCount, 0.0 ); + for( std::size_t u = 0; u < uniqueCount; ++u ) + { + if( st.dfreq[u] + st.dfOut[u] == 0 || termKept[u] == 0 ) { - std::pop_heap( heap.begin(), heap.end(), std::greater<double>{} ); - heap.back() = sc; - std::push_heap( heap.begin(), heap.end(), std::greater<double>{} ); - theta = heap.front(); + continue; // never contributes anywhere — a suppressed term's cap stays 0, and a cap of + // 0 bounds a contribution of 0, so the MaxScore proof above is unchanged } + const int n = st.dfreq[u]; + const int nAll = n + st.dfOut[u]; // an OUT unit's idf: the larger of the two bounds the contribution + const double idfIn = n > 0 ? std::log( ( double( roles.countedCount ) - n + 0.5 ) / ( n + 0.5 ) + 1.0 ) : 0.0; + const double idfAll = st.dfOut[u] > 0 ? std::log( ( double( roles.rankedCount ) - nAll + 0.5 ) / ( nAll + 0.5 ) + 1.0 ) : 0.0; + const double idf = std::max( idfIn, idfAll ); + const double cap1 = bm25ImpactBound( idf, double( st.tfMaxOf[u] ), bm25Params ); // A4: shared bound, same (k1,b) + capOcc_[u] = cap1 * double( occCount[u] ); } - return score; } - std::vector<int> dfreq( uniqueCount, 0 ); - for( std::size_t i = 0; i < S; ++i ) + // true iff unit i provably cannot enter the top-K: its bound (adds only, fixed u-ascending order) is below θ + bool skips( std::uint32_t i, const int* tfRow ) const { - const int w = statsWeight( i ); - if( w == 0 && !isUnranked( i ) ) + if( topK_ == 0 || ( alwaysExact_ && i < alwaysExact_->size() && ( *alwaysExact_ )[i] != 0 ) ) { - countOut( tfFlat.data() + i * uniqueCount ); + return false; } - for( std::size_t u = 0; u < uniqueCount; ++u ) + double ub = 0.0; + for( std::size_t u = 0; u < capOcc_.size(); ++u ) { - if( tfFlat[i * uniqueCount + u] > 0 ) + if( tfRow[u] > 0 ) { - dfreq[u] += w; + ub += capOcc_[u]; } } + return ub < theta_; } - for( std::size_t i = 0; i < S; ++i ) + void record( double sc ) { - if( isUnranked( i ) ) + if( topK_ == 0 ) + { + return; + } + if( heap_.size() < topK_ ) + { + heap_.push_back( sc ); + std::push_heap( heap_.begin(), heap_.end(), std::greater<double>{} ); + theta_ = heap_.size() == topK_ ? heap_.front() : theta_; + return; + } + if( sc > heap_.front() ) + { + std::pop_heap( heap_.begin(), heap_.end(), std::greater<double>{} ); + heap_.back() = sc; + std::push_heap( heap_.begin(), heap_.end(), std::greater<double>{} ); + theta_ = heap_.front(); + } + } + +private: + std::size_t topK_; + const std::vector<char>* alwaysExact_; + std::vector<double> capOcc_; + std::vector<double> heap_; // min-heap over exact final scores + double theta_ = -1.0; // scores are ≥ 0 ⇒ no skips until K units scored +}; + +// The exact BM25 score of every candidate the pruner does not rule out — the historical expressions in the historical +// order (one contribution PER query occurrence, ascending qi; a kept term only, and termKept is all-1 disarmed). Every +// other unit keeps the +0.0f the vector starts with, which is exactly what exhaustive scoring computes for it: +// - a non-candidate has no tf > 0 for any term, so its sum is +0.0, and the Section ×0.30 and the §P4 tier multiplier +// keep it +0.0 because every multiplier is in (0,1] (filter.h rankTierSymbolMultipliersShaped; the DASSERT below); +// - a kRankFlagNotLexRanked unit (model.h) scores 0; +// - a pruned unit provably cannot enter the top-K the caller consumes (LexTopKPruner). +// So the exhaustive mode needs no loop of its own: it is this loop with a pruner that never skips. +inline std::vector<float> scoreLexCandidates( const IngestResult& ing, const LexTfTable& table, const LexBm25Stats& st, const LexCorpusRoles& roles, + const DedupedQueryTerms& dedup, const std::vector<char>& termKept, const Bm25Params& bm25Params, + LexTopKPruner& pruner, const std::vector<float>* symbolScoreMul ) +{ + DASSERT( symbolScoreMul == nullptr || std::ranges::all_of( *symbolScoreMul, []( float mul ) { return mul > 0.f && mul <= 1.f; } ), + "a tier multiplier outside (0,1] would score a non-candidate unit other than +0.0f and break the MaxScore bound" ); + const std::vector<std::size_t>& uniqueIndexOfQtok = dedup.uniqueIndexOfQtok; + const std::vector<int>& dl = table.dl; + const double k1 = bm25Params.k1, b = bm25Params.b; + std::vector<float> score( dl.size(), 0.f ); + for( const std::uint32_t i : st.candidateIds ) + { + const int* tfRow = table.row( i ); + if( roles.isUnranked( i ) || pruner.skips( i, tfRow ) ) { - continue; // a kRankFlagNotLexRanked unit scores 0 (model.h) + continue; } - const bool outI = statsWeight( i ) == 0; - const double Si = outI ? double( allS ) : double( statsS ); - const double avgI = outI ? avgdlAll : avgdl; + const bool outI = roles.isStatsOut( i ); + const double Si = outI ? double( roles.rankedCount ) : double( roles.countedCount ); + const double avgI = outI ? st.avgdlRanked : st.avgdlCounted; double sc = 0; - for( std::size_t qi = 0; qi < qToks.size(); ++qi ) + for( std::size_t qi = 0; qi < uniqueIndexOfQtok.size(); ++qi ) { const std::size_t u = uniqueIndexOfQtok[qi]; if( u == DedupedQueryTerms::kDroppedTerm ) { - continue; // capped past kMaxUniqueQueryTerms — owns no row, no contribution + continue; // capped past kMaxUniqueQueryTerms — owns no row, no contribution } - const int tf = tfFlat[ i * uniqueCount + u ]; + const int tf = tfRow[u]; if( tf == 0 || termKept[u] == 0 ) { continue; // old: docs[i].find( qt ) == end — termKept is all-1 disarmed, so this is that } - const int n = dfreq[u] + ( outI ? dfOut[u] : 0 ); + const int n = st.dfreq[u] + ( outI ? st.dfOut[u] : 0 ); const double idf = std::log( ( Si - n + 0.5 ) / ( n + 0.5 ) + 1.0 ); sc += idf * ( tf * ( k1 + 1.0 ) ) / ( tf + k1 * ( 1.0 - b + b * dl[i] / ( avgI > 0 ? avgI : 1.0 ) ) ); } @@ -1591,15 +1549,78 @@ inline std::vector<float> lexicalScoresTiered( const IngestResult& ing, const st } if( symbolScoreMul && i < symbolScoreMul->size() ) { - sc *= double( ( *symbolScoreMul )[i] ); // §P4 tier down-weight (same factor as the pruned branch) + sc *= double( ( *symbolScoreMul )[i] ); // §P4 tier down-weight — shrink-only, bound-safe } score[i] = float( sc ); + pruner.record( sc ); } return score; } +// BM25 score of `query` against each symbol's doc (name subtokens + callees' names + DOC-COMMENT & BODY +// text). Returns a per-symbol score vector (size = symbols.size()). Cold path: one query. The steps above, in order. +inline std::vector<float> lexicalScoresTiered( const IngestResult& ing, const std::vector<std::uint32_t>& outOff, + const std::vector<NodeId>& outTargets, std::string_view query, + std::size_t pruneTopK, const std::vector<char>* alwaysExact, + const std::vector<float>* symbolScoreMul, int pathFieldDefaultW = 0, + int basenameFieldDefaultW = 0, std::string_view pathRootPrefix = {}, + LexTermEvidence* evidenceOut = nullptr, // L-W: the term evidence, read back out (see the struct) + const std::vector<char>* statsOut = nullptr ) // units scored but kept OUT of the corpus statistics +{ + PROFILE_SCOPE_DESCRIBE( "lexical: lexicalScores (BM25 over symbols)" ); + const std::size_t S = ing.symbols.size(); + const LexCorpusRoles roles = assignLexCorpusRoles( ing, statsOut ); + + // query subtokens — occurrence order preserved (BM25 adds one contribution PER occurrence, as before); + // an empty query scores exactly 0 everywhere (0.0 survives the Section down-weight unchanged) + std::vector<std::string> qToks; + subtokens( query, qToks ); + if( qToks.empty() ) + { + if( evidenceOut ) + { + *evidenceOut = LexTermEvidence{}; + evidenceOut->symbolCount = S; + evidenceOut->statsCount = S; // no term, so no idf ever reads it + } + return std::vector<float>( S, 0.f ); + } + + // dedupe to the unique terms whose statistics we need — a duplicated query word must not double-count + // tf, but still contributes once PER OCCURRENCE in the scoring loop (uniqueIndexOfQtok maps back) — + // capped (see dedupeQueryTerms above) so a pathologically term-rich query cannot blow up the tf table's + // S×terms allocation below. + const DedupedQueryTerms dedup = dedupeQueryTerms( qToks, kMaxUniqueQueryTerms ); + const std::vector<LexMatchTok> matchToks = buildLexMatchTable( dedup.uniqueToks ); + LexTfTable table( S, matchToks, dedup.uniqueToks.size() ); + + // the fields, weakest dependence first: name + callee (pass 1), path (1.5) and basename (1.6) need no file text, + // so they run before the pass-2 source split; then doc-comment + body (pass 2) from whichever source the ingest has + const int marginBits = termMarginBitsFromEnv(); + std::vector<int> nameDf = addNameAndCalleeFields( table, ing, outOff, outTargets, roles, /*countNameDf=*/marginBits > 0, evidenceOut ); + addPathField( table, ing, fieldWeightOrEnv( pathFieldDefaultW, "RIPWIRE_PATHTOK_W" ), pathRootPrefix ); + addBasenameField( table, ing, fieldWeightOrEnv( basenameFieldDefaultW, "RIPWIRE_BASENAME_W" ), pathRootPrefix ); + const std::vector<std::uint32_t> dfVariant = hasPersistedLexStats( ing ) ? addDocBodyFromPersistedStats( table, ing ) : scanDocBodyFields( table, ing ); + + // what the corpus statistics decide: which stem variants stay, then which query terms separate + const std::vector<char> admitted = admitRareStemVariants( dfVariant, roles.rankedCount, table ); + table.foldAdmittedVariants( admitted ); + foldAdmittedNameDf( nameDf, admitted, table ); + if( evidenceOut ) + { + recordTermEvidence( *evidenceOut, table, roles, dedup ); + } + const std::vector<char> termKept = judgeTermMargins( table, roles, nameDf, marginBits, dedup.uniqueToks ); + + // score: corpus statistics, then every candidate the MaxScore pruner (armed only on request) does not rule out + const LexBm25Stats stats = tallyBm25Stats( table, roles ); + const Bm25Params bm25Params = resolveBm25Params(); // A4: the ONE definition — see above + LexTopKPruner pruner( pruneTopK, alwaysExact, stats, roles, dedup, termKept, bm25Params ); + return scoreLexCandidates( ing, table, stats, roles, dedup, termKept, bm25Params, pruner, symbolScoreMul ); +} + // the un-tiered contract every pre-§P4 caller keeps (evals, exemplar, --recall): same arity as always, -// byte-identical scores (a null multiplier is the identity in both scoring branches above). +// byte-identical scores (a null multiplier is the identity in scoreLexCandidates above, pruned or exhaustive). inline std::vector<float> lexicalScores( const IngestResult& ing, const std::vector<std::uint32_t>& outOff, const std::vector<NodeId>& outTargets, std::string_view query, std::size_t pruneTopK = 0, const std::vector<char>* alwaysExact = nullptr, From 81adcac0bbf672919cf7768dc7ef74ae6952396c Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:40:16 -0500 Subject: [PATCH 31/61] refactor(lexical): the BM25 (k1, b) travel with the corpus statistics they score with tallyBm25Stats resolves them (still after the term-margin step, so knob warnings keep their order) and LexTopKPruner and scoreLexCandidates read them from LexBm25Stats instead of a separate parameter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/lexical.h | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/lexical.h b/src/lexical.h index a41063bca..9fe5f4e94 100644 --- a/src/lexical.h +++ b/src/lexical.h @@ -1337,7 +1337,8 @@ inline std::vector<char> judgeTermMargins( const LexTfTable& table, const LexCor return termKept; } -// The corpus statistics BM25 scores against, tallied in ONE pass over the final tf rows in ascending doc id. +// The corpus statistics BM25 scores against, tallied in ONE pass over the final tf rows in ascending doc id, and the +// (k1, b) it scores with (A4: resolveBm25Params, the ONE definition the impact bound reads too). // avgdl accumulates in the historical doc order (integer sums: exact in any order anyway). dfreq[u] = COUNTED units // containing unique query token u (w ≥ 1, so tf > 0 ⇔ the old docs[i] contained it); dfOut[u] = statsOut units carrying // it (all 0 with no statsOut). A counted unit scores with (countedCount, dfreq, avgdlCounted); a statsOut unit against @@ -1350,6 +1351,7 @@ struct LexBm25Stats std::vector<std::uint32_t> candidateIds; // ascending: every unit with any tf > 0 double avgdlCounted = 0; double avgdlRanked = 0; + Bm25Params params = kBm25Default; }; inline LexBm25Stats tallyBm25Stats( const LexTfTable& table, const LexCorpusRoles& roles ) @@ -1384,6 +1386,7 @@ inline LexBm25Stats tallyBm25Stats( const LexTfTable& table, const LexCorpusRole } st.avgdlCounted /= double( roles.countedCount ? roles.countedCount : 1 ); st.avgdlRanked /= double( roles.rankedCount ? roles.rankedCount : 1 ); + st.params = resolveBm25Params(); return st; } @@ -1413,7 +1416,7 @@ class LexTopKPruner { public: LexTopKPruner( std::size_t pruneTopK, const std::vector<char>* alwaysExact, const LexBm25Stats& st, const LexCorpusRoles& roles, - const DedupedQueryTerms& dedup, const std::vector<char>& termKept, const Bm25Params& bm25Params ) + const DedupedQueryTerms& dedup, const std::vector<char>& termKept ) : topK_( std::getenv( "RIPWIRE_NO_PRUNE" ) == nullptr ? pruneTopK : 0 ), alwaysExact_( alwaysExact ) { if( topK_ == 0 ) @@ -1443,7 +1446,7 @@ class LexTopKPruner const double idfIn = n > 0 ? std::log( ( double( roles.countedCount ) - n + 0.5 ) / ( n + 0.5 ) + 1.0 ) : 0.0; const double idfAll = st.dfOut[u] > 0 ? std::log( ( double( roles.rankedCount ) - nAll + 0.5 ) / ( nAll + 0.5 ) + 1.0 ) : 0.0; const double idf = std::max( idfIn, idfAll ); - const double cap1 = bm25ImpactBound( idf, double( st.tfMaxOf[u] ), bm25Params ); // A4: shared bound, same (k1,b) + const double cap1 = bm25ImpactBound( idf, double( st.tfMaxOf[u] ), st.params ); // A4: shared bound, same (k1,b) capOcc_[u] = cap1 * double( occCount[u] ); } } @@ -1505,14 +1508,14 @@ class LexTopKPruner // - a pruned unit provably cannot enter the top-K the caller consumes (LexTopKPruner). // So the exhaustive mode needs no loop of its own: it is this loop with a pruner that never skips. inline std::vector<float> scoreLexCandidates( const IngestResult& ing, const LexTfTable& table, const LexBm25Stats& st, const LexCorpusRoles& roles, - const DedupedQueryTerms& dedup, const std::vector<char>& termKept, const Bm25Params& bm25Params, - LexTopKPruner& pruner, const std::vector<float>* symbolScoreMul ) + const DedupedQueryTerms& dedup, const std::vector<char>& termKept, LexTopKPruner& pruner, + const std::vector<float>* symbolScoreMul ) { DASSERT( symbolScoreMul == nullptr || std::ranges::all_of( *symbolScoreMul, []( float mul ) { return mul > 0.f && mul <= 1.f; } ), "a tier multiplier outside (0,1] would score a non-candidate unit other than +0.0f and break the MaxScore bound" ); const std::vector<std::size_t>& uniqueIndexOfQtok = dedup.uniqueIndexOfQtok; const std::vector<int>& dl = table.dl; - const double k1 = bm25Params.k1, b = bm25Params.b; + const double k1 = st.params.k1, b = st.params.b; std::vector<float> score( dl.size(), 0.f ); for( const std::uint32_t i : st.candidateIds ) { @@ -1613,10 +1616,9 @@ inline std::vector<float> lexicalScoresTiered( const IngestResult& ing, const st const std::vector<char> termKept = judgeTermMargins( table, roles, nameDf, marginBits, dedup.uniqueToks ); // score: corpus statistics, then every candidate the MaxScore pruner (armed only on request) does not rule out - const LexBm25Stats stats = tallyBm25Stats( table, roles ); - const Bm25Params bm25Params = resolveBm25Params(); // A4: the ONE definition — see above - LexTopKPruner pruner( pruneTopK, alwaysExact, stats, roles, dedup, termKept, bm25Params ); - return scoreLexCandidates( ing, table, stats, roles, dedup, termKept, bm25Params, pruner, symbolScoreMul ); + const LexBm25Stats stats = tallyBm25Stats( table, roles ); + LexTopKPruner pruner( pruneTopK, alwaysExact, stats, roles, dedup, termKept ); + return scoreLexCandidates( ing, table, stats, roles, dedup, termKept, pruner, symbolScoreMul ); } // the un-tiered contract every pre-§P4 caller keeps (evals, exemplar, --recall): same arity as always, From 191b7fcb4e4d4f3824e019192d516008c822a54a Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:46:36 -0500 Subject: [PATCH 32/61] refactor(lexical): the BM25 fold phase is a type, and margin arming and idf are decided once Blind-review follow-up on lexicalScoresTiered's named steps (verdict BETTER): - The tf table before the stem-variant fold (LexMatchTfTable: match-row stride, the provisional variant columns, nameDf and the per-variant doc/body df) and after it (LexTermTfTable: one row per unique query term) are separate types. The fold consumes the first and returns the second, folding tf rows and nameDf with the same row fold. The stale post-fold variantCount() and the mutable stride are gone: every step after the fold takes the post-fold type. - Whether the SIRA term margin is armed is one LexTermMargin, read once from the environment and carried by the table. Pass 1's nameDf count, the fold and judgeTermMargins all ask margin.armed(), replacing a bool parameter, nameDf.empty() and marginBits <= 0. - Names say what the passes produce: addNameAndCalleeFieldsCapturingNameHits, addDocBodyFieldsFromPersistedStats / addDocBodyFieldsByFileScan (behind addDocBodyFields), both filling the table's variantDocDf for admitRareStemVariants. - recordTermEvidence computes the mask width itself (LexTermEvidence::maskWordsFor) and asserts that pass 1 captured the name mask at that width. - idf is computed once per term and role in LexBm25Stats (idfCounted / idfRanked, through the one bm25Idf expression). The scoring loop, the MaxScore bound and LexTermEvidence::idf read it, so none re-derives which corpus a unit scores against. No answer changes: fire321 0/321, md5 12/12 on arm64 (also with RIPWIRE_QSTEM=1 and RIPWIRE_TERMMARGIN=1), identity set 75/75. Under -ffast-math, byte identity is a codegen fact; the x86-64-v3 legs are CI's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/lexical.h | 356 ++++++++++++++++++++++++++++++-------------------- 1 file changed, 216 insertions(+), 140 deletions(-) diff --git a/src/lexical.h b/src/lexical.h index 9fe5f4e94..2026507dd 100644 --- a/src/lexical.h +++ b/src/lexical.h @@ -139,6 +139,15 @@ inline bool holdsSubtokenWord( std::string_view text, const std::vector<std::str // anyMask per symbol, bit u set iff it carried terms[u] in any field (the final row, after the fold) // Masks are maskWords 64-bit words per symbol (maskWords = ceil(terms/64)): a pasted stack trace with a // hundred unique terms is tracked in full, nothing silently dropped from the share. +// +// BM25's idf for a term carried by n of the N units the corpus statistics count — the ONE spelling of the expression: +// the scorer's per-term table (LexBm25Stats), its MaxScore bound and the evidence below all read it. An absent term +// (n = 0) weighs as the rarest possible term, ln( (N+0.5)/0.5 + 1 ), never as nothing. +inline double bm25Idf( double N, double n ) noexcept +{ + return std::log( ( N - n + 0.5 ) / ( n + 0.5 ) + 1.0 ); +} + struct LexTermEvidence { std::vector<std::string> terms; @@ -156,16 +165,12 @@ struct LexTermEvidence std::size_t termsSeenTotal = 0; bool termsCapped = false; - const std::uint64_t* anyMaskOf( std::size_t sym ) const noexcept { return anyMask.data() + sym * maskWords; } - static bool hasBit( const std::uint64_t* mask, std::size_t u ) noexcept { return ( mask[ u / 64 ] >> ( u % 64 ) ) & 1u; } + static constexpr std::size_t maskWordsFor( std::size_t termCount ) noexcept { return ( termCount + 63 ) / 64; } + const std::uint64_t* anyMaskOf( std::size_t sym ) const noexcept { return anyMask.data() + sym * maskWords; } + static bool hasBit( const std::uint64_t* mask, std::size_t u ) noexcept { return ( mask[ u / 64 ] >> ( u % 64 ) ) & 1u; } - // BM25's own idf for term u over the `statsCount` symbols the statistics count — the exact expression scoreLexCandidates uses, - // so an absent term (df 0) weighs as the rarest possible term and never as nothing. - double idf( std::size_t u ) const noexcept - { - const double n = double( df[u] ); - return std::log( ( double( statsCount ) - n + 0.5 ) / ( n + 0.5 ) + 1.0 ); - } + // BM25's own idf for term u over the `statsCount` symbols the statistics count (bm25Idf, the scorer's expression) + double idf( std::size_t u ) const noexcept { return bm25Idf( double( statsCount ), double( df[u] ) ); } }; // docCommentStart moved to lexindex.h (B0.2): the index-time stats builder must scan the EXACT spans this @@ -705,13 +710,54 @@ inline std::vector<LexMatchTok> buildLexMatchTable( const std::vector<std::strin return rows; } -// The per-query BM25 term table every field pass adds into (SoA): dl[i] = doc i's weighted subtoken count (the BM25 -// document length) and tf[i * stride + m] = the weighted term frequency of match-table row m in doc i. Integer counts are -// exact, so fill order is free and the float scoring later runs in strict doc order with the historical expressions. -// Until the stem-variant fold, stride == matchCount and provisional variant columns sit at m ≥ uniqueCount; the fold -// (foldAdmittedVariants) shrinks it back to uniqueCount, the historical layout byte-for-byte. Disarmed, the two are equal. +// ── SIRA term margin (docs/EVALS.md "Corpus-statistics term margin", PRE-REGISTERED 2026-09-05) — the arming ── +// The decision itself needs corpus statistics that do not exist until after pass 2 (judgeTermMargins); all that is +// read here is whether it is armed and at which rung, ONCE per query: the tf tables carry it, pass 1 counts nameDf +// only when it is armed, the fold folds nameDf only then, and judgeTermMargins decides only then — one predicate. +// bits is the k of "a term separates iff idf_u >= k * ln 2", k = 1 being the shipped rule and the only rung this round +// may ship (the ladder is frozen in the registration). 0 = disarmed: the scorer is the historical one byte-for-byte. +struct LexTermMargin +{ + int bits = 0; + bool armed() const noexcept { return bits > 0; } +}; + +inline LexTermMargin termMarginFromEnv() +{ + const char* env = std::getenv( "RIPWIRE_TERMMARGIN" ); + if( env == nullptr || *env == '0' ) + { + return {}; + } + const std::optional<int> bits = envKnob<int>( "RIPWIRE_TERMMARGIN_BITS" ); + return { bits ? std::clamp( *bits, 1, 8 ) : 1 }; +} + +// The per-query BM25 term table AFTER the stem-variant fold — the historical layout, one row per unique query term: +// dl[i] = doc i's weighted subtoken count (the BM25 document length), tf[i * uniqueCount + u] = the weighted term +// frequency of unique term u in doc i, and nameDf[u] = the term margin's name-field document frequency (empty when the +// margin is disarmed). Every step from the term evidence on reads THIS type, and the only way to make one is the fold +// (LexMatchTfTable::foldAdmittedVariants below), so no later step can see a provisional variant column or a match-row +// stride. Integer counts are exact, so the float scoring later runs in strict doc order with the historical expressions. +struct LexTermTfTable +{ + std::size_t uniqueCount = 0; + std::vector<int> dl; + std::vector<int> tf; + std::vector<int> nameDf; + LexTermMargin margin; + + std::size_t docCount() const noexcept { return dl.size(); } + const int* row( std::size_t doc ) const noexcept { return tf.data() + doc * uniqueCount; } +}; + +// The same table BEFORE the fold, while the field passes add into it: one row per MATCH-table row (tf[i * matchCount() + m]), +// so the LB-3 stem variants sit in provisional columns m ≥ uniqueCount (none when RIPWIRE_QSTEM is off, and then the fold +// is a move). Beside tf it keeps the two per-row facts only the field passes can see: nameDf (pass 1, the name field +// alone; sized only when the margin is armed) and variantDocDf (pass 2, the units whose doc/body fields carry each +// variant — the R3 admission signal). The fold consumes the table and turns all of it into a LexTermTfTable at once. // -// Every write goes through the four add/fold members below, and every field's evidence through ONE tokenizer: +// Every write goes through the add members below, and every field's evidence through ONE tokenizer: // scanTextInto streams a field through lexindex.h forEachLexSubtoken (the same state machine subtokens() mirrors and the // B0.2 index-time builder uses): a token is a maximal alphanumeric run between separators, cut at a lower/digit → Upper // transition and at the ACRONYMWord seam. Tokens shorter than 2 bytes are dropped, exactly like subtokens(). No strings, @@ -719,25 +765,30 @@ inline std::vector<LexMatchTok> buildLexMatchTable( const std::vector<std::strin // all-caps run survives as ONE token, so a span's INTERIOR bytes can be uppercase and memcmp alone would miss it; the // memcmp stays as the fast path and only a span already agreeing on length AND head falls through to // lexTokenEqualsLowered — the rare acronym case, arm D's seam. -struct LexTfTable +struct LexMatchTfTable { const std::vector<LexMatchTok>& matchToks; - std::size_t uniqueCount; // rows 0..uniqueCount are the exact query terms - std::size_t stride; // matchToks.size() until the fold, uniqueCount after it + std::size_t uniqueCount; // rows 0..uniqueCount are the exact query terms, the rest stem variants + LexTermMargin margin; LexHeadIndex headIndex; std::vector<int> dl; std::vector<int> tf; + std::vector<int> nameDf; // per match row: ranked units whose NAME field alone carries it + std::vector<std::uint32_t> variantDocDf; // per stem variant: units whose doc/body fields carry it - LexTfTable( std::size_t docCount, const std::vector<LexMatchTok>& rows, std::size_t exactCount ) - : matchToks( rows ), uniqueCount( exactCount ), stride( rows.size() ), + LexMatchTfTable( std::size_t docCount, const std::vector<LexMatchTok>& rows, std::size_t exactCount, LexTermMargin termMargin ) + : matchToks( rows ), uniqueCount( exactCount ), margin( termMargin ), headIndex( buildLexHeadIndex( rows.size(), [ &rows ]( std::size_t m ) -> const std::string& { return rows[m].tok; } ) ), - dl( docCount, 0 ), tf( docCount * rows.size(), 0 ) + dl( docCount, 0 ), tf( docCount * rows.size(), 0 ), nameDf( termMargin.armed() ? rows.size() : 0, 0 ), + variantDocDf( rows.size() - exactCount, 0u ) { + DASSERT( exactCount <= rows.size(), "the match table lists the exact query terms first, then their stem variants" ); } + std::size_t matchCount() const noexcept { return matchToks.size(); } std::size_t variantCount() const noexcept { return matchToks.size() - uniqueCount; } - int* row( std::size_t doc ) noexcept { return tf.data() + doc * stride; } - const int* row( std::size_t doc ) const noexcept { return tf.data() + doc * stride; } + int* row( std::size_t doc ) noexcept { return tf.data() + doc * matchCount(); } + const int* row( std::size_t doc ) const noexcept { return tf.data() + doc * matchCount(); } // Streams `text` at weight w into a caller-owned tf row and length accumulator (the per-file basename rows use it // directly; addField is the per-doc form). Exact tokens own rows 0..uniqueCount (m == u there). @@ -767,7 +818,7 @@ struct LexTfTable void addFileField( std::size_t doc, const int* fileRow, int fileWt ) { int* const tfRow = row( doc ); - for( std::size_t m = 0; m < stride; ++m ) + for( std::size_t m = 0; m < matchCount(); ++m ) { tfRow[m] += fileRow[m]; } @@ -778,47 +829,66 @@ struct LexTfTable void addStoredLength( std::size_t doc, int length ) { dl[doc] += length; } void addStoredTf( std::size_t doc, std::size_t m, int count ) { row( doc )[m] += count; } - // The R3 fold: an admitted variant's column adds into its original term's row, a rejected one's is dropped (its - // evidence — name, callee, path, basename, doc, body — vanishes without touching dl: document length counts all - // subtokens scanned, never matches). The table then has the historical uniqueCount stride. - void foldAdmittedVariants( const std::vector<char>& admitted ) + // pass 1, right after a ranked doc's NAME field and before any other field lands in its row: count its name hits + // into nameDf — only while the term margin is armed (nameDf is unsized otherwise) + void countNameFieldDf( std::size_t doc ) { - if( variantCount() == 0 ) + if( !margin.armed() ) + { + return; + } + const int* const nameRow = row( doc ); + for( std::size_t m = 0; m < matchCount(); ++m ) { - return; // disarmed: already the historical layout + nameDf[m] += nameRow[m] > 0 ? 1 : 0; } + } + + // The R3 fold, one flag per variant (admitRareStemVariants): an admitted variant's column adds into its original + // term's row, a rejected one's is dropped (its evidence — name, callee, path, basename, doc, body — vanishes without + // touching dl: document length counts all subtokens scanned, never matches). nameDf folds the SAME way, so the margin + // test sees one row per unique term on either arm. A doc carrying both the exact token and an admitted variant in its + // name is counted twice, so a folded nameDf is a CEILING, not a count — stated rather than hidden. It matters only + // when RIPWIRE_QSTEM and the margin are both armed, and both ship off. + LexTermTfTable foldAdmittedVariants( const std::vector<char>& admitted ) && + { + DASSERT( admitted.size() == variantCount(), "one admission flag per stem variant" ); const std::size_t docCount = dl.size(); - std::vector<int> folded( docCount * uniqueCount, 0 ); + LexTermTfTable terms; + terms.uniqueCount = uniqueCount; + terms.margin = margin; + terms.dl = std::move( dl ); + if( variantCount() == 0 ) + { + terms.tf = std::move( tf ); // disarmed: already the historical layout + terms.nameDf = std::move( nameDf ); + return terms; + } + terms.tf.assign( docCount * uniqueCount, 0 ); for( std::size_t i = 0; i < docCount; ++i ) { - const int* const src = row( i ); - int* const dst = folded.data() + i * uniqueCount; - std::copy( src, src + uniqueCount, dst ); - for( std::size_t v = 0; v < admitted.size(); ++v ) - { - dst[ matchToks[ uniqueCount + v ].u ] += admitted[v] != 0 ? src[ uniqueCount + v ] : 0; - } + foldRowInto( terms.tf.data() + i * uniqueCount, row( i ), admitted ); } - tf = std::move( folded ); - stride = uniqueCount; + if( margin.armed() ) + { + terms.nameDf.assign( uniqueCount, 0 ); + foldRowInto( terms.nameDf.data(), nameDf.data(), admitted ); + } + return terms; } -}; -// ── SIRA term margin (docs/EVALS.md "Corpus-statistics term margin", PRE-REGISTERED 2026-09-05) — the arming ── -// The decision itself needs corpus statistics that do not exist until after pass 2 (judgeTermMargins); all that is -// read here is whether it is armed and at which rung. The result is the k of "a term separates iff idf_u >= k * ln 2", -// k = 1 being the shipped rule and the only rung this round may ship (the ladder is frozen in the registration). -// 0 = disarmed: every step that reads it skips its margin work and the scorer is the historical one byte-for-byte. -inline int termMarginBitsFromEnv() -{ - const char* env = std::getenv( "RIPWIRE_TERMMARGIN" ); - if( env == nullptr || *env == '0' ) +private: + // one match-width row (tf, or nameDf) into a unique-width one: the exact columns copied, each admitted variant's + // column added into its term's + void foldRowInto( int* dst, const int* src, const std::vector<char>& admitted ) const { - return 0; + std::copy( src, src + uniqueCount, dst ); + for( std::size_t v = 0; v < admitted.size(); ++v ) + { + dst[ matchToks[ uniqueCount + v ].u ] += admitted[v] != 0 ? src[ uniqueCount + v ] : 0; + } } - const std::optional<int> bits = envKnob<int>( "RIPWIRE_TERMMARGIN_BITS" ); - return bits ? std::clamp( *bits, 1, 8 ) : 1; -} +}; // A field's weight: the caller's lens default, or the RIPWIRE_* calibration knob (clamped 0..8) when set. 0 = the // field is not scanned at all. @@ -840,27 +910,26 @@ inline constexpr int kLexWeightName = 3, kLexWeightCallee = 1; // pass 1 — name (×kLexWeightName) + callee-name (×kLexWeightCallee) fields, which need no file text. Two per-unit facts // are separable ONLY here, after a unit's name field and before its callee, path, doc and body fields land in the same -// tf row, so they are captured here: -// L-W evidenceOut->nameMask, bit u set iff the NAME field alone carried terms[u] (with maskWords; skipped when null) -// SIRA the returned nameDf[m] = ranked units whose NAME FIELD ALONE carries match-table row m (empty when the margin is -// disarmed). This is the statistic the LB-1 negative is the reason for: that round's IDF floor read document +// tf row, so this pass also captures which terms each unit's NAME carries ("name hits"), two ways: +// L-W evidenceOut->nameMask, bit u set iff the NAME field alone carried terms[u] (skipped when evidenceOut is null) +// SIRA table.nameDf[m] = ranked units whose NAME FIELD ALONE carries match-table row m (only when the margin is +// armed). This is the statistic the LB-1 negative is the reason for: that round's IDF floor read document // frequency only, and so deleted `module` — the truth's OWN name carrier — on a corpus where `module` is // everywhere in bodies. A term that names between 1 and S/2 symbols separates on the field ripwire weights highest // (×3) whatever its body mass says, and is kept. Pass 1 runs before the pass-2 branch split, so the scan and // persisted-stats paths read the identical integers. -inline std::vector<int> addNameAndCalleeFields( LexTfTable& table, const IngestResult& ing, const std::vector<std::uint32_t>& outOff, - const std::vector<NodeId>& outTargets, const LexCorpusRoles& roles, bool countNameDf, - LexTermEvidence* evidenceOut ) +inline void addNameAndCalleeFieldsCapturingNameHits( LexMatchTfTable& table, const IngestResult& ing, const std::vector<std::uint32_t>& outOff, + const std::vector<NodeId>& outTargets, const LexCorpusRoles& roles, + LexTermEvidence* evidenceOut ) { const std::size_t S = ing.symbols.size(); const std::size_t uniqueCount = table.uniqueCount; - const std::size_t evidenceWords = ( uniqueCount + 63 ) / 64; + const std::size_t evidenceWords = LexTermEvidence::maskWordsFor( uniqueCount ); if( evidenceOut ) { evidenceOut->maskWords = evidenceWords; evidenceOut->nameMask.assign( S * evidenceWords, 0u ); } - std::vector<int> nameDf( countNameDf ? table.stride : 0, 0 ); for( std::size_t i = 0; i < S; ++i ) { table.addField( i, ing.symbols[i].name, kLexWeightName ); @@ -873,16 +942,15 @@ inline std::vector<int> addNameAndCalleeFields( LexTfTable& table, const IngestR words[ u / 64 ] |= nameRow[u] > 0 ? std::uint64_t( 1 ) << ( u % 64 ) : 0u; } } - for( std::size_t m = 0; m < nameDf.size() && !roles.isUnranked( i ); ++m ) + if( !roles.isUnranked( i ) ) { - nameDf[m] += nameRow[m] > 0 ? 1 : 0; + table.countNameFieldDf( i ); // SIRA nameDf, armed only } for( std::uint32_t e = outOff[i]; e < outOff[i + 1]; ++e ) { table.addField( i, ing.symbols[ outTargets[e] ].name, kLexWeightCallee ); } } - return nameDf; } // pass 1.5 — path field (×kwPath): the symbol's file path scanned through the SAME state machine. @@ -909,7 +977,7 @@ inline std::vector<int> addNameAndCalleeFields( LexTfTable& table, const IngestR // exactly what a relative-root run already scanned, which is why this is a CONVERGENCE onto the // already-invariant `ripwire .` rather than a new ranking opinion. Multi-root passes no prefix: // ing.files already hold "<label>/<root-relative>". -inline void addPathField( LexTfTable& table, const IngestResult& ing, int kwPath, std::string_view pathRootPrefix ) +inline void addPathField( LexMatchTfTable& table, const IngestResult& ing, int kwPath, std::string_view pathRootPrefix ) { if( kwPath <= 0 ) { @@ -937,27 +1005,27 @@ inline void addPathField( LexTfTable& table, const IngestResult& ing, int kwPath // follows the last '/', which the root prefix cannot change — and applied anyway so the two path passes // cannot drift apart. One reading of ing.files[f], one rule; a future reader who changes one pass finds // the other already agreeing rather than discovering half the path tokenization was still absolute. -inline void addBasenameField( LexTfTable& table, const IngestResult& ing, int kwBase, std::string_view pathRootPrefix ) +inline void addBasenameField( LexMatchTfTable& table, const IngestResult& ing, int kwBase, std::string_view pathRootPrefix ) { if( kwBase <= 0 ) { return; } const std::size_t fileCount = ing.files.size(); - std::vector<int> fileTf( fileCount * table.stride, 0 ); + std::vector<int> fileTf( fileCount * table.matchCount(), 0 ); std::vector<int> fileWt( fileCount, 0 ); for( std::size_t f = 0; f < fileCount; ++f ) { const std::string_view path = rw::sarif::rootRelativeUri( ing.files[f], pathRootPrefix ); const std::size_t cut = path.find_last_of( '/' ); const std::string_view base = cut == std::string_view::npos ? path : path.substr( cut + 1 ); - table.scanTextInto( fileTf.data() + f * table.stride, fileWt[f], base, kwBase ); + table.scanTextInto( fileTf.data() + f * table.matchCount(), fileWt[f], base, kwBase ); } for( std::size_t i = 0; i < ing.symbols.size(); ++i ) { if( const std::uint32_t f = ing.symbols[i].fileId; f < fileCount && fileWt[f] != 0 ) { - table.addFileField( i, fileTf.data() + std::size_t( f ) * table.stride, fileWt[f] ); + table.addFileField( i, fileTf.data() + std::size_t( f ) * table.matchCount(), fileWt[f] ); } } } @@ -972,19 +1040,18 @@ inline bool hasPersistedLexStats( const IngestResult& ing ) noexcept return ing.hasLexStats && ing.lexTokenRowOffsets.size() == S + 1 && ing.lexDocBodyDl.size() == S; } -// pass 2 from persisted stats — doc-comment + body evidence as stored integers. Returns, per stem variant, the units -// whose stored doc/body rows carry it (the R3 guard's admission signal; stored rows hold each hash once → one bump per -// unit). The match rows are reached by the same normalized-lowercase hash index time used, over the FULL match table +// pass 2 from persisted stats — doc-comment + body evidence as stored integers, and table.variantDocDf: per stem variant, +// the units whose stored doc/body rows carry it (the R3 guard's admission signal; stored rows hold each hash once → one +// bump per unit). The match rows are reached by the same normalized-lowercase hash index time used, over the FULL match table // (exact tokens + LB-3 stem variants), each hash mapped to its own tf ROW — the same row targeting the scan applies. // try_emplace keeps the FIRST entry on the astronomically-unlikely 64-bit collision between two DISTINCT table strings, // so both transfer strategies agree deterministically. -inline std::vector<std::uint32_t> addDocBodyFromPersistedStats( LexTfTable& table, const IngestResult& ing ) +inline void addDocBodyFieldsFromPersistedStats( LexMatchTfTable& table, const IngestResult& ing ) { PROFILE_SCOPE_DESCRIBE( "lexical: pass 2 via persisted subtoken stats (cached tf/dl, no corpus re-tokenize)" ); const std::size_t S = ing.symbols.size(); - const std::size_t matchCount = table.stride; + const std::size_t matchCount = table.matchCount(); const std::size_t uniqueCount = table.uniqueCount; - std::vector<std::uint32_t> dfVariant( table.variantCount(), 0u ); // dl first: BM25 length normalization needs EVERY doc's weighted length whether or not it matches // the query (avgdl sums them all), so this runs unconditionally — exact stored integers. @@ -1006,7 +1073,7 @@ inline std::vector<std::uint32_t> addDocBodyFromPersistedStats( LexTfTable& tabl table.addStoredTf( i, m, int( storedTf ) ); if( m >= uniqueCount ) { - ++dfVariant[ m - uniqueCount ]; // stored rows hold each hash once → one df bump per symbol + ++table.variantDocDf[ m - uniqueCount ]; // stored rows hold each hash once → one df bump per symbol } }; @@ -1067,20 +1134,19 @@ inline std::vector<std::uint32_t> addDocBodyFromPersistedStats( LexTfTable& tabl } } } - return dfVariant; } // pass 2 by scanning (lean ingests, --no-cache lean verbs, multi-root merges, stubs) — doc-comment (×kLexWeightDoc) + // body (×kLexWeightBody) evidence, streamed ONE file at a time touching only that file's symbols: peak memory is a single // file's text, not the whole corpus held at once (symbol order within a file is irrelevant: integer counts commute -// exactly). Returns the same per-variant doc/body df the persisted branch returns, from the scan's own counts. +// exactly). Fills the same table.variantDocDf the persisted branch fills, from the scan's own counts. // // Files stream across a small worker pool: each worker holds ONE file's text at a time, and a file's symbols are touched // only by the worker that claimed the file — every dl[i] / tf row has exactly ONE writer (no locks needed). Determinism: // all pooled writes are exact integer counts and the float scoring stays single-threaded in doc order, so worker // scheduling cannot change a byte of output (no cross-doc float reductions — the det-gate rule). The per-(file, variant) // df tallies likewise have ONE writer each and merge single-threaded in file order. -inline std::vector<std::uint32_t> scanDocBodyFields( LexTfTable& table, const IngestResult& ing ) +inline void addDocBodyFieldsByFileScan( LexMatchTfTable& table, const IngestResult& ing ) { const std::size_t fileCount = ing.files.size(); const std::size_t variantCount = table.variantCount(); @@ -1160,15 +1226,24 @@ inline std::vector<std::uint32_t> scanDocBodyFields( LexTfTable& table, const In } } - std::vector<std::uint32_t> dfVariant( variantCount, 0u ); for( std::size_t f = 0; f < fileCount && variantCount > 0; ++f ) // deterministic df merge, file order { for( std::size_t v = 0; v < variantCount; ++v ) { - dfVariant[v] += dfPerFile[ f * variantCount + v ]; + table.variantDocDf[v] += dfPerFile[ f * variantCount + v ]; } } - return dfVariant; +} + +// pass 2 — doc-comment (×kLexWeightDoc) + body (×kLexWeightBody), from whichever source the ingest has (hasPersistedLexStats) +inline void addDocBodyFields( LexMatchTfTable& table, const IngestResult& ing ) +{ + if( hasPersistedLexStats( ing ) ) + { + addDocBodyFieldsFromPersistedStats( table, ing ); + return; + } + addDocBodyFieldsByFileScan( table, ing ); } // ── IDF-guard admission (rung R3) — the same decision after EITHER pass-2 source ───────────────────────── @@ -1176,9 +1251,9 @@ inline std::vector<std::uint32_t> scanDocBodyFields( LexTfTable& table, const In // one is admitted and folds into its original token's row — the exact integers the un-guarded arm would have // accumulated there. The cap reads the ranked corpus: an unranked unit does not widen it. Returns one flag per variant // (empty when disarmed); RIPWIRE_QSTEM_DEBUG prints each verdict on stderr. -inline std::vector<char> admitRareStemVariants( const std::vector<std::uint32_t>& dfVariant, std::size_t rankedCount, - const LexTfTable& table ) +inline std::vector<char> admitRareStemVariants( const LexMatchTfTable& table, std::size_t rankedCount ) { + const std::vector<std::uint32_t>& dfVariant = table.variantDocDf; const std::uint32_t sOver64 = std::uint32_t( rankedCount / 64 ); const std::uint32_t variantCap = sOver64 > 8u ? sOver64 : 8u; std::vector<char> admitted( dfVariant.size(), 0 ); @@ -1195,24 +1270,16 @@ inline std::vector<char> admitRareStemVariants( const std::vector<std::uint32_t> return admitted; } -// fold nameDf the SAME way the tf table folds, so the margin test sees one row per unique token on either arm. A doc -// carrying both the exact token and an admitted variant in its name is counted twice, so a folded nameDf is a CEILING, -// not a count — stated rather than hidden. It matters only when RIPWIRE_QSTEM is also armed, which ships off. -inline void foldAdmittedNameDf( std::vector<int>& nameDf, const std::vector<char>& admitted, const LexTfTable& table ) -{ - for( std::size_t v = 0; v < admitted.size() && !nameDf.empty(); ++v ) - { - nameDf[ table.matchToks[ table.uniqueCount + v ].u ] += admitted[v] != 0 ? nameDf[ table.uniqueCount + v ] : 0; - } -} - -// ── L-W: the term evidence, read off the FINAL tf rows (uniqueCount stride, every field, the fold applied) — one S×U -// integer scan, the same "tf > 0" fact the document frequency counts when scoring. (nameMask was captured in pass 1.) -inline void recordTermEvidence( LexTermEvidence& evidence, const LexTfTable& table, const LexCorpusRoles& roles, const DedupedQueryTerms& dedup ) +// ── L-W: the term evidence, read off the FINAL tf rows (LexTermTfTable: every field, the fold applied) — one S×U +// integer scan, the same "tf > 0" fact the document frequency counts when scoring. nameMask is pass 1's +// (addNameAndCalleeFieldsCapturingNameHits), sized for the same term count — asserted, not assumed. +inline void recordTermEvidence( LexTermEvidence& evidence, const LexTermTfTable& table, const LexCorpusRoles& roles, const DedupedQueryTerms& dedup ) { - const std::size_t S = table.dl.size(); + const std::size_t S = table.docCount(); const std::size_t uniqueCount = table.uniqueCount; - const std::size_t evidenceWords = evidence.maskWords; + const std::size_t evidenceWords = LexTermEvidence::maskWordsFor( uniqueCount ); + DASSERT( evidence.maskWords == evidenceWords && evidence.nameMask.size() == S * evidenceWords, + "pass 1 captures the name mask for the same symbols and terms before the evidence is recorded" ); evidence.termsSeenTotal = dedup.uniqueSeenTotal; evidence.termsCapped = dedup.capped; evidence.terms.assign( dedup.uniqueToks.begin(), dedup.uniqueToks.end() ); @@ -1275,19 +1342,18 @@ enum class TermMarginVerdict : std::uint8_t kSuppressed, }; -// Returns termKept per unique term: all 1 when the margin is disarmed (marginBits 0). -inline std::vector<char> judgeTermMargins( const LexTfTable& table, const LexCorpusRoles& roles, const std::vector<int>& nameDf, int marginBits, - const std::vector<std::string>& uniqueToks ) +// Returns termKept per unique term: all 1 when the margin is disarmed. +inline std::vector<char> judgeTermMargins( const LexTermTfTable& table, const LexCorpusRoles& roles, const std::vector<std::string>& uniqueToks ) { const std::size_t uniqueCount = table.uniqueCount; std::vector<char> termKept( uniqueCount, 1 ); - if( marginBits <= 0 ) + if( !table.margin.armed() ) { return termKept; } // df in fixed doc order over the folded rows — the same integers both pass-2 sources produced std::vector<int> dfMargin( uniqueCount, 0 ); - for( std::size_t i = 0; i < table.dl.size(); ++i ) + for( std::size_t i = 0; i < table.docCount(); ++i ) { const int* const tfRow = table.row( i ); const int w = roles.statsWeight( i ); @@ -1299,13 +1365,13 @@ inline std::vector<char> judgeTermMargins( const LexTfTable& table, const LexCor // "separates" at k bits: idf_u >= k*ln2 ⇔ (S-n+0.5)/(n+0.5) + 1 >= 2^k ⇔ n <= (S+0.5)/2^k - 0.5, // which at k = 1 is exactly n <= S/2. Evaluated in doubles from integer inputs, so it is a pure // function of (S, n, k) and cannot vary run to run. - const double separationCut = ( double( roles.countedCount ) + 0.5 ) / std::exp2( double( marginBits ) ) - 0.5; + const double separationCut = ( double( roles.countedCount ) + 0.5 ) / std::exp2( double( table.margin.bits ) ) - 0.5; std::vector<TermMarginVerdict> verdict( uniqueCount, TermMarginVerdict::kAbsent ); std::size_t presentCount = 0, survivorCount = 0; for( std::size_t u = 0; u < uniqueCount; ++u ) { const bool separatesDoc = double( dfMargin[u] ) <= separationCut; - const bool separatesName = nameDf[u] > 0 && double( nameDf[u] ) <= separationCut; + const bool separatesName = table.nameDf[u] > 0 && double( table.nameDf[u] ) <= separationCut; verdict[u] = dfMargin[u] == 0 ? TermMarginVerdict::kAbsent : separatesDoc ? TermMarginVerdict::kDocSeparates : separatesName ? TermMarginVerdict::kNameSeparates @@ -1329,7 +1395,7 @@ inline std::vector<char> judgeTermMargins( const LexTfTable& table, const LexCor for( std::size_t u = 0; u < uniqueCount; ++u ) { rw::emitTo( stderr, "term-margin: \"{}\" df={}/{} nameDf={} bits={} {}\n", uniqueToks[u].c_str(), dfMargin[u], roles.countedCount, - nameDf[u], marginBits, kVerdictText[ std::size_t( verdict[u] ) ] ); + table.nameDf[u], table.margin.bits, kVerdictText[ std::size_t( verdict[u] ) ] ); } rw::emitTo( stderr, "term-margin: {} present, {} survive, suppression {}\n", presentCount, survivorCount, applySuppression ? "applied" : "withheld (sole-anchor)" ); @@ -1342,21 +1408,28 @@ inline std::vector<char> judgeTermMargins( const LexTfTable& table, const LexCor // avgdl accumulates in the historical doc order (integer sums: exact in any order anyway). dfreq[u] = COUNTED units // containing unique query token u (w ≥ 1, so tf > 0 ⇔ the old docs[i] contained it); dfOut[u] = statsOut units carrying // it (all 0 with no statsOut). A counted unit scores with (countedCount, dfreq, avgdlCounted); a statsOut unit against -// the whole ranked corpus (rankedCount, dfreq + dfOut, avgdlRanked), as with no statsOut. +// the whole ranked corpus (rankedCount, dfreq + dfOut, avgdlRanked), as with no statsOut. That choice is made HERE, +// once per term and role: idfCounted / idfRanked (bm25Idf over each role's N and df) and avgdlOf(role) are what the +// scorer and the MaxScore bound read, so neither re-derives which corpus a unit scores against. struct LexBm25Stats { std::vector<int> dfreq; std::vector<int> dfOut; std::vector<int> tfMaxOf; // per term, its largest weighted tf anywhere — the MaxScore bound's T std::vector<std::uint32_t> candidateIds; // ascending: every unit with any tf > 0 + std::vector<double> idfCounted; // per term, a counted unit's idf: bm25Idf( countedCount, dfreq ) + std::vector<double> idfRanked; // per term, a statsOut unit's idf: bm25Idf( rankedCount, dfreq + dfOut ) double avgdlCounted = 0; double avgdlRanked = 0; Bm25Params params = kBm25Default; + + double idfOf( std::size_t u, bool statsOut ) const noexcept { return statsOut ? idfRanked[u] : idfCounted[u]; } + double avgdlOf( bool statsOut ) const noexcept { return statsOut ? avgdlRanked : avgdlCounted; } }; -inline LexBm25Stats tallyBm25Stats( const LexTfTable& table, const LexCorpusRoles& roles ) +inline LexBm25Stats tallyBm25Stats( const LexTermTfTable& table, const LexCorpusRoles& roles ) { - const std::size_t S = table.dl.size(); + const std::size_t S = table.docCount(); const std::size_t uniqueCount = table.uniqueCount; LexBm25Stats st; st.dfreq.assign( uniqueCount, 0 ); @@ -1386,6 +1459,13 @@ inline LexBm25Stats tallyBm25Stats( const LexTfTable& table, const LexCorpusRole } st.avgdlCounted /= double( roles.countedCount ? roles.countedCount : 1 ); st.avgdlRanked /= double( roles.rankedCount ? roles.rankedCount : 1 ); + st.idfCounted.resize( uniqueCount ); + st.idfRanked.resize( uniqueCount ); + for( std::size_t u = 0; u < uniqueCount; ++u ) + { + st.idfCounted[u] = bm25Idf( double( roles.countedCount ), double( st.dfreq[u] ) ); + st.idfRanked[u] = bm25Idf( double( roles.rankedCount ), double( st.dfreq[u] + st.dfOut[u] ) ); + } st.params = resolveBm25Params(); return st; } @@ -1415,8 +1495,8 @@ inline LexBm25Stats tallyBm25Stats( const LexTfTable& table, const LexCorpusRole class LexTopKPruner { public: - LexTopKPruner( std::size_t pruneTopK, const std::vector<char>* alwaysExact, const LexBm25Stats& st, const LexCorpusRoles& roles, - const DedupedQueryTerms& dedup, const std::vector<char>& termKept ) + LexTopKPruner( std::size_t pruneTopK, const std::vector<char>* alwaysExact, const LexBm25Stats& st, const DedupedQueryTerms& dedup, + const std::vector<char>& termKept ) : topK_( std::getenv( "RIPWIRE_NO_PRUNE" ) == nullptr ? pruneTopK : 0 ), alwaysExact_( alwaysExact ) { if( topK_ == 0 ) @@ -1441,10 +1521,9 @@ class LexTopKPruner continue; // never contributes anywhere — a suppressed term's cap stays 0, and a cap of // 0 bounds a contribution of 0, so the MaxScore proof above is unchanged } - const int n = st.dfreq[u]; - const int nAll = n + st.dfOut[u]; // an OUT unit's idf: the larger of the two bounds the contribution - const double idfIn = n > 0 ? std::log( ( double( roles.countedCount ) - n + 0.5 ) / ( n + 0.5 ) + 1.0 ) : 0.0; - const double idfAll = st.dfOut[u] > 0 ? std::log( ( double( roles.rankedCount ) - nAll + 0.5 ) / ( nAll + 0.5 ) + 1.0 ) : 0.0; + // the larger of the two roles' idf bounds the contribution; a role no unit carrying u plays contributes 0 + const double idfIn = st.dfreq[u] > 0 ? st.idfCounted[u] : 0.0; + const double idfAll = st.dfOut[u] > 0 ? st.idfRanked[u] : 0.0; const double idf = std::max( idfIn, idfAll ); const double cap1 = bm25ImpactBound( idf, double( st.tfMaxOf[u] ), st.params ); // A4: shared bound, same (k1,b) capOcc_[u] = cap1 * double( occCount[u] ); @@ -1507,7 +1586,7 @@ class LexTopKPruner // - a kRankFlagNotLexRanked unit (model.h) scores 0; // - a pruned unit provably cannot enter the top-K the caller consumes (LexTopKPruner). // So the exhaustive mode needs no loop of its own: it is this loop with a pruner that never skips. -inline std::vector<float> scoreLexCandidates( const IngestResult& ing, const LexTfTable& table, const LexBm25Stats& st, const LexCorpusRoles& roles, +inline std::vector<float> scoreLexCandidates( const IngestResult& ing, const LexTermTfTable& table, const LexBm25Stats& st, const LexCorpusRoles& roles, const DedupedQueryTerms& dedup, const std::vector<char>& termKept, LexTopKPruner& pruner, const std::vector<float>* symbolScoreMul ) { @@ -1525,8 +1604,7 @@ inline std::vector<float> scoreLexCandidates( const IngestResult& ing, const Lex continue; } const bool outI = roles.isStatsOut( i ); - const double Si = outI ? double( roles.rankedCount ) : double( roles.countedCount ); - const double avgI = outI ? st.avgdlRanked : st.avgdlCounted; + const double avgI = st.avgdlOf( outI ); double sc = 0; for( std::size_t qi = 0; qi < uniqueIndexOfQtok.size(); ++qi ) { @@ -1540,8 +1618,7 @@ inline std::vector<float> scoreLexCandidates( const IngestResult& ing, const Lex { continue; // old: docs[i].find( qt ) == end — termKept is all-1 disarmed, so this is that } - const int n = st.dfreq[u] + ( outI ? st.dfOut[u] : 0 ); - const double idf = std::log( ( Si - n + 0.5 ) / ( n + 0.5 ) + 1.0 ); + const double idf = st.idfOf( u, outI ); sc += idf * ( tf * ( k1 + 1.0 ) ) / ( tf + k1 * ( 1.0 - b + b * dl[i] / ( avgI > 0 ? avgI : 1.0 ) ) ); } // Markdown headings (sec) compete on name-match with code; down-weight so a doc stays FINDABLE but @@ -1595,30 +1672,29 @@ inline std::vector<float> lexicalScoresTiered( const IngestResult& ing, const st // S×terms allocation below. const DedupedQueryTerms dedup = dedupeQueryTerms( qToks, kMaxUniqueQueryTerms ); const std::vector<LexMatchTok> matchToks = buildLexMatchTable( dedup.uniqueToks ); - LexTfTable table( S, matchToks, dedup.uniqueToks.size() ); + LexMatchTfTable fields( S, matchToks, dedup.uniqueToks.size(), termMarginFromEnv() ); // the fields, weakest dependence first: name + callee (pass 1), path (1.5) and basename (1.6) need no file text, // so they run before the pass-2 source split; then doc-comment + body (pass 2) from whichever source the ingest has - const int marginBits = termMarginBitsFromEnv(); - std::vector<int> nameDf = addNameAndCalleeFields( table, ing, outOff, outTargets, roles, /*countNameDf=*/marginBits > 0, evidenceOut ); - addPathField( table, ing, fieldWeightOrEnv( pathFieldDefaultW, "RIPWIRE_PATHTOK_W" ), pathRootPrefix ); - addBasenameField( table, ing, fieldWeightOrEnv( basenameFieldDefaultW, "RIPWIRE_BASENAME_W" ), pathRootPrefix ); - const std::vector<std::uint32_t> dfVariant = hasPersistedLexStats( ing ) ? addDocBodyFromPersistedStats( table, ing ) : scanDocBodyFields( table, ing ); - - // what the corpus statistics decide: which stem variants stay, then which query terms separate - const std::vector<char> admitted = admitRareStemVariants( dfVariant, roles.rankedCount, table ); - table.foldAdmittedVariants( admitted ); - foldAdmittedNameDf( nameDf, admitted, table ); + addNameAndCalleeFieldsCapturingNameHits( fields, ing, outOff, outTargets, roles, evidenceOut ); + addPathField( fields, ing, fieldWeightOrEnv( pathFieldDefaultW, "RIPWIRE_PATHTOK_W" ), pathRootPrefix ); + addBasenameField( fields, ing, fieldWeightOrEnv( basenameFieldDefaultW, "RIPWIRE_BASENAME_W" ), pathRootPrefix ); + addDocBodyFields( fields, ing ); + + // what the corpus statistics decide: which stem variants stay (the fold leaves one row per query term), then + // which query terms separate + const std::vector<char> admitted = admitRareStemVariants( fields, roles.rankedCount ); + const LexTermTfTable terms = std::move( fields ).foldAdmittedVariants( admitted ); if( evidenceOut ) { - recordTermEvidence( *evidenceOut, table, roles, dedup ); + recordTermEvidence( *evidenceOut, terms, roles, dedup ); } - const std::vector<char> termKept = judgeTermMargins( table, roles, nameDf, marginBits, dedup.uniqueToks ); + const std::vector<char> termKept = judgeTermMargins( terms, roles, dedup.uniqueToks ); // score: corpus statistics, then every candidate the MaxScore pruner (armed only on request) does not rule out - const LexBm25Stats stats = tallyBm25Stats( table, roles ); - LexTopKPruner pruner( pruneTopK, alwaysExact, stats, roles, dedup, termKept ); - return scoreLexCandidates( ing, table, stats, roles, dedup, termKept, pruner, symbolScoreMul ); + const LexBm25Stats stats = tallyBm25Stats( terms, roles ); + LexTopKPruner pruner( pruneTopK, alwaysExact, stats, dedup, termKept ); + return scoreLexCandidates( ing, terms, stats, roles, dedup, termKept, pruner, symbolScoreMul ); } // the un-tiered contract every pre-§P4 caller keeps (evals, exemplar, --recall): same arity as always, From 5020dbdc1841b80c0b45c9090df36bb0af6985c9 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sun, 22 Nov 2026 03:32:37 -0500 Subject: [PATCH 33/61] showcase: the 11-20 capture stays main's; the train re-records once at its tip Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/captures/COMMANDS_showcase_2026-11-20.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/captures/COMMANDS_showcase_2026-11-20.md b/docs/captures/COMMANDS_showcase_2026-11-20.md index b32febb29..a3f728743 100644 --- a/docs/captures/COMMANDS_showcase_2026-11-20.md +++ b/docs/captures/COMMANDS_showcase_2026-11-20.md @@ -5981,7 +5981,7 @@ ripwire: --run-timeout=SECONDS modifies --run-trace — pass it too (e.g. ripwir *The session legend dictionary the MCP server serves as ripwire://legend-dict/full — one definition per line, headed by its dictv= version; no corpus needed. =roster lists the completeness attributes it defines.* ````` -ripwire legend dictionary ripwire.dict/v1 dictv=6ad237691d743450 entries=1178 +ripwire legend dictionary ripwire.dict/v1 dictv=c40ddf725e4befcb entries=1177 <about legend="ref" dict= dictv=>: this LAST child is only the legend pointer; the root keeps every attribute it carries inline, unchanged (schema=, each count, cut and floor); rows follow it; legend="ref": a definition is sent once per session (this dictionary's core, or the first answer that needs … [line truncated: 80 more bytes on this line] schema=ripwire.KEY/v1: the line ripwire.KEY/v1 below reads the answer's rows window: shown= total= capped= has_more= next_offset= offset= limit= page a list (capped=1 cut; next_offset= pastes as offset=) From 103dde822449a1a5c731c30c6664c095bd6d002e Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sun, 22 Nov 2026 06:36:30 -0500 Subject: [PATCH 34/61] test(qdentryceilingcheck): arm L reads the three-exception wording (TANGLE-GATE-B) qd-lessons-2's TANGLE-GATE-B added a third gating exception for new symbols, which turned the sentence into 'format-arity, a new function at the ceiling ... and a new one at tangle 6' (compact: 'format-arity, ceiling=, tangle'). Arm L still searched for the two-exception phrasing and found it 0 times in the full legend, the compact legend and --help=quality-delta. The phrases now match the shipped text, and the arm still requires each 'never gate, except defect-shape' occurrence to carry the ceiling exception. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- test/qdentryceilingcheck.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/qdentryceilingcheck.sh b/test/qdentryceilingcheck.sh index 249c69e67..4f8b0de4f 100755 --- a/test/qdentryceilingcheck.sh +++ b/test/qdentryceilingcheck.sh @@ -287,9 +287,9 @@ JM="$( cd "$WORK/n4" && "$BIN" . --quality-delta --json --no-cache 2>/dev/null ) if printf '%s' "$JM" | grep -q '"origin":"moved"'; then ok "J: --json carries \"origin\":\"moved\""; else no "J: --json lacks origin moved"; fi # ═══ L) LEGEND — the exception is stated wherever the rule is ═════════════════════════════════════════ -PHRASE='new-symbol rows never gate, except defect-shape format-arity and a new function at the ceiling' +PHRASE='new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling' # TANGLE-GATE-B added a third exception after it # compact spends fewer bytes (its prose has a stair-step target): the exception names the ceiling= row it defines -CPHRASE='new-symbol rows never gate, except defect-shape format-arity or a ceiling= row' +CPHRASE='new-symbol rows never gate, except defect-shape format-arity, ceiling=' for leg in full compact; do T="$( cd "$WORK/p1" && "$BIN" . --quality-delta --no-cache --legend=$leg 2>/dev/null | tr '\n' ' ' | tr -s ' ' )" # status: output only — the L arm FAILs when the phrase count is 0 a="$( printf '%s' "$T" | grep -o 'never gate, except defect-shape' | wc -l | tr -d ' ' )" From 9462d3da8c6bde8d47a31ae82fec47cf25c51559 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sun, 22 Nov 2026 06:36:30 -0500 Subject: [PATCH 35/61] showcase: the --compress demo expands collapseBlankLineRuns (compressBody is now a one-line pipeline) ge-serialize split compressBody into stripCommentsKeepLiterals + collapseBlankLineRuns, so compressBody's own body has no comment left to strip and --compress made the demo 13 B LARGER (3459 -> 3472 B, the compress attribute): showcasecapturecheck (A) went red on the composed train. collapseBlankLineRuns shrinks 4236 -> 3984 B. The capture is re-recorded once on the tip in the next commit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- test/showcase_capture.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/showcase_capture.py b/test/showcase_capture.py index c45cae3e8..87ba214d5 100644 --- a/test/showcase_capture.py +++ b/test/showcase_capture.py @@ -481,7 +481,7 @@ def add(section, cmd, what, **opts): add(S3, f"{BIN} . --outline=rankGraphTeleport:1-10 --top-k=0", "CHANGED: a line range on --outline is now STRIPPED with a stderr note (it used to refuse).") add(S3, f"{BIN} . --expand=rankGraphTeleport --top-k=0", "Full body + inline callee signatures.") add(S3, f"{BIN} . --expand=rankGraphTeleport:1-12 --top-k=0", "Body SLICE: lines 1..12 of the symbol's own body, with lines=\"lo-hi/total\" marking it partial.") -add(S3, f"{BIN} . --expand=compressBody --top-k=0 --compress", "Comments stripped + blank runs collapsed — compressBody is the function that implements --compress itself, chosen because it is comment-heavy enough to show a real reduction (the previously captioned symbol had no comments or blank runs, so before/after were byte-identical under a caption promising a difference).") +add(S3, f"{BIN} . --expand=collapseBlankLineRuns --top-k=0 --compress", "Comments stripped + blank runs collapsed — collapseBlankLineRuns is --compress's own second step (compressBody is now the one-line stripCommentsKeepLiterals-then-collapse pipeline, with nothing left to strip), chosen because it is comment-heavy enough to show a real reduction (a symbol with no comments or blank runs reads byte-identical, or a few bytes larger for the compress attribute, under a caption promising a difference).") add(S3, f"{BIN} . --expand=readAckRecords --top-k=0 --no-redact", "--no-redact: emit bodies verbatim (credential redaction is on by default).") add(S3, f"{BIN} . --pack-top-n=3 --top-k=0", "Pack the top-3 ranked symbols' full bodies (deprecated verb; see stderr).") From e134d4fce7b857243466d84e7ce2aefc4e45a694 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:12:59 -0500 Subject: [PATCH 36/61] refactor(quality): QdRowModel's row layout enum is RowShape, not Shape MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ge-runqd named the nested enum QdRowModel::Shape. On ripwire's own tree that added a 25th definition named Shape, and --lego=Shape now picked src/verbs_quality.h's enum (no methods) over the test fixtures' C++ interface, so a9disclosurecheck §A9.4 lost its <m pure="1"> row on every CI leg. The binary's --lego is unchanged: main's b576a95e3 binary gives the same answer on the train tree, and both binaries give the <m> row on main's tree. The name is now specific to what it is, and Shape keeps its one interface. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/verbs_quality.h | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/verbs_quality.h b/src/verbs_quality.h index f0f227702..c423345bb 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -3122,8 +3122,8 @@ struct QdRowModel // and a param-count contract-change (was/now = the real counts). was/now print whenever they differ from each other, // so the contract-change case's was=/now= is visible while the new-symbol case's meaningless was="0" now="0" is // omitted, matching its old sym-only shape. - enum class Shape : std::uint8_t { Members, SymOnly, WasNow }; - Shape shape = Shape::WasNow; + enum class RowShape : std::uint8_t { Members, SymOnly, WasNow }; + RowShape shape = RowShape::WasNow; std::string sym; // quality::displaySym, unescaped: members= for Members, sym= otherwise bool gating = false; // P2.5: the exit predicate (quality::rowGates), stated per row; never on a disclosed row // B10.2 — the optional classification facet: its attribute NAME is chosen by kind (quality::facetAttrName, the ONE @@ -3137,9 +3137,9 @@ QdRowModel qdRowModel( const rw::quality::Regression& r, bool gatingAllowed, std { using namespace rw; QdRowModel m; - m.shape = r.kind == "duplication" ? QdRowModel::Shape::Members - : ( r.kind == "dead-code" || ( r.kind == "api-surface" && r.was == r.now ) ) ? QdRowModel::Shape::SymOnly - : QdRowModel::Shape::WasNow; + m.shape = r.kind == "duplication" ? QdRowModel::RowShape::Members + : ( r.kind == "dead-code" || ( r.kind == "api-surface" && r.was == r.now ) ) ? QdRowModel::RowShape::SymOnly + : QdRowModel::RowShape::WasNow; m.sym = quality::displaySym( r.sym, deltaRoot ); m.gating = gatingAllowed && quality::rowGates( r ); m.facetName = r.facet.empty() ? nullptr : quality::facetAttrName( r.kind ); @@ -3189,14 +3189,14 @@ void emitQdXmlRow( std::FILE* out, const rw::quality::Regression& r, const QdRow common += m.gating ? " gating=\"1\"" : ""; switch( m.shape ) { - case QdRowModel::Shape::Members: + case QdRowModel::RowShape::Members: rw::emitTo( out, "<r kind=\"duplication\" members=\"{}\" tokens=\"{}\"{}{}/>", ex( m.sym ), r.now, common, quality::tangleRowAttrs( r, /*json=*/false, ex ) ); // QD-IDIOM-ELEMTYPE: why= when the operand path demoted it return; - case QdRowModel::Shape::SymOnly: + case QdRowModel::RowShape::SymOnly: rw::emitTo( out, "<r kind=\"{}\" sym=\"{}\"{}{}/>", r.kind, ex( m.sym ), common, qdExpandNextAttr( r, m ) ); return; - case QdRowModel::Shape::WasNow: + case QdRowModel::RowShape::WasNow: // P8 (L7): bar= is the threshold beside the number it judges, on the four numeric kinds (quality.h's // kCcxBar/kLocBar/kNestBar/kParamBar), so was=/now= read without the legend. QD-ENTRY-CEILING: ceiling= is the // ceiling a NEW function reached, beside the gating= it causes; QD-UNCHECKED-STATUS: call= is the call whose @@ -3214,7 +3214,7 @@ void emitQdJsonRow( std::FILE* out, const rw::quality::Regression& r, const QdRo { using namespace rw; rw::emitTo( out, "{{\"kind\":\"{}\"", jsonStr( r.kind ) ); - if( m.shape == QdRowModel::Shape::Members ) + if( m.shape == QdRowModel::RowShape::Members ) { rw::emitTo( out, ",\"members\":\"{}\",\"tokens\":{}", jsonStr( m.sym ), r.now ); } @@ -3222,7 +3222,7 @@ void emitQdJsonRow( std::FILE* out, const rw::quality::Regression& r, const QdRo { rw::emitTo( out, ",\"sym\":\"{}\"", jsonStr( m.sym ) ); } - if( m.shape == QdRowModel::Shape::WasNow ) + if( m.shape == QdRowModel::RowShape::WasNow ) { rw::emitTo( out, ",\"was\":{},\"now\":{}", quality::rowValueText( r, r.was ), quality::rowValueText( r, r.now ) ); } From 64363389a1dca8958560fbe14352603907052e3c Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:12:59 -0500 Subject: [PATCH 37/61] skills: quality-bar description fits the 5,400-char set budget (5,416 -> 5,396) TANGLE-GATE-B's third exception pushed the skill set over skilldescbudgetcheck's ceiling. Same meaning, fewer words: 'new functions at the ceiling or tangled'; 'a one-line fix'. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- skills/ripwire-quality-bar/SKILL.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/skills/ripwire-quality-bar/SKILL.md b/skills/ripwire-quality-bar/SKILL.md index be6ef7d26..b1bbc5fda 100644 --- a/skills/ripwire-quality-bar/SKILL.md +++ b/skills/ripwire-quality-bar/SKILL.md @@ -3,8 +3,8 @@ name: ripwire-quality-bar description: > Code QUALITY of what YOU just wrote, before commit/'done' or a cleanup: --quality-delta lists what got WORSE in 13 kinds; exit 2 if old code did (new-symbol rows never gate, - except defect-shape format-arity, a new function at the ceiling and a tangled new one); the fix each shape calls for. - Merge safety → change-check. Even a single-line leaf fix runs it. + except defect-shape format-arity, new functions at the ceiling or tangled); the fix each shape calls for. + Merge safety → change-check. Even a one-line fix runs it. allowed-tools: Bash, Read --- From e0f61bbf5a64ba6b686f2f49be0198fefa46b7f4 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:30:33 -0500 Subject: [PATCH 38/61] fix(quality): --ack-only's "gating" is an exact token; the verdict fold keeps shell_cut= Two CodeRabbit findings on #721 (both qd-only; answers unchanged): - ackOnlySelects tested "gating" after the kind/sym/facet substring checks, so --ack-only=gating also selected never-gating rows on a symbol such as gatingHelper (acked 3 of 3 where 1 gates). The exact token now answers only rowGates && inScope; every other token keeps substring matching. ackonlycheck (5): red on cbed31d4c ("acknowledged 3 of 3"), green here (1 of 3). - qdNothingElseToDisclose did not know shell_cut=, so an identity tree with a stale ack folded to the root line and dropped the nesting-budget disclosure (--show-stale and --json kept it). A nonzero shellCut now blocks the verdict-only fold. shellnestcheck (f): red on cbed31d4c, green here. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/verbs_quality.h | 15 +++++++++++---- test/ackonlycheck.sh | 18 ++++++++++++++++++ test/shellnestcheck.sh | 16 ++++++++++++++++ 3 files changed, 45 insertions(+), 4 deletions(-) diff --git a/src/verbs_quality.h b/src/verbs_quality.h index c423345bb..7415b2add 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -2676,10 +2676,16 @@ bool ackOnlySelects( std::string_view ackOnly, const rw::quality::Regression& r, return true; } const bool gates = rw::quality::rowGates( r ) && inScope; + // "gating" is RESERVED: the exact token answers only "would this row exit 2", never a substring of a symbol such as + // gatingHelper (CR721 — a substring hit acked a never-gating row, or refused the command on an out-of-scope one). const auto patternSelects = [ & ]( std::string_view pat ) { + if( pat == "gating" ) + { + return gates; + } return !pat.empty() && ( r.kind.find( pat ) != std::string::npos || r.sym.find( pat ) != std::string::npos - || ( !r.facet.empty() && r.facet.find( pat ) != std::string::npos ) || ( pat == "gating" && gates ) ); + || ( !r.facet.empty() && r.facet.find( pat ) != std::string::npos ) ); }; for( std::string_view rest = ackOnly; !rest.empty(); ) { @@ -3303,15 +3309,16 @@ struct QdStaleFold }; // The identity-tree verdict's precondition: a working-tree answer whose floor is this tree's own snapshot -// (head_basis="identity") with no scope, foreign or accepted ack, config warning, absorbed debt, new public surface or -// unreadable sidecar line to disclose — so the root line alone loses nothing. +// (head_basis="identity") with no scope, foreign or accepted ack, config warning, absorbed debt, new public surface, +// unreadable sidecar line or shell scan the nesting budget cut (shell_cut=, CR721) to disclose — so the root line alone +// loses nothing. bool qdNothingElseToDisclose( const QdReport& rep ) { const QdComparison& c = rep.c; const DeltaBasis& basis = c.basis; return !c.refPair && basis.headBasis != nullptr && std::string_view( basis.headBasis ) == "identity" && !c.scope.active() && c.part.foreignAcks.empty() && c.part.ackedCount == 0 && rep.configDiag.total() == 0 && rep.baselineAbsorbed == 0 - && basis.apiNewSurface == 0 && basis.baseSel.sidecarBadLines == 0 && basis.acksBadLines == 0; + && basis.apiNewSurface == 0 && basis.baseSel.sidecarBadLines == 0 && basis.acksBadLines == 0 && basis.extras.shellCut == 0; } // The stale fold this answer could ship (whether it PAYS is emitQualityDeltaXml's to measure), or nullopt when it has a diff --git a/test/ackonlycheck.sh b/test/ackonlycheck.sh index 7ed8fe796..451d2f1c4 100755 --- a/test/ackonlycheck.sh +++ b/test/ackonlycheck.sh @@ -115,5 +115,23 @@ rc=$? if [ $rc -eq 0 ]; then ok "--ack-only=gating clears the gate (exit 0)"; else no "--ack-only=gating left exit $rc"; fi if grep -q 'gating="0"' "$TMP/all.xml"; then ok "…and the header agrees (gating=\"0\")"; else no "…but the header still counts gating findings"; fi +# 5) CR721: "gating" is a RESERVED token, not a substring. A new symbol named gatingHelper carries never-gating +# new-symbol rows (params, dead-code); --ack-only=gating must ack only the one gating contract-change, never those +# rows because "gating" occurs in their sym=. RED before CR721 (train GE3 cbed31d4c): "acknowledged 3 of 3". +R5="$TMP/repo5"; mkdir -p "$R5"; cd "$R5"; git init -q .; git config user.email t@t; git config user.name t +printf '#pragma once\ninline int alpha( int a ) { return a; }\n' > lib.h +git add lib.h; git commit -qm base; "$BIN" . --quality-baseline >/dev/null 2>&1 +printf '#pragma once\ninline int alpha( int a, int b ) { return a + b; }\ninline int gatingHelper( int a, int b, int c ) { return a + b + c; }\n' > lib.h +"$BIN" . --quality-delta >"$TMP/g5.xml" 2>/dev/null +n5="$( grep -oE '<r [^>]*sym="gatingHelper"[^>]*' "$TMP/g5.xml" | wc -l | tr -d ' ' )" +if [ "${n5:-0}" -ge 1 ] && ! grep -oE '<r [^>]*sym="gatingHelper"[^>]*' "$TMP/g5.xml" | grep -q 'gating="1"'; then + ok "(5) premise: $n5 never-gating row(s) on gatingHelper" +else no "(5) premise: want >=1 non-gating gatingHelper row, got $n5: $( grep -oE '<r [^>]*' "$TMP/g5.xml" | tr '\n' ' ' )"; fi +"$BIN" . --quality-delta --ack-only=gating --quality-ack="the gating one" >/dev/null 2>"$TMP/g5.err" +a5="$( grep -c '^ack ' .ripwire_quality_acks 2>/dev/null )" +if grep -q 'acknowledged 1 of ' "$TMP/g5.err" && [ "${a5:-0}" = 1 ] && grep -q '^ack api-surface .*facet=contract-change' .ripwire_quality_acks; then + ok "(5) --ack-only=gating acks only the gating row, not gatingHelper's: $( head -1 "$TMP/g5.err" )" +else no "(5) --ack-only=gating swept in gatingHelper by substring: $( head -1 "$TMP/g5.err" ); ack lines: ${a5:-0}"; fi + [ "$fail" = 0 ] && echo "ALL PASS" || echo "FAILURES ABOVE" exit $fail diff --git a/test/shellnestcheck.sh b/test/shellnestcheck.sh index 50aa0f91d..f87fd5fd2 100755 --- a/test/shellnestcheck.sh +++ b/test/shellnestcheck.sh @@ -15,6 +15,7 @@ # (n1) UNDER THE BUDGET: a function ending in a case with no *) arm (unhandled-arm), 40 subshells deep: the unhandled-arm row is still found # and there is no shell_cut= (the budget cut nothing real). Red on a build with a budget under 40. # (n2) SHALLOW: the same file at depth 1: no shell_cut= (premise for n1: the row exists without nesting too). +# (f) FOLD: the subshell script committed with one stale ack: the identity-tree verdict fold keeps shell_cut="1". # Usage: test/shellnestcheck.sh [BIN] set -u ROOT="$( cd "$( dirname "$0" )/.." && pwd )" @@ -76,5 +77,20 @@ for n in 40 1; do else no "($label) case $n deep: want an unhandled-arm row in deep_check.sh and no shell_cut=; got row='${row:-none}' shell_cut='${c:-none}'"; fi done +# (f) CR721 FOLD: the deep script COMMITTED (tree = HEAD, head_basis="identity") plus one stale ack: the verdict-only fold +# (the root line alone) must still carry shell_cut="1" — it is a disclosure, so the fold must not win. --show-stale is the +# premise (the unfolded root has it). RED before CR721 (train GE3 cbed31d4c): the folded root had no shell_cut=. +R="$TMP/r-fold"; mkdir -p "$R/test"; "${G[@]}" -C "$R" init -q; echo 'echo hi' >"$R/test/a.sh"; gen subshell 5000 "$R/test/deep_check.sh" +printf '# ripwire quality acks v1\nack complexity 0123456789abcdef 5 a target long gone\n' >"$R/.ripwire_quality_acks" +"${G[@]}" -C "$R" add -A && "${G[@]}" -C "$R" commit -qm a +"$BIN" "$R" --quality-delta --no-cache --show-stale >"$TMP/fold-full.xml" 2>/dev/null +"$BIN" "$R" --quality-delta --no-cache >"$TMP/fold.xml" 2>/dev/null; frc=$? +full="$( grep -oE '<quality-delta [^>]*' "$TMP/fold-full.xml" )"; root="$( grep -oE '<quality-delta [^>]*' "$TMP/fold.xml" )" +if printf '%s' "$full" | grep -q 'head_basis="identity"' && printf '%s' "$full" | grep -q 'stale="1"' && [ "$( cutof "$TMP/fold-full.xml" )" = 1 ]; then + ok "(f) premise: identity tree, one stale ack, --show-stale root has shell_cut=\"1\"" +else no "(f) premise: want head_basis=identity, stale=1 and shell_cut=1 under --show-stale; got: $full"; fi +if [ "$frc" = 0 ] && [ "$( cutof "$TMP/fold.xml" )" = 1 ]; then ok "(f) the default (folded) answer keeps shell_cut=\"1\"" +else no "(f) the default answer dropped shell_cut= (rc=$frc): $root"; fi + [ "$fail" = 0 ] && echo "shellnestcheck: PASS" || echo "shellnestcheck: FAIL" exit "$fail" From f21031eeb85e87285b9df5d7ad676bec7c3d79d1 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:56:37 -0500 Subject: [PATCH 39/61] fix(quality): CR721 qd-only findings: clone-group next=, cut shell trees, pin-refusal units, a supervised shellnestcheck CodeRabbit review on #721 (cbed31d4c). Every change here is --quality-delta / gate-only; answers are unchanged. - qdExpandNextAttr: no --expand next= on new-clone-of-reused-helper (sym= is the member list, p= the first member's), as for duplication. qoriginoraclecheck (e2): red on main b576a95e3 and cbed31d4c (next="--expand='copy.cpp:reinvented | sharedHelper'"). - scanVacuousAssertBash: a tree the nesting budget cut is not judged (a guard past the cut is invisible); shell_cut= still discloses it. shellnestcheck (v) red on cbed31d4c, (v0) premise. - the dirty --quality-baseline refusal prints was/now via rowValueText (tangle 10.5, not 105). tanglecheck (p1) red on cbed31d4c. - shellnestcheck: every scan runs under a 60 s alarm (cap60), so a hang fails instead of stalling. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/defectshape.h | 10 ++++++++-- src/verbs_quality.h | 10 ++++++---- test/qoriginoraclecheck.sh | 9 +++++++++ test/shellnestcheck.sh | 38 +++++++++++++++++++++++++++++++++----- test/tanglecheck.sh | 15 +++++++++++++++ 5 files changed, 71 insertions(+), 11 deletions(-) diff --git a/src/defectshape.h b/src/defectshape.h index 38bed4e97..d3aa7edc3 100644 --- a/src/defectshape.h +++ b/src/defectshape.h @@ -4078,8 +4078,14 @@ inline std::vector<Site> scanVacuousAssertBash( std::string_view src, const std: { return {}; } - const rw::shstatus::Tree tree = parseShellScan( src, cut ); - const rw::shstatus::Analysis an = rw::shstatus::analyze( tree, src ); + const rw::shstatus::Tree tree = parseShellScan( src, cut ); + if( tree.cut ) + { + // CR721: a guard PAST the cut (a presence test after the absence assertion it protects) is invisible to the prefix, + // so the prefix alone would call that assertion vacuous. A cut tree is not judged; shell_cut= already says so. + return {}; + } + const rw::shstatus::Analysis an = rw::shstatus::analyze( tree, src ); const va::Script script( src, tree, an ); return script.sites(); } diff --git a/src/verbs_quality.h b/src/verbs_quality.h index 7415b2add..6ebc5d8e3 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -2313,7 +2313,7 @@ DirtyPinVerdict inspectDirtyBaselinePin( const MainDispatch& d, const std::strin if( verdict.firstRow.empty() ) { verdict.firstRow = r.kind + " " + quality::displaySym( r.sym, cfg.rootPath ) - + " (was=" + std::to_string( r.was ) + " now=" + std::to_string( r.now ) + ")"; + + " (was=" + quality::rowValueText( r, r.was ) + " now=" + quality::rowValueText( r, r.now ) + ")"; // CR721: tangle in display units } } return verdict; @@ -3155,11 +3155,13 @@ QdRowModel qdRowModel( const rw::quality::Regression& r, bool gatingAllowed, std // P3 (L7, nextverb.h): a GATING row hands the agent the body to fix — --expand=FILE:NAME (the file-qualified selector, so // a same-named symbol elsewhere cannot answer). The name is the sym key's last :: segment. Only the sym-carrying shapes ask: -// a Members row (duplication) names a SET and has no single body to open. Nor does a FILE-anchored defect-shape row -// (top-level code: sym= is the path, and --expand=FILE:FILE matches no symbol). Empty when the row offers no body. +// a Members row (duplication) names a SET and has no single body to open; nor does new-clone-of-reused-helper, whose sym= is +// the same member list (CR721: its "last :: segment" was "a | b", and p= belongs to the first member). Nor does a +// FILE-anchored defect-shape row (top-level code: sym= is the path, and --expand=FILE:FILE matches no symbol). Empty when +// the row offers no body. std::string qdExpandNextAttr( const rw::quality::Regression& r, const QdRowModel& m ) { - if( !m.gating || r.path.empty() || ( r.kind == "defect-shape" && r.sym == r.path ) ) + if( !m.gating || r.path.empty() || r.kind == "new-clone-of-reused-helper" || ( r.kind == "defect-shape" && r.sym == r.path ) ) { return std::string(); } diff --git a/test/qoriginoraclecheck.sh b/test/qoriginoraclecheck.sh index e271f479d..802866035 100755 --- a/test/qoriginoraclecheck.sh +++ b/test/qoriginoraclecheck.sh @@ -202,5 +202,14 @@ PE="$( cd "$P" && "$BIN" . --quality-delta --no-cache 2>/dev/null )" printf '%s' "$PE" | grep -q 'kind="new-clone-of-reused-helper"' \ && ok "a new clone of a PREEXISTING reused helper is still reported (the kind is narrowed, not emptied)" \ || { no "the reuse-decline kind no longer fires on its own headline case"; printf '%s' "$PE" | tr '<' '\n' | grep '^r kind='; } +# (e2) CR721: that row's sym= is a member LIST and p= is the first member's, so it hands no --expand next= (a single-body +# selector would be "FILE:a | b", which resolves nothing). Premise: the row is there and gates. RED before CR721 +# (main b576a95e3 and train GE3 cbed31d4c): next="--expand='copy.cpp:… | …'". +crow="$( printf '%s' "$PE" | grep -oE '<r kind="new-clone-of-reused-helper"[^>]*' | head -1 )" +case "$crow" in + *'gating="1"'*next=*) no "(e2) the gating clone-group row offers a single-body next=: $crow" ;; + *'gating="1"'*) ok "(e2) the gating clone-group row carries no next=: $crow" ;; + *) no "(e2) PREMISE: want a gating new-clone-of-reused-helper row, got '${crow:-none}'" ;; +esac [ "$fail" -eq 0 ] && echo "qoriginoraclecheck: ALL PASS" || { echo "qoriginoraclecheck: SOME CHECKS FAILED"; exit 1; } diff --git a/test/shellnestcheck.sh b/test/shellnestcheck.sh index f87fd5fd2..73e09211d 100755 --- a/test/shellnestcheck.sh +++ b/test/shellnestcheck.sh @@ -15,6 +15,7 @@ # (n1) UNDER THE BUDGET: a function ending in a case with no *) arm (unhandled-arm), 40 subshells deep: the unhandled-arm row is still found # and there is no shell_cut= (the budget cut nothing real). Red on a build with a budget under 40. # (n2) SHALLOW: the same file at depth 1: no shell_cut= (premise for n1: the row exists without nesting too). +# (v) CUT TREE: an absence assertion whose guard lies past the cut is not judged vacuous (premise v0: the facet is live). # (f) FOLD: the subshell script committed with one stale ack: the identity-tree verdict fold keeps shell_cut="1". # Usage: test/shellnestcheck.sh [BIN] set -u @@ -31,6 +32,9 @@ ok(){ printf ' PASS %s\n' "$*" || { fail=1; printf ' FAIL could not write th no(){ printf ' FAIL %s\n' "$*"; fail=1; } echo "shellnestcheck: BIN=$BIN" G=( git -c user.name=t -c user.email=t@t -c commit.gpgsign=false ) +# cap60 CMD...: the 60 s deadline is ENFORCED, not just measured after the fact (CR721): SIGALRM kills a hung scan (rc 142), which +# every arm below reads as a failure, so regression.sh never stalls on this gate. +cap60(){ perl -e 'alarm 60; exec @ARGV or exit 127' "$@"; } # gen KIND N OUT — one script nested N levels in one shape (python: no shell recursion of our own) gen(){ python3 - "$1" "$2" "$3" <<'PY' @@ -56,19 +60,19 @@ cutof(){ grep -oE '<quality-delta [^>]*' "$1" | grep -oE ' shell_cut="[0-9]+"' | for k in subshell group if quote subst; do R="$( repo "$k" 5000 )"; s=$( date +%s ) - "$BIN" "$R" --quality-delta --no-cache >"$TMP/$k.xml" 2>"$TMP/$k.err"; rc=$?; t=$(( $( date +%s ) - s )) + cap60 "$BIN" "$R" --quality-delta --no-cache >"$TMP/$k.xml" 2>"$TMP/$k.err"; rc=$?; t=$(( $( date +%s ) - s )) c="$( cutof "$TMP/$k.xml" )" if { [ "$rc" = 0 ] || [ "$rc" = 2 ]; } && [ "$t" -le 60 ] && [ "${c:-0}" = 1 ]; then ok "($k) 5000 deep: rc=$rc in ${t}s, shell_cut=\"$c\"" else no "($k) 5000 deep: want rc 0/2 within 60 s and shell_cut=\"1\"; got rc=$rc in ${t}s, shell_cut='${c:-none}' ($( tail -c 160 "$TMP/$k.err" | tr '\n' ' ' ))"; fi done R="$TMP/r-subshell-5000" -"$BIN" "$R" --quality-delta --json --no-cache >"$TMP/j.json" 2>/dev/null; jrc=$? +cap60 "$BIN" "$R" --quality-delta --json --no-cache >"$TMP/j.json" 2>/dev/null; jrc=$? j="$( python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("shell_cut","absent"))' "$TMP/j.json" 2>/dev/null || echo unparseable )" if { [ "$jrc" = 0 ] || [ "$jrc" = 2 ]; } && [ "$j" = 1 ]; then ok "(j) --json: \"shell_cut\":1"; else no "(j) --json: want rc 0/2 and \"shell_cut\":1, got rc=$jrc '$j'"; fi for n in 40 1; do R="$( repo case "$n" )" - "$BIN" "$R" --quality-delta --no-cache >"$TMP/case$n.xml" 2>/dev/null; crc=$? + cap60 "$BIN" "$R" --quality-delta --no-cache >"$TMP/case$n.xml" 2>/dev/null; crc=$? case "$crc" in 0|2) ;; *) no "(case $n) --quality-delta exited $crc";; esac row="$( grep -oE '<r kind="defect-shape"[^>]*defect="unhandled-arm"[^>]*>' "$TMP/case$n.xml" | grep 'deep_check.sh' | head -1 )" c="$( cutof "$TMP/case$n.xml" )" @@ -83,8 +87,8 @@ done R="$TMP/r-fold"; mkdir -p "$R/test"; "${G[@]}" -C "$R" init -q; echo 'echo hi' >"$R/test/a.sh"; gen subshell 5000 "$R/test/deep_check.sh" printf '# ripwire quality acks v1\nack complexity 0123456789abcdef 5 a target long gone\n' >"$R/.ripwire_quality_acks" "${G[@]}" -C "$R" add -A && "${G[@]}" -C "$R" commit -qm a -"$BIN" "$R" --quality-delta --no-cache --show-stale >"$TMP/fold-full.xml" 2>/dev/null -"$BIN" "$R" --quality-delta --no-cache >"$TMP/fold.xml" 2>/dev/null; frc=$? +cap60 "$BIN" "$R" --quality-delta --no-cache --show-stale >"$TMP/fold-full.xml" 2>/dev/null +cap60 "$BIN" "$R" --quality-delta --no-cache >"$TMP/fold.xml" 2>/dev/null; frc=$? full="$( grep -oE '<quality-delta [^>]*' "$TMP/fold-full.xml" )"; root="$( grep -oE '<quality-delta [^>]*' "$TMP/fold.xml" )" if printf '%s' "$full" | grep -q 'head_basis="identity"' && printf '%s' "$full" | grep -q 'stale="1"' && [ "$( cutof "$TMP/fold-full.xml" )" = 1 ]; then ok "(f) premise: identity tree, one stale ack, --show-stale root has shell_cut=\"1\"" @@ -92,5 +96,29 @@ else no "(f) premise: want head_basis=identity, stale=1 and shell_cut=1 under -- if [ "$frc" = 0 ] && [ "$( cutof "$TMP/fold.xml" )" = 1 ]; then ok "(f) the default (folded) answer keeps shell_cut=\"1\"" else no "(f) the default answer dropped shell_cut= (rc=$frc): $root"; fi +# (v) CR721 CUT TREE NOT JUDGED: an absence assertion, a 5,000-deep group, then the presence guard that protects it. The parse +# stops inside the group, so the guard is invisible; the vacuous-assert facet must not judge the prefix (shell_cut="1" says +# the file was cut). Premise (v0): the same assertion with NO guard and no nesting rows vacuous-assert (the facet is live). +# RED before CR721 (train GE3 cbed31d4c): a vacuous-assert row at test/deep_check.sh:4. +vgen(){ python3 - "$1" "$2" "$3" <<'PY' +import sys +n, guard, out = int(sys.argv[1]), sys.argv[2] == "guard", sys.argv[3] +s = '#!/usr/bin/env bash\nset -u\nOUT="$( ./tool --run )"\n' +s += "printf '%s' \"$OUT\" | grep -q 'bad' && echo \"FAIL bad\" || echo \"PASS no bad\"\n" +if n: s += "( " * n + "false" + " )" * n + "\n" +if guard: s += "printf '%s' \"$OUT\" | grep -q 'good' && echo \"PASS good\" || echo \"FAIL no good\"\n" +open(out, "w").write(s) +PY +} +vrepo(){ local R="$TMP/v-$1"; mkdir -p "$R/test"; "${G[@]}" -C "$R" init -q; echo 'echo hi' >"$R/test/a.sh" + "${G[@]}" -C "$R" add -A && "${G[@]}" -C "$R" commit -qm a; vgen "$2" "$3" "$R/test/deep_check.sh"; printf '%s' "$R"; } +vac(){ grep -oE '<r kind="defect-shape"[^>]*defect="vacuous-assert"[^>]*' "$1" | grep 'deep_check.sh'; } +R="$( vrepo v0 0 noguard )"; cap60 "$BIN" "$R" --quality-delta --no-cache >"$TMP/v0.xml" 2>/dev/null +if [ -n "$( vac "$TMP/v0.xml" )" ]; then ok "(v0) premise: the unguarded absence assertion rows vacuous-assert"; else no "(v0) premise: no vacuous-assert row on the unguarded script"; fi +R="$( vrepo v 5000 guard )"; cap60 "$BIN" "$R" --quality-delta --no-cache >"$TMP/v.xml" 2>/dev/null; vrc=$? +vr="$( vac "$TMP/v.xml" )"; c="$( cutof "$TMP/v.xml" )" +if { [ "$vrc" = 0 ] || [ "$vrc" = 2 ]; } && [ -z "$vr" ] && [ "${c:-0}" = 1 ]; then ok "(v) cut tree: no vacuous-assert row, shell_cut=\"1\"" +else no "(v) cut tree: want no vacuous-assert row and shell_cut=\"1\"; got rc=$vrc row='${vr:-none}' shell_cut='${c:-none}'"; fi + [ "$fail" = 0 ] && echo "shellnestcheck: PASS" || echo "shellnestcheck: FAIL" exit "$fail" diff --git a/test/tanglecheck.sh b/test/tanglecheck.sh index ebbbda3e0..8fb4ed705 100755 --- a/test/tanglecheck.sh +++ b/test/tanglecheck.sh @@ -8,6 +8,7 @@ # names the nesting, fix= an extraction with its lines, locals= the flag. # (b1) CROSSING: crossing was 100 flat lines (score 0) and now has tangled's body: a preexisting row (no origin=) with gating="1". # (b2) TEST CODE: harnessmain, new under test/ with tangled's body: a row with sev="minor" and no gating= (premise: the row exists). +# (p1) PIN UNITS: the dirty-tree --quality-baseline refusal names a tangle row as "was=10.5 now=10.9", like the delta row. # (b3) EXIT: the answer exits 2 and the root's gating= counts at least t1 + b1; the stderr line names a tangled new function. # (n1) LONG SEQUENTIAL, (n2) LONG ORCHESTRATOR, (n3) FLAT DISPATCHER, (n4) SHORT NESTED HELPER: no tangle row. Each counts its # premise in --metrics first (the function is there, and n3/n4 really reach depth 4+) and FAILS on a zero premise. @@ -186,5 +187,19 @@ else no "(j) --json: '$jt' (tangle rows, improved) vs XML $tangles rows"; fi # (d) if cmp -s "$Q" "$Q.2"; then ok "(d) two runs byte-identical"; else no "(d) two runs differ"; fi +# (p1) CR721 PIN UNITS: --quality-baseline on a dirty tree whose one gating row is a tangle (grow1 over the bar, growing) refuses +# and names that row in the SAME display units as the --quality-delta row (was="10.5" now="10.9"), not raw tenths. +# RED before CR721 (train GE3 cbed31d4c): "First: tangle grow1 (was=105 now=109)". +P="$TMP/pin"; mkdir -p "$P/src"; "${G[@]}" -C "$P" init -q +g1(){ python3 -c 'import sys; sys.path.insert(0, sys.argv[1]); import tanglefixtures as t; open(sys.argv[2], "w").write("#include <vector>\n" + t.overbar("grow1", int(sys.argv[3]), mult=17))' "$ROOT/test/lib" "$P/src/grow1.cpp" "$1"; } +g1 40; "${G[@]}" -C "$P" add -A && "${G[@]}" -C "$P" commit -qm v1; g1 42 +pr="$( "$BIN" "$P" --quality-delta --no-cache 2>/dev/null | grep -oE '<r kind="tangle"[^>]*sym="grow1"[^>]*gating="1"[^>]*' )" +pw="$( attr "$pr" was )"; pn="$( attr "$pr" now )" +"$BIN" "$P" --quality-baseline --no-cache >/dev/null 2>"$TMP/pin.err"; prc=$? +first="$( tr '\n' ' ' <"$TMP/pin.err" | grep -oE 'First: [^)]*\)' )" +if [ -z "$pr" ] || [ "${pw#*.}" = "$pw" ]; then no "(p1) PREMISE: want a gating tangle row on grow1 with a decimal was=, got '${pr:-none}'" +elif [ "$prc" = 1 ] && [ "$first" = "First: tangle grow1 (was=$pw now=$pn)" ]; then ok "(p1) the pin refusal names the tangle row in display units: $first" +else no "(p1) want rc 1 and 'First: tangle grow1 (was=$pw now=$pn)', got rc=$prc '$first'"; fi + [ "$fail" = 0 ] && echo "tanglecheck: PASS" || echo "tanglecheck: FAIL" exit "$fail" From 1c3b76d572eb2c43cb302b6bca71794140570fe9 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sun, 22 Nov 2026 10:14:52 -0500 Subject: [PATCH 40/61] skills: quality-bar keeps its pinned phrases; the trim comes from unpinned words (5,397 chars) c54b11107's trim reworded two phrases that gates pin: defectshapecheck "surfaces" needs the exception as "a new function at the ceiling and a tangled new one", and agentloopcodexcheck needs "single-line leaf fix" in the frontmatter. Both are restored. The 16+ chars now come from "Code QUALITY of what YOU just wrote" -> "QUALITY of code YOU just wrote", "or a cleanup" -> "or cleanup" and "the fix each shape calls for" -> "each shape's fix". skilldescbudgetcheck: set total 5,397 of 5,400. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- skills/ripwire-quality-bar/SKILL.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/skills/ripwire-quality-bar/SKILL.md b/skills/ripwire-quality-bar/SKILL.md index b1bbc5fda..b1d549ae0 100644 --- a/skills/ripwire-quality-bar/SKILL.md +++ b/skills/ripwire-quality-bar/SKILL.md @@ -1,10 +1,10 @@ --- name: ripwire-quality-bar description: > - Code QUALITY of what YOU just wrote, before commit/'done' or a cleanup: --quality-delta + QUALITY of code YOU just wrote, before commit/'done' or cleanup: --quality-delta lists what got WORSE in 13 kinds; exit 2 if old code did (new-symbol rows never gate, - except defect-shape format-arity, new functions at the ceiling or tangled); the fix each shape calls for. - Merge safety → change-check. Even a one-line fix runs it. + except defect-shape format-arity, a new function at the ceiling and a tangled new one); each shape's fix. + Merge safety → change-check. Even a single-line leaf fix runs it. allowed-tools: Bash, Read --- From 8d53017f4be78c20516d68d4f892934950cbeb87 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:14:46 -0500 Subject: [PATCH 41/61] test: the CR721 arms test each new call's exit status (prereview CI10) ackonlycheck (5) now requires --quality-baseline rc 0, the delta rc 2 and the ack rc 0 beside its output checks (still red on cbed31d4c: "acknowledged 3 of 3", green here). tanglecheck (p1)'s piped premise call states why its status is not read: an empty row fails the premise arm. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- test/ackonlycheck.sh | 14 +++++++------- test/tanglecheck.sh | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/test/ackonlycheck.sh b/test/ackonlycheck.sh index 451d2f1c4..2faa7b289 100755 --- a/test/ackonlycheck.sh +++ b/test/ackonlycheck.sh @@ -120,18 +120,18 @@ if grep -q 'gating="0"' "$TMP/all.xml"; then ok "…and the header agrees (gatin # rows because "gating" occurs in their sym=. RED before CR721 (train GE3 cbed31d4c): "acknowledged 3 of 3". R5="$TMP/repo5"; mkdir -p "$R5"; cd "$R5"; git init -q .; git config user.email t@t; git config user.name t printf '#pragma once\ninline int alpha( int a ) { return a; }\n' > lib.h -git add lib.h; git commit -qm base; "$BIN" . --quality-baseline >/dev/null 2>&1 +git add lib.h; git commit -qm base; "$BIN" . --quality-baseline >/dev/null 2>&1; b5=$? printf '#pragma once\ninline int alpha( int a, int b ) { return a + b; }\ninline int gatingHelper( int a, int b, int c ) { return a + b + c; }\n' > lib.h -"$BIN" . --quality-delta >"$TMP/g5.xml" 2>/dev/null +"$BIN" . --quality-delta >"$TMP/g5.xml" 2>/dev/null; d5=$? n5="$( grep -oE '<r [^>]*sym="gatingHelper"[^>]*' "$TMP/g5.xml" | wc -l | tr -d ' ' )" -if [ "${n5:-0}" -ge 1 ] && ! grep -oE '<r [^>]*sym="gatingHelper"[^>]*' "$TMP/g5.xml" | grep -q 'gating="1"'; then +if [ "$b5" = 0 ] && [ "$d5" = 2 ] && [ "${n5:-0}" -ge 1 ] && ! grep -oE '<r [^>]*sym="gatingHelper"[^>]*' "$TMP/g5.xml" | grep -q 'gating="1"'; then ok "(5) premise: $n5 never-gating row(s) on gatingHelper" -else no "(5) premise: want >=1 non-gating gatingHelper row, got $n5: $( grep -oE '<r [^>]*' "$TMP/g5.xml" | tr '\n' ' ' )"; fi -"$BIN" . --quality-delta --ack-only=gating --quality-ack="the gating one" >/dev/null 2>"$TMP/g5.err" +else no "(5) premise: want baseline rc 0 (got $b5), delta rc 2 (got $d5) and >=1 non-gating gatingHelper row, got $n5: $( grep -oE '<r [^>]*' "$TMP/g5.xml" | tr '\n' ' ' )"; fi +"$BIN" . --quality-delta --ack-only=gating --quality-ack="the gating one" >/dev/null 2>"$TMP/g5.err"; k5=$? a5="$( grep -c '^ack ' .ripwire_quality_acks 2>/dev/null )" -if grep -q 'acknowledged 1 of ' "$TMP/g5.err" && [ "${a5:-0}" = 1 ] && grep -q '^ack api-surface .*facet=contract-change' .ripwire_quality_acks; then +if [ "$k5" = 0 ] && grep -q 'acknowledged 1 of ' "$TMP/g5.err" && [ "${a5:-0}" = 1 ] && grep -q '^ack api-surface .*facet=contract-change' .ripwire_quality_acks; then ok "(5) --ack-only=gating acks only the gating row, not gatingHelper's: $( head -1 "$TMP/g5.err" )" -else no "(5) --ack-only=gating swept in gatingHelper by substring: $( head -1 "$TMP/g5.err" ); ack lines: ${a5:-0}"; fi +else no "(5) --ack-only=gating swept in gatingHelper by substring: $( head -1 "$TMP/g5.err" ) (rc=$k5); ack lines: ${a5:-0}"; fi [ "$fail" = 0 ] && echo "ALL PASS" || echo "FAILURES ABOVE" exit $fail diff --git a/test/tanglecheck.sh b/test/tanglecheck.sh index 8fb4ed705..948b3c414 100755 --- a/test/tanglecheck.sh +++ b/test/tanglecheck.sh @@ -193,7 +193,7 @@ if cmp -s "$Q" "$Q.2"; then ok "(d) two runs byte-identical"; else no "(d) two r P="$TMP/pin"; mkdir -p "$P/src"; "${G[@]}" -C "$P" init -q g1(){ python3 -c 'import sys; sys.path.insert(0, sys.argv[1]); import tanglefixtures as t; open(sys.argv[2], "w").write("#include <vector>\n" + t.overbar("grow1", int(sys.argv[3]), mult=17))' "$ROOT/test/lib" "$P/src/grow1.cpp" "$1"; } g1 40; "${G[@]}" -C "$P" add -A && "${G[@]}" -C "$P" commit -qm v1; g1 42 -pr="$( "$BIN" "$P" --quality-delta --no-cache 2>/dev/null | grep -oE '<r kind="tangle"[^>]*sym="grow1"[^>]*gating="1"[^>]*' )" +pr="$( "$BIN" "$P" --quality-delta --no-cache 2>/dev/null | grep -oE '<r kind="tangle"[^>]*sym="grow1"[^>]*gating="1"[^>]*' )" # status: the delta exits 2 on this gating row; an empty $pr FAILs the (p1) premise below pw="$( attr "$pr" was )"; pn="$( attr "$pr" now )" "$BIN" "$P" --quality-baseline --no-cache >/dev/null 2>"$TMP/pin.err"; prc=$? first="$( tr '\n' ' ' <"$TMP/pin.err" | grep -oE 'First: [^)]*\)' )" From a137178ebedeeaae2ddedb7fe8f69fa23ed5774b Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:47:21 -0500 Subject: [PATCH 42/61] test: tanglecheck reads the whole --metrics answer (--page-bytes=0) Main now pages --metrics at 24 KB. On the rebased train the tangle fixture's steerscope row falls on page 2, so the (s4) premise read 'missing'. The arm now reads the whole answer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- test/tanglecheck.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/tanglecheck.sh b/test/tanglecheck.sh index 948b3c414..651ed6856 100755 --- a/test/tanglecheck.sh +++ b/test/tanglecheck.sh @@ -72,9 +72,9 @@ Q="$TMP/qd.xml" "$BIN" "$R" --quality-delta --no-cache >"$Q" 2>"$Q.err"; echo $? >"$Q.rc" "$BIN" "$R" --quality-delta --no-cache >"$Q.2" 2>/dev/null; rc2=$? "$BIN" "$R" --quality-delta --json --no-cache >"$TMP/qd.json" 2>/dev/null; rcj=$? -M="$( "$BIN" "$R" --metrics --no-cache 2>/dev/null )"; rcm=$? +M="$( "$BIN" "$R" --metrics --page-bytes=0 --no-cache 2>/dev/null )"; rcm=$? # the whole answer: main pages --metrics at 24 KB mkdir -p "$TMP/head" && "${G[@]}" -C "$R" archive HEAD | tar -x -C "$TMP/head" -MH="$( "$BIN" "$TMP/head" --metrics --no-cache 2>/dev/null )"; rcmh=$? +MH="$( "$BIN" "$TMP/head" --metrics --page-bytes=0 --no-cache 2>/dev/null )"; rcmh=$? rc="$( cat "$Q.rc" )" case "$rc" in 0|2) ;; *) no "quality-delta exit status $rc (stderr: $( head -c 300 "$Q.err" ))";; esac if [ "$rc2" != "$rc" ] || [ "$rcj" != "$rc" ]; then no "quality-delta exit status differs between runs: $rc, again $rc2, --json $rcj"; fi From 12c46c4d4f4b43d02ad02ed63d8070aadf7dbf87 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:47:53 -0500 Subject: [PATCH 43/61] fix(quality): a cut shell tree is not judged unhandled-arm (CR721) When the nesting budget is spent inside a quoted substitution, the rest of the file lexes as one word, so a case's *) arm and its esac are lost. endingCaseSites then reported a missing *) arm the file has. scanUnhandledArmBash now skips a cut tree, as scanVacuousAssertBash already does. shell_cut= still discloses the cut. shellnestcheck (u): a function-ending case with a *) arm whose second arm holds a 5,000-deep quoted substitution gets no unhandled-arm row and keeps shell_cut="1". (u0) is the same file at depth 1: no row. RED on the rebased tip 43be39fcd (an unhandled-arm row on kindof). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/defectshape.h | 6 ++++++ test/shellnestcheck.sh | 22 ++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/defectshape.h b/src/defectshape.h index d3aa7edc3..8650045c8 100644 --- a/src/defectshape.h +++ b/src/defectshape.h @@ -5867,6 +5867,12 @@ inline void scanUnhandledArmBash( std::string_view src, const std::vector<Span>& return; } const rw::shstatus::Tree t = parseShellScan( src, cut ); + if( t.cut ) + { + // CR721: a cut inside a quoted substitution makes the rest of the file one word, so a *) arm and its esac past the + // cut are lost and the prefix reads as a case with no catch-all. A cut tree is not judged (as scanVacuousAssertBash). + return; + } uash::endingCaseSites( src, t, out ); uash::assignedCaseSites( src, t, fnSpans, out ); } diff --git a/test/shellnestcheck.sh b/test/shellnestcheck.sh index 73e09211d..812f06e4a 100755 --- a/test/shellnestcheck.sh +++ b/test/shellnestcheck.sh @@ -16,6 +16,7 @@ # and there is no shell_cut= (the budget cut nothing real). Red on a build with a budget under 40. # (n2) SHALLOW: the same file at depth 1: no shell_cut= (premise for n1: the row exists without nesting too). # (v) CUT TREE: an absence assertion whose guard lies past the cut is not judged vacuous (premise v0: the facet is live). +# (u) CUT CASE: a case whose *) arm lies past the cut is not judged unhandled-arm (premise u0: depth 1, no row). # (f) FOLD: the subshell script committed with one stale ack: the identity-tree verdict fold keeps shell_cut="1". # Usage: test/shellnestcheck.sh [BIN] set -u @@ -120,5 +121,26 @@ vr="$( vac "$TMP/v.xml" )"; c="$( cutof "$TMP/v.xml" )" if { [ "$vrc" = 0 ] || [ "$vrc" = 2 ]; } && [ -z "$vr" ] && [ "${c:-0}" = 1 ]; then ok "(v) cut tree: no vacuous-assert row, shell_cut=\"1\"" else no "(v) cut tree: want no vacuous-assert row and shell_cut=\"1\"; got rc=$vrc row='${vr:-none}' shell_cut='${c:-none}'"; fi +# (u) CR721 CUT CASE NOT JUDGED: a function-ending case WITH a *) arm whose second arm holds a 5,000-deep quoted substitution. +# The cut makes the rest of the file one word, so *) and esac are lost; unhandled-arm must not report a missing *) arm the +# file has. Premise (u0): the same file at depth 1 has no row (the *) arm is seen), and n2 above shows the facet is live. +# RED before this fix (train GE3 7a387ab51, and the rebased tip 43be39fcd): an unhandled-arm row on test/deep_check.sh. +ugen(){ python3 - "$1" "$2" <<'PY' +import sys +n, out = int(sys.argv[1]), sys.argv[2] +q = '"' + '$( echo "' * n + "y" + '" )' * n + '"' +open(out, "w").write('#!/usr/bin/env bash\nset -u\nkindof() { case "$1" in a) echo x ;; b) echo ' + q + ' ;; *) echo z ;; esac; }\nkindof a\n') +PY +} +uarm(){ grep -oE '<r kind="defect-shape"[^>]*defect="unhandled-arm"[^>]*' "$1" | grep 'deep_check.sh'; } +for n in 1 5000; do + R="$TMP/u-$n"; mkdir -p "$R/test"; "${G[@]}" -C "$R" init -q; echo 'echo hi' >"$R/test/a.sh" + "${G[@]}" -C "$R" add -A && "${G[@]}" -C "$R" commit -qm a; ugen "$n" "$R/test/deep_check.sh" + cap60 "$BIN" "$R" --quality-delta --no-cache >"$TMP/u$n.xml" 2>/dev/null; urc=$? + ur="$( uarm "$TMP/u$n.xml" )"; c="$( cutof "$TMP/u$n.xml" )"; want=0; label=u0; [ "$n" = 5000 ] && { want=1; label=u; } + if { [ "$urc" = 0 ] || [ "$urc" = 2 ]; } && [ -z "$ur" ] && [ "${c:-0}" = "$want" ]; then ok "($label) depth $n: no unhandled-arm row, shell_cut=${c:-none}" + else no "($label) depth $n: want rc 0/2, no unhandled-arm row and shell_cut=$want; got rc=$urc row='${ur:-none}' shell_cut='${c:-none}'"; fi +done + [ "$fail" = 0 ] && echo "shellnestcheck: PASS" || echo "shellnestcheck: FAIL" exit "$fail" From 43428469e612e968ce967af4848413c88e17a0df Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:49:40 -0500 Subject: [PATCH 44/61] test: shellnestcheck's (f) and (v0) premises check their scan's exit status (CR721) The --show-stale scan behind (f) and the unguarded scan behind (v0) dropped their status, so a scan that printed the expected text and then crashed or hit the deadline still passed its premise. Both now require rc 0 or 2, as the deep-scan arms already do. RED with a wrapper binary that prints the real answer and then exits 134 (tmp red/crashbin.sh): the old (f) and (v0) premises PASS, the new ones FAIL with rc=134. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- test/shellnestcheck.sh | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/shellnestcheck.sh b/test/shellnestcheck.sh index 812f06e4a..4f7db3d14 100755 --- a/test/shellnestcheck.sh +++ b/test/shellnestcheck.sh @@ -88,12 +88,12 @@ done R="$TMP/r-fold"; mkdir -p "$R/test"; "${G[@]}" -C "$R" init -q; echo 'echo hi' >"$R/test/a.sh"; gen subshell 5000 "$R/test/deep_check.sh" printf '# ripwire quality acks v1\nack complexity 0123456789abcdef 5 a target long gone\n' >"$R/.ripwire_quality_acks" "${G[@]}" -C "$R" add -A && "${G[@]}" -C "$R" commit -qm a -cap60 "$BIN" "$R" --quality-delta --no-cache --show-stale >"$TMP/fold-full.xml" 2>/dev/null +cap60 "$BIN" "$R" --quality-delta --no-cache --show-stale >"$TMP/fold-full.xml" 2>/dev/null; ffrc=$? cap60 "$BIN" "$R" --quality-delta --no-cache >"$TMP/fold.xml" 2>/dev/null; frc=$? full="$( grep -oE '<quality-delta [^>]*' "$TMP/fold-full.xml" )"; root="$( grep -oE '<quality-delta [^>]*' "$TMP/fold.xml" )" -if printf '%s' "$full" | grep -q 'head_basis="identity"' && printf '%s' "$full" | grep -q 'stale="1"' && [ "$( cutof "$TMP/fold-full.xml" )" = 1 ]; then +if { [ "$ffrc" = 0 ] || [ "$ffrc" = 2 ]; } && printf '%s' "$full" | grep -q 'head_basis="identity"' && printf '%s' "$full" | grep -q 'stale="1"' && [ "$( cutof "$TMP/fold-full.xml" )" = 1 ]; then ok "(f) premise: identity tree, one stale ack, --show-stale root has shell_cut=\"1\"" -else no "(f) premise: want head_basis=identity, stale=1 and shell_cut=1 under --show-stale; got: $full"; fi +else no "(f) premise: want rc 0/2, head_basis=identity, stale=1 and shell_cut=1 under --show-stale; got rc=$ffrc: $full"; fi if [ "$frc" = 0 ] && [ "$( cutof "$TMP/fold.xml" )" = 1 ]; then ok "(f) the default (folded) answer keeps shell_cut=\"1\"" else no "(f) the default answer dropped shell_cut= (rc=$frc): $root"; fi @@ -114,8 +114,8 @@ PY vrepo(){ local R="$TMP/v-$1"; mkdir -p "$R/test"; "${G[@]}" -C "$R" init -q; echo 'echo hi' >"$R/test/a.sh" "${G[@]}" -C "$R" add -A && "${G[@]}" -C "$R" commit -qm a; vgen "$2" "$3" "$R/test/deep_check.sh"; printf '%s' "$R"; } vac(){ grep -oE '<r kind="defect-shape"[^>]*defect="vacuous-assert"[^>]*' "$1" | grep 'deep_check.sh'; } -R="$( vrepo v0 0 noguard )"; cap60 "$BIN" "$R" --quality-delta --no-cache >"$TMP/v0.xml" 2>/dev/null -if [ -n "$( vac "$TMP/v0.xml" )" ]; then ok "(v0) premise: the unguarded absence assertion rows vacuous-assert"; else no "(v0) premise: no vacuous-assert row on the unguarded script"; fi +R="$( vrepo v0 0 noguard )"; cap60 "$BIN" "$R" --quality-delta --no-cache >"$TMP/v0.xml" 2>/dev/null; v0rc=$? +if { [ "$v0rc" = 0 ] || [ "$v0rc" = 2 ]; } && [ -n "$( vac "$TMP/v0.xml" )" ]; then ok "(v0) premise: the unguarded absence assertion rows vacuous-assert"; else no "(v0) premise: want rc 0/2 and a vacuous-assert row on the unguarded script; got rc=$v0rc"; fi R="$( vrepo v 5000 guard )"; cap60 "$BIN" "$R" --quality-delta --no-cache >"$TMP/v.xml" 2>/dev/null; vrc=$? vr="$( vac "$TMP/v.xml" )"; c="$( cutof "$TMP/v.xml" )" if { [ "$vrc" = 0 ] || [ "$vrc" = 2 ]; } && [ -z "$vr" ] && [ "${c:-0}" = 1 ]; then ok "(v) cut tree: no vacuous-assert row, shell_cut=\"1\"" From cb81ec5af657c65641a9d49ec30b24e7089a7012 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:50:00 -0500 Subject: [PATCH 45/61] test: qoriginoraclecheck (e2) rejects next= in either attribute order (CR721) The case patterns required next= after gating="1", so a row with next= first fell to the second pattern and passed. The gating attribute and the absence of next= are now tested independently; the missing-row premise still fails. Logic check on crafted rows (red/qorigin_logic.sh): next= before gating="1" was PASS, now FAIL; the other three shapes are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- test/qoriginoraclecheck.sh | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/test/qoriginoraclecheck.sh b/test/qoriginoraclecheck.sh index 802866035..71c7eba06 100755 --- a/test/qoriginoraclecheck.sh +++ b/test/qoriginoraclecheck.sh @@ -206,10 +206,9 @@ printf '%s' "$PE" | grep -q 'kind="new-clone-of-reused-helper"' \ # selector would be "FILE:a | b", which resolves nothing). Premise: the row is there and gates. RED before CR721 # (main b576a95e3 and train GE3 cbed31d4c): next="--expand='copy.cpp:… | …'". crow="$( printf '%s' "$PE" | grep -oE '<r kind="new-clone-of-reused-helper"[^>]*' | head -1 )" -case "$crow" in - *'gating="1"'*next=*) no "(e2) the gating clone-group row offers a single-body next=: $crow" ;; - *'gating="1"'*) ok "(e2) the gating clone-group row carries no next=: $crow" ;; - *) no "(e2) PREMISE: want a gating new-clone-of-reused-helper row, got '${crow:-none}'" ;; -esac +# CR721: the two facts are tested independently, so a next= BEFORE gating="1" cannot slip past an order-bound pattern. +if ! printf '%s' "$crow" | grep -q ' gating="1"'; then no "(e2) PREMISE: want a gating new-clone-of-reused-helper row, got '${crow:-none}'" +elif printf '%s' "$crow" | grep -q ' next='; then no "(e2) the gating clone-group row offers a single-body next=: $crow" +else ok "(e2) the gating clone-group row carries no next=: $crow"; fi [ "$fail" -eq 0 ] && echo "qoriginoraclecheck: ALL PASS" || { echo "qoriginoraclecheck: SOME CHECKS FAILED"; exit 1; } From aead22f1ba6ab68476944b11023b1335dff8098f Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:50:37 -0500 Subject: [PATCH 46/61] test: tanglecheck (p1) checks the display units of both was= and now= (CR721) The premise required a decimal was= only, so a delta row and pin refusal that both printed was=10.5 now=109 would pass. Both values must now be one-decimal display units (the fixture gives was=10.5 now=10.9). Logic check: was=10.5 now=109 was premise-ok, now PREMISE-FAIL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- test/tanglecheck.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/tanglecheck.sh b/test/tanglecheck.sh index 651ed6856..6bbf722d5 100755 --- a/test/tanglecheck.sh +++ b/test/tanglecheck.sh @@ -197,7 +197,8 @@ pr="$( "$BIN" "$P" --quality-delta --no-cache 2>/dev/null | grep -oE '<r kind="t pw="$( attr "$pr" was )"; pn="$( attr "$pr" now )" "$BIN" "$P" --quality-baseline --no-cache >/dev/null 2>"$TMP/pin.err"; prc=$? first="$( tr '\n' ' ' <"$TMP/pin.err" | grep -oE 'First: [^)]*\)' )" -if [ -z "$pr" ] || [ "${pw#*.}" = "$pw" ]; then no "(p1) PREMISE: want a gating tangle row on grow1 with a decimal was=, got '${pr:-none}'" +# CR721: BOTH values are display units (tenths as one decimal place: the fixture's was 40 -> now 42 calls both land in 10.x) +if [ -z "$pr" ] || ! printf '%s %s' "$pw" "$pn" | grep -qE '^[0-9]+\.[0-9] [0-9]+\.[0-9]$'; then no "(p1) PREMISE: want a gating tangle row on grow1 with decimal was= and now=, got '${pr:-none}'" elif [ "$prc" = 1 ] && [ "$first" = "First: tangle grow1 (was=$pw now=$pn)" ]; then ok "(p1) the pin refusal names the tangle row in display units: $first" else no "(p1) want rc 1 and 'First: tangle grow1 (was=$pw now=$pn)', got rc=$prc '$first'"; fi From a9797690f98c92ff12254ad02500d27ec50ed799 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:51:11 -0500 Subject: [PATCH 47/61] fix(lexical): RIPWIRE_TERMMARGIN is 0 or 1; any other value is refused (CR721) termMarginFromEnv armed the margin for every value not starting with '0', so RIPWIRE_TERMMARGIN=off, =yes, =2 and an empty value all ARMED it and changed candidate scores. Unset, empty and "0" now leave it disarmed and "1" arms it. Any other value is checked with VALIDATE, refused to the disarmed default, and named on one stderr line, the same way envKnob refuses a bad number. Default (unset) and =1 runs are unchanged. termmargincheck (h): off/yes/2 rank as the disarmed run, print the refusal and no term-margin: trace. An empty value is the silent default. RED on the rebased tip 43be39fcd: all four armed the margin. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/lexical.h | 13 +++++++++++-- test/termmargincheck.sh | 16 ++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/lexical.h b/src/lexical.h index 2026507dd..1c5cc727b 100644 --- a/src/lexical.h +++ b/src/lexical.h @@ -722,13 +722,22 @@ struct LexTermMargin bool armed() const noexcept { return bits > 0; } }; +// RIPWIRE_TERMMARGIN is a switch: unset, empty or "0" leaves the margin disarmed, "1" arms it. Any other value is refused to +// the disarmed default with one stderr line (CR721: "off" used to ARM it, since every value not starting with '0' did). inline LexTermMargin termMarginFromEnv() { - const char* env = std::getenv( "RIPWIRE_TERMMARGIN" ); - if( env == nullptr || *env == '0' ) + const char* const env = std::getenv( "RIPWIRE_TERMMARGIN" ); + if( env == nullptr || std::string_view( env ).empty() || std::string_view( env ) == "0" ) { return {}; } + if( !VALIDATE( std::string_view( env ) == "1", "RIPWIRE_TERMMARGIN is 0 or 1" ) ) + { + rw::emitRaw( stderr, "ripwire: ignoring RIPWIRE_TERMMARGIN=\"" ); + rw::emitRaw( stderr, env ); + rw::emitRaw( stderr, "\" (want 0 or 1) — the margin stays disarmed\n" ); + return {}; + } const std::optional<int> bits = envKnob<int>( "RIPWIRE_TERMMARGIN_BITS" ); return { bits ? std::clamp( *bits, 1, 8 ) : 1 }; } diff --git a/test/termmargincheck.sh b/test/termmargincheck.sh index 52f09b405..1fadd7348 100755 --- a/test/termmargincheck.sh +++ b/test/termmargincheck.sh @@ -232,6 +232,22 @@ cmp -s "$TMP/a_on.xml" "$TMP/a_off.xml" \ && no "(e) the armed and disarmed runs are byte-identical — the arm is inert, so every arm above is measuring nothing" \ || ok "(e) armed and disarmed runs differ, so the arm is live" +# ── (h) CR721 — the switch is 0 or 1: any other value is refused to the disarmed default with one stderr line ───────── +# RED before (rebased train tip 43be39fcd): RIPWIRE_TERMMARGIN=off ARMED the margin (every value not starting with '0' +# did), so its ranking was the armed one and stderr carried term-margin: traces, not a refusal. +for v in off yes 2; do + runq "$v" "evict handler" "$TMP/h_$v.xml" "$TMP/h_$v.err"; hrc=$? + if [ "$hrc" = 0 ] && cmp -s "$TMP/h_$v.xml" "$TMP/a_off.xml" && grep -q "ignoring RIPWIRE_TERMMARGIN=\"$v\"" "$TMP/h_$v.err" \ + && ! grep -q '^term-margin: ' "$TMP/h_$v.err"; then + ok "(h) RIPWIRE_TERMMARGIN=$v is refused: disarmed ranking, one stderr line, no margin trace" + else + no "(h) RIPWIRE_TERMMARGIN=$v: want rc 0, the disarmed ranking and a refusal line; got rc=$hrc, stderr: $( head -c 200 "$TMP/h_$v.err" )" + fi +done +runq "" "evict handler" "$TMP/h_empty.xml" "$TMP/h_empty.err"; hrc=$? +if [ "$hrc" = 0 ] && cmp -s "$TMP/h_empty.xml" "$TMP/a_off.xml" && [ ! -s "$TMP/h_empty.err" ]; then ok "(h) an empty RIPWIRE_TERMMARGIN is the unset default, silently" +else no "(h) an empty RIPWIRE_TERMMARGIN: want rc 0, the disarmed ranking and empty stderr; got rc=$hrc, stderr: $( head -c 200 "$TMP/h_empty.err" )"; fi + # ── (f) determinism + scan/persisted-stats parity, with the arm ON ───────────────────────────────── runq 1 "evict handler" "$TMP/f_1.xml" "$TMP/f_1.err" runq 1 "evict handler" "$TMP/f_2.xml" "$TMP/f_2.err" From 49c76eb90f2932b42ed1cd1ed847c80e6e0753f5 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:53:51 -0500 Subject: [PATCH 48/61] fix(quality): a range answer's stale_next= names the commits it compared (CR721) For --quality-delta=HEAD~1..HEAD the stale fold's replay copied the symbolic range. If HEAD moved before the reader followed it, the replay compared a different pair and could list different stale acks. A range replay is now built from the two resolved shas (the pair kinds_next= already uses). The working-tree replay is still the bare verb. staleackcheck (6): 60 helpers plus knotty() are acked and deleted, then a tweak commit, so HEAD~1..HEAD is regression-free with 61 stale acks and the fold pays. stale_next= must be --quality-delta=<base sha>..<target sha> --show-stale. RED on the rebased tip 43be39fcd (HEAD~1..HEAD). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/verbs_quality.h | 4 +++- test/staleackcheck.sh | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/verbs_quality.h b/src/verbs_quality.h index 6ebc5d8e3..924ad1d39 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -3335,7 +3335,9 @@ std::optional<QdStaleFold> qdStaleFold( const QdReport& rep, const Escape& ex ) return std::nullopt; } const std::string kinds = quality::staleByKindValue( rep.staleAcks ); // shared with the MCP twin (lane lean2b) - std::string replay = c.cfg.qualityDeltaRange.empty() ? std::string( "--quality-delta" ) : rw::nextFlag( "--quality-delta=", c.cfg.qualityDeltaRange ); + // A range replay names the two commits this answer compared (CR721), not the symbolic range: HEAD~1..HEAD followed after + // HEAD moved would compare another pair. The working-tree replay stays the bare verb. + std::string replay = c.refPair ? "--quality-delta=" + c.refs.baseSha + ".." + c.refs.targetSha : std::string( "--quality-delta" ); if( c.scope.active() ) { replay += " " + rw::nextFlag( "--scope=", c.cfg.qualityScope ); diff --git a/test/staleackcheck.sh b/test/staleackcheck.sh index 03685eae3..255121e0b 100755 --- a/test/staleackcheck.sh +++ b/test/staleackcheck.sh @@ -296,4 +296,39 @@ else grep -o '<quality-delta[^>]*>\|<sa[^>]*/>' "$TMP/clean2" fi +# ── (6) CR721 — the RANGE form's stale_next= replays the SAME answer: it names the two commits compared, not the symbolic +# range (HEAD~1..HEAD after HEAD moves compares another pair). Fixture: knotty() + 60 uncalled helpers acked, all deleted, then a tweak commit, so +# HEAD~1..HEAD has no regression and 61 stale acks (enough for the fold to pay). PREMISE: the fold is there (stale_next=). +# RED before (rebased train tip 43be39fcd): stale_next="--quality-delta=HEAD~1..HEAD --show-stale". +REPO3="$( mktemp -d )"; trap 'rm -rf "$REPO" "$REPO2" "$REPO3" "$TMP"' EXIT +run3(){ env -u TMPDIR XDG_CACHE_HOME="$XDG" "$BIN" "$REPO3" "$@"; } +G3=( git -C "$REPO3" -c user.email=x@y -c user.name=x -c commit.gpgsign=false ) +mkdir -p "$REPO3/src"; echo 'int stable( int a ) { return a + 1; }' >"$REPO3/src/lib.cpp" +"${G3[@]}" init -q; "${G3[@]}" add -A; "${G3[@]}" commit -qm init +cat >>"$REPO3/src/lib.cpp" <<'EOF' +int knotty( int a, long b, int c ) { + int r = 0; + for( int i = 0; i < a; ++i ) { + if( i % 2 == 0 ) { if( i > b ) { r += i; } else { r -= 1; } } + else { for( int j = 0; j < b; ++j ) { if( j > c ) { r += j; } else { r--; } } } + while( r > c && r > b ) { r = r - 1; if( r % 3 == 0 ) { r += 2; } } + } + return r; +} +EOF +for i in $( seq 1 60 ); do echo "int helper$i( int a ) { return a * $i + 7; }" >>"$REPO3/src/lib.cpp"; done +run3 --quality-delta --quality-ack="fixture 3: accepted" >/dev/null 2>&1 +"${G3[@]}" add -A; "${G3[@]}" commit -qm knotty +echo 'int stable( int a ) { return a + 1; }' >"$REPO3/src/lib.cpp"; "${G3[@]}" commit -qam gone +echo 'int stable( int a ) { return a + 2; }' >"$REPO3/src/lib.cpp"; "${G3[@]}" commit -qam tweak +b3="$( "${G3[@]}" rev-parse HEAD~1 )"; t3="$( "${G3[@]}" rev-parse HEAD )" +for sel in ""; do + run3 --quality-delta=HEAD~1..HEAD ${sel:+"$sel"} --no-cache >"$TMP/range5" 2>/dev/null; r5=$? + want="--quality-delta=$b3..$t3${sel:+ $sel} --show-stale" + got="$( grep -oE 'stale_next="[^"]*"' "$TMP/range5" | head -1 | sed 's/^stale_next="//; s/"$//' )" + if [ "$r5" != 0 ] || [ -z "$got" ]; then no "(6) PREMISE '${sel:-all kinds}': want rc 0 and a folded range answer with stale_next=, got rc=$r5 '${got:-none}'" + elif [ "$got" = "$want" ]; then ok "(6) '${sel:-all kinds}': stale_next= names the compared commits${sel:+ and keeps $sel}" + else no "(6) '${sel:-all kinds}': want stale_next=\"$want\", got \"$got\""; fi +done + [ "$fail" -eq 0 ] && echo "staleackcheck: ALL PASS" || { echo "staleackcheck: SOME CHECKS FAILED"; exit 1; } From 2dc0065e9d1c81f506b3c1d744cbf8f5e880507d Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:54:59 -0500 Subject: [PATCH 49/61] fix(quality): a range answer's stale_next= keeps its --quality-kinds selector (CR721) A regression-free range answer limited by --quality-kinds folds only the selected kinds' stale acks. Its replay dropped the selector, so following it also listed the other kinds' stale acks: 62 rows for a fold that counted 61. The range replay now carries --quality-kinds when one was given. Unfiltered replays are unchanged. staleackcheck (6) also checks the --quality-kinds=dead-code answer's stale_next= and runs that call exactly as printed: it must list as many <sa> rows as the folded stale= count. RED on the rebased tip 43be39fcd: 62 rows for 61, and no selector in stale_next=. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/verbs_quality.h | 7 ++++++- test/staleackcheck.sh | 17 ++++++++++++++--- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/verbs_quality.h b/src/verbs_quality.h index 924ad1d39..9f800f5ed 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -3336,8 +3336,13 @@ std::optional<QdStaleFold> qdStaleFold( const QdReport& rep, const Escape& ex ) } const std::string kinds = quality::staleByKindValue( rep.staleAcks ); // shared with the MCP twin (lane lean2b) // A range replay names the two commits this answer compared (CR721), not the symbolic range: HEAD~1..HEAD followed after - // HEAD moved would compare another pair. The working-tree replay stays the bare verb. + // HEAD moved would compare another pair. It carries the --quality-kinds selector too, so the replay lists the stale acks + // of the kinds this answer counted and no others. The working-tree replay stays the bare verb. std::string replay = c.refPair ? "--quality-delta=" + c.refs.baseSha + ".." + c.refs.targetSha : std::string( "--quality-delta" ); + if( c.refPair && !c.cfg.qualityKinds.empty() ) + { + replay += " " + rw::nextFlag( "--quality-kinds=", c.cfg.qualityKinds ); + } if( c.scope.active() ) { replay += " " + rw::nextFlag( "--scope=", c.cfg.qualityScope ); diff --git a/test/staleackcheck.sh b/test/staleackcheck.sh index 255121e0b..ab78d1779 100755 --- a/test/staleackcheck.sh +++ b/test/staleackcheck.sh @@ -297,9 +297,11 @@ else fi # ── (6) CR721 — the RANGE form's stale_next= replays the SAME answer: it names the two commits compared, not the symbolic -# range (HEAD~1..HEAD after HEAD moves compares another pair). Fixture: knotty() + 60 uncalled helpers acked, all deleted, then a tweak commit, so +# range (HEAD~1..HEAD after HEAD moves compares another pair), and it keeps --quality-kinds (an unfiltered replay lists +# the other kinds' stale acks too). Fixture: knotty() + 60 uncalled helpers acked, all deleted, then a tweak commit, so # HEAD~1..HEAD has no regression and 61 stale acks (enough for the fold to pay). PREMISE: the fold is there (stale_next=). -# RED before (rebased train tip 43be39fcd): stale_next="--quality-delta=HEAD~1..HEAD --show-stale". +# RED before (rebased train tip 43be39fcd): stale_next="--quality-delta=HEAD~1..HEAD --show-stale" with and without +# --quality-kinds=dead-code; on 7905e958e (shas, no selector) the dead-code answer's replay lists 62 rows for its 61. REPO3="$( mktemp -d )"; trap 'rm -rf "$REPO" "$REPO2" "$REPO3" "$TMP"' EXIT run3(){ env -u TMPDIR XDG_CACHE_HOME="$XDG" "$BIN" "$REPO3" "$@"; } G3=( git -C "$REPO3" -c user.email=x@y -c user.name=x -c commit.gpgsign=false ) @@ -322,7 +324,7 @@ run3 --quality-delta --quality-ack="fixture 3: accepted" >/dev/null 2>&1 echo 'int stable( int a ) { return a + 1; }' >"$REPO3/src/lib.cpp"; "${G3[@]}" commit -qam gone echo 'int stable( int a ) { return a + 2; }' >"$REPO3/src/lib.cpp"; "${G3[@]}" commit -qam tweak b3="$( "${G3[@]}" rev-parse HEAD~1 )"; t3="$( "${G3[@]}" rev-parse HEAD )" -for sel in ""; do +for sel in "" "--quality-kinds=dead-code"; do run3 --quality-delta=HEAD~1..HEAD ${sel:+"$sel"} --no-cache >"$TMP/range5" 2>/dev/null; r5=$? want="--quality-delta=$b3..$t3${sel:+ $sel} --show-stale" got="$( grep -oE 'stale_next="[^"]*"' "$TMP/range5" | head -1 | sed 's/^stale_next="//; s/"$//' )" @@ -330,5 +332,14 @@ for sel in ""; do elif [ "$got" = "$want" ]; then ok "(6) '${sel:-all kinds}': stale_next= names the compared commits${sel:+ and keeps $sel}" else no "(6) '${sel:-all kinds}': want stale_next=\"$want\", got \"$got\""; fi done +# the call stale_next= names, run as printed, lists what the folded answer counted: as many <sa> rows as its stale= +run3 --quality-delta=HEAD~1..HEAD --quality-kinds=dead-code --no-cache >"$TMP/range5f" 2>/dev/null +n5="$( grep -oE ' stale="[0-9]+"' "$TMP/range5f" | head -1 | grep -oE '[0-9]+' )" +next5="$( grep -oE 'stale_next="[^"]*"' "$TMP/range5f" | head -1 | sed 's/^stale_next="//; s/"$//' )" +read -r -a next5argv <<<"$next5" +run3 "${next5argv[@]}" --no-cache >"$TMP/range5r" 2>/dev/null; rr5=$? +rows5="$( grep -o '<sa ' "$TMP/range5r" | wc -l | tr -d ' ' )" +if [ "$rr5" = 0 ] && [ -n "$n5" ] && [ "$n5" -gt 0 ] && [ "$rows5" = "$n5" ]; then ok "(6) the stale_next= call lists the $n5 stale rows the folded answer counted" +else no "(6) the stale_next= call '${next5:-none}' (rc=$rr5) lists $rows5 <sa> rows, the folded answer counted '${n5:-none}'"; fi [ "$fail" -eq 0 ] && echo "staleackcheck: ALL PASS" || { echo "staleackcheck: SOME CHECKS FAILED"; exit 1; } From 8954c404c573e209dc270914f1ed794c39711785 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:58:15 -0500 Subject: [PATCH 50/61] docs(quality): the qd legend states the whole exit-2 predicate (CR721) The full legend said EXIT 2 fires only on preexisting-worse AND major, then listed the new-symbol exceptions in a separate clause. A new function at the ceiling or at tangle 6 can be the only gating row while preexisting-worse=0. The sentence now reads: EXIT 2 fires only on a row that GATES (an unacked, in-scope major row that is preexisting-worse or one of the new-symbol exceptions), with the exceptions named in the same sentence. Exit 0 is no verdict on the other new-symbol rows or the minor ones. defectshapecheck surfaces: the legend must not say "EXIT 2 fires only on preexisting-worse". RED on the rebased tip 43be39fcd. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/verbs_quality.h | 7 ++++--- test/defectshapecheck.sh | 4 ++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/verbs_quality.h b/src/verbs_quality.h index 9f800f5ed..bd6713116 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -1482,9 +1482,10 @@ inline constexpr const char* kQdLegendCore = "order: (1) acked findings are suppressed entirely (acked= counts them); (2) ORIGIN — a finding on a " "symbol that EXISTED at the baseline is preexisting-worse (no origin attribute), one that exists only " "because the code is NEW carries origin=\"new-symbol\"; (3) MATERIALITY — a small numeric delta is " - "sev=\"minor\", and minor= counts them. EXIT 2 fires only on preexisting-worse AND major, the gating= count; " - "new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling and a tangled new function, so exit 0 " - "is NOT a verdict on them — nothing that existed got worse, but the new debt is yours: read them. Clone kinds are new-symbol only when EVERY member is new; short-horizon-churn is " + "sev=\"minor\", and minor= counts them. EXIT 2 fires only on a row that GATES (gating= counts them): an unacked, " + "in-scope major row that is preexisting-worse or one of the new-symbol exceptions — new-symbol rows never gate, except " + "defect-shape format-arity, a new function at the ceiling and a tangled new function. So exit 0 is NOT a verdict on the " + "other new-symbol rows or the minor ones: the new debt is yours, read them. Clone kinds are new-symbol only when EVERY member is new; short-horizon-churn is " "preexisting by construction. preexisting-worse= and new-symbol= partition regressions=. stale= is a " "FOURTH axis, never gating and never counted in regressions=: rows in the .ripwire_quality_acks ledger " "whose target no longer applies. " diff --git a/test/defectshapecheck.sh b/test/defectshapecheck.sh index 377574162..d3f203621 100644 --- a/test/defectshapecheck.sh +++ b/test/defectshapecheck.sh @@ -2173,6 +2173,10 @@ if printf '%s' "$LEG" | grep -q '<quality-delta '; then EX="$( printf '%s' "$LEG" | grep -o 'EXIT 2 fires only on[^.]*' )" if [ -n "$EX" ] && ! printf '%s\n' "$EX" | grep -vq 'format-arity'; then ok "$L: every 'EXIT 2 fires only on' sentence names the format-arity exception" else no "$L: an 'EXIT 2 fires only on' sentence omits format-arity (or none found): ${EX:-<none>}"; fi + # CR721: the exit-2 sentence states the whole predicate. A new function at the ceiling or tangle 6 can be the only gating + # row, with preexisting-worse=0, so "fires only on preexisting-worse" is false. RED before (43be39fcd): that wording. + if printf '%s' "$LEG" | grep -q 'EXIT 2 fires only on preexisting-worse'; then no "$L: the legend says EXIT 2 fires only on preexisting-worse rows" + else ok "$L: the exit-2 sentence does not limit gating to preexisting-worse rows"; fi if printf '%s' "$LEG" | grep -q 'report-only by facet, not by size'; then ok "$L: the legend says the report-only facets are sev=minor by facet, not by size (D3)" else no "$L: the legend does not say 'report-only by facet, not by size' — sev=minor is otherwise defined as a small numeric delta"; fi if printf '%s' "$LEG" | grep -q 'f-strings are not checked'; then ok "$L: the legend names the Python formats it does not check" From 22f06fed59d7f56c5381286e8301f4cffbce9c86 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:58:15 -0500 Subject: [PATCH 51/61] docs(cli): --quality-delta help: moved-and-rewritten functions can gate; what exit 0 means (CR721) Two sentences in the --quality-delta help contradicted the exception rule they sit beside. A function moved with a changed body reads as new and gates the way a new function does (at the ceiling or at tangle 6 or more), so "a regression carried in with it will not gate" was wrong. "exit 0 means nothing that already existed got worse" was also wrong, because preexisting minor rows still print. Exit 0 now reads: no unacked, in-scope row gated over the kinds the answer ran, which is not "clean". docs/COMMANDS.md is regenerated from the help in the regen commit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/cli.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cli.h b/src/cli.h index 8f1c15e21..2ba112398 100644 --- a/src/cli.h +++ b/src/cli.h @@ -1919,8 +1919,8 @@ inline constexpr char kHelpHead[] = " preexisting-worse, defect-shape format-arity (any origin), a new function at the ceiling or a tangled new one — the gating=\"N\" header count. New-symbol rows are still PRINTED (they are the debt you are adding — read them);\n" " new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling (4x the bar: ccx 60 or 240 lines,\n" " not a moved body, not test code, ceiling= on the row) and a new one at tangle 6 or more (not moved, not test code); exit 0 means\n" - " \"nothing that already existed got worse\", not \"clean\". Clone kinds classify by member set (new-symbol only if EVERY member is new); short-horizon-churn is preexisting\n" - " by construction. LIMIT: origin is canonId (path::scope::name) identity; a function RENAMED or MOVED with its body unchanged (whitespace and its own name aside: one body that left its key, matched to one new key) keeps its identity and the move reports nothing (and a file rename git recorded keeps each symbol in it under its own name, twins and changed bodies included), while one whose body also changed reads as new and a regression carried in with it will not gate;\n" + " no unacked, in-scope row gated over the kinds the answer ran, not \"clean\": minor rows and the other new-symbol rows still print. Clone kinds classify by member set (new-symbol only if EVERY member is new); short-horizon-churn is preexisting\n" + " by construction. LIMIT: origin is canonId (path::scope::name) identity; a function RENAMED or MOVED with its body unchanged (whitespace and its own name aside: one body that left its key, matched to one new key) keeps its identity and the move reports nothing (and a file rename git recorded keeps each symbol in it under its own name, twins and changed bodies included), while one whose body also changed reads as new and gates only as a new function does (at the ceiling or at tangle 6 or more);\n" " a function over the ccx or line bar whose body moved with a small edit (a clone-sketch match to a body that left its key) reads origin=\"moved\" and never gates.\n" " error-masking = a NEW empty/pass/comment-only handler, or log-only (a broad handler whose body only logs and never names the error) or rethrow-only (the sole\n" " handler re-throws it unchanged); those two gate only where their precision was measured (Python) and are sev=\"minor\" in every other language.\n" From 334be908e585b6aec36e0e7f2707181d64808e18 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:58:38 -0500 Subject: [PATCH 52/61] docs: the --whereis showcase captions describe the page each capture shows (CR721) The default --whereis capture now serves listing="defs" with the branch lines as kind="text" rows, but its caption still said the default serves the shorter whole list. The --whereis-listing=all caption called itself "the default's own page". The --whereis-full-text caption said "the page above", which is now the --quality-kinds demo. The three captions in test/showcase_capture.py and the 11-23 capture now describe what each block shows. The full-text caption names the --whereis-listing=all page it replays. docs/COMMANDS.md is rebuilt in the regen commit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/captures/COMMANDS_showcase_2026-11-23.md | 6 +++--- test/showcase_capture.py | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/captures/COMMANDS_showcase_2026-11-23.md b/docs/captures/COMMANDS_showcase_2026-11-23.md index 08ccf6416..c40059847 100644 --- a/docs/captures/COMMANDS_showcase_2026-11-23.md +++ b/docs/captures/COMMANDS_showcase_2026-11-23.md @@ -3226,7 +3226,7 @@ stderr: ## `./build/ripwire . --whereis=rankGraphTeleport` -*Which ref's tree defines or mentions SYM — HEAD first, then every local branch. The default renders two pages under the same 60-row cap, the definitions page (kind="def" rows and the kind="text" lines no parse read, the references counted in <refs count= next=>) and the whole list, and serves the definitions page when it shows more definitions, whatever its bytes, else only when it is strictly shorter. Here the branches' copies sit in blobs past the parse guard (<unparsed>, kind="text", never counted as definitions), so both pages show HEAD's one definition and the default serves the shorter whole list: that definition, then HEAD's references.* +*Which ref's tree defines or mentions SYM — HEAD first, then every local branch. The default renders two pages under the same 60-row cap, the definitions page (kind="def" rows and the kind="text" lines no parse read, the references counted in <refs count= next=>) and the whole list, and serves the definitions page when it shows more definitions, whatever its bytes, else only when it is strictly shorter. Here it serves the definitions page (listing="defs"): HEAD's one definition, then the branches' lines in blobs past the parse guard (<unparsed>) as kind="text" rows, a line several refs hold printed once with refs=N (folded= counts the copies it stands for), and HEAD's references counted in <refs count= next=>.* **wall time: 5.48s** @@ -3280,7 +3280,7 @@ ripwire: warning: --whereis left 252 branch blobs unparsed, their rows kind=text ## `./build/ripwire . --whereis=rankGraphTeleport --whereis-listing=all` -*The whole hit list asked for by name: under the same 60-row cap HEAD's references fill the list before any branch row arrives, so it can show fewer definitions than the definitions page. The default serves this page only when both show the same definitions and the definitions page is not strictly shorter (a tie serves this page), as above: here it is the default's own page, HEAD's one definition and then its references.* +*The whole hit list asked for by name: under the same 60-row cap HEAD's references fill the list before any branch row arrives, so it can show fewer definitions than the definitions page. The default serves this page only when both show the same definitions and the definitions page is not strictly shorter (a tie serves this page); here the default served the definitions page above, so this page is asked for by name: HEAD's one definition, then its references.* **wall time: 5.45s** @@ -3339,7 +3339,7 @@ ripwire: warning: --whereis left 252 branch blobs unparsed, their rows kind=text ## `./build/ripwire . --whereis=rankGraphTeleport --whereis-listing=all --whereis-full-text` -*The same page with every t= line whole: the page above previews each line over 300 B (200 B and t_bytes=, the <t_cut rows= next=> naming this call), and --whereis-full-text replays it with the same listing, window, rows and labels. MCP: full_text=true.* +*The --whereis-listing=all page with every t= line whole: that page previews each line over 300 B (200 B and t_bytes=, its <t_cut rows= next=> naming this call), and --whereis-full-text replays it with the same listing, window, rows and labels. MCP: full_text=true.* **wall time: 6.11s** diff --git a/test/showcase_capture.py b/test/showcase_capture.py index 87ba214d5..789803ace 100644 --- a/test/showcase_capture.py +++ b/test/showcase_capture.py @@ -563,10 +563,10 @@ def _strayScope( sub, kind ): add(S4, f"{BIN} . --stray-content={shlex.quote( _famB )} --plan", f"Select the genuinely-unmerged refs of {_strayScope( _famB, _famBKind )} and feed them to merge-scout for a landing order (a fully merged selection yields an empty landing set — still a measurement, disclosed on the root).", timeout=900) add(S4, f"{BIN} . --stray-content=zzzz-no-such-ref --plan", "A --plan filter that selects NO ref REFUSES (exit 1) naming the substring — before the wave-3 close this fell through to the '>512 refs match' sentence, and --abi under the same filter answered an empty measurement at exit 0.") add(S4, f"{BIN} . --stray-content={shlex.quote( _famB )} --abi", f"Cross-branch ABI-break gate over {_strayScope( _famB, _famBKind )}: struct byte-contract drift on each ref's AUTHORED paths — exit 2 when any drift row is found (the only kind that gates), 0 when the compared refs are clean, and exit 1 if the --stray-content filter matches no ref at all.", timeout=600) -add(S4, f"{BIN} . --whereis=rankGraphTeleport", "Which ref's tree defines or mentions SYM — HEAD first, then every local branch. The default renders two pages under the same 60-row cap, the definitions page (kind=\"def\" rows and the kind=\"text\" lines no parse read, the references counted in <refs count= next=>) and the whole list, and serves the definitions page when it shows more definitions, whatever its bytes, else only when it is strictly shorter. Here the branches' copies sit in blobs past the parse guard (<unparsed>, kind=\"text\", never counted as definitions), so both pages show HEAD's one definition and the default serves the shorter whole list: that definition, then HEAD's references.", timeout=600) -add(S4, f"{BIN} . --whereis=rankGraphTeleport --whereis-listing=all", "The whole hit list asked for by name: under the same 60-row cap HEAD's references fill the list before any branch row arrives, so it can show fewer definitions than the definitions page. The default serves this page only when both show the same definitions and the definitions page is not strictly shorter (a tie serves this page), as above: here it is the default's own page, HEAD's one definition and then its references.", timeout=600) +add(S4, f"{BIN} . --whereis=rankGraphTeleport", "Which ref's tree defines or mentions SYM — HEAD first, then every local branch. The default renders two pages under the same 60-row cap, the definitions page (kind=\"def\" rows and the kind=\"text\" lines no parse read, the references counted in <refs count= next=>) and the whole list, and serves the definitions page when it shows more definitions, whatever its bytes, else only when it is strictly shorter. Here it serves the definitions page (listing=\"defs\"): HEAD's one definition, then the branches' lines in blobs past the parse guard (<unparsed>) as kind=\"text\" rows, a line several refs hold printed once with refs=N (folded= counts the copies it stands for), and HEAD's references counted in <refs count= next=>.", timeout=600) +add(S4, f"{BIN} . --whereis=rankGraphTeleport --whereis-listing=all", "The whole hit list asked for by name: under the same 60-row cap HEAD's references fill the list before any branch row arrives, so it can show fewer definitions than the definitions page. The default serves this page only when both show the same definitions and the definitions page is not strictly shorter (a tie serves this page); here the default served the definitions page above, so this page is asked for by name: HEAD's one definition, then its references.", timeout=600) add(S4, f"{BIN} . --quality-delta=HEAD~1..HEAD --quality-kinds=complexity,dead-code", "A ref range run for two of the thirteen kinds only: the named kinds' rows are exactly their rows in the full answer, the header names the others (kinds_skipped=, skipped_why=\"selector\"), and a pass no named kind needs does not run. The replay a memory-stopped range answer hands back (kinds_next=) is this flag. Refused without --quality-delta=A..B.") -add(S4, f"{BIN} . --whereis=rankGraphTeleport --whereis-listing=all --whereis-full-text", "The same page with every t= line whole: the page above previews each line over 300 B (200 B and t_bytes=, the <t_cut rows= next=> naming this call), and --whereis-full-text replays it with the same listing, window, rows and labels. MCP: full_text=true.") +add(S4, f"{BIN} . --whereis=rankGraphTeleport --whereis-listing=all --whereis-full-text", "The --whereis-listing=all page with every t= line whole: that page previews each line over 300 B (200 B and t_bytes=, its <t_cut rows= next=> naming this call), and --whereis-full-text replays it with the same listing, window, rows and labels. MCP: full_text=true.") add(S4, f"{BIN} . --whereis=computeOnePairOverlap --with-history", "Same, plus a git-history <fate> row (never / removed-by-commit) for names no tree carries.", timeout=600) add(S4, f"{BIN} . --flags", "The dark-content dashboard: gates BUILT but OFF. CHANGED: no longer invents gates from comments/heredocs, so the count only reflects real ifndef/define, CMake option(), and getenv gates.") add(S4, f"{BIN} . --flags --flip=RIPWIRE_ASAN", "Blast radius of turning ONE gate on: live code, symbols, transitive reach, covering tests.") From 73a25ba302a11595db9d1d05338a026ace343005 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:08:07 -0500 Subject: [PATCH 53/61] regen: COMMANDS.md, help_all pin and qschemetrip pin on the rebased train (main 326dec9f4) The rebase took main's generated files in every conflict. They are rebuilt here from the rebased binary: - docs/COMMANDS.md: docs_commands_build.py --bin build/ripwire. Four lines move: the --quality-delta help (CR721) and the three --whereis captions. - test/printf_parity.manifest: help_all re-pinned with UPDATE_GOLDEN=1. It is the only label that moved. - test/qschemetrip.hash: re-pinned once, with a RE-PIN LOG entry in qschemetripcheck.sh. No scheme or parser bump. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/COMMANDS.md | 8 ++++---- test/qschemetrip.hash | 2 +- test/qschemetripcheck.sh | 6 ++++++ 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index 985d02fec..3b1005735 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -2980,7 +2980,7 @@ $ ./build/ripwire . --quality-delta --show-stale **Answers:** before a PR: report ONLY what your change made worse, across 13 kinds — pair with --test-gate. -Each kind is measured against the baseline (complexity/verbosity/nesting/params/dup/dead/api-surface + error-masking/short-horizon-churn/new-clone-of-reused-helper + placeholder + defect-shape + tangle); every finding is classified by ORIGIN: a symbol that EXISTED at the baseline and got worse (preexisting-worse="N", no attribute on the row) vs one that exists only because the code is NEW (new-symbol="N", origin="new-symbol" on the row). A small numeric delta is additionally sev="minor". EXIT 2 ONLY on a major AND unacked row that is preexisting-worse, defect-shape format-arity (any origin), a new function at the ceiling or a tangled new one — the gating="N" header count. New-symbol rows are still PRINTED (they are the debt you are adding — read them); new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling (4x the bar: ccx 60 or 240 lines, not a moved body, not test code, ceiling= on the row) and a new one at tangle 6 or more (not moved, not test code); exit 0 means "nothing that already existed got worse", not "clean". Clone kinds classify by member set (new-symbol only if EVERY member is new); short-horizon-churn is preexisting by construction. LIMIT: origin is canonId (path::scope::name) identity; a function RENAMED or MOVED with its body unchanged (whitespace and its own name aside: one body that left its key, matched to one new key) keeps its identity and the move reports nothing (and a file rename git recorded keeps each symbol in it under its own name, twins and changed bodies included), while one whose body also changed reads as new and a regression carried in with it will not gate; a function over the ccx or line bar whose body moved with a small edit (a clone-sketch match to a body that left its key) reads origin="moved" and never gates. error-masking = a NEW empty/pass/comment-only handler, or log-only (a broad handler whose body only logs and never names the error) or rethrow-only (the sole handler re-throws it unchanged); those two gate only where their precision was measured (Python) and are sev="minor" in every other language. Empty counts Go's `if err != nil {}` on a call's err and Rust's `if let Err(..) = f() {}` / `Err(..) => {}` or `=> ()`, and gates like Python's `except: pass`; log-only counts a Rust Err arm of print/log macros and a C++ catch of `std::cerr <<`, `LOG( x ) <<` or `fprintf( stderr, … )` (sev="minor"). facet="failure-default": a read, parse or spawn failure returned as an empty success (a TypeScript catch or .catch returning []/null/{}/false/0/'' around JSON.parse/fs reads/exec/spawn/fetch, in a function typed to return an array/boolean/object; a C++ value_or( empty ) on a file read); it never gates by itself. placeholder = a stub the change ADDED (todo!()/unimplemented!(), Kotlin TODO(), NotImplementedException, a bare raise NotImplementedError as a free function's body, a throw/raise/panic/assert saying "not implemented") or a comment line opening with TODO/FIXME that names no issue (#12, ABC-12, a URL); new-symbol by construction, so it never gates. Counted per enclosing symbol, like error-masking: a file-level TODO outside every definition is not counted. defect-shape = a known defect shape the change ADDED, named by defect=: format-arity (a literal std::format/print/format_to, fmt::, rw::emitTo/formatTo or Python "literal".format whose fields do not match its arguments — GATES on any origin, a defect not debt), utf8-cut and dedup-first (C++) and vacuous-assert (Bash test scripts) and unchecked-status (a dropped pclose/rename/write/system/fflush/close/waitpid status in C/C++; Python subprocess.run without check=, subprocess.call, os.system; the row carries call=) and unhandled-arm (a C/C++ switch with no default: that leaves an in-tree enum's enumerator out, a shell case with no *) arm whose result is read, a Python if/elif or match ending a value-returning function with no else; the row carries why=) — report-only, always sev="minor". A site is new only when its text occurs more often than in the baseline: a moved one is not. Test-fixture dirs + doc sections are exempt from dead-code/churn; churn needs COMMITTED thrash evidence (rewritten across recent commits AND again by this diff), never the current edit alone WHICH FLOOR IT COMPARES AGAINST, and a side effect: the sidecar is honored only when the sha it was pinned at EQUALS the current git HEAD (strict equality — an ancestor commit describes a DIFFERENT tree, so everything committed since would read as your regression). A sidecar pinned anywhere else is STALE: this verb then DELETES it from your working tree (self-heal, so the next run does not rediscover the dead pin) and auto-compares the working tree vs git HEAD instead. Re-pin with --quality-baseline. The read-only MCP quality_delta verb applies the SAME staleness test but never deletes. A sidecar at the current HEAD that ANOTHER ripwire build pinned (its producer stamp names other sources — a dead set depends on how calls were resolved) is FOREIGN: both arms ignore it, never delete it, and auto-compare vs git HEAD. Which floor was actually used is on every report as baseline=: sidecar | git-HEAD | git-HEAD (stale sidecar removed) | git-HEAD (stale sidecar ignored) | git-HEAD (foreign sidecar ignored) — the stale two say a stale sidecar existed, and 'removed' means the file is gone. A non-git root has no HEAD to fall back to, so its sidecar is honored whenever this build pinned it; without one there, or with another build's, the verb exits 1. +Each kind is measured against the baseline (complexity/verbosity/nesting/params/dup/dead/api-surface + error-masking/short-horizon-churn/new-clone-of-reused-helper + placeholder + defect-shape + tangle); every finding is classified by ORIGIN: a symbol that EXISTED at the baseline and got worse (preexisting-worse="N", no attribute on the row) vs one that exists only because the code is NEW (new-symbol="N", origin="new-symbol" on the row). A small numeric delta is additionally sev="minor". EXIT 2 ONLY on a major AND unacked row that is preexisting-worse, defect-shape format-arity (any origin), a new function at the ceiling or a tangled new one — the gating="N" header count. New-symbol rows are still PRINTED (they are the debt you are adding — read them); new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling (4x the bar: ccx 60 or 240 lines, not a moved body, not test code, ceiling= on the row) and a new one at tangle 6 or more (not moved, not test code); exit 0 means no unacked, in-scope row gated over the kinds the answer ran, not "clean": minor rows and the other new-symbol rows still print. Clone kinds classify by member set (new-symbol only if EVERY member is new); short-horizon-churn is preexisting by construction. LIMIT: origin is canonId (path::scope::name) identity; a function RENAMED or MOVED with its body unchanged (whitespace and its own name aside: one body that left its key, matched to one new key) keeps its identity and the move reports nothing (and a file rename git recorded keeps each symbol in it under its own name, twins and changed bodies included), while one whose body also changed reads as new and gates only as a new function does (at the ceiling or at tangle 6 or more); a function over the ccx or line bar whose body moved with a small edit (a clone-sketch match to a body that left its key) reads origin="moved" and never gates. error-masking = a NEW empty/pass/comment-only handler, or log-only (a broad handler whose body only logs and never names the error) or rethrow-only (the sole handler re-throws it unchanged); those two gate only where their precision was measured (Python) and are sev="minor" in every other language. Empty counts Go's `if err != nil {}` on a call's err and Rust's `if let Err(..) = f() {}` / `Err(..) => {}` or `=> ()`, and gates like Python's `except: pass`; log-only counts a Rust Err arm of print/log macros and a C++ catch of `std::cerr <<`, `LOG( x ) <<` or `fprintf( stderr, … )` (sev="minor"). facet="failure-default": a read, parse or spawn failure returned as an empty success (a TypeScript catch or .catch returning []/null/{}/false/0/'' around JSON.parse/fs reads/exec/spawn/fetch, in a function typed to return an array/boolean/object; a C++ value_or( empty ) on a file read); it never gates by itself. placeholder = a stub the change ADDED (todo!()/unimplemented!(), Kotlin TODO(), NotImplementedException, a bare raise NotImplementedError as a free function's body, a throw/raise/panic/assert saying "not implemented") or a comment line opening with TODO/FIXME that names no issue (#12, ABC-12, a URL); new-symbol by construction, so it never gates. Counted per enclosing symbol, like error-masking: a file-level TODO outside every definition is not counted. defect-shape = a known defect shape the change ADDED, named by defect=: format-arity (a literal std::format/print/format_to, fmt::, rw::emitTo/formatTo or Python "literal".format whose fields do not match its arguments — GATES on any origin, a defect not debt), utf8-cut and dedup-first (C++) and vacuous-assert (Bash test scripts) and unchecked-status (a dropped pclose/rename/write/system/fflush/close/waitpid status in C/C++; Python subprocess.run without check=, subprocess.call, os.system; the row carries call=) and unhandled-arm (a C/C++ switch with no default: that leaves an in-tree enum's enumerator out, a shell case with no *) arm whose result is read, a Python if/elif or match ending a value-returning function with no else; the row carries why=) — report-only, always sev="minor". A site is new only when its text occurs more often than in the baseline: a moved one is not. Test-fixture dirs + doc sections are exempt from dead-code/churn; churn needs COMMITTED thrash evidence (rewritten across recent commits AND again by this diff), never the current edit alone WHICH FLOOR IT COMPARES AGAINST, and a side effect: the sidecar is honored only when the sha it was pinned at EQUALS the current git HEAD (strict equality — an ancestor commit describes a DIFFERENT tree, so everything committed since would read as your regression). A sidecar pinned anywhere else is STALE: this verb then DELETES it from your working tree (self-heal, so the next run does not rediscover the dead pin) and auto-compares the working tree vs git HEAD instead. Re-pin with --quality-baseline. The read-only MCP quality_delta verb applies the SAME staleness test but never deletes. A sidecar at the current HEAD that ANOTHER ripwire build pinned (its producer stamp names other sources — a dead set depends on how calls were resolved) is FOREIGN: both arms ignore it, never delete it, and auto-compare vs git HEAD. Which floor was actually used is on every report as baseline=: sidecar | git-HEAD | git-HEAD (stale sidecar removed) | git-HEAD (stale sidecar ignored) | git-HEAD (foreign sidecar ignored) — the stale two say a stale sidecar existed, and 'removed' means the file is gone. A non-git root has no HEAD to fall back to, so its sidecar is honored whenever this build pinned it; without one there, or with another build's, the verb exits 1. **Try it** @@ -3745,7 +3745,7 @@ Each distinct blob is read ONCE (content-addressed), so N branches cost ~one tre **Try it** -_Which ref's tree defines or mentions SYM — HEAD first, then every local branch. The default renders two pages under the same 60-row cap, the definitions page (kind="def" rows and the kind="text" lines no parse read, the references counted in <refs count= next=>) and the whole list, and serves the definitions page when it shows more definitions, whatever its bytes, else only when it is strictly shorter. Here the branches' copies sit in blobs past the parse guard (<unparsed>, kind="text", never counted as definitions), so both pages show HEAD's one definition and the default serves the shorter whole list: that definition, then HEAD's references._ +_Which ref's tree defines or mentions SYM — HEAD first, then every local branch. The default renders two pages under the same 60-row cap, the definitions page (kind="def" rows and the kind="text" lines no parse read, the references counted in <refs count= next=>) and the whole list, and serves the definitions page when it shows more definitions, whatever its bytes, else only when it is strictly shorter. Here it serves the definitions page (listing="defs"): HEAD's one definition, then the branches' lines in blobs past the parse guard (<unparsed>) as kind="text" rows, a line several refs hold printed once with refs=N (folded= counts the copies it stands for), and HEAD's references counted in <refs count= next=>._ ``` $ ./build/ripwire . --whereis=rankGraphTeleport @@ -3775,7 +3775,7 @@ The listing, window, rows and labels are the page's own, so the <t_cut next=> of **Try it** -_The same page with every t= line whole: the page above previews each line over 300 B (200 B and t_bytes=, the <t_cut rows= next=> naming this call), and --whereis-full-text replays it with the same listing, window, rows and labels. MCP: full_text=true._ +_The --whereis-listing=all page with every t= line whole: that page previews each line over 300 B (200 B and t_bytes=, its <t_cut rows= next=> naming this call), and --whereis-full-text replays it with the same listing, window, rows and labels. MCP: full_text=true._ ``` $ ./build/ripwire . --whereis=rankGraphTeleport --whereis-listing=all --whereis-full-text @@ -3804,7 +3804,7 @@ The default lists defs when that page lists MORE definitions than all under the **Try it** -_The whole hit list asked for by name: under the same 60-row cap HEAD's references fill the list before any branch row arrives, so it can show fewer definitions than the definitions page. The default serves this page only when both show the same definitions and the definitions page is not strictly shorter (a tie serves this page), as above: here it is the default's own page, HEAD's one definition and then its references._ +_The whole hit list asked for by name: under the same 60-row cap HEAD's references fill the list before any branch row arrives, so it can show fewer definitions than the definitions page. The default serves this page only when both show the same definitions and the definitions page is not strictly shorter (a tie serves this page); here the default served the definitions page above, so this page is asked for by name: HEAD's one definition, then its references._ ``` $ ./build/ripwire . --whereis=rankGraphTeleport --whereis-listing=all diff --git a/test/qschemetrip.hash b/test/qschemetrip.hash index 10d5ed676..92c1f48e7 100644 --- a/test/qschemetrip.hash +++ b/test/qschemetrip.hash @@ -1 +1 @@ -a606e48d5bb4b8c7349021a6ad695c0da29586e3f682a426646c63ed2f4e02ec +4e92d58b1885e2df7c486ef0a1fa5b1647e015a0e1179dc41be7f89f50535f5b diff --git a/test/qschemetripcheck.sh b/test/qschemetripcheck.sh index 2236f5187..0f6263580 100755 --- a/test/qschemetripcheck.sh +++ b/test/qschemetripcheck.sh @@ -34,6 +34,12 @@ SRC="$ROOT/src/quality.h" ING="$ROOT/src/ingest_cache.h" # extraction-identity constants moved here (2026-08-29 ingest.cpp section split); the hashed CONCAT label keeps its historical spelling so the pin holds PIN="$ROOT/test/qschemetrip.hash" # RE-PIN LOG (the pin is a bare hash, so its justification has to live here). +# 2026-11-23, train ge3 rebased onto main 326dec9f4 (#721, lane GE721): RE-PINNED ONCE with UPDATE_GOLDEN=1 from the +# rebased build (hash 4e92d58b18…50535f5b). Watched text moved by the train's qd-lessons-2 members (defectSitesOf's shell-cut +# counter + legacySite, as on the 11-22 composed tip) on top of main's pin a606e48d5b…2f4e02ec, and by the CR721 fix +# that a cut shell tree yields no unhandled-arm site (only a tree the nesting budget cut). No kParserVer, +# kCacheVersion (54) or kQSnapCacheScheme (38) bump: the qsnap key carries the producer identity, so no blob from +# another build is read. # 2026-11-22, IN9 (the 0.7.0 train integration/070-cut-1121 merged with origin/main b576a95e3, which carries #715): RE-PINNED # ONCE with UPDATE_GOLDEN=1 on the merged sources. kParserVer and kIngestParserVerMirror 340/337 -> 342 (rich 343): ONE # number above BOTH sides' bumps (the train's 340, rich 341; main's 337, rich 338). kCacheVersion 54 and kQSnapCacheScheme 38 From b9bd5feeaac94f4f17ac6f18994f0d3f68fec320 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:55:40 -0500 Subject: [PATCH 54/61] docs(quality): the exit-2 legend sentence fits the full-legend byte targets f97fe5d30's wording was 89 B longer than the sentence it replaced. That put the qd_clean full legend 44 B over donelegendcheck's 2,800 B target. The sentence keeps the whole predicate (gating row: unacked, in-scope, major, and preexisting-worse or a new-symbol exception, with the three exceptions named) in 286 B, 11 B under the original 297 B. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/verbs_quality.h | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/verbs_quality.h b/src/verbs_quality.h index bd6713116..5473e582c 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -1482,10 +1482,9 @@ inline constexpr const char* kQdLegendCore = "order: (1) acked findings are suppressed entirely (acked= counts them); (2) ORIGIN — a finding on a " "symbol that EXISTED at the baseline is preexisting-worse (no origin attribute), one that exists only " "because the code is NEW carries origin=\"new-symbol\"; (3) MATERIALITY — a small numeric delta is " - "sev=\"minor\", and minor= counts them. EXIT 2 fires only on a row that GATES (gating= counts them): an unacked, " - "in-scope major row that is preexisting-worse or one of the new-symbol exceptions — new-symbol rows never gate, except " - "defect-shape format-arity, a new function at the ceiling and a tangled new function. So exit 0 is NOT a verdict on the " - "other new-symbol rows or the minor ones: the new debt is yours, read them. Clone kinds are new-symbol only when EVERY member is new; short-horizon-churn is " + "sev=\"minor\", and minor= counts them. EXIT 2 fires only on a gating row (gating=): unacked, in-scope, major, and " + "preexisting-worse or a new-symbol exception — new-symbol rows never gate, except defect-shape format-arity, a new " + "function at the ceiling and a tangled new function. Exit 0 is no verdict on new or minor rows: read them. Clone kinds are new-symbol only when EVERY member is new; short-horizon-churn is " "preexisting by construction. preexisting-worse= and new-symbol= partition regressions=. stale= is a " "FOURTH axis, never gating and never counted in regressions=: rows in the .ripwire_quality_acks ledger " "whose target no longer applies. " From a7dd10698f96ae3dbffb5670e3c3cef37ed31573 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:55:40 -0500 Subject: [PATCH 55/61] test: legend (G) floor follows this tree's --partition rows legendcoveragecheck (G) runs --partition on ripwire's own tree, so its partition-default lines depend on the tree, not the binary. Main 326dec9f4's own binary gives the same set on the rebased tree: +bn@l, and six lines that no longer reproduce (b@n b@t c@n d@n s@n s@t). The floor is updated, with a note saying so. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- test/legendcoverage_g_baseline.txt | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/test/legendcoverage_g_baseline.txt b/test/legendcoverage_g_baseline.txt index 00ab97bcf..9904948ae 100644 --- a/test/legendcoverage_g_baseline.txt +++ b/test/legendcoverage_g_baseline.txt @@ -6,6 +6,8 @@ # BURN-DOWN 2026-11-11 (same lane): 175 -> 50. The 125 lines gone are defined now (src/compactlegend.h kCompactAttributeReadings, # the LEGEND-G-BLIND block; the MCP for closure). The 50 left are the rarely used modifiers: --stray-content --plan, # --pack-task --partition, --cochange-groups, --slice-flow, --layout, --gateability, --field-affinity. +# 2026-11-23 (train ge3 rebased on 326dec9f4, #721): --partition picks its rows from THIS tree, so the partition-default lines +# follow the tree, not the binary (main 326dec9f4's own binary gives the same set on this tree): +bn@l, -b@n -b@t -c@n -d@n -s@n -s@t. cochange-groups-default | cochange@cover cochange-groups-default | cochange@groups cochange-groups-default | cochange@pairs_covered @@ -21,15 +23,10 @@ gateability-default | gateability@projected_drift layout-default | caveat@k layout-default | def@l layout-default | f@n +partition-default | bn@l partition-default | b@l -partition-default | b@n -partition-default | b@t partition-default | c@l -partition-default | c@n partition-default | d@l -partition-default | d@n -partition-default | s@n -partition-default | s@t slice-flow-default | s@f slice-flow-default | slice@flow slice-flow-default | slice@flow_redundant From a5d3ad3aee8533bb187070cee02e75f65dd36c29 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:38:10 -0500 Subject: [PATCH 56/61] regen: COMMANDS.md, help_all pin and the 11-23 --legend-dict block on main 6c018f611 The rebase onto main 6c018f611 took main's generated files in every conflict. They are rebuilt here from the rebased binary: - docs/captures/COMMANDS_showcase_2026-11-23.md: the --legend-dict block re-recorded with the capture's own formatter (the qd legend sentence moved). - docs/COMMANDS.md: docs_commands_build.py --bin build/ripwire. - test/printf_parity.manifest: help_all re-pinned with UPDATE_GOLDEN=1. qschemetripcheck passes on the existing pin; no re-pin. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/COMMANDS.md | 2 +- docs/captures/COMMANDS_showcase_2026-11-23.md | 4 ++-- test/printf_parity.manifest | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index 3b1005735..1942e8e46 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -4790,7 +4790,7 @@ _The session legend dictionary the MCP server serves as ripwire://legend-dict/fu ``` $ ./build/ripwire . --legend-dict -ripwire legend dictionary ripwire.dict/v1 dictv=0d983acad983c50f entries=1322 +ripwire legend dictionary ripwire.dict/v1 dictv=644fc535e75ce62e entries=1323 <about legend="ref" dict= dictv=>: this LAST child is only the legend pointer; the root keeps every attribute it carries inline, unchanged (schema=, each count, cut and floor); rows follow it; legend="ref": a definition is sent once per session (this dictionary's core, or the first answer that needs … [line truncated: 80 more bytes on this line] schema=ripwire.KEY/v1: the line ripwire.KEY/v1 below reads the answer's rows window: shown= total= capped= has_more= next_offset= offset= limit= page a list (capped=1 cut; next_offset= pastes as offset=) diff --git a/docs/captures/COMMANDS_showcase_2026-11-23.md b/docs/captures/COMMANDS_showcase_2026-11-23.md index c40059847..fd58f815c 100644 --- a/docs/captures/COMMANDS_showcase_2026-11-23.md +++ b/docs/captures/COMMANDS_showcase_2026-11-23.md @@ -6325,7 +6325,7 @@ ripwire: --run-timeout=SECONDS modifies --run-trace — pass it too (e.g. ripwir *The session legend dictionary the MCP server serves as ripwire://legend-dict/full — one definition per line, headed by its dictv= version; no corpus needed. =roster lists the completeness attributes it defines.* ````` -ripwire legend dictionary ripwire.dict/v1 dictv=0d983acad983c50f entries=1322 +ripwire legend dictionary ripwire.dict/v1 dictv=644fc535e75ce62e entries=1323 <about legend="ref" dict= dictv=>: this LAST child is only the legend pointer; the root keeps every attribute it carries inline, unchanged (schema=, each count, cut and floor); rows follow it; legend="ref": a definition is sent once per session (this dictionary's core, or the first answer that needs … [line truncated: 80 more bytes on this line] schema=ripwire.KEY/v1: the line ripwire.KEY/v1 below reads the answer's rows window: shown= total= capped= has_more= next_offset= offset= limit= page a list (capped=1 cut; next_offset= pastes as offset=) @@ -6355,7 +6355,7 @@ ripwire.pack-task/v1 <ctx>: one-call task bundle for task= under budget_tokens=: ripwire.from-trace/v1 <ctx>: trace frames mapped to indexed symbols, innermost first; the innermost in-corpus body included ripwire.exemplar/v1 <ctx>: the best-in-class instance of kind= for the task, chosen by role: <exemplar n= p= in= ccx= tested=>, <bodies><b> to imitate ripwire.pack-task/v1 <ctx-partitions>: N minimally overlapping agent bundles carved along call-graph communities plus one shared core; each <bundle> wraps a <ctx>; bundle role=core|partition i= symbols= modules= bytes= tokens=: one agent's ctx, symbols= ids assigned, bytes= its size; tokens= = est_t … [line truncated: 503 more bytes on this line] -… [1299 more display lines; full output is 168478 bytes on 1323 raw line(s)] +… [1300 more display lines; full output is 168563 bytes on 1324 raw line(s)] ````` ## `./build/ripwire . --lint --lint-select=cache-` diff --git a/test/printf_parity.manifest b/test/printf_parity.manifest index 4786ea500..f75e496c1 100644 --- a/test/printf_parity.manifest +++ b/test/printf_parity.manifest @@ -38,5 +38,5 @@ safe_delete 0 7b17c59f7606ebe5c5119ffc2a712e8249feea645887d791368324bb3f60b6c1 e verify_layer 1 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 5288c345d7d6e335f88b9c1daa8935db22e1dcf89c0c8bc1f6140d4cb5af0b48 graph_query 1 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 bfa4319feb9dee09cfbd3991cf6fbd752297e99d14de9e75768820d2a9c8832f callers_limit 0 793f97d6460e77b126434209d8efb2b887bd4cec57c6a1d06a74be79aab06ee8 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 -help_all 0 0769ffc5072b0a6bff5ef569a92437536b45ff2c5ad79d4caca2938e0b09552f e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 +help_all 0 a389157983a15771a6c295a282c15941bc0e56dc53606dcf3b43201d27b8153f e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 help_one 0 938ff4f8802a8f5d9cb10f9a1f3804ac755be44c8ab00e24e45bfe8255224a21 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 From 18afe4065d52567cbf4c30dea513975ffa371f10 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:09:34 -0500 Subject: [PATCH 57/61] GE-RUNQD: emitQdXmlDocument fills QualityDeltaLegendParts by designated initializers The legend call filled ~27 mostly-bool fields by position; a swapped pair compiled silently. Named fields make the compiler check the order. Byte-neutral. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/verbs_quality.h | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/verbs_quality.h b/src/verbs_quality.h index 5473e582c..c866962c7 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -3364,14 +3364,19 @@ void emitQdXmlDocument( std::FILE* out, const QdReport& rep, const QdStaleFold* const std::vector<quality::StaleAck>& served = fold != nullptr ? c.part.foreignAcks : rep.saRows; // the legend is passed the same values the root element below prints, so "the legend defines what the header emits" is // read off one set of values rather than restated as a second condition that could drift from it - emitQualityDeltaLegend( { basis.baseSel.marker, c.refPair, rep.root.identity.xml, !served.empty(), c.part.ackedCount > 0, - basis.registerMacroExcluded > 0, rep.configDiag.total() > 0, basis.regs, c.part.outOfScope, - c.scope.active() || !c.part.foreignAcks.empty(), !c.part.foreignAcks.empty(), rep.baselineAbsorbed, - basis.headBasis, basis.declinedCallExcluded > 0, basis.valueRefExcluded > 0, fold != nullptr, - refs.kinds != quality::kAllKinds, refs.degraded, !refs.memoryStop.empty(), rep.kd.peakOver != 0, - rep.kd.memorySkipped != 0 && refs.selected != quality::kAllKinds, basis.historyUnread.any(), - basis.rustTestExcluded, refs.staleTree, !basis.extras.ratchetRef.empty(), !basis.extras.improved.empty(), - basis.extras.shellCut > 0 }, out ); + emitQualityDeltaLegend( { .marker = basis.baseSel.marker, .refPair = c.refPair, .identityAttrs = rep.root.identity.xml, + .anySaRow = !served.empty(), .anyAcked = c.part.ackedCount > 0, + .anyRegisterMacro = basis.registerMacroExcluded > 0, .anyRegisterMacroWarning = rep.configDiag.total() > 0, + .rows = basis.regs, .disclosedRows = c.part.outOfScope, + .scoped = c.scope.active() || !c.part.foreignAcks.empty(), .anyForeignAck = !c.part.foreignAcks.empty(), + .baselineAbsorbed = rep.baselineAbsorbed, .headBasis = basis.headBasis, + .anyDeclinedCallExcluded = basis.declinedCallExcluded > 0, .anyValueRefExcluded = basis.valueRefExcluded > 0, + .staleCollapsed = fold != nullptr, .kindsSkipped = refs.kinds != quality::kAllKinds, .degraded = refs.degraded, + .memoryStopped = !refs.memoryStop.empty(), .memoryPeak = rep.kd.peakOver != 0, + .memorySkippedShare = rep.kd.memorySkipped != 0 && refs.selected != quality::kAllKinds, + .historyUnread = basis.historyUnread.any(), .anyRustTestExcluded = basis.rustTestExcluded, + .staleTree = refs.staleTree, .ratchetRead = !basis.extras.ratchetRef.empty(), + .anyImproved = !basis.extras.improved.empty(), .shellCut = basis.extras.shellCut > 0 }, out ); // at= anchors this regression list to the commit (+dirty state) it was computed against (QdRootFields::at). R-I: the range // form's base_ref= and target_ref= carry FULL shas because a wave measurement gets quoted into handoffs where a 9-char // prefix is one collision from unverifiable. From a7f8a0cb38f7ab17cb9cb8a27c5f6f638e7ea68d Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:10:24 -0500 Subject: [PATCH 58/61] GE-CAPTURETAGS: extract elixirReferenceArity from the two Elixir arity clones inertQuoteFate and the Elixir call-reference path both counted an operator reference as binary/unary by its node, overriding elixirCallArity. One helper now decides it; elixirCallArity is pure, so skipping it for operators is equivalent. Byte-neutral. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/ingest_sidecap.h | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/ingest_sidecap.h b/src/ingest_sidecap.h index 5cc3ac93f..b21251e49 100644 --- a/src/ingest_sidecap.h +++ b/src/ingest_sidecap.h @@ -2223,6 +2223,17 @@ inline CaptureFate languageFilterFate( const TagsFile& file, const TagsMatch& m } } +// An Elixir reference's arity and whether it is known: an operator reference is binary or unary by its node, always known; any +// other reference counts its call's arguments (elixirCallArity). +inline std::pair<std::uint16_t, bool> elixirReferenceArity( const TagsMatch& m, std::string_view src ) noexcept +{ + if( m.refCap == "reference.operator" ) + { + return { static_cast<std::uint16_t>( elixirNodeIs( m.roleNode, "binary_operator" ) ? 2 : 1 ), true }; + } + return elixirCallArity( m.roleNode, m.name.node, src ); +} + // A capture inside an inert quote region ends here: call/operator/named-capture candidates are kept as declined facts, never edges // (Emitted); every other capture is dropped. Heads, special forms and non-call operators already failed their syntax filters. Bare // AST names remain variable-shaped syntax unless they explicitly name a function capture. @@ -2244,8 +2255,7 @@ inline CaptureFate inertQuoteFate( const TagsFile& file, TagsSinks& sinks, const r.line = m.name.row + 1; r.lang = Lang::Elixir; r.role = RefRole::Inert; - auto [ count, known ] = elixirCallArity( m.roleNode, m.name.node, file.src ); - if( m.refCap == "reference.operator" ) { count = elixirNodeIs( m.roleNode, "binary_operator" ) ? 2 : 1; known = true; } + const auto [ count, known ] = elixirReferenceArity( m, file.src ); r.name = known ? elixirFunctionName( m.name.text, count ) : std::string( m.name.text ); sinks.refs.push_back( std::move( r ) ); return CaptureFate::Emitted; @@ -2918,8 +2928,7 @@ inline CaptureFate qualifyElixirReference( const TagsFile& file, TagsSinks& sink r.recv = nodeTextOf( receiver, file.src ).starts_with( "__MODULE__" ) || file.elixir.selfRelativeAlias( receiver, m.roleNode ) ? RecvKind::ElixirSelfModule : RecvKind::ElixirModule; } - auto [ count, known ] = elixirCallArity( m.roleNode, m.name.node, file.src ); - if( m.refCap == "reference.operator" ) { count = elixirNodeIs( m.roleNode, "binary_operator" ) ? 2 : 1; known = true; } + const auto [ count, known ] = elixirReferenceArity( m, file.src ); if( !known ) { return CaptureFate::Drop; } r.argCount = count; r.argCountKnown = true; r.name = elixirFunctionName( m.name.text, count ); From feda8154a35c1fc3aec11c867cacc7fa9fba3fd5 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:11:13 -0500 Subject: [PATCH 59/61] qd dogfood: kTwoBitFacets derives from one kLegacyFacetMask addDefectFacetSchemeAliases restated the two-bit facet count as a bare 4 beside defectLegacySiteValue's local mask 3. Both now read one namespace constant. Byte-neutral. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/quality.h | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/quality.h b/src/quality.h index aba3c0aa5..687770b20 100644 --- a/src/quality.h +++ b/src/quality.h @@ -1390,20 +1390,22 @@ inline std::uint64_t defectSiteValue( defectshape::Facet f, std::string_view tex // defectRowKey of every row holding such a site: a released ack of a format-arity row stopped matching and the row gated // again. addDefectFacetSchemeAliases re-files such an ack to the current key; this is the old value it needs. A facet the // two-bit scheme never had (unchecked-status, unhandled-arm) has none (0). +// The two-bit scheme's facet mask: facets 0..kLegacyFacetMask (format-arity, utf8-cut, dedup-first, vacuous-assert) had a site value. +inline constexpr std::uint64_t kLegacyFacetMask = 3; + inline std::uint64_t defectLegacySiteValue( defectshape::Facet f, std::string_view text ) { - constexpr std::uint64_t kLegacyMask = 3; - if( static_cast<std::uint64_t>( f ) > kLegacyMask ) + if( static_cast<std::uint64_t>( f ) > kLegacyFacetMask ) { return 0; } std::string id( defectshape::facetName( f ) ); id.push_back( '\0' ); id.append( text ); - std::uint64_t h = fnv1a64( id ) & ~kLegacyMask; + std::uint64_t h = fnv1a64( id ) & ~kLegacyFacetMask; if( h == 0 ) { - h = kLegacyMask + 1; + h = kLegacyFacetMask + 1; } return h | static_cast<std::uint64_t>( f ); } @@ -9810,7 +9812,7 @@ inline void addDefectFacetSchemeAliases( IdentityAliases& al, const gtl::btree_m { return; } - constexpr std::size_t kTwoBitFacets = 4; // format-arity, utf8-cut, dedup-first, vacuous-assert + constexpr std::size_t kTwoBitFacets = kLegacyFacetMask + 1; // every facet the two-bit scheme had const std::vector<DefectSiteAt> sites = defectSitesOf( ing, root, nullptr ); // sorted by (anchor, site) for( auto it = sites.begin(); it != sites.end(); ) { From 6d040f3ccfc54812f80abdb9aadcba2e3db8f51e Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:13:02 -0500 Subject: [PATCH 60/61] qd dogfood: the skip trio's recursion bound is an ASSUME, not only a comment skipQuote and skipBrace lost their own nesting guards; they stay bounded only because every cycle of the trio passes through skipParen's NestLevel. UnguardedSkip counts their frames since the innermost NestLevel and ASSUMEs at most two (skipBrace -> skipQuote): a true invariant of the call graph, so a new call closing a cycle around skipParen fails the debug check. Byte-neutral. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- src/shstatus.h | 41 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/src/shstatus.h b/src/shstatus.h index 06296848e..c3e5702b8 100644 --- a/src/shstatus.h +++ b/src/shstatus.h @@ -24,6 +24,7 @@ // Regular expressions are spelled as small hand matchers (the binary links no regex engine for this); each names the // Python pattern it implements. +#include "infra/Diagnostics.h" // ASSUME — the skip trio's recursion bound (UnguardedSkip) #include "infra/namesplit.h" // isIdentChar / isIdentStart — the ONE ASCII identifier-character pair #include "infra/shellword.h" // trimView / shellIsRedirect — shared with darkflags.h #include "infra/sortutil.h" // sortUnique / svLess @@ -127,26 +128,33 @@ struct Tree inline constexpr int kMaxShellNest = 64; // shell nesting past this depth is cut and not judged; --quality-delta says shell_cut=N struct NestBudget { - int depth = 0; - bool cut = false; + int depth = 0; + int unguarded = 0; // skipQuote/skipBrace frames since the innermost NestLevel (UnguardedSkip) + bool cut = false; }; // One level of the budget for the scope of a recursion; `over` = the budget is spent (and the cut is recorded). class NestLevel { public: - explicit NestLevel( NestBudget& b ) noexcept : b_( b ) + explicit NestLevel( NestBudget& b ) noexcept : b_( b ), savedUnguarded_( b.unguarded ) { + b_.unguarded = 0; over_ = b_.depth >= kMaxShellNest; b_.cut = b_.cut || over_; // the disclosure: Tree::cut, then the answer's shell_cut= (quality.h defectSitesOf) ++b_.depth; } - ~NestLevel() { --b_.depth; } + ~NestLevel() + { + --b_.depth; + b_.unguarded = savedUnguarded_; + } NestLevel( const NestLevel& ) = delete; NestLevel& operator=( const NestLevel& ) = delete; bool over() const noexcept { return over_; } private: NestBudget& b_; + int savedUnguarded_; bool over_ = false; }; @@ -499,9 +507,31 @@ inline std::size_t pastBacktick( std::string_view s, std::size_t i ) noexcept return j == std::string_view::npos ? s.size() : j + 1; } +// skipQuote and skipBrace carry no budget guard of their own: they stay bounded only because every cycle of the skip trio +// passes through skipParen's NestLevel. skipBrace calls only skipQuote and skipQuote calls only skipParen, so at most +// kMaxUnguardedSkips of their frames ever sit above one NestLevel. A new call that closes a cycle around skipParen would +// recurse unbudgeted; this frame count is that invariant in code. +inline constexpr int kMaxUnguardedSkips = 2; // skipBrace -> skipQuote +class UnguardedSkip +{ +public: + explicit UnguardedSkip( NestBudget& b ) noexcept : b_( b ) + { + ++b_.unguarded; + ASSUME( b_.unguarded <= kMaxUnguardedSkips, "skipQuote/skipBrace recurse only through skipParen's budget guard" ); + } + ~UnguardedSkip() { --b_.unguarded; } + UnguardedSkip( const UnguardedSkip& ) = delete; + UnguardedSkip& operator=( const UnguardedSkip& ) = delete; + +private: + NestBudget& b_; +}; + std::size_t skipParen( std::string_view s, std::size_t i, NestBudget& nb ); inline std::size_t skipQuote( std::string_view s, std::size_t i, char q, NestBudget& nb ) // s[i] is the opening quote { + const UnguardedSkip frame( nb ); ++i; while( i < s.size() ) { @@ -529,7 +559,7 @@ inline std::size_t skipQuote( std::string_view s, std::size_t i, char q, NestBud } return i; } -// The one budget guard of the skip trio: skipQuote and skipBrace recurse only through skipParen, so each nesting level of +// The one budget guard of the skip trio: skipQuote and skipBrace recurse only through skipParen (UnguardedSkip), so each nesting level of // "$( … "$( … )" … )" or ${ … "$( … )" … } costs one level here. inline std::size_t skipParen( std::string_view s, std::size_t i, NestBudget& nb ) // s[i] == '(' { @@ -576,6 +606,7 @@ inline std::size_t skipParen( std::string_view s, std::size_t i, NestBudget& nb } inline std::size_t skipBrace( std::string_view s, std::size_t i, NestBudget& nb ) // s[i] == '{' of a ${...} { + const UnguardedSkip frame( nb ); int depth = 0; while( i < s.size() ) { From 5abe97ab2f057cab90d95e699bad2d568e65f89d Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:08:19 -0500 Subject: [PATCH 61/61] qd dogfood: UnguardedSkip follow-through: capdisclose row, LIMITS.md, harness links diagnostics.cpp CI on 6d040f3cc: kMaxUnguardedSkips had no capdisclose.map row (none: an ASSUME bound, not a cut), docs/LIMITS.md was stale (regenerated), and gateexitcheck (H4) compiled test/shstatus_harness.cpp without src/infra/diagnostics.cpp, which supplies ConsoleLog::handleAssert for shstatus.h's new ASSUME (linked as columnarcommacheck and clonepersistcheck link it). Answers byte-neutral. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- docs/LIMITS.md | 1 + test/capdisclose.map | 1 + test/gateexitcheck.sh | 5 ++++- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/LIMITS.md b/docs/LIMITS.md index d31a52332..1f5127e81 100644 --- a/docs/LIMITS.md +++ b/docs/LIMITS.md @@ -1551,6 +1551,7 @@ Discloses: **none** | constant | value | class | note | | --- | --- | --- | --- | | `kMaxShellNest` | `64` | — | shell nesting past this depth is cut and not judged; --quality-delta says shell_cut=N | +| `kMaxUnguardedSkips` | `2` | — | skipBrace -> skipQuote | ### `src/siblift.h` diff --git a/test/capdisclose.map b/test/capdisclose.map index ff38fd900..729508c37 100644 --- a/test/capdisclose.map +++ b/test/capdisclose.map @@ -194,6 +194,7 @@ kMaxRestUnits sink:noteCapped kMaxRoleBytes pending:B43 ingest extraction bound (LARGE-PARTIAL-1 widened the lint to ingest*.h); the sibling lane NO-SKIP-INGEST owns the ingest limits and audits it kMaxSkipRowsPerClass pending:B43 disclosed elsewhere: the --skipped rows and grep unindexed_candidates_capped= state the row cap kMaxTrackedFiles sink:truncated +kMaxUnguardedSkips none:an ASSUME bound on the shell skip trio's call graph (skipBrace -> skipQuote -> skipParen), not a cut: no frame past it is ever reached, and the nesting cut itself is kMaxShellNest's (shell_cut=) kMaxWorktreePaths sink:DISCLOSE kMaxYamlNestDepth pending:B43 ingest extraction bound (LARGE-PARTIAL-1 widened the lint to ingest*.h); the sibling lane NO-SKIP-INGEST owns the ingest limits and audits it kRadixThreshold none:an algorithm switch (radix vs comparison sort), the bytes are identical diff --git a/test/gateexitcheck.sh b/test/gateexitcheck.sh index 76aae6c33..aba159e98 100755 --- a/test/gateexitcheck.sh +++ b/test/gateexitcheck.sh @@ -744,7 +744,10 @@ SHHDIR="$( mktemp -d )" . "$ROOT/scripts/cxxstd.sh" SHCXX="${CXX:-c++}" if command -v "$SHCXX" >/dev/null 2>&1; then - if "$SHCXX" "$( ripwire_cxx_std_flag "$SHCXX" )" -O1 -I"$ROOT/src" "$ROOT/test/shstatus_harness.cpp" -o "$SHHDIR/shh" 2>"$SHHDIR/cc.log"; then + # diagnostics.cpp supplies Diagnostics::ConsoleLog::handleAssert for shstatus.h's ASSUME (UnguardedSkip): linked as every + # other standalone harness links it (columnarcommacheck, clonepersistcheck) + if "$SHCXX" "$( ripwire_cxx_std_flag "$SHCXX" )" -O1 -I"$ROOT/src" -I"$ROOT/src/infra" "$ROOT/test/shstatus_harness.cpp" \ + "$ROOT/src/infra/diagnostics.cpp" -o "$SHHDIR/shh" 2>"$SHHDIR/cc.log"; then SHH="$SHHDIR/shh" else no "(H4) test/shstatus_harness.cpp did not compile with $SHCXX: $( head -c 600 "$SHHDIR/cc.log" )"