From 1d63651506c039256af42c7a91143235dedcdda6 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:24:49 -0500 Subject: [PATCH 01/65] qd: call-sequence clone idiom (QD-FALSE-ROWS-E0) + stale_tree header (D3) A fifth closed clone idiom, call-sequence: a body made only of call statements, where the callees are the meaning. It reuses one-statement's narrowed shared-identifier test and the alpha-rename refusal, so call runs that share a callee or are parameter-renamed copies still gate. Removes the sortUnique | writeStream and sortUnique | infraSortSmall false rows (duplication + new-clone-of-reused-helper); every other census row unchanged. --quality-delta=A..B now says stale_tree="1" (attribute + one stderr note + legend clause) when the working tree is not the target commit's tree (dirty, or HEAD elsewhere). Never gating; answers outside qd byte-identical. Gates: cloneidiomcheck (P) arms + qd half, qdrefpaircheck (B2). Co-Authored-By: Claude Opus 5.5 --- changelog.d/qd-false-rows.md | 15 ++ skills/ripwire-fresh-eyes/SKILL.md | 4 +- src/cloneidiom.h | 162 +++++++++++++++++--- src/compactlegend.h | 5 +- src/verbs_quality.h | 65 ++++++-- src/verbs_report.h | 2 +- test/cloneidiomcheck.sh | 233 ++++++++++++++++++++++++++++- test/legend_over_target.tsv | 1 + test/qdrefpaircheck.sh | 40 ++++- 9 files changed, 481 insertions(+), 46 deletions(-) create mode 100644 changelog.d/qd-false-rows.md diff --git a/changelog.d/qd-false-rows.md b/changelog.d/qd-false-rows.md new file mode 100644 index 000000000..726d3ea51 --- /dev/null +++ b/changelog.d/qd-false-rows.md @@ -0,0 +1,15 @@ +### Changed — quality-delta: a run of calls that shares no callee is an idiom collision, not a copy; range answers say when the files on disk moved on + +Duplication rows gain a fifth recognized idiom, `call-sequence`: a body that is only call statements (no return, +declaration, assignment or control flow). Normalized, every such body reads `$I . $I ( … ) ;` repeated, so a +reused two-line helper (`sortUnique`: sort, then erase-unique) gated as a NEW clone of a four-call stream writer +and of a bench wrapper it has nothing in common with. A call-sequence group whose members share no callee or +other identifier (parameter names, `std::` chains and container words aside), sit in different files or scopes, +are under 80 tokens and are not one body with renamed parameters is now reported `sev="minor"` with +`idiom="call-sequence"` instead of gating. A shared callee, one namespace, or a parameter-only rename keeps it +gating. On this repo, tmux and hono the rule demotes no existing clone group; `test/cloneidiomcheck.sh` arm (P) +pins both directions. + +`--quality-delta=A..B` now carries `stale_tree="1"` (and a one-line stderr note) when the working tree is not B's +tree — uncommitted edits, untracked files, or HEAD on another commit — so a green range answer is not read as a +pass for the files on disk. Never gating; `test/qdrefpaircheck.sh` arm (B2). diff --git a/skills/ripwire-fresh-eyes/SKILL.md b/skills/ripwire-fresh-eyes/SKILL.md index 93916d45f..8958e7bde 100644 --- a/skills/ripwire-fresh-eyes/SKILL.md +++ b/skills/ripwire-fresh-eyes/SKILL.md @@ -190,11 +190,11 @@ sections your question needs. check `type=` before assuming two members are byte-identical. Larger `tokens=` = more dedup value; a fix to one likely belongs in all. **Rule of Three:** extract on the *third* occurrence, not the second — a little duplication beats the *wrong* abstraction. - A group carrying `idiom="…"` (`threshold-ladder`, `switch-name-table`, `builder-chain`, `one-statement`) + A group carrying `idiom="…"` (`threshold-ladder`, `switch-name-table`, `builder-chain`, `one-statement`, `call-sequence`) plus `demoted="1"` is one the detector judged an IDIOM COLLISION, not shared logic: same shape, no shared domain identifiers, different scopes — five unrelated bucketing ladders in five subsystems match each other's token stream and consolidating them would be the wrong abstraction. For `one-statement` (a body - of one `return`), parameter names, `std::` names and container words like `find`/`size` do not count as + of one `return`) and `call-sequence` (a body of calls only, where the callees are the meaning), parameter names, `std::` names and container words like `find`/`size` do not count as shared, and a copy that only renamed its parameters never demotes. Demoted groups still print and still count; they stop *gating*. The idiom is named precisely so you can overrule it by reading the bodies — treat it as the tool showing its work, not as a row it decided for you. diff --git a/src/cloneidiom.h b/src/cloneidiom.h index bf2fca2fe..01b0adf40 100644 --- a/src/cloneidiom.h +++ b/src/cloneidiom.h @@ -10,12 +10,13 @@ // spell "bucket a scalar", not because anybody copied anybody. Every one of the five needed a reasoned // ack, twice. // -// WHAT THIS ADDS. A CLOSED set of four recognized idioms — and closed means closed; each one past the +// WHAT THIS ADDS. A CLOSED set of five recognized idioms — and closed means closed; each one past the // first three is a decision, not a patch: // threshold-ladder a chain of `if( x < C ) return K` and nothing else // switch-name-table a `switch` whose every arm is a label plus a literal return // builder-chain a param-struct initializer chain: declare, assign every field, return // one-statement the body is ONE `return ;` (leading contract asserts aside) — DECISION C3 +// call-sequence the body is a straight run of call statements and nothing else — QD-FALSE-ROWS-E0 // A clone group whose members ALL classify to the SAME idiom is annotated with that idiom's name. It is // additionally DEMOTED — reported, but no longer gating — only when the whole conjunction holds: // (1) every member classifies to the same recognized idiom, AND @@ -48,6 +49,23 @@ // is the safe side of condition (2), but the alpha-rename refusal then cannot see a parameter-only rename, // so the reader finds the list after a generic signature's type parameters as well (idiomParamListOpen). // +// THE FIFTH IDIOM, call-sequence (QD-FALSE-ROWS-E0, 2026-11-19). A two-line helper promoted for reuse, +// std::sort( values.begin(), values.end(), less ); values.erase( std::unique( … ), values.end() ); +// gated as a NEW duplicate of a stream writer it has nothing to do with, +// o.u64( rowCount ); o.vec( chunkAt ); o.u64( bytes.size() ); o.put( bytes.data(), bytes.size() ); +// at 51 tokens and 0.80 similarity, and again of a bench wrapper (`scratch.resize( … ); radix::sortKeySmall( … );`): +// normalized, every body that only calls things is `$I . $I ( … ) ;` repeated, so any two short ones collide. Here +// the CALLEES are the whole meaning of the body, and two such bodies that call nothing in common are not one +// body twice. The shape: every top-level statement is ONE call expression — a name, reached through `.`, `->` +// or `::`, called (and possibly called again on its result) — ending in `;`; its arguments may hold anything +// bracketed, a lambda included. No `return`, no declaration (two adjacent names), no assignment, no keyword, no +// subscript or template argument at the top level. Condition (2) reads the SAME narrowed identifier set as +// one-statement (parameters, `std::` chains and the container stop words left out), and the same alpha-rename +// refusal holds: a call run that differs from another only in its parameter names is a copy. Shared callees +// (`u64`, `erase`, an in-repo helper) and shared members stay in the set, so a real copy of a call run, which +// keeps its callees, still gates; (3) and (4) are unchanged. A run that calls a reused helper is not a clone of +// that helper, and this is the shape in which that reads as one. +// // ON (4), AND WHY IT IS A CEILING RATHER THAN A DROP. The design note that prompted this asked for a // "higher token floor (e.g. 2x the normal one) before it can group at all". Implemented literally that // DELETES rows — a 47-token ladder pair would simply stop being reported — and the house rule is demotion, @@ -64,6 +82,8 @@ // * `builder-chain` covers the param-STRUCT spelling (`p.field = v;` repeated). The fluent // `Builder().withX().withY().build()` spelling is deliberately NOT modelled — it is one statement with // call parens in it, which every classifier here refuses on purpose. +// * `call-sequence` needs braces and a `;` after every statement: a Go or Python body (no `;`) and a Rust +// macro call (`name!( … )`) are not modelled. // * `one-statement` needs a literal `return`: a Rust/Kotlin expression body (`{ a == b }`, `= a == b`) is // not modelled, and a Python body is read as the same token stream (a leading `:` refuses). // * Condition (2) is literal token equality, so ONE coincidental word in common (two unrelated enums that @@ -90,14 +110,20 @@ namespace rw // The closed set. Row order IS the enum's declaration order and the static_assert is what makes reordering // the enum a compile error rather than a silent re-labelling of every emitted row. -enum class CloneIdiom : std::uint8_t { None = 0, ThresholdLadder = 1, SwitchNameTable = 2, BuilderChain = 3, OneStatement = 4 }; +enum class CloneIdiom : std::uint8_t { None = 0, ThresholdLadder = 1, SwitchNameTable = 2, BuilderChain = 3, OneStatement = 4, CallSequence = 5 }; -inline constexpr std::string_view kCloneIdiomNames[] = { "", "threshold-ladder", "switch-name-table", "builder-chain", "one-statement" }; -static_assert( std::size( kCloneIdiomNames ) == std::size_t( CloneIdiom::OneStatement ) + 1, +inline constexpr std::string_view kCloneIdiomNames[] = { "", "threshold-ladder", "switch-name-table", "builder-chain", "one-statement", "call-sequence" }; +static_assert( std::size( kCloneIdiomNames ) == std::size_t( CloneIdiom::CallSequence ) + 1, "kCloneIdiomNames must carry exactly one row per CloneIdiom, in declaration order" ); inline std::string_view cloneIdiomName( CloneIdiom k ) noexcept { return kCloneIdiomNames[ std::size_t( k ) ]; } +// The idioms whose condition (2) reads the NARROWED identifier set and carries the alpha-rename refusal (see the +// header): the short shapes whose only common words are often parameter names and standard-library vocabulary. +// A bit per idiom, the shape CONTRIBUTING.md asks of an "is this one of N constants" test (clones.h's langBit). +inline constexpr std::uint32_t kIdiomNarrowVocabularyMask = ( 1u << std::uint32_t( CloneIdiom::OneStatement ) ) | ( 1u << std::uint32_t( CloneIdiom::CallSequence ) ); +inline constexpr bool idiomReadsNarrowVocabulary( CloneIdiom k ) noexcept { return ( ( kIdiomNarrowVocabularyMask >> std::uint32_t( k ) ) & 1u ) != 0; } + // The demotion CEILING — see the "ON (4)" note above. 2x the 40-token default floor of the clones verb. constexpr std::uint32_t kIdiomCloneTokenFloor = 80; @@ -543,16 +569,12 @@ inline int idiomBracketStep( std::string_view w ) noexcept } } -// `MACRO ( ) ;?` for a kIdiomContractMacros name. Advances past it on a match. -inline bool idiomEatContract( const std::vector& t, std::size_t& i, std::size_t end ) +// The index of the bracket that closes the one opened at t[open], searched before `end`; `end` when it does not close +// there. Bracket kinds are not matched against each other: a body the scanner read is balanced or is not this shape. +inline std::size_t idiomCloseOf( const std::vector& t, std::size_t open, std::size_t end ) noexcept { - if( i + 1 >= end || t[i + 1].text != "(" - || std::find( std::begin( kIdiomContractMacros ), std::end( kIdiomContractMacros ), t[i].text ) == std::end( kIdiomContractMacros ) ) - { - return false; - } - std::size_t j = i + 1, depth = 0; - for( ; j < end; ++j ) + std::size_t depth = 0; + for( std::size_t j = open; j < end; ++j ) { const int step = idiomBracketStep( t[j].text ); if( step > 0 ) @@ -561,9 +583,29 @@ inline bool idiomEatContract( const std::vector& t, std::size_t& i, st } else if( step < 0 && --depth == 0 ) { - break; + return j; } } + return end; +} + +// The member-access spellings: a name after one of these is a MEMBER (oneStatementFacts) or the next link of a call +// chain (idiomEatCallStatement). A table, for the same reason as kIdiomRelOps. +inline constexpr std::string_view kIdiomAccessOps[] = { ".", "->", "::" }; +inline bool idiomIsAccessOp( std::string_view w ) noexcept +{ + return std::find( std::begin( kIdiomAccessOps ), std::end( kIdiomAccessOps ), w ) != std::end( kIdiomAccessOps ); +} + +// `MACRO ( ) ;?` for a kIdiomContractMacros name. Advances past it on a match. +inline bool idiomEatContract( const std::vector& t, std::size_t& i, std::size_t end ) +{ + if( i + 1 >= end || t[i + 1].text != "(" + || std::find( std::begin( kIdiomContractMacros ), std::end( kIdiomContractMacros ), t[i].text ) == std::end( kIdiomContractMacros ) ) + { + return false; + } + std::size_t j = idiomCloseOf( t, i + 1, end ); if( j >= end ) { return false; // unbalanced: not a contract statement this grammar can bound @@ -624,6 +666,72 @@ inline CloneIdiom classifyOneStatement( const std::vector& t ) return ( depth == 0 && taken >= 1 ) ? CloneIdiom::OneStatement : CloneIdiom::None; // a `;`-less language } +// ── idiom 5, call-sequence (QD-FALSE-ROWS-E0; see the header) ───────────────────────────────────────── + +// One ` ;` statement starting at t[i], before `end`: a name, then any run of `.`/`->`/`::` + name and of +// balanced `( … )` groups, ending in a call and a `;`. Advances past the `;` on a match. The state is whether a +// name is due and whether the last thing was a call, so `a b` (a declaration), `a = …`, `a[ i ]`, `a< T >`, a +// keyword and a bare name all fall to the catch-all refusal. +inline bool idiomEatCallStatement( const std::vector& t, std::size_t& i, std::size_t end ) +{ + bool nameDue = true, endsInCall = false; + for( std::size_t k = i; k < end; ++k ) + { + const std::string_view w = t[k].text; + if( nameDue ) + { + if( t[k].kind != CodeTokenKind::Identifier ) + { + return false; + } + nameDue = false; + endsInCall = false; + } + else if( w == "(" ) + { + k = idiomCloseOf( t, k, end ); // the arguments: anything bracketed, a lambda included + endsInCall = k < end; + } + else if( w == ";" && endsInCall ) + { + i = k + 1; + return true; + } + else if( idiomIsAccessOp( w ) ) + { + nameDue = true; + } + else + { + return false; + } + } + return false; // unbalanced, or the body ended before the statement's `;` +} + +// The body is `{ ; [ ; ]* }` and nothing else. +inline CloneIdiom classifyCallSequence( const std::vector& t ) +{ + if( t.size() < 2 || t.front().text != "{" || t.back().text != "}" ) + { + return CloneIdiom::None; + } + const std::size_t end = t.size() - 1; + std::size_t i = 1; + if( i >= end ) + { + return CloneIdiom::None; // an empty body calls nothing + } + while( i < end ) + { + if( !idiomEatCallStatement( t, i, end ) ) + { + return CloneIdiom::None; + } + } + return CloneIdiom::CallSequence; +} + // One type-parameter group opened at sig[open] — `` (TypeScript, Rust, Java, C#, Swift, // Kotlin) or `[T any]` (Go) — skipped: the index just past its close, or sig.size() when it never closes // before a body or statement starts. @@ -822,7 +930,7 @@ inline std::vector idiomParamNames( const std::vector& body, c const std::string_view w = body[k].text; // A name after `.`/`->`/`::` is a MEMBER, never the parameter it happens to be spelled like (`vf.prefix` // beside a parameter `prefix`): it stays in the set and is not renamed. - const bool afterAccess = k > 0 && ( body[k - 1].text == "." || body[k - 1].text == "->" || body[k - 1].text == "::" ); + const bool afterAccess = k > 0 && idiomIsAccessOp( body[k - 1].text ); const auto param = afterAccess ? params.end() : std::find( params.begin(), params.end(), w ); if( body[k].kind == CodeTokenKind::Identifier && param != params.end() ) { @@ -881,10 +989,11 @@ inline OneStatementFacts oneStatementFacts( const std::vector& body, c return f; } -// The one entry point: the first grammar that accepts wins, and the four are mutually exclusive by +// The one entry point: the first grammar that accepts wins, and the five are mutually exclusive by // construction (a ladder has no `switch` and at least two `if`s, a table's first token IS `switch`, a -// builder has no control flow and at least three statements, a one-statement body starts with `return` -// and holds no second statement), so the order is not load-bearing. +// builder has no control flow and at least three field assignments, a one-statement body starts with `return` +// and holds no second statement, a call-sequence holds no `return`, `=` or keyword at the top level), so the +// order is not load-bearing. inline CloneIdiom classifyCloneIdiom( const std::vector& t ) { const CloneIdiom ladder = classifyThresholdLadder( t ); @@ -902,7 +1011,12 @@ inline CloneIdiom classifyCloneIdiom( const std::vector& t ) { return builder; } - return classifyOneStatement( t ); + const CloneIdiom oneStatement = classifyOneStatement( t ); + if( oneStatement != CloneIdiom::None ) + { + return oneStatement; + } + return classifyCallSequence( t ); } // ── group verdicts ──────────────────────────────────────────────────────────────────────────────────── @@ -922,8 +1036,8 @@ namespace cloneidiomdetail struct MemberShape { CloneIdiom idiom = CloneIdiom::None; - std::vector ids; // sorted + unique FNV-1a of every non-keyword identifier in the body (one-statement: the narrowed set) - std::uint64_t alpha = 0; // one-statement only: the parameter-renamed body hash (OneStatementFacts::alpha) + std::vector ids; // sorted + unique FNV-1a of every non-keyword identifier in the body (one-statement, call-sequence: the narrowed set) + std::uint64_t alpha = 0; // one-statement and call-sequence only: the parameter-renamed body hash (OneStatementFacts::alpha) std::uint32_t fileId = 0; std::string scope; }; @@ -1010,7 +1124,7 @@ inline std::vector classifyCloneGroupIdioms( const IngestResu { continue; } - if( shapes[k].idiom == CloneIdiom::OneStatement ) + if( idiomReadsNarrowVocabulary( shapes[k].idiom ) ) { std::vector sig; if( s.sigStartByte < s.sigEndByte ) @@ -1087,7 +1201,7 @@ inline std::vector classifyCloneGroupIdioms( const IngestResu { demote = false; } - else if( idiom == CloneIdiom::OneStatement && ms[a]->alpha == ms[b]->alpha ) + else if( idiomReadsNarrowVocabulary( idiom ) && ms[a]->alpha == ms[b]->alpha ) { demote = false; // a Type-1 copy after renaming parameters — a copy whatever its vocabulary } diff --git a/src/compactlegend.h b/src/compactlegend.h index c4cd56fe1..ed7846241 100644 --- a/src/compactlegend.h +++ b/src/compactlegend.h @@ -1832,8 +1832,8 @@ inline constexpr CompactCompletenessTerm kCompactAttributeReadings[] = { "layer", "layer=: built-in arch layer (game|infra|render|math|audio|ai|test) from a dir name in p=; absent if none", true, "d", MapHeaderRead::No, {}, "pack-task" }, // clones: src/verbs_report.h emitClonesReport (groupExemptKind, cloneIdiomAttrs) { "exempt", "group exempt=fixture|shell-runner: every member is on such a path; quality-delta duplication ignores it", true, "group", MapHeaderRead::No, {}, "clones" }, - { "idiom", "group idiom=: the recognized shape every member spells: threshold-ladder, switch-name-table, builder-chain, one-statement", true, "group", MapHeaderRead::No, {}, "clones" }, - { "demoted", "group demoted=1: idiom collision (no shared identifier or context, under 80 tokens, where one-statement leaves out parameter names, std:: chains and container words and never demotes a parameter-renamed copy); quality-delta: minor", true, "group", MapHeaderRead::No, {}, "clones" }, + { "idiom", "group idiom=: the recognized shape every member spells: threshold-ladder, switch-name-table, builder-chain, one-statement, call-sequence", true, "group", MapHeaderRead::No, {}, "clones" }, + { "demoted", "group demoted=1: idiom collision (no shared identifier or context, under 80 tokens, where one-statement and call-sequence leave out parameter names, std:: chains and container words and never demote a parameter-renamed copy); quality-delta: minor", true, "group", MapHeaderRead::No, {}, "clones" }, // quality-delta: src/verbs_quality.h (range attrs, duplication r row); staleAcksXml in src/quality.h { "key", "sa key=/why=: the stale ack's ledger hash / target-gone (names nothing now) or finding-gone (no longer fires)", true, "sa", MapHeaderRead::No, {}, "quality-delta" }, // also defines why= { "members", "r members=/tokens=: a duplication row's clone group (member ids) / their shared normalized-token count", true, "r", MapHeaderRead::No, {}, "quality-delta" }, // also defines tokens= @@ -1842,6 +1842,7 @@ inline constexpr CompactCompletenessTerm kCompactAttributeReadings[] = { "head_basis", "head_basis=identity: the floor is this tree's own snapshot; archived-index-hidden: refused, a tracked path is skip-worktree/assume-unchanged; absent: the archived HEAD tree", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, { "base_ref", "base_ref=/target_ref=: the two resolved full shas a range compared (committed trees; at= omitted)", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, // also defines target_ref= { "churn", "churn=unavailable: range form; short-horizon-churn cannot be measured, so its silence is not no churn", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, + { "stale_tree", "stale_tree=1: the working tree is not target_ref's tree (uncommitted edits or HEAD elsewhere): this answers for target_ref, not the files on disk; never gating", false, "quality-delta", MapHeaderRead::No, {}, "quality-delta" }, // from-trace: src/tracelocus.h (frame and skipped rows) { "line", "skipped line=: that frame's line; p= is its path, outside every root, so never ranked", true, "skipped", MapHeaderRead::No, {}, "from-trace" }, { "line_encloses", "frame line_encloses=: the other def today's line sits in; STALE trace, the name binding was kept", true, "frame", MapHeaderRead::No, {}, "from-trace" }, diff --git a/src/verbs_quality.h b/src/verbs_quality.h index 116c1429e..f601b4993 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -90,6 +90,7 @@ struct RefPairDelta rw::quality::RefTree targetTree; rw::quality::Snapshot baseSnapshot; // the floor: computeSnapshot over the base tree, which is gone bool sameRef = false; + bool staleTree = false; // D3 QD-STALE-HEADER: the working tree is not target_ref's tree (rangeTreeIsStale) std::string attrs; // XML: ` base_ref="…" target_ref="…" churn="unavailable"` std::string jsonAttrs; // JSON: the SAME three facts — built beside attrs so the // two emitters cannot disclose different things @@ -940,6 +941,22 @@ void releaseFullTrees( RefPairDelta& out ) std::swap( dropped.p, out.targetGuard.p ); // its destructor removes the cut tree's temp dir now } +// D3 QD-STALE-HEADER — a range answer judges target_ref's COMMITTED tree, while a reader acts on the files in front of +// it: a check run before the last edit (or before a commit moved HEAD) cannot pass for the current tree, and nothing +// in the document said which one it was. True when HEAD's tree is not target_ref's tree, or the working tree has +// tracked changes or untracked files (the porcelain listing gitstamp's +dirty reads). False when git cannot say: +// the attribute is a disclosure that may only appear on evidence, never a guess. Two git subprocesses per range call. +inline bool rangeTreeIsStale( const std::string& root, const std::string& targetSha ) +{ + const std::string headTree = rw::quality::gitOneLine( root, "rev-parse --verify --quiet HEAD^{tree} 2>/dev/null" ); + const std::string targetTree = rw::quality::gitOneLine( root, "rev-parse --verify --quiet " + targetSha + "^{tree} 2>/dev/null" ); + if( headTree.empty() || targetTree.empty() ) + { + return false; + } + return headTree != targetTree || !rw::quality::gitOneLine( root, "status --porcelain --ignore-submodules=dirty 2>/dev/null" ).empty(); +} + // Resolve the spec and materialize both sides. Returns an EXIT CODE on any refusal or environment failure // (already reported on stderr), or nullopt when `out` is ready to compare. Splitting user error from // environment failure is the same line --dmm's handler draws: a revision that does not resolve is a typo the @@ -1017,6 +1034,16 @@ std::optional loadRefPairDelta( const std::string& root, std::string_view s // reasoning gitstamp::atAttr states for its own hex value. out.attrs = " base_ref=\"" + ref.baseSha + "\" target_ref=\"" + ref.targetSha + "\" churn=\"unavailable\""; out.jsonAttrs = ",\"base_ref\":\"" + ref.baseSha + "\",\"target_ref\":\"" + ref.targetSha + "\",\"churn\":\"unavailable\""; + // D3: present only when true (absent means the working tree IS target_ref's tree, or git could not say); the base + // child's document is never the answer, so it asks git nothing. + out.staleTree = !role.child && rangeTreeIsStale( root, ref.targetSha ); + if( out.staleTree ) + { + out.attrs += " stale_tree=\"1\""; + out.jsonAttrs += ",\"stale_tree\":1"; + rw::emitRaw( stderr, "ripwire: --quality-delta: stale_tree=1 - the working tree is not the target commit's tree (uncommitted edits, or " + "HEAD is elsewhere), so this answer is about the target commit, not the files on disk\n" ); + } // R1: the same two resolved shas as a range, for the rename record. Empty when the target IS the working // tree — `A..` is not a range git will walk, and the working-tree form's own uncommitted+window query is // the right scope there anyway. @@ -1531,6 +1558,11 @@ inline constexpr const char* kQdBaseRefPair = "that one kind, short-horizon-churn, cannot be measured at all in that form: it needs git " "history at the tree being judged, and both trees are materialized OUT of the repo into temp dirs. Its " "silence in such a report is not evidence that nothing churned. "; +// D3 QD-STALE-HEADER — emitted ONLY when stale_tree= is on the root (a range answer whose target is not the tree on disk). +inline constexpr const char* kQdStaleTreeLegend = + "stale_tree=\"1\" means the working tree is NOT target_ref's tree: it has uncommitted edits or untracked files, or HEAD " + "is another commit. This answer is about target_ref as committed, so a clean result here does not pass the files on " + "disk; commit and re-run, or run the bare form on the working tree. Never gating. "; // #228 — emitted only when head_basis= is on the root, i.e. only when the identity basis produced the floor. // The attribute exists because a zero from a self-comparison and a zero from an archived comparison are // DIFFERENT CLAIMS, and the honesty rule is that a zero means "none found", never "none exists". Its absence @@ -1676,23 +1708,24 @@ inline constexpr const char* kQdMonsterLegend = inline constexpr const char* kQdCloneLegend = "CLONE ROWS name the whole group rather than one symbol: members= is the member list and tokens= its " "shared normalized-token count (the same per-group pair the clones verb reports). idiom= names a " - "RECOGNIZED BODY SHAPE every member spells, out of a closed set of four (threshold-ladder, " - "switch-name-table, builder-chain, one-statement). idiom= alone changes nothing; a group that ALSO shares no " + "RECOGNIZED BODY SHAPE every member spells, from a closed set of five (threshold-ladder, " + "switch-name-table, builder-chain, one-statement, call-sequence). idiom= alone changes nothing; a group that ALSO shares no " "non-keyword identifier between any two members, sits in pairwise-distinct enclosing contexts, and " "stays under 80 normalized tokens is an idiom COLLISION rather than a copy, and is reported minor " "instead of gating. Break any one of those and it gates as before, idiom= and all: two bucketing " "ladders over the SAME enum are a copy. The shape is read off the body's token stream and not a parse " "tree, so a macro-assembled body classifies as whatever its raw tokens spell — the name is printed so " - "the call can be overruled by reading. "; + "a reader can overrule it. "; -// The one-statement half of the clone paragraph, printed only when a row carries idiom="one-statement": its -// narrowed shared-identifier test is the one rule a reader of THAT row needs, and a ladder-only document -// should not pay for it (the same G4 rule as every conditional section here). +// The one-statement / call-sequence half of the clone paragraph, printed only when a row carries one of those two +// idioms: their narrowed shared-identifier test is the one rule a reader of THAT row needs, and a ladder-only +// document should not pay for it (the same G4 rule as every conditional section here). inline constexpr const char* kQdOneStatementLegend = "one-statement is a body of one return statement (leading EXPECTS/ASSUME/DASSERT/VALIDATE asserts aside); " - "its shared-identifier test leaves out each member's own parameter names, every std:: chain and standard " - "container/string words (size, find, npos, first, second and the like), and a pair identical once its " - "parameters are renamed always gates. "; + "call-sequence is a body of call statements only (no return, declaration, assignment or control flow), where the " + "callees are the meaning; for both, the shared-identifier test leaves out each member's own parameter names, " + "every std:: chain and standard container/string words (size, find, npos, first, second and the like), and a " + "pair identical once its parameters are renamed always gates. "; // P1 — the SCOPE half of the quality-delta legend, printed ONLY when the report actually contains a // scope partition or a foreign-ack row. That is a G4 (token density) decision, not a hedge: the @@ -1761,6 +1794,7 @@ struct QualityDeltaLegendParts bool memorySkippedShare = false; // ... memory_skipped= (skipped_why="selector,memory") bool historyUnread = false; // hwh-fix4 (N1): unread_history= is on the root bool anyRustTestExcluded = false; // issue #499: the excluded set holds Rust test functions + bool staleTree = false; // D3 QD-STALE-HEADER: stale_tree= is on the root }; // qd-memory-degrade — present-only: each rides only with the attributes it defines. No double dash anywhere in them @@ -1818,9 +1852,10 @@ inline void emitQualityDeltaLegend( const QualityDeltaLegendParts& p, std::FILE* } return false; }; - const auto anyOneStatementRow = [] ( const std::vector& v ) + const auto anyNarrowIdiomRow = [] ( const std::vector& v ) { - return std::any_of( v.begin(), v.end(), []( const rw::quality::Regression& r ) { return r.facet == rw::cloneIdiomName( rw::CloneIdiom::OneStatement ); } ); + return std::any_of( v.begin(), v.end(), []( const rw::quality::Regression& r ) + { return r.facet == rw::cloneIdiomName( rw::CloneIdiom::OneStatement ) || r.facet == rw::cloneIdiomName( rw::CloneIdiom::CallSequence ); } ); }; const auto anyMinorMaskRow = [] ( const std::vector& v ) { @@ -1856,6 +1891,10 @@ inline void emitQualityDeltaLegend( const QualityDeltaLegendParts& p, std::FILE* else if( p.marker == "git-HEAD (symlinked sidecar refused)" ) { std::fputs( kQdBaseHeadSymlinkRefused, out ); } else if( p.marker == "git-HEAD (foreign sidecar ignored)" ) { std::fputs( kQdBaseHeadForeign, out ); } else { std::fputs( kQdBaseHead, out ); } + if( p.staleTree ) + { + std::fputs( kQdStaleTreeLegend, out ); // D3 — the attribute that says the answer is not about the files on disk + } if( p.baselineAbsorbed > 0 ) { std::fputs( kQdBaselineAbsorbedLegend, out ); // H11 — the attribute that re-reads the exit code @@ -1938,7 +1977,7 @@ inline void emitQualityDeltaLegend( const QualityDeltaLegendParts& p, std::FILE* if( anyCloneRow( p.rows ) || anyCloneRow( p.disclosedRows ) ) { std::fputs( kQdCloneLegend, out ); - if( anyOneStatementRow( p.rows ) || anyOneStatementRow( p.disclosedRows ) ) + if( anyNarrowIdiomRow( p.rows ) || anyNarrowIdiomRow( p.disclosedRows ) ) { std::fputs( kQdOneStatementLegend, out ); } @@ -3064,7 +3103,7 @@ std::optional runQualityDelta( const MainDispatch& d ) 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 }, out ); + basis.rustTestExcluded, refs.staleTree }, 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; diff --git a/src/verbs_report.h b/src/verbs_report.h index 87b2eb614..716569431 100644 --- a/src/verbs_report.h +++ b/src/verbs_report.h @@ -1051,7 +1051,7 @@ int emitClonesReport( const rw::Config& cfg, const rw::IngestResult& ing ) // a paging artefact, not a measurement. const CloneGrouping grouping = groupClones( ing, cg, cg3 ); - rw::emitTo( stdout, "{}", rw::rootRelPathsLegend( clnSingleRoot ) ); + rw::emitTo( stdout, "{}", rw::rootRelPathsLegend( clnSingleRoot ) ); rw::emitTo( stdout, "", cg.size(), cg3.size(), // M2: pageDisclosure's paging half (which spells total= itself) now also rides on a CUT bare run, diff --git a/test/cloneidiomcheck.sh b/test/cloneidiomcheck.sh index df86c1923..d07345a5f 100755 --- a/test/cloneidiomcheck.sh +++ b/test/cloneidiomcheck.sh @@ -39,6 +39,12 @@ # group carries no idiom); a pair identical once its parameters are renamed gates although it shares # no other identifier at all, also when its signature is generic (`name(…)`, `name[T any](…)`) or one default holds a template comma or a less-than; a pair sharing a MEMBER spelled like a parameter gates. The quality-delta half: the demoted pair is minor, the shared-constant # pair gates. The real-history replays live in test/dupshortcheck.sh. +# (P) THE FIFTH IDIOM, call-sequence (QD-FALSE-ROWS-E0): the reused sortUnique helper and a four-call stream +# writer — two call runs with no callee in common, the shape that gated a sort-unique lane twice — +# demote; the writer beside a twin that calls the SAME writer methods gates; the first pair in one file and +# one namespace gates; a std-only run identical once its parameter is renamed gates; a twin whose last +# statement is an assignment carries no idiom at all. The quality-delta half: the demoted pair is minor and +# not gating, its document defines call-sequence, and the shared-callee pair still gates. # # Usage: bash test/cloneidiomcheck.sh | RIPWIRE_BIN=asan/ripwire bash test/cloneidiomcheck.sh # Exits non-zero on any failure; prints PASS/FAIL per check and ALL PASS on success. @@ -63,6 +69,200 @@ command -v git >/dev/null 2>&1 || { echo "git required"; exit 2; } CORPUS="$TMP/corpus"; mkdir -p "$CORPUS" cp -R "$FIX/." "$CORPUS/" +# (P) THE CALL-SEQUENCE FIXTURES ARE WRITTEN HERE, NOT COMMITTED under test/cloneidiomfix: they copy real call runs +# (warmsnap writeStream, the sortUnique helper) on purpose, and a committed copy would sit in the repo as a NEW clone of +# src/ code that this repo's own quality-delta reports beside every change (a mixed src/fixture group is not exempt). +mkfix(){ mkdir -p "$CORPUS/$1"; cat >"$CORPUS/$1/$2"; } +mkfix callseq_demote frame.h <<'FIXEOF' +#pragma once +// call-sequence fixture: a row stream's frame writer, four calls on one writer. Normalized it is `$I . $I ( … ) ;` +// four times, which is all sortutil.h's helper is too. +#include +#include +#include +namespace frame +{ +struct Out +{ + void u64( std::uint64_t ) {} + void vec( const std::vector& ) {} + void put( const char*, std::size_t ) {} +}; +inline void writeStream( Out& o, std::size_t rowCount, const std::vector& chunkAt, const std::string& bytes ) +{ + o.u64( rowCount ); + o.vec( chunkAt ); + o.u64( bytes.size() ); + o.put( bytes.data(), bytes.size() ); +} +} +FIXEOF +mkfix callseq_demote sortutil.h <<'FIXEOF' +#pragma once +// call-sequence fixture (QD-FALSE-ROWS-E0): the reused sort-then-unique helper. Its body only CALLS things, and +// nothing it calls (sort, erase, unique) is called by frame.h's stream writer: two call runs, no shared callee. +#include +#include +namespace sortutil +{ +template< class Container, class Less = std::less<> > +inline void sortUnique( Container& values, Less less = {} ) +{ + std::sort( values.begin(), values.end(), less ); + values.erase( std::unique( values.begin(), values.end() ), values.end() ); +} +} +FIXEOF +mkfix callseq_sharedcallee frame.h <<'FIXEOF' +#pragma once +// call-sequence fixture: the stream writer again. Its twin (header.h) calls the SAME writer methods (u64, put): +// that is a copy of the framing, so the pair classifies but must keep gating. +#include +#include +#include +namespace frame +{ +struct Out +{ + void u64( std::uint64_t ) {} + void vec( const std::vector& ) {} + void put( const char*, std::size_t ) {} +}; +inline void writeStream( Out& o, std::size_t rowCount, const std::vector& chunkAt, const std::string& bytes ) +{ + o.u64( rowCount ); + o.vec( chunkAt ); + o.u64( bytes.size() ); + o.put( bytes.data(), bytes.size() ); +} +} +FIXEOF +mkfix callseq_sharedcallee header.h <<'FIXEOF' +#pragma once +#include "frame.h" +namespace header +{ +inline void writeHeader( frame::Out& w, std::size_t version, const std::vector& offsets, const std::string& name ) +{ + w.u64( version ); + w.vec( offsets ); + w.u64( name.size() ); + w.put( name.data(), name.size() ); +} +} +FIXEOF +mkfix callseq_samefile pair.h <<'FIXEOF' +#pragma once +// call-sequence fixture: two call runs that share no callee, but in ONE file and ONE namespace — copy-paste next +// door is copy-paste, so the pair classifies and keeps gating. +#include +#include +#include +#include +#include +namespace near +{ +struct Out +{ + void u64( std::uint64_t ) {} + void vec( const std::vector& ) {} + void put( const char*, std::size_t ) {} +}; +template< class Container, class Less = std::less<> > +inline void sortUnique( Container& values, Less less = {} ) +{ + std::sort( values.begin(), values.end(), less ); + values.erase( std::unique( values.begin(), values.end() ), values.end() ); +} +inline void writeStream( Out& o, std::size_t rowCount, const std::vector& chunkAt, const std::string& bytes ) +{ + o.u64( rowCount ); + o.vec( chunkAt ); + o.u64( bytes.size() ); + o.put( bytes.data(), bytes.size() ); +} +} +FIXEOF +mkfix callseq_alpha order.h <<'FIXEOF' +#pragma once +// call-sequence fixture: a call run over standard vocabulary only. Its twin (rank.h) is the same body with the +// parameter renamed — no identifier is left to share once parameters and std:: chains are set aside, so only the +// alpha-rename refusal can say it is a copy, and it must. +#include +#include +namespace order +{ +inline void sortDescending( std::vector& values ) +{ + std::sort( values.begin(), values.end() ); + std::reverse( values.begin(), values.end() ); + std::rotate( values.begin(), values.begin(), values.end() ); +} +} +FIXEOF +mkfix callseq_alpha rank.h <<'FIXEOF' +#pragma once +#include +#include +namespace rank +{ +inline void rankHighFirst( std::vector& scores ) +{ + std::sort( scores.begin(), scores.end() ); + std::reverse( scores.begin(), scores.end() ); + std::rotate( scores.begin(), scores.begin(), scores.end() ); +} +} +FIXEOF +mkfix callseq_assign frame.h <<'FIXEOF' +#pragma once +// call-sequence fixture: a row stream's frame writer, four calls on one writer. Normalized it is `$I . $I ( … ) ;` +// four times, which is all sortutil.h's helper is too. +#include +#include +#include +namespace frame +{ +struct Out +{ + void u64( std::uint64_t ) {} + void vec( const std::vector& ) {} + void put( const char*, std::size_t ) {} +}; +inline void writeStream( Out& o, std::size_t rowCount, const std::vector& chunkAt, const std::string& bytes ) +{ + o.u64( rowCount ); + o.vec( chunkAt ); + o.u64( bytes.size() ); + o.put( bytes.data(), bytes.size() ); +} +} +FIXEOF +mkfix callseq_assign sink.h <<'FIXEOF' +#pragma once +// call-sequence fixture: frame.h's writer beside a near twin whose last statement is an ASSIGNMENT. A body with +// an assignment is not a call run, so the group carries no idiom and keeps gating. +#include +#include +#include +namespace sink +{ +struct Log +{ + void tag( std::uint64_t ) {} + void list( const std::vector& ) {} + std::size_t mark = 0; +}; +inline void recordBatch( Log& log, std::size_t batchId, const std::vector& ids, const std::string& label ) +{ + log.tag( batchId ); + log.list( ids ); + log.tag( label.size() ); + log.mark = label.size() + ids.size(); +} +} +FIXEOF + echo "cloneidiomcheck: BIN=$BIN" # One row per line, for grep-per-row assertions. @@ -118,13 +318,19 @@ expect_row onestmt_alpha_tdefault widthBetween gapOf one-statement no # (O) t expect_row onestmt_alpha_ltdefault widthBetween gapOf one-statement no # (O) the same, with a less-than in one default (`hi = kLo < kHi`: the `<` opens no template, `pad` is still a parameter) expect_row onestmt_alpha_gogeneric WidthBetween GapOf one-statement no # (O) the same through Go type parameters (`GapOf[T int | int64](…)`) expect_row onestmt_memberparam rowFits cellFits one-statement no # (O) a shared MEMBER spelled like a parameter +expect_row callseq_demote sortUnique writeStream call-sequence yes # (P) two call runs, no callee in common +expect_row callseq_sharedcallee writeStream writeHeader call-sequence no # (P) the same writer methods called: a copy +expect_row callseq_samefile sortUnique writeStream call-sequence no # (P) one file, one namespace +expect_row callseq_alpha sortDescending rankHighFirst call-sequence no # (P) identical after renaming the parameter +expect_row callseq_assign writeStream recordBatch NONE no # (P) an assignment is not a call statement # ── (G) true-positive preservation: the row stream itself is untouched ──────────────────────────────── # Demotion is an ANNOTATION. Every fixture must still yield exactly ONE group of exactly TWO members — # the shape each yielded before any of this existed. A classifier that suppressed a row would pass every # attribute arm above and fail here. for d in ladder_demote ladder_sharedids ladder_samefile switchtable paramstruct nonidiom \ - onestmt_demote onestmt_sharedconst onestmt_samefile onestmt_expects onestmt_ifreturn onestmt_alpha onestmt_alpha_generic onestmt_alpha_gogeneric onestmt_alpha_tdefault onestmt_alpha_ltdefault onestmt_memberparam; do + onestmt_demote onestmt_sharedconst onestmt_samefile onestmt_expects onestmt_ifreturn onestmt_alpha onestmt_alpha_generic onestmt_alpha_gogeneric onestmt_alpha_tdefault onestmt_alpha_ltdefault onestmt_memberparam \ + callseq_demote callseq_sharedcallee callseq_samefile callseq_alpha callseq_assign; do n="$( rows "$d" | wc -l | tr -d ' ' )" m="$( rows "$d" | grep -c 'n="2"' )" if [ "$n" = 1 ] && [ "$m" = 1 ]; then @@ -287,6 +493,31 @@ case "$CROW" in *) no "quality-delta: the shared-constant one-statement pair stopped gating (row: ${CROW:-})";; esac +# (P) the quality-delta half of the fifth idiom. The writer is committed and the helper arrives in the working tree, +# so the pair is preexisting-worse (the writer existed) — the shape that gated: without call-sequence it is a gating row. +mkrepo qd_callseq "callseq_demote/frame.h" "callseq_demote/sortutil.h" || { echo "git fixture setup failed"; exit 2; } +QROW="$( qd qd_callseq | tr '<' '\n' | grep 'kind="duplication"' | grep 'sortUnique' )" # status: --quality-delta exits 0 or 2 (gating) by design; the row's sev= is the verdict, and an empty row FAILs +case "$QROW" in + '') no "quality-delta: no row for the call-sequence pair at all — the arms below are vacuous";; + *'idiom="call-sequence"'*'sev="minor"'*|*'sev="minor"'*'idiom="call-sequence"'*) ok "quality-delta: the no-shared-callee call-sequence pair is minor, idiom named";; + *) no "quality-delta: the no-shared-callee call-sequence pair is not a minor call-sequence row (row: $QROW)";; +esac +case "$QROW" in + *'gating="1"'*) no "quality-delta: the demoted call-sequence pair still gates";; + '') ;; + *) ok "quality-delta: the demoted call-sequence pair does not gate";; +esac +case "$( qdfull qd_callseq )" in + *'call-sequence is a body of call statements only'*) ok "quality-delta: the call-sequence row's document defines the idiom's narrowed test";; + *) no "quality-delta: a document with a call-sequence row never defines the narrowed test";; +esac +mkrepo qd_callseq_shared "callseq_sharedcallee/frame.h" "callseq_sharedcallee/header.h" || { echo "git fixture setup failed"; exit 2; } +KROW="$( qd qd_callseq_shared | tr '<' '\n' | grep 'kind="duplication"' | grep 'writeHeader' )" # status: --quality-delta exits 2 here by design (the pair gates); the row's gating= is the verdict, and an empty row FAILs +case "$KROW" in + *'idiom="call-sequence"'*'gating="1"'*|*'gating="1"'*'idiom="call-sequence"'*) ok "quality-delta: the shared-callee call-sequence pair still gates";; + *) no "quality-delta: the shared-callee call-sequence pair is not a gating call-sequence row (row: ${KROW:-})";; +esac + # ── (J) determinism ─────────────────────────────────────────────────────────────────────────────────── "$BIN" "$CORPUS" --clones --no-cache >"$TMP/a" 2>/dev/null "$BIN" "$CORPUS" --clones --no-cache >"$TMP/b" 2>/dev/null diff --git a/test/legend_over_target.tsv b/test/legend_over_target.tsv index d373a2688..b41817dbf 100644 --- a/test/legend_over_target.tsv +++ b/test/legend_over_target.tsv @@ -42,3 +42,4 @@ ripwire.arch/v1 no-file-edges 283 no_file_edges=" no_file_edges=LANGS: this bui ripwire.arch/v1 unmeasured-files 132 unmeasured_files=" unmeasured_files=N: files in the no_file_edges= languages abiarch-retire-register: the tool-wide unmeasured_files= reading, present-only beside the attribute ripwire.arch/v1 masked-files 180 masked_files=" masked_files=N: no_file_edges= files, left out of abiarch-retire-register: the tool-wide masked_files= reading, present-only beside full:impact all-next 140 all_next=" all_next=: the ONE call that lists every row BAND DC (DC2, handoffwindow.h kAllNextLegend): a --impact root that windows names the one call that lists every row; the clause rides only beside all_next=, so only a windowed answer pays for it +ripwire.quality-delta/v1 stale-tree 161 stale_tree=" stale_tree=1: the working tree is not target_ref D3 QD-STALE-HEADER (QD-FALSE-ROWS lane): a range answer whose target is not the tree on disk (uncommitted edits, untracked files, HEAD elsewhere) says so on its root, and the compact legend defines stale_tree=; present-only (absent on a clean tree at target_ref, e.g. CI) diff --git a/test/qdrefpaircheck.sh b/test/qdrefpaircheck.sh index b1cfd37c1..76e1a6be0 100755 --- a/test/qdrefpaircheck.sh +++ b/test/qdrefpaircheck.sh @@ -155,6 +155,33 @@ if [ "$sameRc" = 0 ]; then ok "(B) A==B exits 0"; else no "(B) A==B exit was $sa [ "$( attr "$TMP/same.xml" base_ref )" = "$( attr "$TMP/same.xml" target_ref )" ] \ && ok "(B) A==B still discloses both refs" || no "(B) A==B ref disclosure inconsistent" +# ── (B2) D3 QD-STALE-HEADER: stale_tree= says when the files on disk are not the tree the range judged ───────── +# A range answer is about target_ref as COMMITTED. Run before the last edit (or on a commit HEAD has left), its green +# exit cannot pass for the current files, and the root now says so: stale_tree="1", present only when true. +# Premise: (A) ran A..B with B = HEAD on a clean tree, which is the one case it must be ABSENT. +hdr "$TMP/syn.xml" | grep -q ' stale_tree=' \ + && no "(B2) a clean tree whose HEAD is target_ref carries stale_tree= (it is present only when true)" \ + || ok "(B2) clean tree at target_ref: no stale_tree=" +"$BIN" . "--quality-delta=$A_SHA..$A_SHA" >"$TMP/stale_head.xml" 2>"$TMP/stale_head.err"; staleHeadRc=$? +[ "$( attr "$TMP/stale_head.xml" stale_tree )" = "1" ] \ + && ok "(B2) target_ref is not HEAD's tree: stale_tree=\"1\"" \ + || { no "(B2) target_ref A is not HEAD (B), yet stale_tree= is '$( attr "$TMP/stale_head.xml" stale_tree )'"; hdr "$TMP/stale_head.xml"; } +[ "$staleHeadRc" = 0 ] && ok "(B2) stale_tree= never gates (A..A still exits 0)" || no "(B2) A..A exit was $staleHeadRc, expected 0" +grep -q 'stale_tree=1' "$TMP/stale_head.err" && ok "(B2) the stale note is on stderr" || no "(B2) no stale_tree note on stderr: $( head -c 300 "$TMP/stale_head.err" )" +printf '// an edit after the commit\n' >> lib.h +"$BIN" . "--quality-delta=$A_SHA..$B_SHA" >"$TMP/stale_dirty.xml" 2>/dev/null; staleDirtyRc=$? +"$BIN" . "--quality-delta=$A_SHA..$B_SHA" --legend=full >"$TMP/stale_dirty_full.xml" 2>/dev/null # status: exits 2 like the run above (same rows); only its legend is read +git checkout -q -- lib.h +[ "$( attr "$TMP/stale_dirty.xml" stale_tree )" = "1" ] \ + && ok "(B2) an uncommitted edit after target_ref: stale_tree=\"1\"" \ + || { no "(B2) a dirty working tree, yet stale_tree= is '$( attr "$TMP/stale_dirty.xml" stale_tree )'"; hdr "$TMP/stale_dirty.xml"; } +[ "$staleDirtyRc" = "$synRc" ] && [ "$( attr "$TMP/stale_dirty.xml" gating )" = "$( attr "$TMP/syn.xml" gating )" ] \ + && ok "(B2) the same rows and exit ($staleDirtyRc) with and without stale_tree= (a disclosure, never a gate)" \ + || no "(B2) stale_tree= moved the answer: exit $staleDirtyRc vs $synRc, gating $( attr "$TMP/stale_dirty.xml" gating ) vs $( attr "$TMP/syn.xml" gating )" +grep -q 'stale_tree=1:' "$TMP/stale_dirty.xml" && ok "(B2) the compact legend defines stale_tree=" || no "(B2) the compact legend never defines stale_tree=" +grep -qF 'stale_tree="1" means' "$TMP/stale_dirty_full.xml" && ok "(B2) the full legend defines stale_tree=" || no "(B2) the full legend never defines stale_tree=" +grep -q 'stale_tree' "$TMP/syn.xml" && no "(B2) a document without stale_tree= pays for its legend" || ok "(B2) no stale_tree legend without the attribute" + # ── (C) refusals: a bad ref, the three-dot form, and a half-typed value ─────────────────────────────────── "$BIN" . --quality-delta=nosuchref..HEAD >/dev/null 2>"$TMP/badrev.err"; badRc=$? if [ "$badRc" = 1 ]; then ok "(C) an unresolvable ref exits 1"; else no "(C) unresolvable ref exit was $badRc, expected 1"; fi @@ -205,9 +232,16 @@ grep -q '^\[stats\]' "$TMP/g3.err" && grep -q '^ripwire: cache-stats .* files=2 && ok "(G) control: the bare form still indexes the 2-file working tree, and both observables see it" \ || no "(G) control: the bare form showed no working-tree ingest — the two observables above prove nothing" "$BIN" . "--quality-delta=$A_SHA..$B_SHA" >"$TMP/g4.xml" 2>/dev/null -cmp -s "$TMP/syn.xml" "$TMP/g4.xml" \ - && ok "(G) an untracked working-tree file does not change the A..B answer" \ - || { no "(G) an untracked working-tree file changed the A..B answer"; diff "$TMP/syn.xml" "$TMP/g4.xml" | head -4; } +# D3 (QD-STALE-HEADER): the untracked file makes the tree on disk differ from B's, which the root now DISCLOSES — +# stale_tree="1" and its one compact-legend reading. Everything else (rows, counts, the rest of the legend) must be +# byte-identical: the range form still never reads the working tree's CONTENT. +[ "$( attr "$TMP/g4.xml" stale_tree )" = "1" ] \ + && ok "(G) the untracked file is disclosed as stale_tree=\"1\"" \ + || no "(G) an untracked working-tree file, yet no stale_tree=\"1\" on the root" +sed -e 's/ stale_tree="1"//' -e 's/ stale_tree=1: [^.]*; never gating\.//' "$TMP/g4.xml" >"$TMP/g4.nostale.xml" +cmp -s "$TMP/syn.xml" "$TMP/g4.nostale.xml" \ + && ok "(G) an untracked working-tree file does not change the A..B answer (stale_tree= and its legend aside)" \ + || { no "(G) an untracked working-tree file changed the A..B answer"; diff "$TMP/syn.xml" "$TMP/g4.nostale.xml" | head -4; } "$BIN" "$R" "--for=tangle" "--quality-delta=$A_SHA..$B_SHA" >/dev/null 2>"$TMP/g5.err"; g5Rc=$? [ "$g5Rc" = 0 ] && grep -q 'IGNORED this run: --quality-delta' "$TMP/g5.err" \ && ok "(G) a verb that outranks --quality-delta still answers from the working tree (--for wins, the range is disclosed as ignored)" \ From f2be3cd27c11bae1115f9d7c789649026c1c7d6e Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:29:16 -0500 Subject: [PATCH 02/65] qd-false-rows: prereview fixes (if/else verdicts in (B2), legend dictv for the stale_tree entry) Co-Authored-By: Claude Opus 5.5 --- docs/captures/COMMANDS_showcase_2026-11-18.md | 2 +- test/qdrefpaircheck.sh | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/captures/COMMANDS_showcase_2026-11-18.md b/docs/captures/COMMANDS_showcase_2026-11-18.md index 10e3ebda1..9ca2e68c2 100644 --- a/docs/captures/COMMANDS_showcase_2026-11-18.md +++ b/docs/captures/COMMANDS_showcase_2026-11-18.md @@ -5902,7 +5902,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=3a03a2c74f654d09 entries=1164 +ripwire legend dictionary ripwire.dict/v1 dictv=9190bd952902a371 entries=1165 : 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/test/qdrefpaircheck.sh b/test/qdrefpaircheck.sh index 76e1a6be0..36ad1baf8 100755 --- a/test/qdrefpaircheck.sh +++ b/test/qdrefpaircheck.sh @@ -166,8 +166,8 @@ hdr "$TMP/syn.xml" | grep -q ' stale_tree=' \ [ "$( attr "$TMP/stale_head.xml" stale_tree )" = "1" ] \ && ok "(B2) target_ref is not HEAD's tree: stale_tree=\"1\"" \ || { no "(B2) target_ref A is not HEAD (B), yet stale_tree= is '$( attr "$TMP/stale_head.xml" stale_tree )'"; hdr "$TMP/stale_head.xml"; } -[ "$staleHeadRc" = 0 ] && ok "(B2) stale_tree= never gates (A..A still exits 0)" || no "(B2) A..A exit was $staleHeadRc, expected 0" -grep -q 'stale_tree=1' "$TMP/stale_head.err" && ok "(B2) the stale note is on stderr" || no "(B2) no stale_tree note on stderr: $( head -c 300 "$TMP/stale_head.err" )" +if [ "$staleHeadRc" = 0 ]; then ok "(B2) stale_tree= never gates (A..A still exits 0)"; else no "(B2) A..A exit was $staleHeadRc, expected 0"; fi +if grep -q 'stale_tree=1' "$TMP/stale_head.err"; then ok "(B2) the stale note is on stderr"; else no "(B2) no stale_tree note on stderr: $( head -c 300 "$TMP/stale_head.err" )"; fi printf '// an edit after the commit\n' >> lib.h "$BIN" . "--quality-delta=$A_SHA..$B_SHA" >"$TMP/stale_dirty.xml" 2>/dev/null; staleDirtyRc=$? "$BIN" . "--quality-delta=$A_SHA..$B_SHA" --legend=full >"$TMP/stale_dirty_full.xml" 2>/dev/null # status: exits 2 like the run above (same rows); only its legend is read @@ -178,8 +178,8 @@ git checkout -q -- lib.h [ "$staleDirtyRc" = "$synRc" ] && [ "$( attr "$TMP/stale_dirty.xml" gating )" = "$( attr "$TMP/syn.xml" gating )" ] \ && ok "(B2) the same rows and exit ($staleDirtyRc) with and without stale_tree= (a disclosure, never a gate)" \ || no "(B2) stale_tree= moved the answer: exit $staleDirtyRc vs $synRc, gating $( attr "$TMP/stale_dirty.xml" gating ) vs $( attr "$TMP/syn.xml" gating )" -grep -q 'stale_tree=1:' "$TMP/stale_dirty.xml" && ok "(B2) the compact legend defines stale_tree=" || no "(B2) the compact legend never defines stale_tree=" -grep -qF 'stale_tree="1" means' "$TMP/stale_dirty_full.xml" && ok "(B2) the full legend defines stale_tree=" || no "(B2) the full legend never defines stale_tree=" +if grep -q 'stale_tree=1:' "$TMP/stale_dirty.xml"; then ok "(B2) the compact legend defines stale_tree="; else no "(B2) the compact legend never defines stale_tree="; fi +if grep -qF 'stale_tree="1" means' "$TMP/stale_dirty_full.xml"; then ok "(B2) the full legend defines stale_tree="; else no "(B2) the full legend never defines stale_tree="; fi grep -q 'stale_tree' "$TMP/syn.xml" && no "(B2) a document without stale_tree= pays for its legend" || ok "(B2) no stale_tree legend without the attribute" # ── (C) refusals: a bad ref, the three-dot form, and a half-typed value ─────────────────────────────────── From 6e7ab89a2761e786c82f114f37e2a5724b6f4178 Mon Sep 17 00:00:00 2001 From: joyful-ii-V-I <210578314+joyful-ii-V-I@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:01:01 -0500 Subject: [PATCH 03/65] qd: tangle kind (report-only), D4 best-since ratchet, improved section (WIP, unbuilt) QD-TANGLE lane, first cut. Compile-checked only (clang -fsyntax-only of main.cpp and ingest.cpp); no build yet because /Users sat at 9 GiB, under the lane's 11 GiB floor. - cc_walk gains the one new fact, steering locals (Symbol::steer, u8), plus a flat-dispatch share (Symbol::dispatchShare, u8): deep regions inside short arms of a 4+-arm switch or else-if chain are left out of the score. Symbol stays 112 B (locals narrowed to u16). Ingest cache 53, warmsnap 3, qsnap scheme 35. - model.h: TangleInputs, T and S = T x log2(loc/50), bar S >= 6 (tenths). - --metrics: steer= and tangle= (present-only) plus legend. - quality.h: the thirteenth kind `tangle`, always sev="minor", with why= / fix= / locals=; the D4 ratchet (appendTangleRatchet: best since the last tag, ratchet="TAG" facet); QD-CREDIT-ROW improvements via a new trailing computeDelta param (DeltaExtras). - qdbestsince.h: the history reader (ls-tree at the tag, log --raw since it, cat-file batch in 64 MB chunks, cap 512 versions), measured by ingest's tangleInputsInBlobs (the whereis blob pool, refactored into runBlobPool). - XML/JSON/MCP: / "improved", ratchet_ref= on the root, legends. - test/tanglecheck.sh (+ test/lib/tanglefixtures.py), listed in regression.sh. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +- docs/COMMANDS.md | 4 +- skills/ripwire-quality-bar/SKILL.md | 9 +- skills/ripwire-quality-bar/quality-metrics.md | 2 +- src/cli.h | 6 +- src/compactlegend.h | 8 + src/ingest.h | 23 + src/ingest_astquery.h | 137 +++- src/ingest_cache.h | 9 +- src/ingest_metrics.h | 627 +++++++++++++++++- src/ingest_model.h | 4 +- src/ingest_sidecap.h | 11 +- src/main.cpp | 1 + src/mcpverbs.h | 20 +- src/model.h | 129 +++- src/qdbestsince.h | 219 ++++++ src/quality.h | 599 ++++++++++++++++- src/serialize.h | 24 + src/verbs_quality.h | 95 ++- src/warmsnap.h | 3 +- src/warmsnap_model.h | 5 +- test/lib/tanglefixtures.py | 140 ++++ test/qddegradecheck.sh | 14 +- test/regression.sh | 1 + test/tanglecheck.sh | 111 ++++ 25 files changed, 2116 insertions(+), 90 deletions(-) create mode 100644 src/qdbestsince.h create mode 100644 test/lib/tanglefixtures.py create mode 100755 test/tanglecheck.sh diff --git a/README.md b/README.md index a3572946c..e701955e1 100644 --- a/README.md +++ b/README.md @@ -961,12 +961,13 @@ firing on the same function is corroboration rather than one metric counted twic That matters most for code an agent wrote. Empty-catch error masking is **+47%** more common in AI-authored commits, a function rewritten again inside two weeks **+15%** more likely, and reuse is *declining* as AI's share of commits grows (GitClear, *AI Copilot Code Quality*, 2026). Ten of -`--quality-delta`'s 12 kinds each target one measured mode like those (the eleventh, `placeholder`, +`--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, 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), and it reports **only what your +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 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/docs/COMMANDS.md b/docs/COMMANDS.md index 718dcffef..d4bebbdf5 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -2975,9 +2975,9 @@ $ ./build/ripwire . --quality-delta --show-stale ### `--quality-delta` -**Answers:** before a PR: report ONLY what your change made worse, across 12 kinds — pair with --test-gate. +**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); 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) — 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, 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) — 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** diff --git a/skills/ripwire-quality-bar/SKILL.md b/skills/ripwire-quality-bar/SKILL.md index 9ef78ca19..d8abf9bab 100644 --- a/skills/ripwire-quality-bar/SKILL.md +++ b/skills/ripwire-quality-bar/SKILL.md @@ -2,7 +2,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 12 kinds; exit 2 if old code did (new-symbol rows never gate, + 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. Merge safety → change-check. Even a single-line leaf fix runs it. allowed-tools: Bash, Read @@ -132,7 +132,7 @@ something always fires.) 2. **Make your change.** 3. **Measure the delta** — `ripwire --quality-delta --legend=compact` → only the regressions you introduced, across the - 12 kinds in the table below. Each emits `` (`members=` for duplication). + 13 kinds in the table below. Each emits `` (`members=` for duplication). Test-fixture dirs are exempt from `dead-code`; `short-horizon-churn` ignores your own current edit and exempts brand-new symbols/markdown/fixtures. Two exemptions are DISCLOSED on the report rather than silent, and both change how you read a zero: a symbol defined by a self-registering test/benchmark @@ -265,13 +265,14 @@ 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 absence check read off a command whose failure is unchecked) | `--expand=SYM` | `format-arity` gates on any origin: match the fields to the arguments. The other three 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 | +| `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 | -These 12 kinds aren't a generic lint list. Ten target an agent-code degradation mode validated at large N +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 honesty check on your own "done"; `defect-shape` is four defect shapes code review kept finding by hand. Numbers + why the loop must be continuous, not a one-time prompt → [`quality-metrics.md`](quality-metrics.md). -**Read the Fix column as DIRECTION, not a computed answer.** None of these 12 kinds has a corpus-derivable +**Read the Fix column as DIRECTION, not a computed answer.** None of these 13 kinds has a corpus-derivable correct replacement — "split the fn" names a move, not a target function shape, and you still judge it. That is deliberate: complexity, coupling, and colocation don't have a computable right answer the way a naming CONVENTION does. The one exception in this whole tool is `--naming-consistency` (→ **ripwire-fresh-eyes**), diff --git a/skills/ripwire-quality-bar/quality-metrics.md b/skills/ripwire-quality-bar/quality-metrics.md index 1daaf46e3..148a40b45 100644 --- a/skills/ripwire-quality-bar/quality-metrics.md +++ b/skills/ripwire-quality-bar/quality-metrics.md @@ -59,7 +59,7 @@ defect- and vulnerability-prone files in the empirical literature. Push hardest | **Resolution ambiguity `amb=`** | the map's OWN honesty signal — K calls the resolver guessed | verify high-`amb` in source | header `ambiguous=`, per-symbol `amb=` | read the source before trusting a high-`amb` edge | | **Cache-friendly data layout (DOD)** | hot-path perf + this codebase's house value: SoA over AoS, smallest type that fits, 32-bit ids | contextual | `--field-affinity[=STRUCT]` for co-accessed-but-far-apart fields (`split-line`/`straddle`); `--for` finds the hot struct. A static HYPOTHESIS, not a measurement — see `ripwire-perf-target` for what it cannot see | mirror the surrounding hot-path layout; don't AoS a hot loop — confirm on hardware counters before changing a layout | -## Why `--quality-delta`'s 12 kinds — the measured agent failure modes +## Why `--quality-delta`'s 13 kinds — the measured agent failure modes Not a generic lint list; each targets what the 2025-26 literature found agent-written code actually degrades on (large-N studies): - **Verbosity**: agent code runs **2.3× more verbose** than human code on matched tasks. diff --git a/src/cli.h b/src/cli.h index fc2e4fe09..335d541e2 100644 --- a/src/cli.h +++ b/src/cli.h @@ -359,7 +359,7 @@ struct Config bool qualityDelta = false; // --quality-delta: report only code-quality regressions vs that baseline (exit 2 if any MAJOR unacked one) std::string_view qualityDeltaRange; // --quality-delta=REV|A..B (R-I): compare two COMMITTED trees instead of the working // tree vs a baseline — the WAVE-level measurement. Same grammar --dmm= takes - // (quality::resolveRefSpec owns it), same 12 kinds/gating/ack contract out + // (quality::resolveRefSpec owns it), same 13 kinds/gating/ack contract out bool qualityAck = false; // --quality-ack[=REASON]: accept the current findings into .ripwire_quality_acks (per-finding ratchet); shares qualityDelta's baseline resolution std::string_view qualityAckReason; // the reason recorded next to each acked finding std::string_view qualityAckOnly; // --ack-only=SUBSTR[,SUBSTR]: ack only findings whose kind, canonical id or facet (e.g. format-arity) contains one of these (default: all) @@ -1877,8 +1877,8 @@ inline constexpr char kHelpHead[] = " --show-stale (with --quality-delta) print the stale-ack rows and the full header a clean answer collapses\n" " — 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 12 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);\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" " 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" diff --git a/src/compactlegend.h b/src/compactlegend.h index ed7846241..1431caa4a 100644 --- a/src/compactlegend.h +++ b/src/compactlegend.h @@ -1056,6 +1056,8 @@ inline constexpr CompactCompletenessTerm kCompactAttributeReadings[] = // idea #11 (lane lean-trio): present-only, on a regression-free answer whose stale sa rows were collapsed to counts { "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" }, { "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" }, { "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" }, @@ -1592,6 +1594,10 @@ inline constexpr CompactCompletenessTerm kCompactAttributeReadings[] = { "idiom", "r idiom=: the recognized clone-body shape of a duplication row", true, "r", MapHeaderRead::No, {}, "quality-delta" }, { "facet", "r facet=failure-default: an error-masking row whose growth includes a read/parse/spawn failure returned as an empty success; it never gates by itself", true, "r", MapHeaderRead::No, {}, "quality-delta" }, { "monster", "r monster=1: over 5x the ccx bar and grew by now-was (10+): major at any %; put the new branch in a helper", true, "r", MapHeaderRead::No, {}, "quality-delta" }, + { "why", "r why=: a tangle row's inputs that rose (nest, deep lines, steer, length); fix=: the shape that rise calls for, with lines", true, "r", MapHeaderRead::No, {}, "quality-delta" }, // also defines fix= + { "locals", "r locals=: a tangle row's steering locals (set in one step, read by a branch 10+ statements later)", true, "r", MapHeaderRead::No, {}, "quality-delta" }, + { "ratchet", "r ratchet=TAG: a tangle row above its best since TAG (an input rose over its minimum); why= adds best since TAG", true, "r", MapHeaderRead::No, {}, "quality-delta" }, + { "improved", "improved n= more=: what this change made better, never a row or gating; i kind= sym= was= now= p=: over the kind's bar at baseline, lower now", true, "improved", MapHeaderRead::No, {}, "quality-delta" }, { "defect", "r defect=: a defect-shape row's shape: format-arity (gates, any origin) or utf8-cut / dedup-first / vacuous-assert (always sev=minor)", true, "r", MapHeaderRead::No, {}, "quality-delta" }, // --expand's bundle (src/main.cpp runDefaultMap): the ride-along note and the map it carries inside the . { "note", "note=: the ranked map rides along with the payload; top-k=0 serves the payload alone", false, "ctx", MapHeaderRead::No, {}, "expand" }, @@ -1806,6 +1812,8 @@ inline constexpr CompactCompletenessTerm kCompactAttributeReadings[] = // metrics: src/serialize.h (s row metrics, f layer= via builtinLayer in src/arch.h) { "humps", "humps=/deep=: regions reaching the nesting bar / lines inside them; absent when nest= is under the bar", true, "s", MapHeaderRead::No, {}, "metrics" }, // also defines deep= { "deep_floor", "deep_floor=1: deep= is a FLOOR; a line two humps share is billed once, so deep below humps is legal", true, "s", MapHeaderRead::No, {}, "metrics" }, + { "steer", "steer=N: primitive locals rewritten, then read in a branch condition 10+ statements later; absent at 0", true, "s", MapHeaderRead::No, {}, "metrics" }, + { "tangle", "tangle=S: quality-delta's tangle score, (nest past 3 + deep%/5 + steer/100 lines) x log2(loc/50); bar 6", true, "s", MapHeaderRead::No, {}, "metrics" }, { "ev", "ev=/ev_why=: essential complexity (2+: jumps block extract-method; absent: 1) / the jumps behind it, tag:count", true, "s", MapHeaderRead::No, {}, "metrics" }, // also defines ev_why= { "ev_floor", "ev_floor=1: ev= is a FLOOR; noreturn calls, macro-hidden exits and unresolved gotos are unseen", true, "s", MapHeaderRead::No, {}, "metrics" }, { "ppalt", "ppalt=N: #else/#elif branches in the body; metrics sum ALL branches, no one build compiles them all", true, "s", MapHeaderRead::No, {}, "metrics" }, diff --git a/src/ingest.h b/src/ingest.h index af87a4d5a..0f428aa4a 100644 --- a/src/ingest.h +++ b/src/ingest.h @@ -930,6 +930,12 @@ inline bool astQueryNestsTooDeep( std::string_view query ) // local to the re-parsed substring. std::vector collectGatedLocalNames( std::string_view defBytes, std::uint32_t defStartLine, Lang lang ); +// ---- QD-TANGLE detail: the steering locals and deep regions a tangle row names (model.h TangleDetailFacts) ---- +// Re-parses the whole file `fileBytes` (its grammar from `path`'s extension, the crawl's .h → ObjC reroute included) and re-runs the +// ingest walk on the node spanning [startByte, endByte) — Symbol::sigStartByte / endByte. Called only for the rows a --quality-delta +// answer emits, never cached; `ok` is false when the file does not parse or no node spans the def. +TangleDetailFacts tangleDetailOf( std::string_view fileBytes, std::string_view path, std::uint32_t startByte, std::uint32_t endByte ); + // ---- --whereis on other refs: where the TAGS PATH defines one name inside blobs the index never read ---- // HEAD's rows take kind="def" from the index; a row on another ref comes from a git blob the index never saw. This // runs the index's own extraction on such a blob — the crawl's extension → grammar rule (with the .h → ObjC content @@ -960,4 +966,21 @@ struct BlobDefinitions // long-lived server must call this under quality::headSnapshotIngestMutex, like every other ingest call site. std::vector definitionLinesInBlobs( std::span blobs, std::string_view name ); +// QD-TANGLE D4 (quality's best-since store): every callable definition of each blob with its tangle inputs (model.h TangleInputs), +// by the same extraction as definitionLinesInBlobs plus the callables' cc_walk — so a history blob's inputs are the ones HEAD's +// index would give the same bytes. `defs` is empty unless `status` is Parsed. Same pool, same single-writer rule. +struct BlobTangleDef +{ + std::string scope; + std::string name; + TangleInputs in; +}; +struct BlobTangleDefs +{ + std::vector defs; + Lang lang = Lang::Unknown; + BlobDefsStatus status = BlobDefsStatus::Failed; +}; +std::vector tangleInputsInBlobs( std::span blobs ); + } // namespace rw diff --git a/src/ingest_astquery.h b/src/ingest_astquery.h index e7503c540..abf9312ed 100644 --- a/src/ingest_astquery.h +++ b/src/ingest_astquery.h @@ -2104,6 +2104,46 @@ std::vector collectGatedLocalNames( std::string_view defBytes, st return out; } +// QD-TANGLE detail (ingest.h tangleDetailOf): ONE function's steering locals and deep regions, by re-parsing its file and re-running +// the same fused walk with a detail sink. The node is the smallest one that starts at the definition's first byte and ends at its last +// — the def node complexityOf measured at ingest (a body-sibling or literal-bound def measures a different node, and gets no detail). +TangleDetailFacts tangleDetailOf( std::string_view fileBytes, std::string_view path, std::uint32_t startByte, std::uint32_t endByte ) +{ + TangleDetailFacts out; + const LangEntry* le = lookupLang( lowerExtensionOf( path ) ); + if( le != nullptr && le->grammar != nullptr && lowerExtensionOf( path ) == ".h" && looksObjC( fileBytes ) ) + { + le = lookupLang( ".m" ); // the SAME reroute the crawl applies + } + if( le == nullptr || le->grammar == nullptr || startByte >= endByte || endByte > fileBytes.size() ) + { + return out; + } + ParserGuard pg; + const TSLanguage* g = le->grammar(); + if( pg.p == nullptr || g == nullptr || !ts_parser_set_language( pg.p, g ) || !grammarAbiOk( g ) ) + { + return out; + } + TSTree* tree = ts_parser_parse_string( pg.p, nullptr, fileBytes.data(), std::uint32_t( fileBytes.size() ) ); + if( tree == nullptr ) + { + return out; + } + TSNode n = ts_node_descendant_for_byte_range( ts_tree_root_node( tree ), startByte, endByte - 1u ); + while( !ts_node_is_null( n ) && ts_node_start_byte( n ) > startByte ) + { + n = parentOf( n ); + } + if( !ts_node_is_null( n ) && ts_node_start_byte( n ) == startByte && ts_node_end_byte( n ) == endByte ) + { + complexityOf( n, fileBytes, le->lang, &out ); + out.ok = true; + } + ts_tree_delete( tree ); + return out; +} + // ---- definitionLinesInBlobs (ingest.h): the tags path over blobs from other git refs ---- // // The DISCLOSE sink of one blob: a degrade sets its slot's status, which is exactly what the caller reads (a blob @@ -2130,7 +2170,7 @@ struct BlobDefsSlot // member-macro re-parse when the first parse holds errors, the `#if 0` ranges, the definitions-only tags pass. False when // the slot is already final (a template-only .astro, or a degrade it discloses). inline bool tagsDefinitionsOfBlob( std::string_view bytes, const LangEntry& le, TSParser* parser, TSQueryCursor* cursor, MemberMacroReparse& macroWork, - std::vector& defs, BlobDefinitions& slot, std::string_view fileStem ) + std::vector& defs, BlobDefinitions& slot, std::string_view fileStem, TagsCapture mode ) { IncludedRangeGuard rangeGuard; const AstroFrontmatter astro = restrictAstroToFrontmatter( parser, le, bytes, rangeGuard ); @@ -2160,7 +2200,7 @@ inline bool tagsDefinitionsOfBlob( std::string_view bytes, const LangEntry& le, std::vector binds; std::vector incs; ExtractShortfall shortfall; - captureTagsFacts( cursor, le, 0, bytes, root, defs, refs, binds, incs, ppDead, shortfall, TagsCapture::DefinitionsOnly, fileStem ); + captureTagsFacts( cursor, le, 0, bytes, root, defs, refs, binds, incs, ppDead, shortfall, mode, fileStem ); if( shortfall.isShort ) { DISCLOSE( ( BlobDefsSlot{ slot } ), BlobDefsSlot::DisclosureWhy::ExtractPartial, "whereis: the tags pass over a blob was partial — its rows confirm no definition" ); @@ -2169,23 +2209,24 @@ inline bool tagsDefinitionsOfBlob( std::string_view bytes, const LangEntry& le, return true; } -// One blob through the crawl's language rule and the parse-pool worker's extraction steps, in the worker's order. -// `scan` is a one-slot scan the nesting refusal records into (its --skipped bookkeeping has no reader here: the -// slot's Unread status is this blob's disclosure). -inline void definitionLinesOfOneBlob( const BlobText& blob, std::string_view name, TSParser* parser, TSQueryCursor* cursor, - MemberMacroReparse& macroWork, IngestFileScan& scan, BlobDefinitions& slot ) +// One blob through the crawl's language rule and the parse-pool worker's extraction steps, in the worker's order, into +// the definitions HEAD's index would make SYMBOLS of. `scan` is a one-slot scan the nesting refusal records into (its +// --skipped bookkeeping has no reader here: the slot's Unread status is this blob's disclosure). Null when the slot is +// already final (no grammar, unread, a degrade it discloses, a template-only .astro); else the language the blob read as. +inline const LangEntry* rawDefsOfOneBlob( const BlobText& blob, TSParser* parser, TSQueryCursor* cursor, MemberMacroReparse& macroWork, + IngestFileScan& scan, BlobDefinitions& slot, TagsCapture mode, std::vector& defs ) { const std::string ext = lowerExtensionOf( blob.path ); const LangEntry* le = lookupLang( ext ); if( le == nullptr ) { slot.status = BlobDefsStatus::NoGrammar; - return; + return nullptr; } if( blob.bytes.size() > kDefaultMaxFileBytes || looksBinary( blob.bytes ) ) { slot.status = BlobDefsStatus::Unread; // the crawl's own ceiling and binary sniff: the index skips these too - return; + return nullptr; } if( le->ext == ".h" && looksObjC( blob.bytes ) ) { @@ -2199,28 +2240,27 @@ inline void definitionLinesOfOneBlob( const BlobText& blob, std::string_view nam if( refuseNesting( *le, blob.bytes, pathText.c_str(), 0, scan ) ) { slot.status = BlobDefsStatus::Unread; - return; + return nullptr; } if( !prepareParserFor( parser, *le ) ) { DISCLOSE( ( BlobDefsSlot{ slot } ), BlobDefsSlot::DisclosureWhy::GrammarRejected, "whereis: a blob's grammar could not be set — its rows confirm no definition" ); - return; + return nullptr; } - std::vector defs; if( le->lang == Lang::Markdown ) { TreeGuard mdTree( parseTree( parser, blob.bytes ) ); if( mdTree.get() == nullptr ) { DISCLOSE( ( BlobDefsSlot{ slot } ), BlobDefsSlot::DisclosureWhy::ParseNull, "whereis: a markdown blob did not parse — its rows confirm no definition" ); - return; + return nullptr; } std::vector refs; extractMarkdown( 0, blob.bytes, fs::path( pathText ).stem().string(), ts_tree_root_node( mdTree.get() ), defs, refs ); } - else if( !tagsDefinitionsOfBlob( blob.bytes, *le, parser, cursor, macroWork, defs, slot, cjsExportStem( le->lang, pathText ) ) ) + else if( !tagsDefinitionsOfBlob( blob.bytes, *le, parser, cursor, macroWork, defs, slot, cjsExportStem( le->lang, pathText ), mode ) ) { - return; // the slot says why (template-only .astro: Parsed with nothing; a degrade: Failed) + return nullptr; // the slot says why (template-only .astro: Parsed with nothing; a degrade: Failed) } // The model build's steps that decide which captured definitions become SYMBOLS (ingest.cpp 3a..3a-ter), so a // blob answers what HEAD's index answers for the same bytes: overlapping patterns collapse to one definition, an @@ -2229,6 +2269,17 @@ inline void definitionLinesOfOneBlob( const BlobText& blob, std::string_view nam dedupRawDefs( defs ); collapseObjCDeclDefs( defs ); (void)partitionFieldDefs( defs ); + return le; +} + +inline void definitionLinesOfOneBlob( const BlobText& blob, std::string_view name, TSParser* parser, TSQueryCursor* cursor, + MemberMacroReparse& macroWork, IngestFileScan& scan, BlobDefinitions& slot ) +{ + std::vector defs; + if( rawDefsOfOneBlob( blob, parser, cursor, macroWork, scan, slot, TagsCapture::DefinitionsOnly, defs ) == nullptr ) + { + return; + } for( const RawDef& d : defs ) { if( d.name == name ) @@ -2276,9 +2327,10 @@ inline void installBlobQueries( std::span blobs ) } // One parse worker: its own parser, query cursor and scratch, claiming blobs in `walkOrder` until none is left. Each blob -// writes only its own slot of `out`. -inline void definitionLinesWorker( std::span blobs, std::string_view name, std::span walkOrder, - std::atomic& nextSlot, std::span out ) noexcept +// writes only its own slot of `out` (and whatever `oneBlob` writes at that blob's index). +template +inline void blobPoolWorker( std::span blobs, std::span walkOrder, std::atomic& nextSlot, + std::span out, const OneBlob& oneBlob ) noexcept { ParserGuard pg; TSQueryCursor* cursor = ts_query_cursor_new(); @@ -2301,7 +2353,7 @@ inline void definitionLinesWorker( std::span blobs, std::string_ BlobDefinitions& slot = out[ walkOrder[ s ] ]; try { - definitionLinesOfOneBlob( blobs[ walkOrder[ s ] ], name, pg.p, cursor, macroWork, scan, slot ); + oneBlob( walkOrder[ s ], pg.p, cursor, macroWork, scan, slot ); } catch( ... ) // a throw escaping a worker thread is std::terminate: the blob degrades instead { @@ -2311,7 +2363,9 @@ inline void definitionLinesWorker( std::span blobs, std::string_ ts_query_cursor_delete( cursor ); } -std::vector definitionLinesInBlobs( std::span blobs, std::string_view name ) +// The blob pool: queries installed single-threaded first, then hardware_concurrency() workers, biggest blob first. +template +inline std::vector runBlobPool( std::span blobs, const OneBlob& oneBlob ) { std::vector out( blobs.size() ); if( blobs.empty() ) @@ -2331,7 +2385,7 @@ std::vector definitionLinesInBlobs( std::span b pool.reserve( threadCount ); for( unsigned t = 0; t < threadCount; ++t ) { - pool.emplace_back( [ & ]() noexcept { definitionLinesWorker( blobs, name, walkOrder, nextSlot, out ); } ); + pool.emplace_back( [ & ]() noexcept { blobPoolWorker( blobs, walkOrder, nextSlot, out, oneBlob ); } ); } for( std::thread& w : pool ) { @@ -2340,6 +2394,47 @@ std::vector definitionLinesInBlobs( std::span b return out; } +std::vector definitionLinesInBlobs( std::span blobs, std::string_view name ) +{ + return runBlobPool( blobs, [ & ]( std::uint32_t at, TSParser* parser, TSQueryCursor* cursor, MemberMacroReparse& macroWork, IngestFileScan& scan, BlobDefinitions& slot ) + { definitionLinesOfOneBlob( blobs[ at ], name, parser, cursor, macroWork, scan, slot ); } ); +} + +// QD-TANGLE D4 (ingest.h): every callable's tangle inputs in each blob, by the index's own extraction and cc_walk. +std::vector tangleInputsInBlobs( std::span blobs ) +{ + std::vector out( blobs.size() ); + const std::vector status = runBlobPool( blobs, [ & ]( std::uint32_t at, TSParser* parser, TSQueryCursor* cursor, MemberMacroReparse& macroWork, + IngestFileScan& scan, BlobDefinitions& slot ) + { + std::vector defs; + const LangEntry* le = rawDefsOfOneBlob( blobs[ at ], parser, cursor, macroWork, scan, slot, TagsCapture::DefinitionsAndShape, defs ); + if( le == nullptr ) + { + return; + } + BlobTangleDefs& mine = out[ at ]; + mine.lang = le->lang; + for( const RawDef& d : defs ) + { + if( d.kind == SymKind::Function || d.kind == SymKind::Method ) + { + mine.defs.push_back( { d.scope, d.name, tangleInputsFrom( d.loc, d.maxNest, d.deepLoc, d.steer, tangleDispatchShare( d.deepLoc, d.deepDispatch ) ) } ); + } + } + slot.status = BlobDefsStatus::Parsed; + } ); + for( std::size_t i = 0; i < out.size(); ++i ) + { + out[ i ].status = status[ i ].status; + if( status[ i ].status != BlobDefsStatus::Parsed ) + { + out[ i ].defs.clear(); + } + } + return out; +} + // ---- QD-CONSTRUCTS-AT-INGEST: the --quality-delta construct hits, found in the parse worker's own tree ---------- // findQualityConstructs (lintrules.h) used to re-read and re-parse every file on every --quality-delta call — the // largest item of a warm working-tree call (43 / 22 / 68 % of envoy / cockroach / vscode instructions, ML Stage 0 diff --git a/src/ingest_cache.h b/src/ingest_cache.h index 337daf2ed..f84494e37 100644 --- a/src/ingest_cache.h +++ b/src/ingest_cache.h @@ -47,6 +47,8 @@ struct RawDef std::uint16_t params = 0; // Q4: parameter count (from the def's parameter-list child); fns/methods std::uint16_t paramsMin = 0; // B2.2: the fewest arguments a call can pass (params − defaulted); 0 = no lower bound known std::uint8_t maxNest = 0; // Q4: max control-structure nesting depth inside the def (from cc_walk) + std::uint8_t steer = 0; // QD-TANGLE steering locals (model.h Symbol::steer; from cc_walk, saturating at 255) + std::uint16_t deepDispatch = 0; // QD-TANGLE: deepLoc lines inside short flat-dispatch arms (model.h Symbol::dispatchShare; saturating) std::uint8_t arityExact = 0; // B2.2: 1 ⇒ params is a fixed call-comparable arity (no variadic/default, not implicit-self) std::uint8_t testScope = 0; // L8: 1 ⇒ an IN-FILE test convention encloses this def (see inFileTestScope) std::uint8_t recovered = 0; // extent honesty (extentsuspect.h kRecovered*): the parse RECOVERED this def's container @@ -156,7 +158,8 @@ constexpr std::uint32_t kCacheMagic = 0x4b505443; // "CTPK" // lane rust-degraded's placeholder 42. // 44 (train 37b, lane rust-degraded; its placeholder was 42): the FILE record gains a sixth FileHealth u32, useBoundsBlanked // (the Rust precise-capture re-parse, src/rustusebounds.h), so an older cache must be rejected. 44 is above train 36's 43. -constexpr std::uint32_t kCacheVersion = 52; // 52: lane failure-default — the construct hits gain the failure-default shape tag +constexpr std::uint32_t kCacheVersion = 53; // 53: lane qd-tangle — a def record gains the steering-locals byte and the dispatch-deep u16 (RawDef::steer, ::deepDispatch, after maxNest). + // 52: lane failure-default — the construct hits gain the failure-default shape tag // (lintrules.h kConstructShapeTags, appended); an older record lacks those hits. // 51: lane qd-constructs — the FILE record gains a ninth family, the --quality-delta // construct hits (ConstructHit: startByte, line, tag byte), with its head count. @@ -2596,7 +2599,7 @@ inline constexpr std::uint32_t kCloneKeyKindBits = ( 1u << unsigned( SymKind::Fu static_assert( kSymKindCount <= 32, "kCloneKeyKindBits holds one bit per SymKind" ); inline void writeDef( ByteW& w, const RawDef& d, bool withLex, std::size_t fileDictCount, const std::uint32_t* rowDictIndex ) { - w.u32( d.line ); w.u32( d.startByte ); w.u32( d.endByte ); w.u32( d.nameByte ); w.u32( d.bodyByte ); w.u32( d.cx ); w.u32( d.ccx ); w.u32( d.loc ); w.u32( d.locals ); w.u32( d.ppAlt ); w.u32( d.humps ); w.u32( d.deepLoc ); w.u32( d.ev ); w.u32( d.params ); w.u32( d.paramsMin ); w.u8( d.maxNest ); w.u8( d.arityExact ); w.u8( d.testScope ); w.u8( d.recovered ); w.u8( d.internalLinkage ); w.u8( d.scopeRootsStd ); w.u32( d.fnScopeStart ); w.u32( d.fnScopeEnd ); w.u8( std::uint8_t( d.kind ) ); w.u8( std::uint8_t( d.lang ) ); w.str( d.name ); w.str( d.scope ); + w.u32( d.line ); w.u32( d.startByte ); w.u32( d.endByte ); w.u32( d.nameByte ); w.u32( d.bodyByte ); w.u32( d.cx ); w.u32( d.ccx ); w.u32( d.loc ); w.u32( d.locals ); w.u32( d.ppAlt ); w.u32( d.humps ); w.u32( d.deepLoc ); w.u32( d.ev ); w.u32( d.params ); w.u32( d.paramsMin ); w.u8( d.maxNest ); w.u8( d.steer ); w.u32( d.deepDispatch ); w.u8( d.arityExact ); w.u8( d.testScope ); w.u8( d.recovered ); w.u8( d.internalLinkage ); w.u8( d.scopeRootsStd ); w.u32( d.fnScopeStart ); w.u32( d.fnScopeEnd ); w.u8( std::uint8_t( d.kind ) ); w.u8( std::uint8_t( d.lang ) ); w.str( d.name ); w.str( d.scope ); for( const std::uint8_t tagCount : d.evWhy ) { w.u8( tagCount ); } // 8×u8, fixed order (model.h kEvWhyTagTable) w.u8( d.cloneKey != 0 ? 1 : 0 ); // v50: clone-key presence byte (0 = no key), then the key if( d.cloneKey != 0 ) { w.u64( d.cloneKey ); } @@ -2781,7 +2784,7 @@ inline void verifyCacheRecordMinimaTripwire() noexcept inline RawDef readDef( ByteR& r, bool withLex, const std::vector& fileDict ) { - RawDef d; d.line = r.u32(); d.startByte = r.u32(); d.endByte = r.u32(); d.nameByte = r.u32(); d.bodyByte = r.u32(); d.cx = r.u32(); d.ccx = r.u32(); d.loc = r.u32(); d.locals = r.u32(); d.ppAlt = r.u16Of32(); d.humps = r.u16Of32(); d.deepLoc = r.u16Of32(); d.ev = r.u16Of32(); d.params = r.u16Of32(); d.paramsMin = r.u16Of32(); d.maxNest = r.u8(); d.arityExact = r.u8(); d.testScope = r.u8(); d.recovered = r.u8(); d.internalLinkage = r.u8(); d.scopeRootsStd = r.u8(); d.fnScopeStart = r.u32(); d.fnScopeEnd = r.u32(); d.kind = r.enumU8( kSymKindCount ); d.lang = r.enumU8( kLangCount ); d.name = r.str(); d.scope = r.str(); + RawDef d; d.line = r.u32(); d.startByte = r.u32(); d.endByte = r.u32(); d.nameByte = r.u32(); d.bodyByte = r.u32(); d.cx = r.u32(); d.ccx = r.u32(); d.loc = r.u32(); d.locals = r.u32(); d.ppAlt = r.u16Of32(); d.humps = r.u16Of32(); d.deepLoc = r.u16Of32(); d.ev = r.u16Of32(); d.params = r.u16Of32(); d.paramsMin = r.u16Of32(); d.maxNest = r.u8(); d.steer = r.u8(); d.deepDispatch = r.u16Of32(); d.arityExact = r.u8(); d.testScope = r.u8(); d.recovered = r.u8(); d.internalLinkage = r.u8(); d.scopeRootsStd = r.u8(); d.fnScopeStart = r.u32(); d.fnScopeEnd = r.u32(); d.kind = r.enumU8( kSymKindCount ); d.lang = r.enumU8( kLangCount ); d.name = r.str(); d.scope = r.str(); // B2.2: the extractor (ingest_sidecap.h) stores paramsMin only when it is <= params. A record past that rule is // corruption, and a too-high minimum is the UNSAFE direction (the resolver drops a candidate for too few arguments), // so it takes the same one refusal path as a short read: that file reparses and the rest of the blob stands. diff --git a/src/ingest_metrics.h b/src/ingest_metrics.h index b472a7ac3..f32d3a4b7 100644 --- a/src/ingest_metrics.h +++ b/src/ingest_metrics.h @@ -337,8 +337,168 @@ struct CcAccum std::uint32_t humps = 0; // regions reaching quality::kNestBar → Symbol::humps (see model.h) std::uint32_t deepLoc = 0; // lines inside those regions → Symbol::deepLoc (a FLOOR) std::uint32_t deepEnd = 0; // 1-based end row of the last counted hump — the anti-double-count clamp + // QD-TANGLE steering locals (model.h Symbol::steer) — the walk's one new fact, filled only when `steerOn` (a function over 50 + // lines in steerCountedLang). `stmt` is the statement ordinal in document order (the DFS pops left to right), the clock the + // 10-statement distance is measured on; `slots` are the candidate locals seen so far, searched newest first (a shadowing + // redeclaration wins). `detail` is null in ingest; tangleDetailOf (--quality-delta time, one function) points it at the names. + bool tangleOn = false; // a body over 50 lines: the flat-dispatch tagging below runs (every language) + bool steerOn = false; // ... and in steerCountedLang: the steering locals too + bool anyRewritten = false; // some slot was written after its declaration: until then no condition can steer + std::uint32_t stmt = 0; + std::uint32_t steered = 0; // distinct slots that steered a branch → Symbol::steer (saturated by the caller) + struct SteerSlot + { + std::string_view name; + std::uint32_t lastWrite = 0; // statement ordinal of the latest write so far (the declaration counts as one) + std::uint32_t lastWriteRow = 0; // 1-based line of that write (detail only) + bool prim = false; + bool rewritten = false; + bool steered = false; + }; + std::vector slots; + TangleDetailFacts* detail = nullptr; + std::uint32_t deepDispatch = 0; // the part of deepLoc inside short arms of a flat dispatch (dispatch_* below) }; +// QD-TANGLE FLAT DISPATCH (the false-positive class STAGE0 2.4 named: parseArgs, an `if( a == "--flag" )` chain; envoy's 40-case +// switch). A switch with kDispatchMinArms or more case arms, or an if / else-if chain with that many arms, whose arm is at most +// kDispatchArmMaxRows lines: each arm reads alone, like a row of a table, so the depth it reaches is the arm's own business. The +// walk tags every frame with where it sits in such a construct; a deep region that first crosses the bar inside a short arm is +// billed to deepLoc as always (the published metric is unchanged) AND to deepDispatch, which the tangle score leaves out. +enum class ChainState : std::uint8_t +{ + None, // not inside a dispatch construct + Structure, // the construct's own frame: a condition, an else clause, the link between arms + Arm, // inside one short arm — a deep region here is exempt from the tangle score + SwitchBody, // a switch's body: its children are the case arms +}; +inline constexpr std::uint32_t kDispatchMinArms = 4; +inline constexpr std::uint32_t kDispatchArmMaxRows = 40; + +inline std::uint32_t dispatch_rows( TSNode n ) noexcept +{ + return ts_node_end_point( n ).row - ts_node_start_point( n ).row + 1u; +} +inline ChainState dispatch_armState( TSNode arm ) noexcept +{ + return dispatch_rows( arm ) <= kDispatchArmMaxRows ? ChainState::Arm : ChainState::None; +} +inline bool dispatch_isBlock( const char* t ) noexcept +{ + return kindIs( t, "compound_statement" ) || kindIs( t, "block" ) || kindIs( t, "statement_block" ); +} +inline bool dispatch_isIf( const char* t ) noexcept +{ + return kindIs( t, "if_statement" ) || kindIs( t, "if_expression" ); +} +inline bool dispatch_isSwitch( const char* t ) noexcept +{ + return kindIs( t, "switch_statement" ) || kindIs( t, "switch_expression" ) || kindIs( t, "match_expression" ); +} +inline bool dispatch_isCaseArm( const char* t ) noexcept +{ + static constexpr std::string_view kArms[] = { "case_statement", "switch_case", "switch_default", "switch_block_statement_group", "switch_rule", + "switch_section", "match_arm" }; + return std::find( std::begin( kArms ), std::end( kArms ), std::string_view( t ) ) != std::end( kArms ); +} + +// The arms of the if / else-if chain that starts at `n`: Python counts its elif/else clauses, every other grammar follows the +// alternative links (an else_clause wrapper in C, C++, JS/TS and Rust; the bare statement in Java, C# and Go). +inline std::uint32_t dispatch_ifChainArms( TSNode n ) +{ + std::uint32_t arms = 1; + bool clauses = false; // Python: the elif / else clauses are the if's own children, not a chain of ifs + { + ChildCursor cursor( n ); + forEachChild( n, cursor.cur, [ & ]( TSNode c ) + { + const char* t = ts_node_type( c ); + if( kindIs( t, "elif_clause" ) || ( kindIs( t, "else_clause" ) && !ts_node_is_null( fieldChild( c, NodeField::Body ) ) ) ) + { + ++arms; + clauses = true; + } + return true; + } ); + } + for( TSNode cur = n; !clauses && arms < 1000u; ) + { + TSNode alt = fieldChild( cur, NodeField::Alternative ); + if( ts_node_is_null( alt ) ) + { + break; + } + if( kindIs( ts_node_type( alt ), "else_clause" ) && ts_node_named_child_count( alt ) > 0 ) + { + alt = ts_node_named_child( alt, ts_node_named_child_count( alt ) - 1u ); + } + ++arms; + if( !dispatch_isIf( ts_node_type( alt ) ) ) + { + break; // the final else + } + cur = alt; + } + return arms; +} + +inline std::uint32_t dispatch_switchArms( TSNode n ) +{ + const TSNode body = fieldChild( n, NodeField::Body ); + const TSNode box = ts_node_is_null( body ) ? n : body; + std::uint32_t arms = 0; + ChildCursor cursor( box ); + forEachChild( box, cursor.cur, [ & ]( TSNode c ) { arms += dispatch_isCaseArm( ts_node_type( c ) ) ? 1u : 0u; return true; } ); + return arms; +} + +// True when the control `n`, popped in state `st`, opens a dispatch (state None, enough arms) or continues one (an else-if link a +// grammar walks as its own frame, state Structure). Only ever asked inside a tangle walk (tangleOn). +inline bool dispatch_opensOrLinks( TSNode n, const char* t, ChainState st, bool elseIf ) +{ + if( st == ChainState::Structure ) + { + return dispatch_isIf( t ); + } + if( st != ChainState::None ) + { + return false; + } + if( dispatch_isIf( t ) ) + { + return !elseIf && dispatch_ifChainArms( n ) >= kDispatchMinArms; + } + return dispatch_isSwitch( t ) && dispatch_switchArms( n ) >= kDispatchMinArms; +} + +// The state a child of `parent` is pushed with. `link`: `parent` opened or continues a dispatch (dispatch_opensOrLinks), so its +// consequence and its final else block are arms, a switch's body holds the arms, and the rest is the construct's structure. +inline ChainState dispatch_childState( TSNode parent, ChainState parentState, bool link, TSNode child ) +{ + const char* ct = ts_node_type( child ); + if( link ) + { + if( ts_node_eq( child, fieldChild( parent, NodeField::Consequence ) ) + || ( dispatch_isBlock( ct ) && ts_node_eq( child, fieldChild( parent, NodeField::Alternative ) ) ) ) + { + return dispatch_armState( child ); + } + if( dispatch_isSwitch( ts_node_type( parent ) ) && ts_node_eq( child, fieldChild( parent, NodeField::Body ) ) ) + { + return ChainState::SwitchBody; + } + return ChainState::Structure; + } + switch( parentState ) + { + case ChainState::SwitchBody: return dispatch_isCaseArm( ct ) ? dispatch_armState( child ) : ChainState::Structure; + case ChainState::Structure: return dispatch_isBlock( ct ) ? dispatch_armState( child ) : ChainState::Structure; // an else / elif clause's body + case ChainState::Arm: return ChainState::Arm; + case ChainState::None: return ChainState::None; + } + return ChainState::None; +} + // An ALTERNATIVE-introducing preprocessor node: `#else` / `#elif` / `#elifdef` inside the def mean the // body carries code that never coexists at compile time, so every summed structural metric (cx/ccx/nest/ @@ -365,7 +525,7 @@ inline bool cc_isPreprocAlternative( const char* t ) noexcept // children in reverse, so pops run left to right), so a hump starting on the line the previous one ended is // clamped to start after it. The clamp can only ever SUBTRACT: if the order assumption is ever violated the // result is an under-count, never an over-count, which is exactly why deepLoc is published as a floor. -inline void cc_noteHump( TSNode n, std::uint32_t fromNesting, std::uint32_t toNesting, CcAccum& acc ) noexcept +inline void cc_noteHump( TSNode n, std::uint32_t fromNesting, std::uint32_t toNesting, CcAccum& acc, bool inDispatchArm = false ) noexcept { if( fromNesting >= quality::kNestBar || toNesting < quality::kNestBar ) { @@ -378,11 +538,422 @@ inline void cc_noteHump( TSNode n, std::uint32_t fromNesting, std::uint32_t toNe if( endRow >= from ) { acc.deepLoc += endRow - from + 1u; + acc.deepDispatch += inDispatchArm ? endRow - from + 1u : 0u; // QD-TANGLE: a short dispatch arm's own depth (ChainState) } if( endRow > acc.deepEnd ) { acc.deepEnd = endRow; } + if( acc.detail != nullptr && endRow >= from && !inDispatchArm ) + { + acc.detail->humps.push_back( { from, endRow } ); // the span deepLoc billed — the region a tangle row's fix= names + } +} + +// ═══ QD-TANGLE steering locals (STAGE0 2.1; model.h Symbol::steer) ═══════════════════════════════════════════════════ +// +// A STEERING LOCAL is a local of a primitive written type that is written again after its declaration and read in a branch +// condition 10 or more statements after its last preceding write: the flag or counter set in one step that steers a branch in +// another. A flag set and tested in the same step does not count, and neither does a loop's own induction variable (a +// declaration in a for head is no slot). Three facts per node, read in the fused walk's document order: is it a STATEMENT (the +// distance clock), a DECLARATION of a primitive local (a new slot), or a WRITE to a slot; and at every branch, the identifiers +// its condition reads. Per-language shapes, verified against the vendored grammars by test/tanglecheck.sh's fixtures; a shape +// this table does not know is no slot (fewer steering locals, never a wrong one). +inline constexpr std::uint32_t kSteerStmts = 10; // the distance, in statements, that makes a read "far" from its write + +inline bool steer_isStatement( const char* t ) noexcept +{ + const std::size_t n = std::strlen( t ); + constexpr std::string_view kStmt = "_statement"; + if( n > kStmt.size() && std::string_view( t + n - kStmt.size(), kStmt.size() ) == kStmt ) + { + return !kindIs( t, "compound_statement" ); // a C-family block is a container, not a step + } + return kindIs( t, "declaration" ) || kindIs( t, "lexical_declaration" ) || kindIs( t, "variable_declaration" ) + || kindIs( t, "local_variable_declaration" ) || kindIs( t, "short_var_declaration" ) || kindIs( t, "let_declaration" ); +} + +// A literal of a primitive value (number, boolean, string, char) in any steered grammar — the initializer that makes an untyped +// declaration (Python, an untyped `let`, Go's `:=`) a primitive local. +inline bool steer_isPrimitiveLiteral( const char* t ) noexcept +{ + static constexpr std::string_view kLits[] = { + "number_literal", "number", "integer", "float", "true", "false", "string", "string_literal", "char_literal", + "decimal_integer_literal", "hex_integer_literal", "decimal_floating_point_literal", "integer_literal", "real_literal", + "boolean_literal", "int_literal", "float_literal", "interpreted_string_literal", "raw_string_literal", "character_literal", + }; + const std::string_view v( t ); + return std::find( std::begin( kLits ), std::end( kLits ), v ) != std::end( kLits ); +} + +// A written type that names a primitive: the grammar's own primitive node, or a typedef spelling of one (size_t, uint32_t, u32 … +// arrive as type_identifier in some grammars and as std::size_t qualified in C++). +inline bool steer_isPrimitiveType( TSNode type, std::string_view src ) noexcept +{ + if( ts_node_is_null( type ) ) + { + return false; + } + const char* t = ts_node_type( type ); + if( kindIs( t, "primitive_type" ) || kindIs( t, "sized_type_specifier" ) || kindIs( t, "integral_type" ) || kindIs( t, "floating_point_type" ) + || kindIs( t, "boolean_type" ) ) + { + return true; + } + std::string_view text = nodeTextOf( type, src ); + if( kindIs( t, "type_annotation" ) ) // TS `: number` — the annotation wraps the type + { + const TSNode inner = ts_node_named_child( type, 0 ); + text = nodeTextOf( inner, src ); + } + if( text.starts_with( "std::" ) ) + { + text.remove_prefix( 5 ); + } + static constexpr std::string_view kNames[] = { + "size_t", "ssize_t", "ptrdiff_t", "intptr_t", "uintptr_t", "int8_t", "int16_t", "int32_t", "int64_t", "uint8_t", "uint16_t", + "uint32_t", "uint64_t", "u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64", "u_int", "u_char", "u_short", "u_long", + "int", "uint", "bool", "char", "long", "short", "float", "double", "number", "boolean", "string", "usize", "isize", "byte", + "rune", "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", "float32", "float64", "sbyte", "ushort", + "ulong", "decimal", "str", + }; + return std::find( std::begin( kNames ), std::end( kNames ), text ) != std::end( kNames ); +} + +inline CcAccum::SteerSlot* steer_find( CcAccum& acc, std::string_view name ) noexcept +{ + for( std::size_t i = acc.slots.size(); i > 0; --i ) + { + if( acc.slots[ i - 1 ].name == name ) + { + return &acc.slots[ i - 1 ]; + } + } + return nullptr; +} + +inline void steer_declare( CcAccum& acc, TSNode nameNode, bool prim, std::string_view src ) +{ + if( ts_node_is_null( nameNode ) || !kindIs( ts_node_type( nameNode ), "identifier" ) ) + { + return; // a pattern, a pointer or a destructuring declarator: no single name, no slot + } + CcAccum::SteerSlot slot; + slot.name = nodeTextOf( nameNode, src ); + slot.lastWrite = acc.stmt; + slot.lastWriteRow = ts_node_start_point( nameNode ).row + 1u; + slot.prim = prim; + acc.slots.push_back( slot ); +} + +inline void steer_write( CcAccum& acc, TSNode target, std::string_view src ) +{ + if( ts_node_is_null( target ) || !kindIs( ts_node_type( target ), "identifier" ) ) + { + return; // a member, an element or a dereference: not a local's own write + } + if( CcAccum::SteerSlot* slot = steer_find( acc, nodeTextOf( target, src ) ) ) + { + slot->rewritten = true; + slot->lastWrite = acc.stmt; + slot->lastWriteRow = ts_node_start_point( target ).row + 1u; + acc.anyRewritten = acc.anyRewritten || slot->prim; + } +} + +// True when `n` is in a for-loop head (an induction variable, never a slot). +inline bool steer_inForHead( TSNode n ) noexcept +{ + const TSNode p = parentOf( n ); + if( ts_node_is_null( p ) ) + { + return false; + } + const char* pt = ts_node_type( p ); + return std::strncmp( pt, "for", 3 ) == 0; // for_statement, for_range_loop, for_in_statement, for_clause +} + +// The C-family declaration: `[const] TYPE a = 1, b;` — every declarator slot, primitive by the written type, never a const one. +inline void steer_cDeclaration( CcAccum& acc, TSNode n, std::string_view src ) +{ + bool isConst = false; + { + ChildCursor cursor( n ); + forEachChild( n, cursor.cur, [ & ]( TSNode c ) + { + if( kindIs( ts_node_type( c ), "type_qualifier" ) && nodeTextOf( c, src ).starts_with( "const" ) ) { isConst = true; } + return !isConst; + } ); + } + if( isConst ) + { + return; + } + const bool prim = steer_isPrimitiveType( fieldChild( n, NodeField::Type ), src ); + forEachDeclaratorSlot( n, [ & ]( TSNode d ) + { + steer_declare( acc, kindIs( ts_node_type( d ), "init_declarator" ) ? fieldChild( d, NodeField::Declarator ) : d, prim, src ); + } ); +} + +// One declarator list (JS/TS variable_declarator, Java/C# variable_declarator): the name, and primitive by the declaration's +// written type or, untyped, by its initializer. +inline void steer_declaratorList( CcAccum& acc, TSNode n, bool typePrim, std::string_view src ) +{ + ChildCursor cursor( n ); + forEachChild( n, cursor.cur, [ & ]( TSNode c ) + { + if( !kindIs( ts_node_type( c ), "variable_declarator" ) ) + { + return true; + } + TSNode name = fieldChild( c, NodeField::Name ); + if( ts_node_is_null( name ) ) + { + name = ts_node_named_child( c, 0 ); // C#: the identifier is the declarator's first named child + } + const TSNode value = fieldChild( c, NodeField::Value ); + const bool prim = typePrim || steer_isPrimitiveType( fieldChild( c, NodeField::Type ), src ) + || ( !ts_node_is_null( value ) && steer_isPrimitiveLiteral( ts_node_type( value ) ) ); + steer_declare( acc, name, prim, src ); + return true; + } ); +} + +// Python has no declaration: the FIRST binding of a bare name is its declaration (primitive by a literal, a len()/int()/str()/ +// float()/bool() call, or an int/str/bool/float annotation); every later one is a write. +inline void steer_pythonAssignment( CcAccum& acc, TSNode n, std::string_view src ) +{ + const TSNode left = fieldChild( n, NodeField::Left ); + if( ts_node_is_null( left ) || !kindIs( ts_node_type( left ), "identifier" ) ) + { + return; + } + const std::string_view name = nodeTextOf( left, src ); + if( name == "self" || name == "cls" ) + { + return; + } + if( steer_find( acc, name ) != nullptr || kindIs( ts_node_type( n ), "augmented_assignment" ) ) + { + steer_write( acc, left, src ); + return; + } + const TSNode right = fieldChild( n, NodeField::Right ); + bool prim = steer_isPrimitiveType( fieldChild( n, NodeField::Type ), src ); + if( !prim && !ts_node_is_null( right ) ) + { + const char* rt = ts_node_type( right ); + if( steer_isPrimitiveLiteral( rt ) ) + { + prim = true; + } + else if( kindIs( rt, "call" ) ) + { + const std::string_view fn = nodeFieldText( right, NodeField::Function, src ); + prim = fn == "len" || fn == "int" || fn == "str" || fn == "float" || fn == "bool"; + } + } + steer_declare( acc, left, prim, src ); +} + +// The declaration shapes, per grammar. True when `n` was a declaration (its children are still walked: an initializer can write). +inline bool steer_noteDeclaration( CcAccum& acc, TSNode n, const char* t, Lang lang, std::string_view src ) +{ + if( lang == Lang::Python ) + { + if( kindIs( t, "assignment" ) || kindIs( t, "augmented_assignment" ) ) + { + steer_pythonAssignment( acc, n, src ); + return true; + } + return false; + } + const bool cFamily = lang == Lang::Cpp || lang == Lang::C || lang == Lang::ObjC; + if( cFamily && kindIs( t, "declaration" ) ) + { + if( !steer_inForHead( n ) ) + { + steer_cDeclaration( acc, n, src ); + } + return true; + } + if( ( lang == Lang::TypeScript || lang == Lang::JavaScript ) && ( kindIs( t, "lexical_declaration" ) || kindIs( t, "variable_declaration" ) ) ) + { + if( !steer_inForHead( n ) && !nodeTextOf( n, src ).starts_with( "const" ) ) + { + steer_declaratorList( acc, n, false, src ); + } + return true; + } + if( lang == Lang::Java && kindIs( t, "local_variable_declaration" ) ) + { + if( !steer_inForHead( n ) && !nodeTextOf( n, src ).starts_with( "final" ) ) + { + steer_declaratorList( acc, n, steer_isPrimitiveType( fieldChild( n, NodeField::Type ), src ), src ); + } + return true; + } + if( lang == Lang::CSharp && kindIs( t, "variable_declaration" ) ) + { + const TSNode p = parentOf( n ); + if( !ts_node_is_null( p ) && kindIs( ts_node_type( p ), "local_declaration_statement" ) && !nodeTextOf( p, src ).starts_with( "const" ) ) + { + steer_declaratorList( acc, n, steer_isPrimitiveType( fieldChild( n, NodeField::Type ), src ), src ); + } + return true; + } + if( lang == Lang::Go && kindIs( t, "short_var_declaration" ) ) + { + if( !steer_inForHead( n ) ) + { + const TSNode left = fieldChild( n, NodeField::Left ); + const TSNode right = fieldChild( n, NodeField::Right ); + const std::uint32_t names = ts_node_is_null( left ) ? 0u : ts_node_named_child_count( left ); + for( std::uint32_t i = 0; i < names; ++i ) + { + const TSNode value = ts_node_is_null( right ) ? TSNode{} : ts_node_named_child( right, i ); + steer_declare( acc, ts_node_named_child( left, i ), !ts_node_is_null( value ) && steer_isPrimitiveLiteral( ts_node_type( value ) ), src ); + } + } + return true; + } + if( lang == Lang::Go && kindIs( t, "var_spec" ) ) + { + const TSNode value = fieldChild( n, NodeField::Value ); + const bool prim = steer_isPrimitiveType( fieldChild( n, NodeField::Type ), src ) + || ( !ts_node_is_null( value ) && ts_node_named_child_count( value ) > 0 && steer_isPrimitiveLiteral( ts_node_type( ts_node_named_child( value, 0 ) ) ) ); + steer_declare( acc, fieldChild( n, NodeField::Name ), prim, src ); + return true; + } + if( lang == Lang::Rust && kindIs( t, "let_declaration" ) ) + { + if( !ts_node_is_null( firstChildOfType( n, "mutable_specifier" ) ) ) + { + const TSNode value = fieldChild( n, NodeField::Value ); + const bool prim = steer_isPrimitiveType( fieldChild( n, NodeField::Type ), src ) + || ( !ts_node_is_null( value ) && steer_isPrimitiveLiteral( ts_node_type( value ) ) ); + steer_declare( acc, fieldChild( n, NodeField::Pattern ), prim, src ); + } + return true; + } + return false; +} + +// A write to a bare name, in any steered grammar: assignment (plain and compound) and increment/decrement. +inline void steer_noteWrite( CcAccum& acc, TSNode n, const char* t, std::string_view src ) +{ + if( kindIs( t, "assignment_expression" ) || kindIs( t, "augmented_assignment_expression" ) || kindIs( t, "compound_assignment_expr" ) ) + { + steer_write( acc, fieldChild( n, NodeField::Left ), src ); + } + else if( kindIs( t, "assignment_statement" ) ) // Go: `a, b = …` / `a += …` + { + const TSNode left = fieldChild( n, NodeField::Left ); + const std::uint32_t names = ts_node_is_null( left ) ? 0u : ts_node_named_child_count( left ); + for( std::uint32_t i = 0; i < names; ++i ) + { + steer_write( acc, ts_node_named_child( left, i ), src ); + } + } + else if( kindIs( t, "update_expression" ) || kindIs( t, "inc_statement" ) || kindIs( t, "dec_statement" ) ) + { + const TSNode arg = fieldChild( n, NodeField::Argument ); + steer_write( acc, ts_node_is_null( arg ) ? ts_node_named_child( n, 0 ) : arg, src ); + } + else if( kindIs( t, "postfix_unary_expression" ) || kindIs( t, "prefix_unary_expression" ) ) // C#: only ++ / -- write + { + const std::string_view text = nodeTextOf( n, src ); + if( text.starts_with( "++" ) || text.starts_with( "--" ) || text.ends_with( "++" ) || text.ends_with( "--" ) ) + { + steer_write( acc, ts_node_named_child( n, 0 ), src ); + } + } +} + +// Per named node, before the walk dispatches on it: the statement clock, then a declaration or a write. +inline void steer_noteNode( CcAccum& acc, TSNode n, const char* t, Lang lang, std::string_view src ) +{ + if( steer_isStatement( t ) ) + { + ++acc.stmt; + } + if( !steer_noteDeclaration( acc, n, t, lang, src ) ) + { + steer_noteWrite( acc, n, t, src ); + } +} + +// A branch's condition: every identifier it reads (a member's own name and a callee's name are not reads of a local). The +// condition is small, so a bounded explicit stack is enough; a slot that steers is counted once. +inline void steer_noteCondition( CcAccum& acc, TSNode branch, std::string_view src ) +{ + if( !acc.anyRewritten ) + { + return; // nothing written since its declaration yet: no read can be far from a rewrite + } + TSNode cond = fieldChild( branch, NodeField::Condition ); + if( ts_node_is_null( cond ) ) + { + cond = fieldChild( branch, NodeField::Value ); // JS/TS switch, Go expression switch + } + if( ts_node_is_null( cond ) ) + { + return; + } + TSNode stack[ 64 ]; + std::size_t depth = 0; + stack[ depth++ ] = cond; + while( depth > 0 ) + { + const TSNode c = stack[ --depth ]; + const char* t = ts_node_type( c ); + if( kindIs( t, "identifier" ) ) + { + CcAccum::SteerSlot* slot = steer_find( acc, nodeTextOf( c, src ) ); + if( slot != nullptr && slot->prim && slot->rewritten && !slot->steered && acc.stmt - slot->lastWrite >= kSteerStmts ) + { + slot->steered = true; + ++acc.steered; + if( acc.detail != nullptr ) + { + acc.detail->steer.push_back( { std::string( slot->name ), slot->lastWriteRow, ts_node_start_point( c ).row + 1u } ); + } + } + continue; + } + // a member access reads its OBJECT only (Python `self.done`, Java `this.done`, C# `x.Done`); a call's callee is no local + TSNode only = TSNode{}; + if( kindIs( t, "attribute" ) || kindIs( t, "field_access" ) ) + { + only = fieldChild( c, NodeField::Object ); + } + else if( kindIs( t, "member_access_expression" ) ) + { + only = fieldChild( c, NodeField::Expression ); + } + else if( kindIs( t, "call_expression" ) || kindIs( t, "call" ) || kindIs( t, "method_invocation" ) || kindIs( t, "invocation_expression" ) ) + { + only = fieldChild( c, NodeField::Arguments ); + } + else if( kindIs( t, "lambda_expression" ) || kindIs( t, "lambda" ) || kindIs( t, "arrow_function" ) || kindIs( t, "closure_expression" ) ) + { + continue; + } + if( !ts_node_is_null( only ) ) + { + if( depth < std::size( stack ) ) + { + stack[ depth++ ] = only; + } + continue; + } + const std::uint32_t kids = ts_node_named_child_count( c ); + for( std::uint32_t i = kids; i > 0 && depth < std::size( stack ); --i ) + { + stack[ depth++ ] = ts_node_named_child( c, i - 1 ); + } + } } // ═══ essential complexity ev(G) — the syntactic single-exit reduction (the essential-complexity design note) ═══ @@ -1049,10 +1620,14 @@ inline void cc_walk( TSNode start, std::uint32_t startNesting, std::string_view // iterative pre-order DFS — an EXPLICIT frame stack, not recursion: worker threads get 512 KB stacks on // macOS, so a deep AST overflows the call stack well inside the depth guard. Children are pushed in // reverse so pops preserve the original left-to-right visit order; the guard bounds the heap stack. - struct CcFrame { TSNode node; std::uint32_t nesting; std::uint32_t ctrl; std::uint16_t depth; }; // ctrl: innermost enclosing ev arena index (kNoCtrl at root) + // ctrl: innermost enclosing ev arena index (kNoCtrl at root); chain: where the frame sits in a flat dispatch (tangle walks only) + struct CcFrame { TSNode node; std::uint32_t nesting; std::uint32_t ctrl; std::uint16_t depth; ChainState chain; }; std::vector stack; stack.reserve( 64 ); - stack.push_back( { start, startNesting, kNoCtrl, static_cast( startDepth ) } ); + stack.push_back( { start, startNesting, kNoCtrl, static_cast( startDepth ), ChainState::None } ); + // the state each child is pushed with: None for every walk outside the tangle score (tangleOn), so nothing else changes + const auto childChain = [ &acc ]( TSNode parent, ChainState st, bool link, TSNode child ) + { return acc.tangleOn ? dispatch_childState( parent, st, link, child ) : ChainState::None; }; ChildCursor cursor( start ); std::vector kids; kids.reserve( 64 ); std::vector elifKids; elifKids.reserve( 64 ); // the else-if grandchild descent below nests inside a kids iteration @@ -1092,6 +1667,11 @@ inline void cc_walk( TSNode start, std::uint32_t startNesting, std::string_view { continue; // quoted AST is not executed control flow } + // QD-TANGLE: the statement clock, a declaration or a write — before the dispatch below, so every named node is seen once. + if( acc.steerOn && isNamed ) + { + steer_noteNode( acc, n, t, lang, src ); + } const bool elixirDecision = elixirKeyword == "if" || elixirKeyword == "unless" || elixirKeyword == "for" || elixirKeyword == "with"; const bool elixirControl = elixirDecision || elixirKeyword == "case" || elixirKeyword == "cond" || elixirKeyword == "receive" || elixirKeyword == "try"; if( isNamed && ( isDecisionType( t, lang ) || elixirDecision || ( lang == Lang::Elixir && kindIs( t, "stab_clause" ) ) ) ) @@ -1133,11 +1713,16 @@ inline void cc_walk( TSNode start, std::uint32_t startNesting, std::string_view { acc.maxNest = childNest; // Q4: deepest control nesting reached } - cc_noteHump( n, nesting, childNest, acc ); // profile: did THIS control cross the bar? + cc_noteHump( n, nesting, childNest, acc, frame.chain == ChainState::Arm ); // profile: did THIS control cross the bar? + const bool link = acc.tangleOn && dispatch_opensOrLinks( n, t, frame.chain, elseIf ); + if( acc.steerOn ) + { + steer_noteCondition( acc, n, src ); // QD-TANGLE: the locals this branch's condition reads + } collectChildren( n, cursor.cur, kids ); for( std::size_t i = kids.size(); i > 0; --i ) { - stack.push_back( { kids[i - 1], childNest, ctrl, childDepth } ); + stack.push_back( { kids[i - 1], childNest, ctrl, childDepth, childChain( n, frame.chain, link, kids[i - 1] ) } ); } continue; } @@ -1145,6 +1730,10 @@ inline void cc_walk( TSNode start, std::uint32_t startNesting, std::string_view || kindIs( t, "elsif" ) ) ) // else / elif / else-if (+ Ruby `elsif`): flat +1 (cognitive) { acc.cog += 1u; + if( acc.steerOn ) + { + steer_noteCondition( acc, n, src ); // QD-TANGLE: Python's elif_clause carries its own condition (an else carries none) + } collectChildren( n, cursor.cur, kids ); for( std::size_t i = kids.size(); i > 0; --i ) { @@ -1152,6 +1741,11 @@ inline void cc_walk( TSNode start, std::uint32_t startNesting, std::string_view const char* ct = ts_node_type( c ); if( kindIs( ct, "if_statement" ) || kindIs( ct, "if_expression" ) ) { + if( acc.steerOn ) + { + steer_noteNode( acc, c, ct, lang, src ); // QD-TANGLE: the C-family else-if never becomes a frame — clock and condition here + steer_noteCondition( acc, c, src ); + } // C-family `else if`: descend into the if's CHILDREN so cognitive doesn't re-score it as a // fresh control — but cyclomatic still counts that `if` as a decision (parity with the old walk). // ev: that if never becomes a frame, so it gets its arena node HERE (Branch, weight 1 — 1:1 @@ -1159,9 +1753,10 @@ inline void cc_walk( TSNode start, std::uint32_t startNesting, std::string_view ++acc.cyclo; const std::uint32_t elifCtrl = ( evCtx != nullptr ) ? ev_appendCtrl( *evCtx, c, CtrlKind::Branch, 1, ctrl, lang, src ) : ctrl; collectChildren( c, cursor.cur, elifKids ); // NOT kids — that iteration is still live + const bool link = frame.chain == ChainState::Structure; // an else-if link of a dispatch chain for( std::size_t j = elifKids.size(); j > 0; --j ) { - stack.push_back( { elifKids[j - 1], nesting, elifCtrl, childDepth } ); + stack.push_back( { elifKids[j - 1], nesting, elifCtrl, childDepth, childChain( c, frame.chain, link, elifKids[j - 1] ) } ); } } else @@ -1175,7 +1770,7 @@ inline void cc_walk( TSNode start, std::uint32_t startNesting, std::string_view // the parent construct recorded this depth when IT crossed, and a clause opens no new // depth (matches Java/Go/C#, whose grammars have no clause node and were always flat). // (ev rides along untouched: `ctrl` is the clause's own arena index from ev_noteNode.) - stack.push_back( { c, nesting, ctrl, childDepth } ); + stack.push_back( { c, nesting, ctrl, childDepth, childChain( n, frame.chain, false, c ) } ); } } continue; @@ -1186,11 +1781,11 @@ inline void cc_walk( TSNode start, std::uint32_t startNesting, std::string_view { acc.maxNest = nesting + 1; // Q4: a lambda/closure body deepens nesting } - cc_noteHump( n, nesting, nesting + 1, acc ); + cc_noteHump( n, nesting, nesting + 1, acc, frame.chain == ChainState::Arm ); collectChildren( n, cursor.cur, kids ); for( std::size_t i = kids.size(); i > 0; --i ) { - stack.push_back( { kids[i - 1], nesting + 1, ctrl, childDepth } ); + stack.push_back( { kids[i - 1], nesting + 1, ctrl, childDepth, childChain( n, frame.chain, false, kids[i - 1] ) } ); } continue; } @@ -1203,19 +1798,25 @@ inline void cc_walk( TSNode start, std::uint32_t startNesting, std::string_view collectChildren( n, cursor.cur, kids ); for( std::size_t i = kids.size(); i > 0; --i ) { - stack.push_back( { kids[i - 1], nesting, ctrl, childDepth } ); + stack.push_back( { kids[i - 1], nesting, ctrl, childDepth, childChain( n, frame.chain, false, kids[i - 1] ) } ); } } } -struct Complexity { std::uint32_t cx; std::uint32_t ccx; std::uint32_t maxNest; std::uint32_t locals; std::uint32_t ppAlt; std::uint32_t humps; std::uint32_t deepLoc; std::uint32_t ev; std::array evWhy; }; +struct Complexity { std::uint32_t cx; std::uint32_t ccx; std::uint32_t maxNest; std::uint32_t locals; std::uint32_t ppAlt; std::uint32_t humps; std::uint32_t deepLoc; std::uint32_t ev; std::array evWhy; std::uint32_t steer; std::uint32_t deepDispatch; }; // `lang`: Phase 1 (local-variable-indexing) gates the locals accumulator to model.h's localsCountedLang // (C/C++ only, MVP scope) INSIDE the same fused walk — every other language pays one branch-not-taken // per node and gets locals=0, which the caller (this file, RawDef→Symbol) leaves at 0 and serialize.h // never emits (absent, not a bare "0" — see localsCountedLang's own comment). -inline Complexity complexityOf( TSNode root, std::string_view src, Lang lang ) // one fused DFS → cx, ccx, maxNest, locals, ppAlt, the nesting profile, AND ev +// QD-TANGLE: the steering-locals fact is walked only where the tangle score can be non-zero — a body over kTangleAmpLoc lines +// (S = T × log2(loc/50), so 0 at 50 or fewer) — in steerCountedLang. `detail` (tangleDetailOf only) collects the names and spans. +inline constexpr std::uint32_t kSteerMinRows = 51; +inline Complexity complexityOf( TSNode root, std::string_view src, Lang lang, TangleDetailFacts* detail = nullptr ) // one fused DFS → cx, ccx, maxNest, locals, ppAlt, the nesting profile, ev AND steer { PROFILE_SCOPE_DESCRIBE( "ingest/metrics: complexityOf one function (fused DFS)" ); // A4-F25: NOT noexcept — cc_walk (and kids here) allocate CcAccum acc; + acc.tangleOn = ts_node_end_point( root ).row - ts_node_start_point( root ).row + 1u >= kSteerMinRows; + acc.steerOn = acc.tangleOn && steerCountedLang( lang ); + acc.detail = detail; const bool countLocals = localsCountedLang( lang ); // essential complexity rides the SAME walk (zero new tree-sitter queries). ONE arena/label/pending set // across all top-level children — a goto and its label can sit in sibling statements — finalized once @@ -1237,7 +1838,7 @@ inline Complexity complexityOf( TSNode root, std::string_view src, Lang lang ) // locals = Phase 1 floor count ; ppAlt = preproc alternative branches (model.h Symbol::ppAlt) ; // humps/deepLoc = the nesting profile ; ev/evWhy = essential complexity (model.h Symbol) — // 0 outside evCountedLang, >= 1 inside it. - Complexity out{ 1u + acc.cyclo, acc.cog, acc.maxNest, acc.locals, acc.ppAlt, acc.humps, acc.deepLoc, 0u, {} }; + Complexity out{ 1u + acc.cyclo, acc.cog, acc.maxNest, acc.locals, acc.ppAlt, acc.humps, acc.deepLoc, 0u, {}, acc.steered, acc.deepDispatch }; if( evPtr != nullptr ) { ev_finalize( evCtx, out.ev, out.evWhy ); diff --git a/src/ingest_model.h b/src/ingest_model.h index d1be48c8a..c1b6e50c5 100644 --- a/src/ingest_model.h +++ b/src/ingest_model.h @@ -412,7 +412,9 @@ inline void assignSymbols( IngestResult& result, std::vector& rawDefs, b s.cx = d.cx; s.ccx = d.ccx; s.loc = d.loc; // Q4: physical line span - s.locals = d.locals; // Phase 1: local-decl floor count (C/C++ only; model.h localsCountedLang) + s.locals = std::uint16_t( d.locals > 65535u ? 65535u : d.locals ); // Phase 1: local-decl floor count (C/C++ only; model.h localsCountedLang); u16 saturating (model.h) + s.steer = d.steer; // QD-TANGLE steering locals (model.h Symbol::steer; 0 outside steerCountedLang and at 50 lines or fewer) + s.dispatchShare = tangleDispatchShare( d.deepLoc, d.deepDispatch ); // QD-TANGLE (model.h) s.ppAlt = d.ppAlt; // ppalt disclosure: preproc alternative branches in the body (model.h) s.params = d.params; // Q4: parameter count (fns/methods) s.paramsMin = std::uint8_t( d.paramsMin < 15 ? d.paramsMin : 15 ); // B2.2: fewest arguments a call can pass (0 = no bound); a 4-bit field — saturating LOWERS it, which only keeps candidates diff --git a/src/ingest_sidecap.h b/src/ingest_sidecap.h index c4bc9b9e9..91191704e 100644 --- a/src/ingest_sidecap.h +++ b/src/ingest_sidecap.h @@ -1889,7 +1889,9 @@ inline void applyAnnotationRename( RawDef& d, const AnnotationRename& renamed, T // complexityOf, the function-scope span, the def arm's IS-A / HAS-A / macro-body reference minting and Ruby's // reference and bind passes. Measured on 104 C++ header blobs: those were ~60% of this function's samples (cc_walk alone // ~30%, the reference arm's qualifier / receiver parent walks ~30%). -enum class TagsCapture : std::uint8_t { Full, DefinitionsOnly }; +// DefinitionsAndShape (QD-TANGLE D4): DefinitionsOnly plus each callable's cc_walk facts (ccx, nesting, deep lines, steering locals) — +// the best-since store's reading of a history blob (ingest.h tangleInputsOfBlob). +enum class TagsCapture : std::uint8_t { Full, DefinitionsOnly, DefinitionsAndShape }; /// 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. @@ -1901,7 +1903,8 @@ 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 full = mode == TagsCapture::Full; + const bool shape = full || mode == TagsCapture::DefinitionsAndShape; // the callables' cc_walk facts if( cursor == nullptr ) { return; @@ -2405,7 +2408,7 @@ void captureTagsFacts( TSQueryCursor* cursor, const LangEntry& le, std::uint32_t // 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 ] = fnOrMethod && full ? complexityOf( spanThroughBody ? body : metricNode, src, le.lang ) : Complexity{ 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, {} }; + const auto [ cxVal, ccxVal, nestVal, localsVal, ppAltVal, humpsVal, deepVal, evVal, evWhyVal, steerVal, dispatchVal ] = fnOrMethod && shape ? complexityOf( spanThroughBody ? body : metricNode, src, le.lang ) : Complexity{ 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 @@ -2436,6 +2439,8 @@ void captureTagsFacts( TSQueryCursor* cursor, const LangEntry& le, std::uint32_t // 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 ); + d.steer = fnOrMethod ? std::uint8_t( steerVal > 255u ? 255u : steerVal ) : std::uint8_t( 0 ); // QD-TANGLE (model.h Symbol::steer) + d.deepDispatch = fnOrMethod ? std::uint16_t( dispatchVal > 65535u ? 65535u : dispatchVal ) : std::uint16_t( 0 ); // QD-TANGLE (model.h Symbol::dispatchShare) // 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. diff --git a/src/main.cpp b/src/main.cpp index d28c379f8..79bc4f675 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -82,6 +82,7 @@ static_assert( rw::kTestGateCcxBarMirror == rw::quality::kCcxBar, "situ.h kTestG #include "binstale.h" // --doctor's tracked-binary-staleness check (git-order, not mtime) #include "codexdoctor.h" // --doctor --agent=codex: live binary/skills/hooks/MCP surface parity #include "crossref.h" // --stray-content / --whereis — the cross-branch content index +#include "qdbestsince.h" // D4: quality::tangleBestSince — the --quality-delta ratchet's history reader #include "darkflags.h" // --flags — the dark-content (compile/cmake/env gate) dashboard #include "flipimpact.h" // --flags --flip=NAME: the blast radius of turning ONE of those gates ON #include "layout.h" // --layout=STRUCT — computed field offsets + tripwires + mirror drift diff --git a/src/mcpverbs.h b/src/mcpverbs.h index 62a17a8b5..ed9fda251 100644 --- a/src/mcpverbs.h +++ b/src/mcpverbs.h @@ -33,6 +33,7 @@ #include "callhierarchy.h" // H14/M13: the shared 1-hop call-hierarchy computation — find_symbol / find_referencing_symbols #include "graphlegend.h" // §H4 §3.4: the ONE counts_floor= marker + shared graph-count legend wording (CLI ≡ MCP) #include "crossref.h" // the shared cross-branch content index (whereis / stray_content) +#include "qdbestsince.h" // D4: quality::tangleBestSince — quality_delta's ratchet (CLI parity) #include "darkflags.h" // the shared dark-content gate harvest (flags) #include "flipimpact.h" // the flags verb's `symbol` argument: one gate's flip blast radius #include "typeuse.h" // L7: the impact verb's type tier (CLI ≡ MCP) @@ -4766,7 +4767,7 @@ inline std::string connectText( const std::string& root, const std::vector& relPaths ) { return rw::quality::tangleBestSince( root, "HEAD", relPaths ); }; // the CLI's source oc.regs = rw::quality::computeDelta( ing, g, baseSel.snapshot, root, {}, rw::kDefaultMaxFileBytes, &oc.registerMacroExcluded, &oc.apiNewSurface, - nullptr, &oc.declinedCallExcluded, &oc.valueRefExcluded, rw::quality::KindScope{}, &historyUnread, &passes ); + nullptr, &oc.declinedCallExcluded, &oc.valueRefExcluded, rw::quality::KindScope{}, &historyUnread, &passes, &oc.extras ); historyUnread.renames = heal.renames.refusedPartial && baseSel.marker == std::string_view( "sidecar" ); // the CLI's own rule oc.historyJson = rw::quality::historyUnreadDisclosure( historyUnread ).second; @@ -5046,6 +5049,7 @@ inline std::pair qualityDeltaJson( const std::string& // #228 — the CLI root's head_basis= twin, present-only: absent means the archived HEAD tree. + ( oc.headBasis == nullptr ? std::string() : std::string( ",\"head_basis\":\"" ) + mcpdetail::jsonEscape( oc.headBasis ) + "\"" ) + oc.historyJson + + rw::quality::ratchetAttrsJson( oc.extras ) + ",\"at\":" + atJson + ",\"r\":["; bool first = true; for( const rw::quality::Regression& r : oc.regs ) @@ -5068,7 +5072,7 @@ inline std::pair qualityDeltaJson( const std::string& out += ",\"sym\":\"" + mcpdetail::jsonEscape( rw::quality::displaySym( r.sym, root ) ) + "\""; if( !( r.kind == "dead-code" ) && !( r.kind == "api-surface" && r.was == r.now ) ) { - out += ",\"was\":" + std::to_string( r.was ) + ",\"now\":" + std::to_string( r.now ); + out += ",\"was\":" + rw::quality::rowValueText( r, r.was ) + ",\"now\":" + rw::quality::rowValueText( r, r.now ); } } if( !r.path.empty() ) @@ -5099,6 +5103,13 @@ inline std::pair qualityDeltaJson( const std::string& { out += ",\"ceiling\":" + std::to_string( r.ceiling ); // QD-ENTRY-CEILING (mirrors the XML) } + for( const auto& [ name, text ] : { std::pair{ "why", &r.why }, { "fix", &r.fix }, { "locals", &r.locals } } ) + { + if( !text->empty() ) + { + out += ",\"" + std::string( name ) + "\":\"" + mcpdetail::jsonEscape( *text ) + "\""; // QD-TANGLE (mirrors the XML) + } + } out += "}"; } out += "],"; @@ -5107,9 +5118,10 @@ inline std::pair qualityDeltaJson( const std::string& if( !showStale && oc.regs.empty() && !oc.staleAcks.empty() ) { folded = out + "\"stale_by_kind\":\"" + mcpdetail::jsonEscape( rw::quality::staleByKindValue( oc.staleAcks ) ) - + "\",\"stale_next\":\"" + mcpdetail::jsonEscape( rw::nextFlag( "show_stale=", "true" ) ) + "\"}"; + + "\",\"stale_next\":\"" + mcpdetail::jsonEscape( rw::nextFlag( "show_stale=", "true" ) ) + "\"" + rw::quality::improvedJson( oc.extras.improved, root ) + "}"; } out += rw::quality::staleAcksJsonArray( oc.staleAcks ); // L2 — "sa":[...], same taxonomy the CLI's rows carry + out += rw::quality::improvedJson( oc.extras.improved, root ); // QD-CREDIT-ROW (the CLI's own renderer; absent when none) out += "}"; if( !folded.empty() && rw::foldPays( folded, out ) ) { diff --git a/src/model.h b/src/model.h index b8c59c637..e875eb8cc 100644 --- a/src/model.h +++ b/src/model.h @@ -17,6 +17,7 @@ #include "refnames.h" // rw::InternedText — Reference::calleeName / qualifier / recvVar (MEM-REF-SHRINK step 2) #include "infra/sharedOnce.h" // rw::sharedOnce — RefColdFields::block, the cold text block made on its first write +#include // std::log2 — tangleScore10 #include // std::sort — symbolsByFile below; std::binary_search — isJsTsBuiltinMember #include // IngestResult::rustCrateRoots — the per-run Rust crate-root table #include // std::tie — lessUnindexedExt's mixed-direction compare @@ -945,7 +946,22 @@ struct Symbol // with no declarator (a local forward decl, e.g. `struct Foo;`) now correctly counts as 0 rather than // the pre-fix "1". `--metrics` emits it as locals="N" locals_floor="1" (never a bare 0 for an // uncovered language — see localsCountedLang). - std::uint32_t locals = 0; + // u16, SATURATING at 65535 in ingest_model.h::assignSymbols (the cache record keeps the full u32): a def past that many local + // declarators is beyond every triage threshold, and the count is a floor already. Narrowed from u32 so `steer` below lands in the + // freed bytes and Symbol does not grow (the static_assert below holds unchanged). + std::uint16_t locals = 0; + // QD-TANGLE STEERING LOCALS (--quality-delta's tangle kind; gate test/tanglecheck.sh): how many locals of a primitive written type + // (bool/int/size_t/char/…; never `auto`, never const) are written again after their declaration AND read in a branch condition + // (if/while/for/switch/elif) 10 or more statements after their last preceding write — a flag or counter set in one place that + // steers a branch far away. Counted by the SAME fused cc_walk DFS (no new parse), only for functions/methods over 50 lines (the + // tangle score is 0 at 50 lines or fewer, so a shorter body is not walked for it) in steerCountedLang's languages. 0 elsewhere, + // and absent (never a bare 0) on --metrics there. Saturates at 255. + std::uint8_t steer = 0; + // QD-TANGLE FLAT DISPATCH: the share of deepLoc (in 255ths; 255 exactly when ALL of it) that lies inside short arms of a flat + // dispatch — a switch, or an if / else-if chain, of 4+ arms whose arm is at most 40 lines (ingest_metrics.h ChainState). Such an + // arm reads alone, like a row of a table, so the tangle score leaves those lines out (and the nesting past the bar with them, + // when every deep line is such an arm's). deepLoc itself is unchanged. Walked with `steer`, so 0 under the same conditions. + std::uint8_t dispatchShare = 0; // PPALT DISCLOSURE — count of ALTERNATIVE-introducing preprocessor nodes (`#else`/`#elif`/`#elifdef`) // inside the def, filled by the SAME fused cc_walk DFS that computes cx/ccx/maxNest/locals (zero new // tree-sitter queries). When > 0 the body carries branches that never coexist at compile time, so every @@ -1195,6 +1211,14 @@ inline bool localsCountedLang( Lang lang ) noexcept return lang == Lang::Cpp || lang == Lang::C; } +// QD-TANGLE steering locals (Symbol::steer): the languages whose declaration, assignment and condition shapes the walk reads +// (ingest_metrics.h steer_*). Every other language keeps steer 0, and the tangle score there is nesting and deep share alone. +inline bool steerCountedLang( Lang lang ) noexcept +{ + return lang == Lang::Cpp || lang == Lang::C || lang == Lang::ObjC || lang == Lang::Python || lang == Lang::TypeScript + || lang == Lang::JavaScript || lang == Lang::Java || lang == Lang::CSharp || lang == Lang::Go || lang == Lang::Rust; +} + // Essential-complexity coverage: 12 of the 18 CODE languages — every one EXCEPT Bash, PHP, Lua, Elixir, Dart and // Kotlin (Elixir and Dart landed without joining it, so their ev is withheld the same way). Bash (the // essential-complexity design note, §3.2.8: `break N`/`continue N` take a numeric @@ -1240,6 +1264,109 @@ struct LocalNameFact std::uint8_t declDepth = 0; }; +// QD-TANGLE SCORE (STAGE0 2.1; --quality-delta's tangle kind, --metrics tangle=). LENGTH AMPLIFIES TANGLE, NEVER STANDS ALONE: +// T (length-free) = max(0, nest - 3) one point per nesting level past 3 (quality::kNestBar 4 is the first counted) +// + 20 * deep / loc one point per 5 % of lines inside regions at nesting >= 4 (short flat-dispatch arms left out) +// + 100 * steer / loc one point per steering local per 100 lines (Symbol::steer) +// S = T * max(0, log2(loc / 50)) 0 at 50 lines or fewer, +1 multiplier per doubling of length; the bar is S >= 6 +// A short nested helper scores 0 (no length to amplify), and a long flat body or an orchestrator of named steps scores 0 (no tangle). +// Each input counts in units of an existing bar: a nesting level past kNestBar - 1, 1 in 20 lines inside a deep region, 1 steering +// local per 100 lines (the prototype's 1 per 50 statements: a body runs about two lines a statement). Kept in tenths, so every +// surface prints the same rounded number and a ratchet compares integers. +struct TangleInputs +{ + std::uint32_t loc = 0; // physical lines (Symbol::loc) + std::uint32_t nest = 0; // max control nesting, the tangle reading (3 at most when every deep line is a dispatch arm's) + std::uint32_t deep = 0; // deep lines the score counts: deepLoc less the short dispatch arms' share + std::uint32_t steer = 0; // steering locals +}; +inline constexpr std::uint32_t kTangleAmpLoc = 50; // the length the amplifier starts above +inline constexpr std::uint32_t kTangleNestFree = 3; // nesting levels that score nothing (quality::kNestBar - 1, asserted in quality.h) +inline constexpr std::uint32_t kTangleBar10 = 60; // the bar, S >= 6, in tenths + +// The dispatch share Symbol::dispatchShare stores: deepDispatch of deepLoc in 255ths, 255 only when every deep line is an arm's. +inline std::uint8_t tangleDispatchShare( std::uint32_t deepLoc, std::uint32_t deepDispatch ) noexcept +{ + if( deepDispatch == 0 || deepLoc == 0 ) + { + return 0; + } + if( deepDispatch >= deepLoc ) + { + return 255; + } + return std::uint8_t( std::min( 254u, ( deepDispatch * 255u + deepLoc / 2u ) / deepLoc ) ); +} + +// The inputs from the raw facts — the ONE rule a Symbol (tangleInputsOf) and a history blob's definition (ingest.h tangleInputsOfBlob) share. +inline TangleInputs tangleInputsFrom( std::uint32_t loc, std::uint32_t maxNest, std::uint32_t deepLoc, std::uint32_t steer, std::uint8_t dispatchShare ) noexcept +{ + TangleInputs in; + in.loc = loc; + in.steer = steer; + in.nest = maxNest; + in.deep = deepLoc; + if( dispatchShare == 255 ) + { + in.deep = 0; + in.nest = in.nest < kTangleNestFree ? in.nest : kTangleNestFree; // every deep line is a dispatch arm's: no depth past the bar is the body's + } + else if( dispatchShare > 0 ) + { + in.deep = deepLoc - ( deepLoc * dispatchShare + 127u ) / 255u; + } + return in; +} + +inline TangleInputs tangleInputsOf( const Symbol& s ) noexcept +{ + return tangleInputsFrom( s.loc, s.maxNest, s.deepLoc, s.steer, s.dispatchShare ); +} + +// T (length-free) as a real, and T and S in tenths — rounded half up, so every surface prints the same number. +inline double tangleT( const TangleInputs& in ) noexcept +{ + if( in.loc == 0 ) + { + return 0.0; + } + return double( in.nest > kTangleNestFree ? in.nest - kTangleNestFree : 0u ) + 20.0 * double( in.deep ) / double( in.loc ) + + 100.0 * double( in.steer ) / double( in.loc ); +} +inline std::uint32_t tangleT10( const TangleInputs& in ) noexcept +{ + return std::uint32_t( tangleT( in ) * 10.0 + 0.5 ); +} +inline std::uint32_t tangleScore10( const TangleInputs& in ) noexcept +{ + if( in.loc <= kTangleAmpLoc ) + { + return 0; + } + return std::uint32_t( tangleT( in ) * std::log2( double( in.loc ) / double( kTangleAmpLoc ) ) * 10.0 + 0.5 ); +} + +// QD-TANGLE detail (ingest.h tangleDetailOf): what a tangle row names, read by re-walking ONE function at --quality-delta time — never +// stored on a Symbol, never cached. A steering local with the line of the write before the far read and the read itself; a deep region +// (a hump: a control-nesting region that first reaches quality::kNestBar) with its 1-based line span. +struct TangleSteerHit +{ + std::string name; + std::uint32_t setLine = 0; + std::uint32_t readLine = 0; +}; +struct TangleHumpSpan +{ + std::uint32_t startLine = 0; + std::uint32_t endLine = 0; +}; +struct TangleDetailFacts +{ + bool ok = false; // false: the file did not parse or no node spans the function — the row then names no locals or span + std::vector steer; // in first-read order + std::vector humps; // in document order +}; + // An unresolved reference (call/usage). Resolved into an edge in the graph stage. // The prefix of a C++ call's memberPath that marks an ELEMENT-ACCESS receiver (Reference::memberPath, its C++ reading). inline constexpr std::string_view kCppElementMark = "[]"; diff --git a/src/qdbestsince.h b/src/qdbestsince.h new file mode 100644 index 000000000..404e4765f --- /dev/null +++ b/src/qdbestsince.h @@ -0,0 +1,219 @@ +#pragma once + +// qdbestsince.h — D4 BEST-SINCE (STAGE0 2.8, #697 idea 2): the history reader behind quality::BestSinceSource. +// +// The ratchet compares a symbol with its BEST value since a reference point, the last release tag reachable from the judged tip +// (`git describe --tags --abbrev=0`). This reads that history for the few files computeDelta names (the files of the functions a +// ratchet row could be about), measures every version with the index's own extraction (ingest.h tangleInputsInBlobs: the tags +// pass plus the callables' cc_walk), and folds each key's per-input minima and lowest score into flat sorted rows. Nothing is +// stored on disk: the walk is one ls-tree, one log and one cat-file batch per chunk over those files only, measured on demand. +// A symbol created after the tag is judged from its creation, because its first version is its first fold. + +#include "crossref.h" // crossref::gitListChecked / catFileBatch / isBlobSha / isNullSha — the read-only git plumbing +#include "ingest.h" // tangleInputsInBlobs +#include "quality.h" // BestSinceStore, pathQualifiedKey, foldTangleBest, gitOneLine, headSnapshotIngestMutex + +#include "btree.hpp" // gtl::btree_map — sorted iteration (house rule: never std::map) + +#include +#include +#include + +namespace rw::quality +{ + +inline constexpr std::uint32_t kBestSinceMaxBlobs = 512; // history versions measured per call, newest first; more = cut +inline constexpr std::size_t kBestSinceChunkBytes = 64u << 20; // blob bytes held at once: a chunk is read, measured, dropped + +// One version of one judged file: the blob and the ROOT-relative path the ingest keys it under. +struct HistoryBlob +{ + std::string sha; + std::string relPath; +}; + +// The git-relative spelling of a root-relative path and back: `prefix` is `git rev-parse --show-prefix` of the ingest root. +inline bool rootRelOfGitPath( std::string_view gitPath, std::string_view prefix, std::string& rel ) +{ + if( gitPath.empty() || gitPath.front() == '"' || !gitPath.starts_with( prefix ) ) + { + return false; // a C-quoted path (a tab, newline or quote in it) or one outside the root: not a judged file + } + rel.assign( gitPath.substr( prefix.size() ) ); + return true; +} + +// The versions of `relPaths` since `refSha`: each file's blob at the reference first, then every blob a non-merge commit in refSha..tip +// wrote, newest first; distinct (sha, path) pairs. nullopt when git could not list them. +inline std::optional> bestSinceBlobs( const std::string& root, const std::string& refSha, const std::string& tipSha, + const std::vector& relPaths, std::string_view prefix ) +{ + std::string pathspec; + for( const std::string& p : relPaths ) + { + pathspec += " " + shSingleQuote( p ); + } + std::vector out; + std::string rel; + const crossref::GitListing atRef = crossref::gitListChecked( root, "--literal-pathspecs ls-tree -r --full-name " + refSha + " --" + pathspec ); + if( !atRef.ok ) + { + return std::nullopt; + } + for( const std::string& line : atRef.lines ) + { + // " blob \t" + const std::size_t tab = line.find( '\t' ); + const std::vector fields = wsdetail::segmentsOf( std::string_view( line ).substr( 0, tab == std::string::npos ? 0 : tab ), ' ' ); + if( fields.size() == 3 && fields[1] == "blob" && crossref::isBlobSha( fields[2] ) && rootRelOfGitPath( std::string_view( line ).substr( tab + 1 ), prefix, rel ) ) + { + out.push_back( { std::string( fields[2] ), rel } ); + } + } + const crossref::GitListing log = crossref::gitListChecked( root, "--literal-pathspecs log --format= --raw --no-abbrev --no-renames " + refSha + ".." + tipSha + " --" + pathspec ); + if( !log.ok ) + { + return std::nullopt; + } + for( const std::string& line : log.lines ) + { + // ":100644 100644 M\t" — the new side; an all-zero sha is a delete + const std::size_t tab = line.find( '\t' ); + if( line.empty() || line.front() != ':' || tab == std::string::npos ) + { + continue; + } + const std::vector fields = wsdetail::segmentsOf( std::string_view( line ).substr( 1, tab - 1 ), ' ' ); + if( fields.size() >= 4 && crossref::isBlobSha( fields[3] ) && !crossref::isNullSha( fields[3] ) && rootRelOfGitPath( std::string_view( line ).substr( tab + 1 ), prefix, rel ) ) + { + out.push_back( { std::string( fields[3] ), rel } ); + } + } + std::vector distinct; + gtl::btree_map seen; + for( HistoryBlob& b : out ) + { + if( seen.emplace( b.sha + '\0' + b.relPath, 0 ).second ) + { + distinct.push_back( std::move( b ) ); + } + } + return distinct; +} + +// One chunk of versions measured and folded into `best` (key → packed best, `seen` per key). +inline void foldTangleChunk( const std::vector& chunk, const std::vector& bytes, gtl::btree_map& best, + BestSinceStore& store ) +{ + std::vector texts; + texts.reserve( chunk.size() ); + for( std::size_t i = 0; i < chunk.size(); ++i ) + { + texts.push_back( { chunk[i].relPath, bytes[i] } ); + } + std::vector measured; + { + std::lock_guard ingestLk( headSnapshotIngestMutex() ); // the blob pool installs queries into the process-global cache + measured = tangleInputsInBlobs( texts ); + } + for( std::size_t i = 0; i < chunk.size(); ++i ) + { + if( measured[i].status != BlobDefsStatus::Parsed ) + { + store.unread += measured[i].status == BlobDefsStatus::NoGrammar ? 0u : 1u; + continue; + } + ++store.blobs; + gtl::btree_map version; // this version's highest-scoring overload per key (computeSnapshot's rule) + for( const BlobTangleDef& d : measured[i].defs ) + { + const std::uint64_t key = pathQualifiedKey( chunk[i].relPath, d.scope, measured[i].lang == Lang::Elixir ? elixirBaseName( d.name ) : std::string_view( d.name ) ); + const auto [ it, fresh ] = version.emplace( key, d.in ); + if( !fresh && tangleOutranks( d.in, it->second ) ) + { + it->second = d.in; + } + } + for( const auto& [ key, in ] : version ) + { + const auto [ it, fresh ] = best.emplace( key, 0 ); + it->second = foldTangleBest( it->second, !fresh, in ); + } + } +} + +// THE SOURCE: the best-since store of every symbol in `relPaths` (root-relative), read from the history of the repo at `root` up to +// `tip` ("HEAD" for the working-tree form). An empty ref is the store's "not read" state (no tag, not a repo, git refused). +inline BestSinceStore tangleBestSince( const std::string& root, const std::string& tip, const std::vector& relPaths ) +{ + BestSinceStore store; + const std::string tipSha = gitResolveCommitSha( root, tip ); + if( tipSha.empty() || relPaths.empty() ) + { + return store; + } + const std::string ref = gitOneLine( root, "describe --tags --abbrev=0 " + tipSha + " 2>/dev/null" ); + const std::string refSha = ref.empty() ? std::string() : gitResolveCommitSha( root, "refs/tags/" + ref ); + if( refSha.empty() ) + { + return store; + } + const std::string prefix = gitOneLine( root, "rev-parse --show-prefix 2>/dev/null" ); + std::optional> blobs = bestSinceBlobs( root, refSha, tipSha, relPaths, prefix ); + if( !blobs ) + { + return store; + } + if( blobs->size() > kBestSinceMaxBlobs ) + { + // the reference versions first, then the log newest first: the cut keeps the reference and the recent versions, and says it cut + store.cut = true; + blobs->resize( kBestSinceMaxBlobs ); + } + gtl::btree_map best; + std::vector chunk; + std::vector bytes; + std::size_t held = 0; + const auto flush = [ & ]() + { + foldTangleChunk( chunk, bytes, best, store ); + chunk.clear(); + bytes.clear(); + held = 0; + }; + std::vector shas; + for( const HistoryBlob& b : *blobs ) + { + shas.push_back( b.sha ); + } + std::size_t next = 0; + const bool read = crossref::catFileBatch( root, shas, [ & ]( const std::string&, std::string_view type, std::string_view body ) + { + if( type == "blob" ) + { + chunk.push_back( ( *blobs )[ next ] ); + bytes.emplace_back( body ); + held += body.size(); + } + ++next; + if( held >= kBestSinceChunkBytes ) + { + flush(); + } + return true; + } ); + flush(); + if( !read ) + { + store.unread += std::uint32_t( shas.size() - std::min( next, shas.size() ) ); + } + store.ref = ref; + store.rows.reserve( best.size() ); + for( const auto& [ key, value ] : best ) + { + store.rows.push_back( { key, value } ); // btree order: sorted by key, as BestSinceStore::find reads it + } + return store; +} + +} // namespace rw::quality diff --git a/src/quality.h b/src/quality.h index 68cab79da..38d140237 100644 --- a/src/quality.h +++ b/src/quality.h @@ -59,11 +59,13 @@ #include // std::memcpy / std::memcmp — POD (de)serialization of the qsnap blob #include #include +#include // D4: BestSinceSource — the verb hands computeDelta its history reader #include // std::numeric_limits::max() — "no count cap" sentinel (evictOldCacheFamily) #include // Phase-M: serialize concurrent ingest() (prefetch worker vs request thread) #include // L2 — computeStaleAcks' per-kind dispatch: nullopt = "not stale" #include #include +#include // std::tie — the improved section's place order #include // std::is_trivially_copyable_v — the qsnap POD put/get static_assert #include #include // mergeBuiltinsWithConfig — a non-owning view over either built-in list @@ -85,7 +87,8 @@ constexpr std::uint32_t kCcxBar = 15; // P8 (L7): situ.h spells th // kCcxBar): defensible defaults, the loop applies judgment; report numbers, never gate a normal run. constexpr std::uint32_t kLocBar = 60; // "large function" LOC bar (below Sonar's 75 default) — a verbosity regression must END UP over it (SIZE is the master variable, §1d) constexpr std::uint32_t kNestBar = 4; // max-nesting-depth bar — deep nesting (>3-4) is the structural-erosion signal; a regression must end up over it -constexpr std::uint32_t kParamBar = 5; // param-count bar — a REGRESSION (grew AND now high), NOT the debunked absolute 7±2 rule (§1d kill-list); the growth is the signal, the bar just suppresses tiny-fn noise +constexpr std::uint32_t kParamBar = 5; +static_assert( kTangleNestFree == kNestBar - 1, "model.h's tangle score counts nesting from the nesting bar: one point per level past kNestBar - 1" ); // param-count bar — a REGRESSION (grew AND now high), NOT the debunked absolute 7±2 rule (§1d kill-list); the growth is the signal, the bar just suppresses tiny-fn noise // §D#4 / §E-17 — three GitClear-2026-backed kinds. Each fires ONLY on a regression vs baseline (the // quality-delta contract), never on pre-existing debt. See the per-kind comments in computeSnapshot/computeDelta. @@ -334,6 +337,11 @@ struct Snapshot gtl::btree_map bodyHashBySym; // §D#4 short-horizon-churn — pathQualifiedKey(path,scope,name) → fnv1a64 of the RAW body bytes (change detection; literal-only edits move NO metric, so metrics can't detect them). Path-qualified since v6: a bare canonId key folded every scope-less same-named symbol ACROSS FILES into one join identity (the W1-S2 cross-file churn misattribution) gtl::btree_map moveCidBySym; // QD-ENTRY-CEILING MOVED-BODY — qualityKey → moveCidOf (the scrubbed hash of the callable's BODY), recorded only for a function or method over the ccx or the line bar: the baseline half of "this new function is a body the same diff removed elsewhere" (origin="moved"). A sidecar or blob without it recognizes no move gtl::btree_map bodyCidBySym; // QD-RENAME-IDENTITY — qualityKey → moveCidOf of EVERY function or method (the MAX over overloads, read only where defsBySym is 1): the baseline half of "this new key is a vacated key's body under a new name or file" (ContentMoves). A sidecar or blob without it matches no rename + // QD-TANGLE — qualityKey → packTangle( tangleInputsOf ) of the overload with the highest score: recorded for a function or method over + // 50 lines, reaching the nesting bar, or with a steering local (tangleRecorded) — every other one scores 0 and reads as absent. A + // sidecar or blob without it (tangleKnown false) judges no tangle row. + gtl::btree_map tangleBySym; + bool tangleKnown = false; gtl::btree_map moveSketchBySym; // QD-ENTRY-CEILING MOVES — qualityKey → the clone matcher's minhash sketch (cloneSketchOfStream, 128 B) of the same body moveCidBySym identifies, so a body moved WITH a small edit is still recognized (MovedBodies). A sidecar or blob without it recognizes exact moves only std::vector cloneGroups; // sorted hash(sorted member canonIds) std::vector dead; // sorted hash(canonId) of dead-candidate symbols @@ -345,7 +353,48 @@ struct Snapshot std::vector renamedKeys; // sorted: the current keys the rename record re-filed (dead-code rows on them read origin="moved") }; -// ─── THE TWELVE KINDS AS A SET (qd-memory-degrade) ───────────────────────────────────────────────────────── +// QD-TANGLE's snapshot record: one u64 per key — loc (24 bits) | nest (8) | deep (16) | steer (8), each saturating (owner 11-05: +// packed per-symbol words). The inputs, not the score: a row says WHICH input rose, and the score is recomputed from them. +inline std::uint64_t packTangle( const TangleInputs& in ) noexcept +{ + return ( std::uint64_t( std::min( in.loc, 0xFFFFFFu ) ) << 32 ) | ( std::uint64_t( std::min( in.nest, 0xFFu ) ) << 24 ) + | ( std::uint64_t( std::min( in.deep, 0xFFFFu ) ) << 8 ) | std::uint64_t( std::min( in.steer, 0xFFu ) ); +} +inline TangleInputs unpackTangle( std::uint64_t v ) noexcept +{ + TangleInputs in; + in.loc = std::uint32_t( v >> 32 ) & 0xFFFFFFu; + in.nest = std::uint32_t( v >> 24 ) & 0xFFu; + in.deep = std::uint32_t( v >> 8 ) & 0xFFFFu; + in.steer = std::uint32_t( v ) & 0xFFu; + return in; +} +// Worth a record: anything that can score, or that a row's why= would name as the was= side of a rise. A key with no record has +// inputs nest < kNestBar, deep 0, steer 0, and 50 lines or fewer — S 0. +inline bool tangleRecorded( const TangleInputs& in ) noexcept +{ + return in.loc > kTangleAmpLoc || in.nest >= kNestBar || in.steer > 0; +} +// The overload set shares a key: keep the member with the highest score (then the larger packed word), so the record is order-independent. +inline bool tangleOutranks( const TangleInputs& a, const TangleInputs& b ) noexcept +{ + const std::uint32_t sa = tangleScore10( a ), sb = tangleScore10( b ); + return sa != sb ? sa > sb : packTangle( a ) > packTangle( b ); +} +inline void recordTangle( gtl::btree_map& m, std::uint64_t key, const TangleInputs& in ) +{ + if( !tangleRecorded( in ) ) + { + return; + } + const auto [ it, fresh ] = m.try_emplace( key, packTangle( in ) ); + if( !fresh && tangleOutranks( in, unpackTangle( it->second ) ) ) + { + it->second = packTangle( in ); + } +} + +// ─── THE THIRTEEN KINDS AS A SET (qd-memory-degrade) ───────────────────────────────────────────────────────── // --quality-kinds=K[,K] runs a subset of the kinds (the replay a degraded --quality-delta=A..B hands back), and the // degraded range form runs the subset its changed files can decide. Each kind stays a separately reported, separately // skippable unit: the mask decides which passes run and which rows are kept, never how a row is computed — a kind that @@ -353,12 +402,12 @@ struct Snapshot // of them (kinds_skipped=, the refusal, the help) is spelled in. inline constexpr std::string_view kQualityKindNames[] = { "api-surface", "complexity", "dead-code", "defect-shape", "duplication", "error-masking", "nesting", - "new-clone-of-reused-helper", "params", "placeholder", "short-horizon-churn", "verbosity", + "new-clone-of-reused-helper", "params", "placeholder", "short-horizon-churn", "tangle", "verbosity", }; using KindMask = std::uint16_t; inline constexpr KindMask kAllKinds = KindMask( ( 1u << std::size( kQualityKindNames ) ) - 1u ); -static_assert( std::size( kQualityKindNames ) == 12 && std::size( kQualityKindNames ) <= 16, "one bit per kind" ); -// the kind's bit, or 0 for a name that is not one of the twelve +static_assert( std::size( kQualityKindNames ) == 13 && std::size( kQualityKindNames ) <= 16, "one bit per kind" ); +// the kind's bit, or 0 for a name that is not one of the thirteen inline constexpr KindMask kindBit( std::string_view kind ) noexcept { const auto* const at = std::find( std::begin( kQualityKindNames ), std::end( kQualityKindNames ), kind ); @@ -3143,7 +3192,7 @@ inline std::string cacheRootKeyHex( const std::string& root ) // `static_assert( quality::kIngestParserVerMirror == kParserVer && … )`, so a missed mirror now fails the build. It does // not include this header; it relies on ingest.cpp including quality.h (line 13) before ingest_cache.h, and a reorder // that broke that fails the build on the undeclared name rather than passing. -constexpr std::uint32_t kIngestCacheVersionMirror = 52; // MUST equal ingest.cpp's kCacheVersion (gated); 52 = lane failure-default (construct-hit failure-default tag), 51 = lane qd-constructs (FILE record construct-hit family), 50 = lane clones-persist (Function/Method def record clone key), 49 = lane warm-direct (FILE record head family counts), 48 = train 42b (alias-import LocalBindKind ReExport; its placeholder 47), 46 = train 40 (js-def-naming JsObjectLiteral; its placeholder 45), 44 = train 37b (rust-degraded FileHealth::useBoundsBlanked; its placeholder 42), 43 = train 36 (#155 trailingLambda ref byte; above main 40, #438's placeholder 41, rust-degraded's 42), 40 = train 34 (fc3-js-rebind JsRebind; above main 39), 39 = train 33 (above main 36 and l6-iface 38), 38 = train 32 lane l6-iface fix round 1: LocalBindKind ImplBlock (train renumbers), 37 = train 32 lane l6-iface: LocalBindKind DispatchType (train renumbers), 36 = train 30 (above call-result-typing's and fcall-forward's 33, name-template-dispatch's 35, main's 34), 34 = train 29 (above lane arity-min's and call-result-typing's 33), 33 = train 29 lane arity-min: def record paramsMin (the train renumbers), 33 = lane call-result-typing: RawBind resultIndex + unwrapDepth, 33 = lane fcall-forward: ref `forwarded` byte, 35 = lane name-template-dispatch: RefRole Pattern 11, 32 = train 28: RefRole Subscript 9 + Inert 10, 31 = train 27: lego-transitive's inherit-ref baseBind (the lane's 30), 29 = FE-B ref memberPath/memberCtor + 4 bind kinds, 28 = FE-A ref memberCall/memberRoot, 27 = corrected fnScope values, 26 = function-local def scope span (25 = #157 + #150) +constexpr std::uint32_t kIngestCacheVersionMirror = 53; // MUST equal ingest.cpp's kCacheVersion (gated); 53 = lane qd-tangle (def record steering-locals byte), 52 = lane failure-default (construct-hit failure-default tag), 51 = lane qd-constructs (FILE record construct-hit family), 50 = lane clones-persist (Function/Method def record clone key), 49 = lane warm-direct (FILE record head family counts), 48 = train 42b (alias-import LocalBindKind ReExport; its placeholder 47), 46 = train 40 (js-def-naming JsObjectLiteral; its placeholder 45), 44 = train 37b (rust-degraded FileHealth::useBoundsBlanked; its placeholder 42), 43 = train 36 (#155 trailingLambda ref byte; above main 40, #438's placeholder 41, rust-degraded's 42), 40 = train 34 (fc3-js-rebind JsRebind; above main 39), 39 = train 33 (above main 36 and l6-iface 38), 38 = train 32 lane l6-iface fix round 1: LocalBindKind ImplBlock (train renumbers), 37 = train 32 lane l6-iface: LocalBindKind DispatchType (train renumbers), 36 = train 30 (above call-result-typing's and fcall-forward's 33, name-template-dispatch's 35, main's 34), 34 = train 29 (above lane arity-min's and call-result-typing's 33), 33 = train 29 lane arity-min: def record paramsMin (the train renumbers), 33 = lane call-result-typing: RawBind resultIndex + unwrapDepth, 33 = lane fcall-forward: ref `forwarded` byte, 35 = lane name-template-dispatch: RefRole Pattern 11, 32 = train 28: RefRole Subscript 9 + Inert 10, 31 = train 27: lego-transitive's inherit-ref baseBind (the lane's 30), 29 = FE-B ref memberPath/memberCtor + 4 bind kinds, 28 = FE-A ref memberCall/memberRoot, 27 = corrected fnScope values, 26 = function-local def scope span (25 = #157 + #150) constexpr std::uint32_t kIngestParserVerMirror = 331; // MUST equal ingest.cpp's kParserVer (gated) // 331 = 2026-11-18 (train 1117d1, rich 332; members below, each was a placeholder) // go-cpp-edges (placeholder 317): a Go generic result type `Set[T]` records its ReturnType as the instantiated class @@ -4556,7 +4605,7 @@ inline void evictOldHeadSnapCaches( const std::string& dir, const std::string& r // rustTestAttributed tests EVERY top-level attribute on a line (classifyRustAttributeLine), so `#[tokio::test(x)] #[allow(unused)]` // now exempts the fn below it, and a `#[` inside a string is text, so `#[doc = "#[tokio::test(x)]"]` no longer does. A v33 blob // holds the old set, so it is rejected. Bumped 33 -> 34. kParserVer stays: no extraction change. -constexpr std::uint32_t kQSnapCacheScheme = 34; +constexpr std::uint32_t kQSnapCacheScheme = 35; // 35: lane qd-tangle — the tangle map (tangleBySym) and its known byte, after bodyCidBySym constexpr char kQSnapMagic[4] = { 'Q', 'S', 'N', 'P' }; // The qsnap EXCLUDES-config key folds the qsnap SCHEME (independent of the ingest cache's kHeadSnapCacheScheme) @@ -4687,6 +4736,8 @@ inline std::string serializeSnapshot( const Snapshot& s, const std::string& head putHashMap( s.bodyHashBySym ); putHashMap( s.moveCidBySym ); // v28 (MOVED-BODY) putHashMap( s.bodyCidBySym ); // v30 (QD-RENAME-IDENTITY) + putHashMap( s.tangleBySym ); // v35 (QD-TANGLE), then whether it was recorded at all + qsnapPut( buf, std::uint8_t( s.tangleKnown ? 1 : 0 ) ); qsnapPut( buf, std::uint32_t( s.moveSketchBySym.size() ) ); // v29 (MOVES): key, then the 128 sketch bytes for( const auto& [ k, sk ] : s.moveSketchBySym ) { @@ -4787,6 +4838,16 @@ inline bool deserializeSnapshot( const std::string& blob, const std::string& hea } return true; }; + const auto getTangleKnown = [ & ]() -> bool + { + std::uint8_t known = 0; + if( !qsnapGet( p, end, known ) ) + { + return false; + } + s.tangleKnown = known != 0; + return true; + }; const auto getHashMap = [ & ]( gtl::btree_map& m ) -> bool { std::uint32_t n = 0; @@ -4864,7 +4925,7 @@ inline bool deserializeSnapshot( const std::string& blob, const std::string& hea return true; }; - if( !getValMap( s.ccxBySym ) || !getValMap( s.locBySym ) || !getValMap( s.nestBySym ) || !getValMap( s.paramsBySym ) || !getValMap( s.defsBySym ) || !getValMap( s.maskBySym ) || !getValMap( s.maskReportBySym ) || !getValMap( s.failureDefaultBySym ) || !getValMap( s.placeholderBySym ) || !getHashMap( s.bodyHashBySym ) || !getHashMap( s.moveCidBySym ) || !getHashMap( s.bodyCidBySym ) || !getSketchMap( s.moveSketchBySym ) || !getVec( s.cloneGroups ) || !getVec( s.dead ) || !getVec( s.publicApi ) + if( !getValMap( s.ccxBySym ) || !getValMap( s.locBySym ) || !getValMap( s.nestBySym ) || !getValMap( s.paramsBySym ) || !getValMap( s.defsBySym ) || !getValMap( s.maskBySym ) || !getValMap( s.maskReportBySym ) || !getValMap( s.failureDefaultBySym ) || !getValMap( s.placeholderBySym ) || !getHashMap( s.bodyHashBySym ) || !getHashMap( s.moveCidBySym ) || !getHashMap( s.bodyCidBySym ) || !getHashMap( s.tangleBySym ) || !getTangleKnown() || !getSketchMap( s.moveSketchBySym ) || !getVec( s.cloneGroups ) || !getVec( s.dead ) || !getVec( s.publicApi ) || !getDefectSites( s.defectSites ) ) { return false; @@ -6726,6 +6787,7 @@ inline Snapshot computeSnapshot( const IngestResult& ing, const Graph& g, std::s const std::vector* fileInBaseline, const KindScope& scope, TreePasses* passes ) { Snapshot snap; + snap.tangleKnown = true; // QD-TANGLE: this binary records the tangle inputs MoveIdentities moveIds; // MOVED-BODY: the move identity of every body over a bar std::vector codeLoc = codeLocByNode( ing, &moveIds ); // Q-DIAL-3: the verbosity kind's metric is CODE lines const std::vector& moveCid = moveIds.cid; @@ -6757,6 +6819,10 @@ inline Snapshot computeSnapshot( const IngestResult& ing, const Graph& g, std::s { std::uint32_t& slot = snap.locBySym[ key ]; slot = std::max( slot, codeLoc[i] ); } // Q-DIAL-3: CODE lines, not the physical span { std::uint32_t& slot = snap.nestBySym[ key ]; slot = std::max( slot, std::uint32_t( s.maxNest ) ); } { std::uint32_t& slot = snap.paramsBySym[ key ]; slot = std::max( slot, std::uint32_t( s.params ) ); } + if( s.kind == SymKind::Function || s.kind == SymKind::Method ) + { + recordTangle( snap.tangleBySym, key, tangleInputsOf( s ) ); // QD-TANGLE: the highest-scoring overload's inputs + } recordMoveIdentity( snap.moveCidBySym, key, moveCid[i] ); // overloads share a key: the MAX, so the record is order-independent recordMoveIdentity( snap.bodyCidBySym, key, moveIds.body[i] ); // QD-RENAME-IDENTITY: every callable (an overload set never matches) // THE ONE KIND THAT IS NOT A MAX, and the reason is the MAX itself. Every metric above collapses the @@ -7203,6 +7269,14 @@ inline bool writeBaseline( const Snapshot& s, const std::string& path, std::stri { f << "stub " << std::hex << h << std::dec << ' ' << v << '\n'; // the placeholder count } + if( s.tangleKnown ) + { + f << "tangleon 1\n"; // QD-TANGLE: the inputs were recorded (an empty map then means no function scores) + } + for( const auto& [h, v] : s.tangleBySym ) + { + f << "tangle " << std::hex << h << ' ' << v << std::dec << '\n'; // QD-TANGLE packed inputs (packTangle) + } for( const auto& [h, v] : s.defsBySym ) { f << "defs " << std::hex << h << std::dec << ' ' << v << '\n'; // overload-set CARDINALITY (a count, not a max) @@ -7392,7 +7466,7 @@ inline bool readBaseline( const std::string& path, Snapshot& out, BaselineReadSt if( is.fail() ) { DISCLOSE( stats, BaselineReadStats::DisclosureWhy::MalformedLine ); return; } m[h] = v; }; if( kind == "ccx" || kind == "loc" || kind == "nest" || kind == "params" || kind == "mask" || kind == "maskr" || kind == "maskfd" || kind == "stub" || kind == "body" || kind == "clone" || kind == "dead" || kind == "api" || kind == "head" || kind == "defs" - || kind == "producer" || kind == "defect" ) + || kind == "producer" || kind == "defect" || kind == "tangle" || kind == "tangleon" ) { ++recognizedLineCount; // structure seen — this file IS a baseline } @@ -7401,6 +7475,14 @@ inline bool readBaseline( const std::string& path, Snapshot& out, BaselineReadSt { readValMap( out.ccxBySym ); } + else if( kind == "tangleon" ) + { + out.tangleKnown = true; // QD-TANGLE: a sidecar without this line was written before the kind and judges no tangle row + } + else if( kind == "tangle" ) + { + readHashMap( out.tangleBySym ); + } else if( kind == "loc" ) { readValMap( out.locBySym ); @@ -7964,6 +8046,102 @@ inline std::uint32_t churnEditWindowCommitCount( DiffHunkMemo& memo, const std:: return std::uint32_t( shas.size() ); } +// ─── D4 BEST-SINCE — each symbol's best (lowest) value of a metric since a reference point (#697 idea 2; STAGE0 2.8) ───────────────── +// +// The reference point is the last release tag (`git describe --tags --abbrev=0`); a symbol created after it is judged from its creation. +// The store is computed from git history on demand by the verb (qdbestsince.h reads the blobs and the index's own extraction measures +// them), over the files of the symbols a row could be about only, and handed to computeDelta as flat sorted data: one (key, packed +// best) pair per symbol. Tangle is its first metric; a metric is a value packing plus a fold, so ccx / nest / params can join as rows of +// BestMetric with their own packing. A ratchet row is REPORT-ONLY (sev="minor") like every tangle row. +enum class BestMetric : std::uint8_t { Tangle }; +struct BestSinceRow +{ + std::uint64_t key = 0; // qualityKey (pathQualifiedKey of the current path) + std::uint64_t value = 0; // the metric's packed best: Tangle = packTangleBest +}; +struct BestSinceStore +{ + BestMetric metric = BestMetric::Tangle; + std::string ref; // the reference point's name ("" = none: no tag, not a git repo, history unreadable) + std::vector rows; // sorted by key + std::uint32_t blobs = 0; // history blobs measured + std::uint32_t unread = 0; // history blobs that could not be measured (a parse degrade, a missing object): their minima are absent + bool cut = false; // the blob cap stopped the walk: minima are over the newest blobs only + const BestSinceRow* find( std::uint64_t key ) const noexcept + { + const auto it = std::lower_bound( rows.begin(), rows.end(), key, []( const BestSinceRow& r, std::uint64_t k ) { return r.key < k; } ); + return it != rows.end() && it->key == key ? &*it : nullptr; + } +}; +// Tangle's best: the per-input minima (nest 8 | deep 16 | steer 8) and the lowest score (tenths, 24 bits) over every version measured. +inline std::uint64_t packTangleBest( const TangleInputs& minima, std::uint32_t minScore10 ) noexcept +{ + return ( std::uint64_t( std::min( minScore10, 0xFFFFFFu ) ) << 32 ) | ( std::uint64_t( std::min( minima.nest, 0xFFu ) ) << 24 ) + | ( std::uint64_t( std::min( minima.deep, 0xFFFFu ) ) << 8 ) | std::uint64_t( std::min( minima.steer, 0xFFu ) ); +} +struct TangleBest +{ + TangleInputs minima; // loc 0: a minimum line count is not an input the ratchet reads + std::uint32_t score10 = 0; +}; +inline TangleBest unpackTangleBest( std::uint64_t v ) noexcept +{ + TangleBest b; + b.score10 = std::uint32_t( v >> 32 ) & 0xFFFFFFu; + b.minima.nest = std::uint32_t( v >> 24 ) & 0xFFu; + b.minima.deep = std::uint32_t( v >> 8 ) & 0xFFFFu; + b.minima.steer = std::uint32_t( v ) & 0xFFu; + return b; +} +// Fold one version's inputs into a key's running best (`seen` false = the first version). +inline std::uint64_t foldTangleBest( std::uint64_t best, bool seen, const TangleInputs& version ) noexcept +{ + const std::uint32_t score10 = tangleScore10( version ); + if( !seen ) + { + return packTangleBest( version, score10 ); + } + TangleBest b = unpackTangleBest( best ); + b.minima.nest = std::min( b.minima.nest, version.nest ); + b.minima.deep = std::min( b.minima.deep, version.deep ); + b.minima.steer = std::min( b.minima.steer, version.steer ); + return packTangleBest( b.minima, std::min( b.score10, score10 ) ); +} + +// The store's source: given the root-relative paths of the files whose symbols a ratchet row could be about, the best-since rows of +// every symbol in them. Empty = no source (the ref-pair form, a caller that reads no history): no ratchet is judged. +using BestSinceSource = std::function& relPaths )>; + +// QD-CREDIT-ROW — one improvement this change made (STAGE0 2.5 "credit"; QD_LESSONS 11-19: a fix's gain was invisible): a symbol that was +// over a kind's bar at the baseline and is lower now by at least the kind's minor delta. Never a row, never gating; listed in the +// answer's section so a refactor lane and the ratchet see the credit. +struct Improvement +{ + std::string kind; // complexity | verbosity | nesting | params | tangle + std::string sym; // canonical id (display-normalized by the surface, like a row's sym) + std::uint32_t was = 0; + std::uint32_t now = 0; // a tangle score in tenths (rowValueText's rule) + std::string path; // root-relative, "" = no locator + std::uint32_t line = 0; +}; +// A metric value as every surface prints it: the integer, or a tangle score's tenths as a decimal ("48.4"). +inline std::string metricValueText( std::string_view kind, std::uint32_t v ) +{ + return kind == "tangle" ? std::to_string( v / 10u ) + "." + std::to_string( v % 10u ) : std::to_string( v ); +} +inline constexpr std::size_t kImprovedShown = 20; // the section lists at most this many (largest fall first), then more=N + +// What computeDelta reads and writes beyond its rows: the D4 source (in) and the improvements plus the ratchet's disclosure (out). +struct DeltaExtras +{ + BestSinceSource bestSince; + std::vector improved; + 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 + bool ratchetCut = false; +}; + // one reported regression (something the change made WORSE). struct Regression { @@ -8000,6 +8178,12 @@ struct Regression // function, so the members= text carries no path segment for exactly the symbols most likely to clone. // Empty for every other kind (their `path` IS the whole answer) and empty when no member resolved. std::vector memberPaths; + // QD-TANGLE — the tangle kind's three texts (empty on every other kind, and then emitted by no surface): why= the inputs that + // rose (or, on a new function, the inputs it has), fix= the shape the rise calls for with its lines, locals= the steering locals. + // was/now carry the score in TENTHS on a tangle row (every surface prints them as decimals). + std::string why; + std::string fix; + std::string locals; // P0.3 (r27) — ZERO MAGNITUDE. A finding with was == now == 0 carries no magnitude at all, so the ack // ratchet's `now <= ackNow` test degenerates to `0 <= 0` = "always suppressed" — a permanent blank check, @@ -8019,6 +8203,12 @@ inline const char* originValue( const Regression& r ) noexcept return !r.isNewSymbol ? nullptr : r.isMoved ? "moved" : "new-symbol"; } +// A row's was= / now= as every surface prints it (metricValueText). +inline std::string rowValueText( const Regression& r, std::uint32_t v ) +{ + return metricValueText( r.kind, v ); +} + 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 ) ) ); @@ -8045,6 +8235,7 @@ inline constexpr FacetAttr kFacetAttrs[] = { { "defect-shape", "defect" }, // format-arity / utf8-cut / dedup-first / vacuous-assert { "error-masking", "facet" }, // failure-default: the growth includes a read failure returned as an empty success { "complexity", "monster" }, // QD-MONSTER-GROWTH: "1" when isMonsterGrowth made (or would make) the row major + { "tangle", "ratchet" }, // D4: the reference point (a tag) whose best this function is above (appendTangleRatchet) { "new-clone-of-reused-helper", "idiom" }, // T13/fix2 gave this kind duplication's idiom demotion (Regression::facet // is populated the same way, from the same CloneIdiomVerdict); this row was // missing, so a demoted row's idiom name never reached the reader even @@ -9526,6 +9717,14 @@ inline std::size_t remapSnapshotIdentity( Snapshot& base, const IdentityAliases& healMap( base.failureDefaultBySym ); healMap( base.placeholderBySym ); healMap( base.bodyHashBySym ); + for( const auto& [ from, to ] : al.toCurrent ) // QD-TANGLE: re-filed like the metric maps, not counted (the count predates the kind) + { + const auto src = base.tangleBySym.find( from ); + if( src != base.tangleBySym.end() && !base.tangleBySym.contains( to ) ) + { + base.tangleBySym[ to ] = src->second; + } + } moved += rekeyMoveRecords( base.moveCidBySym, al ); (void) rekeyMoveRecords( base.bodyCidBySym, al ); // QD-RENAME-IDENTITY: re-keyed like the move record, so the old key is no vacated body (void) rekeyMoveRecords( base.moveSketchBySym, al ); // its sketch follows it; not a separate healed key in the count @@ -10207,6 +10406,14 @@ inline std::optional staleWhyForKind( std::string_view base, std::u { why = staleForMetricKind( base, key, snap ); } + else if( base == "tangle" ) + { + // QD-TANGLE: existence by locBySym, then whether the score is still at or over the bar + const auto it = snap.tangleBySym.find( key ); + why = !snap.locBySym.contains( key ) ? std::optional( StaleAckWhy::TargetGone ) + : ( !snap.tangleKnown || ( it != snap.tangleBySym.end() && tangleScore10( unpackTangle( it->second ) ) >= kTangleBar10 ) ) ? std::nullopt + : std::optional( StaleAckWhy::FindingGone ); + } else if( base == "dead-code" ) { why = staleForSetMembership( key, snap, snap.dead ); @@ -10503,6 +10710,95 @@ inline std::string staleAcksJsonArray( const std::vector& staleAcks ) return out; } +// QD-CREDIT-ROW — the section, one renderer per dialect shared by the CLI and MCP surfaces. In place order (path, line, kind), +// at most kImprovedShown entries, the rest counted in more=. Never a row: regressions= / gating= / the exit code never read it. +inline std::vector improvementsInPlaceOrder( std::vector v ) +{ + std::sort( v.begin(), v.end(), []( const Improvement& a, const Improvement& b ) + { return std::tie( a.path, a.line, a.kind, a.sym ) < std::tie( b.path, b.line, b.kind, b.sym ); } ); + return v; +} +template +inline std::string improvedXml( const std::vector& improved, std::string_view root, Escape&& ex ) +{ + if( improved.empty() ) + { + return {}; + } + const std::vector v = improvementsInPlaceOrder( improved ); + std::string out = " kImprovedShown ) + { + out += " more=\"" + std::to_string( v.size() - kImprovedShown ) + "\""; + } + out += ">"; + for( std::size_t i = 0; i < v.size() && i < kImprovedShown; ++i ) + { + const Improvement& m = v[i]; + out += "& improved, std::string_view root ) // `,"improved":[...]` (and "improved_more"), "" when none +{ + if( improved.empty() ) + { + return {}; + } + const std::vector v = improvementsInPlaceOrder( improved ); + std::string out = ",\"improved\":["; + for( std::size_t i = 0; i < v.size() && i < kImprovedShown; ++i ) + { + const Improvement& m = v[i]; + out += i == 0 ? "" : ","; + out += "{\"kind\":\"" + m.kind + "\",\"sym\":\"" + rw::jsonesc::escapeMcp( displaySym( m.sym, root ) ) + "\",\"was\":" + metricValueText( m.kind, m.was ) + + ",\"now\":" + metricValueText( m.kind, m.now ); + if( !m.path.empty() ) + { + out += ",\"p\":\"" + rw::jsonesc::escapeMcp( m.path ) + ":" + std::to_string( m.line ) + "\""; + } + out += "}"; + } + out += "]"; + if( v.size() > kImprovedShown ) + { + out += ",\"improved_more\":" + std::to_string( v.size() - kImprovedShown ); + } + 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. +template +inline std::string ratchetAttrsXml( const DeltaExtras& x, Escape&& ex ) +{ + if( x.ratchetRef.empty() ) + { + return {}; + } + 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 ) +{ + if( x.ratchetRef.empty() ) + { + return {}; + } + 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; +} + // P1 SCOPE — every member's root-relative path, for Regression::memberPaths. A clone row's `path` names only // the first-sorting member, and the ownership partition has to ask "does ANY member live in this scope"; the // members= TEXT cannot answer that, because a canonId degrades to a BARE NAME for a scope-less free function @@ -10834,6 +11130,276 @@ 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) ─────────── +// +// 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. +inline constexpr std::uint32_t kTangleDeepRise = 5; // deep lines that count as a rise (STAGE0 2.5's "worse" tier) + +struct TangleRise +{ + bool nest = false; + bool deep = false; + bool steer = false; + bool any() const noexcept { return nest || deep || steer; } +}; +inline TangleRise tangleRise( const TangleInputs& was, const TangleInputs& now ) noexcept +{ + return { now.nest > was.nest && now.nest > kTangleNestFree, now.deep >= was.deep + kTangleDeepRise, now.steer > was.steer }; +} + +// "nest 3->6, deep 0->39 lines, steer 1->2, 120->180 lines": each input that changed (all of them on a new function, single values). +inline std::string tangleWhy( const TangleInputs& was, const TangleInputs& now, bool isNew ) +{ + std::string out; + const auto add = [ & ]( std::string_view label, std::uint32_t w, std::uint32_t n, std::string_view unit ) + { + if( isNew ? n == 0 : w == n ) + { + return; + } + out += out.empty() ? "" : ", "; + out += label; + out += isNew ? std::to_string( n ) : std::to_string( w ) + "->" + std::to_string( n ); + out += unit; + }; + add( "nest ", was.nest, now.nest, "" ); + add( "deep ", was.deep, now.deep, " lines" ); + add( "steer ", was.steer, now.steer, "" ); + out += out.empty() ? "" : ", "; + out += ( isNew || was.loc == 0 || was.loc == now.loc ) ? std::to_string( now.loc ) + " lines" : std::to_string( was.loc ) + "->" + std::to_string( now.loc ) + " lines"; + return out; +} + +// The fix each rise calls for, with its lines: a new steering local → split the step that sets it from the branch that reads it; a +// deep rise → extract the largest deep region; a crossing by length alone → split into named phases. At most two, most specific first. +inline std::string tangleFix( const TangleRise& rise, bool isNew, const TangleInputs& now, const TangleDetailFacts& d ) +{ + std::vector fixes; + if( ( rise.steer || ( isNew && now.steer > 0 ) ) && !d.steer.empty() ) + { + const TangleSteerHit& h = d.steer.back(); + fixes.push_back( "split the step that sets " + h.name + " (L" + std::to_string( h.setLine ) + ") from the branch that reads it (L" + + std::to_string( h.readLine ) + "), or pass " + h.name + " to a named step" ); + } + if( ( rise.nest || rise.deep || ( isNew && now.deep > 0 ) ) && !d.humps.empty() ) + { + const auto widest = std::max_element( d.humps.begin(), d.humps.end(), []( const TangleHumpSpan& a, const TangleHumpSpan& b ) + { return a.endLine - a.startLine < b.endLine - b.startLine; } ); + fixes.push_back( "extract the " + std::to_string( widest->endLine - widest->startLine + 1u ) + "-line deep region at L" + + std::to_string( widest->startLine ) + "..L" + std::to_string( widest->endLine ) + + " into a named function, or invert it into guard clauses" ); + } + if( fixes.empty() ) + { + fixes.push_back( "split into named phases, an orchestrator of steps that each read locally" ); + } + std::string out = fixes[0]; + if( fixes.size() > 1 ) + { + out += "; " + fixes[1]; + } + return out; +} + +// locals= — the steering locals by name, first-read order, at most six then +N. +inline std::string tangleLocals( const TangleDetailFacts& d ) +{ + std::string out; + std::size_t shown = 0; + for( const TangleSteerHit& h : d.steer ) + { + if( shown == 6 ) + { + out += ",+" + std::to_string( d.steer.size() - shown ); + break; + } + out += out.empty() ? "" : ","; + out += h.name; + ++shown; + } + return out; +} + +// Each callable key's current inputs: the highest-scoring overload, as computeSnapshot records it. +struct TangleNow +{ + TangleInputs in; + NodeId at = kNoNode; +}; +inline gtl::btree_map tangleNowByKey( const IngestResult& ing, const Graph& g, const std::vector& keyByNode ) +{ + gtl::btree_map nowByKey; + for( NodeId i = 0; i < ing.symbols.size(); ++i ) + { + const Symbol& s = ing.symbols[i]; + if( i >= g.canonId.size() || g.canonId[i].empty() || ( s.kind != SymKind::Function && s.kind != SymKind::Method ) ) + { + continue; + } + const TangleInputs in = tangleInputsOf( s ); + TangleNow& slot = nowByKey[ keyByNode[i] ]; + if( slot.at == kNoNode || tangleOutranks( in, slot.in ) ) + { + slot = { in, i }; + } + } + return nowByKey; +} + +// A key's baseline inputs: its record, else (under every recording bar) only its nesting is known. +inline TangleInputs tangleBaseInputs( const Snapshot& base, std::uint64_t key ) +{ + TangleInputs was; + if( const auto it = base.tangleBySym.find( key ); it != base.tangleBySym.end() ) + { + was = unpackTangle( it->second ); + } + else if( const auto nest = base.nestBySym.find( key ); nest != base.nestBySym.end() ) + { + was.nest = nest->second; // no record: under the nesting bar, 50 lines or fewer, no deep line, no steering local + } + return was; +} + +// The re-walk of ONE function for its row's fix= and locals= (ingest.h tangleDetailOf), reading each file once across a key-ordered pass. +struct TangleDetailReader +{ + const IngestResult& ing; + std::string fileBytes; + std::uint32_t fileOf = 0xFFFFFFFFu; + TangleDetailFacts of( const Symbol& s ) + { + if( s.fileId != fileOf ) + { + fileOf = s.fileId; + fileBytes = docparse::detail::readWholeFile( diskPath( ing, s.fileId ) ).value_or( std::string() ); + } + return tangleDetailOf( fileBytes, diskPath( ing, s.fileId ), s.sigStartByte, s.endByte ); + } +}; + +// QD-CREDIT-ROW for tangle (STAGE0 2.5): over the bar at the baseline, an input fell and none rose, and the score is lower. +inline bool tangleCredited( const TangleInputs& was, const TangleInputs& now ) noexcept +{ + const bool fell = now.nest < was.nest || now.deep < was.deep || now.steer < was.steer; + return tangleScore10( was ) >= kTangleBar10 && fell && !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 gtl::btree_map& nowByKey, + const std::vector& ratchetable, const gtl::btree_map& rowOfKey, + TangleDetailReader& detailOf, Stamp&& stamp, std::string_view root, DeltaExtras& extras ) +{ + std::vector paths; + for( const std::uint64_t key : ratchetable ) + { + paths.emplace_back( relForHash( ing.files[ ing.symbols[ nowByKey.at( key ).at ].fileId ], root ) ); + } + std::sort( paths.begin(), paths.end() ); + paths.erase( std::unique( paths.begin(), paths.end() ), paths.end() ); + const BestSinceStore store = extras.bestSince( paths ); + extras.ratchetRef = store.ref; + extras.ratchetUnread = store.unread; + extras.ratchetCut = store.cut; + if( store.ref.empty() ) + { + return; + } + for( const std::uint64_t key : ratchetable ) + { + const BestSinceRow* row = store.find( key ); + if( row == nullptr ) + { + continue; + } + ++extras.ratchetJudged; + const TangleNow& now = nowByKey.at( key ); + 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() ) + { + 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 ); + } +} + +// 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). +template +inline void appendTangleRows( std::vector& regs, const IngestResult& ing, const Graph& g, const std::vector& keyByNode, + const Snapshot& base, std::string_view root, Existed&& existed, MovedAt&& movedAt, Stamp&& stamp, DeltaExtras* extras ) +{ + 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 + for( const auto& [ key, best ] : nowByKey ) + { + const bool isNew = !existed( key ); + const TangleInputs was = tangleBaseInputs( base, key ); + const std::uint32_t was10 = tangleScore10( was ); + const std::uint32_t now10 = tangleScore10( best.in ); + if( extras != nullptr && !isNew && tangleCredited( was, best.in ) ) + { + const Symbol& s = ing.symbols[ best.at ]; + extras->improved.push_back( { "tangle", g.canonId[ best.at ], was10, now10, std::string( relForHash( ing.files[ s.fileId ], root ) ), s.line } ); + } + if( now10 < kTangleBar10 ) + { + continue; // under the bar now: no row, whatever it was + } + if( !isNew && packTangle( was ) != packTangle( best.in ) ) + { + ratchetable.push_back( key ); + } + const TangleRise rise = tangleRise( was, best.in ); + if( !isNew && was10 >= kTangleBar10 && !rise.any() ) + { + continue; // already over the bar and nothing rose: the change did not make it so + } + 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 ) }; + r.why = tangleWhy( was, best.in, isNew ); + r.fix = tangleFix( rise, isNew, best.in, detail ); + r.locals = tangleLocals( detail ); + rowOfKey[ key ] = regs.size(); + regs.push_back( std::move( r ) ); + stamp( best.at ); + } + if( extras != nullptr && extras->bestSince && !ratchetable.empty() ) + { + appendTangleRatchet( regs, ing, g, nowByKey, ratchetable, rowOfKey, detailOf, stamp, root, *extras ); + } +} + // `root` = the ingest root exactly as invoked; every baseline COMPARISON key is the root-relative // baselineCanonId (S2) so a committed baseline matches regardless of how the root was spelled on either run. // The human-readable `Regression.sym` keeps the FULL g.canonId (display only — never hashed/compared), so the @@ -10852,7 +11418,8 @@ inline std::vector computeDelta( const IngestResult& ing, const Grap std::size_t* valueRefExcludedOut = nullptr, // ... ONLY because a table/field/argument holds them as a VALUE const KindScope& scope = {}, // qd-memory-degrade: the kinds to report (see computeSnapshot) HistoryUnread* historyUnreadOut = nullptr, // hwh-fix4 (N1): history a gating kind could not read - TreePasses* sharedPasses = nullptr ) // QD-IDENTITY-ONCE: pure passes over `ing` another consumer may already hold + TreePasses* sharedPasses = nullptr, // QD-IDENTITY-ONCE: pure passes over `ing` another consumer may already hold + DeltaExtras* extras = nullptr ) // D4 best-since source in; QD-CREDIT-ROW improvements + ratchet disclosure out { TreePasses ownPasses; TreePasses& passes = sharedPasses != nullptr ? *sharedPasses : ownPasses; @@ -11088,6 +11655,12 @@ inline std::vector computeDelta( const IngestResult& ing, const Grap const std::uint32_t now = nowIt->second.now; const auto it = baseMap.find( key ); const std::uint32_t was = ( it == baseMap.end() ) ? 0u : it->second; + if( extras != nullptr && kindSelected( scope.kinds, mb.kind ) && it != baseMap.end() && was > bar && now + std::max( mb.minorDelta, 1u ) <= was ) + { + // QD-CREDIT-ROW: over the bar at the baseline and lower now by at least the kind's minor delta — listed, never a row + const Symbol& at = ing.symbols[ nowIt->second.at ]; + extras->improved.push_back( { std::string( mb.kind ), g.canonId[i], was, now, at.fileId < ing.files.size() ? std::string( relForHash( ing.files[ at.fileId ], root ) ) : std::string(), at.line } ); + } if( now <= was ) { continue; // nothing got worse on this axis @@ -11130,6 +11703,12 @@ inline std::vector computeDelta( const IngestResult& ing, const Grap perSymbolKind( kMaterialityBars[1], newSymbolCeiling( kLocBar ), base.locBySym, [ & ]( NodeId i ){ return nowCodeLoc[i]; } ); perSymbolKind( kMaterialityBars[2], 0, base.nestBySym, [ & ]( NodeId i ){ return std::uint32_t( ing.symbols[i].maxNest ); } ); perSymbolKind( kMaterialityBars[3], 0, base.paramsBySym, [ & ]( NodeId i ){ return std::uint32_t( ing.symbols[i].params ); } ); + // QD-TANGLE (report-only): judged only 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. + if( kindSelected( scope.kinds, "tangle" ) && base.tangleKnown ) + { + appendTangleRows( regs, ing, g, keyByNode, base, root, existedAtBaseline, [ & ]( NodeId at ) { return moved.isMoved( at ); }, stampLoc, extras ); + } // PERF (P5W2) — the working-tree clone pass is the dominant --quality-delta cost: on a large private C++ corpus the // Type-3 pass alone is ~2.7-3.2 s (60 M intra-bucket pair-visits; tokenization is only ~3 %). It is a PURE diff --git a/src/serialize.h b/src/serialize.h index fb60e5c68..517a33bb5 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -2792,6 +2792,9 @@ inline void appendExtentSuspectAttr( std::string& row, const Symbol& s ) inline constexpr const char* kMetricsLegend = " - - + + - - + + ... [17 more line(s); run it to see the whole thing] @@ -108,17 +108,17 @@ $ ./build/ripwire . --top-k=5 --no-inventory - - + + - - + + -... [13 more line(s); run it to see the whole thing] +... [14 more line(s); run it to see the whole thing] ``` **Caveats (stated by the binary):** @@ -142,8 +142,8 @@ $ ./build/ripwire . --max-tokens=1500 - - + + @@ -172,7 +172,7 @@ _GATE form: exit 3 if the map's own est_tokens exceeds the budget (over-budget f ``` $ ./build/ripwire . --token-budget=100 - + ``` **Shaped by:** `--top-k`, `--max-tokens`, `--for`, `--sections`, `--recall`, `--handoff`, `--pr-context`, `--from-trace` @@ -225,14 +225,14 @@ _Name-shaped query: the router picks name-exact BM25 (header says which/why)._ ``` $ ./build/ripwire . --for="rankGraphTeleport" - + - + PageRank with an explicit teleport / personalization vector p (Σp = 1). The prior is name-quality-biased through biasPrior() so all rank modes share one weighting seam; the transition matrix (edgesinline RankedGraph rankGraphTeleport( const Graph& g, const std::vector<float>&am … [line truncated: 31 more bytes on this line] #### The convergence disclosure contract -### Wave-2 adversarial verification (2026-08-19) — six probes against `aa97c9e` +### Wave-2 adversarial verification (2026-08-19) — six probes against `aa97c9e` @@ -262,14 +262,14 @@ _Restore the / sections the --for bundle collapses to a counted s ``` $ ./build/ripwire . --for="tree-sitter parse of a source file" --sections=lego,compose - + inline bool topLevelEvidence( std::string_view source, const TSLanguage* language, const Predicate& predicate ) + The crawl's per-file byte ceiling. A text file larger than this is skipped: at this size it is o…constexpr std::size_t kDefaultMaxFileBytes = 4u * 1024u * 1024u -TSTree* parseTree( TSParser* parser, std::string_view src ) +TSTree* parseTree( TSParser* parser, std::string_view src ) Exercise every registered grammar and its embedded query, reporting loaded and expected totalsinline DoctorGrammarProbe doctorProbeGrammars() ... [21 more line(s); run it to see the whole thing] @@ -289,14 +289,14 @@ _T3 opt-out: the signatures-only lens (no auto bodies, no bundle="auto" attribut ``` $ ./build/ripwire . --for="rankGraphTeleport" --signatures-only - + - + PageRank with an explicit teleport / personalization vector p (Σp = 1). The prior is name-quality-biased through biasPrior() so all rank modes share one weighting seam; the transition matrix (edgesinline RankedGraph rankGraphTeleport( const Graph& g, const std::vector<float>&am … [line truncated: 31 more bytes on this line] #### The convergence disclosure contract -### Wave-2 adversarial verification (2026-08-19) — six probes against `aa97c9e` +### Wave-2 adversarial verification (2026-08-19) — six probes against `aa97c9e` @@ -324,14 +324,14 @@ _Opt OUT of compact conceptual serving: restore the rank-first auto wal ``` $ ./build/ripwire . --for="tree-sitter parse of a source file" --auto-bodies - + inline bool topLevelEvidence( std::string_view source, const TSLanguage* language, const Predicate& predicate ) + The crawl's per-file byte ceiling. A text file larger than this is skipped: at this size it is o…constexpr std::size_t kDefaultMaxFileBytes = 4u * 1024u * 1024u -TSTree* parseTree( TSParser* parser, std::string_view src ) +TSTree* parseTree( TSParser* parser, std::string_view src ) Exercise every registered grammar and its embedded query, reporting loaded and expected totalsinline DoctorGrammarProbe doctorProbeGrammars() ... [21 more line(s); run it to see the whole thing] @@ -356,17 +356,17 @@ _Same query with routing forced OFF (plain subtoken+body BM25) — contrast with ``` $ ./build/ripwire . --for="rankGraphTeleport" --no-route - + - + PageRank with an explicit teleport / personalization vector p (Σp = 1). The prior is name-quali…inline RankedGraph rankGraphTeleport( const Graph& g, const std::vector<float>& p, float alpha = 0.85f ) - + uniform-teleport PageRank (the default). A kRankFlagNotNamed unit (model.h) has no edge and a 0 …inline RankedGraph rankGraph( const Graph& g, float alpha = 0.85f ) The default map's PageRank — uniform teleport, the one rank that is a function of the Graph al…inline std::optional<RankedGraph>& storedDefaultRank() noexcept -inline ChurnRanking churnRankedGraph( const MainDispatch& d ) +inline ChurnRanking churnRankedGraph( const MainDispatch& d ) ... [20 more line(s); run it to see the whole thing] ``` @@ -388,14 +388,14 @@ _Cut the result at the relevance cliff (Adaptive-k) — on a flat ranking nothin ``` $ ./build/ripwire . --for="tree-sitter parse of a source file" --adaptive - + inline bool topLevelEvidence( std::string_view source, const TSLanguage* language, const Predicate& predicate ) + The crawl's per-file byte ceiling. A text file larger than this is skipped: at this size it is o…constexpr std::size_t kDefaultMaxFileBytes = 4u * 1024u * 1024u -TSTree* parseTree( TSParser* parser, std::string_view src ) +TSTree* parseTree( TSParser* parser, std::string_view src ) Exercise every registered grammar and its embedded query, reporting loaded and expected totalsinline DoctorGrammarProbe doctorProbeGrammars() ... [21 more line(s); run it to see the whole thing] @@ -419,11 +419,11 @@ _Same task with the anchor disabled — the contrast the flag exists for._ ``` $ ./build/ripwire . --for="why does src/lexical.h chooseForRanker pick name-exact BM25" --no-mention-boost - - + The name-exact ranker AS THE RETRIEVAL LENS SERVES IT: whole-name BM25 plus the definition-over-…inline std::vector<float> lexicalScoresNameExactRanked( const IngestResult& ing, std::string_view query, const std::vector<float>* symbolScoreMul ) P11.12: the interpretive footer for --eval's ranker table, pulled into its own function so the 9…inline void printEvalRankerNote() @@ -449,15 +449,15 @@ _The same task with doc-mention surfacing OFF — the contrast the flag exists f ``` $ ./build/ripwire . --for="quality delta acks ledger rubber stamp" --no-doc-mention - + - - + + L2 stale acks in the range form. A changed-files answer holds no whole target tree to check the …std::vector<rw::quality::StaleAck> refPairStaleAcks( const gtl::btree_map<std::string, rw::quality::AckRecord>& acks, const RefPairDelta& refs ) -inline QualityDeltaOutcome computeQualityDelta( const std::string& root ) -inline std::string staleByKindValue( const std::vector<StaleAck>& staleAcks ) -inline constexpr const char* kAtStampLegend = "<!-- at= is the git commit these numbers were computed at +inline QualityDeltaOutcome computeQualityDelta( const std::string& root ) +inline std::string staleByKindValue( const std::vector<StaleAck>& staleAcks ) +inline constexpr const char* kAtStampLegend = "<!-- at= is the git commit these numbers were computed at ... [22 more line(s); run it to see the whole thing] ``` @@ -479,7 +479,7 @@ _Interface -> implementors view: every existing impl of the named interface; the $ ./build/ripwire . --lego=Vehicle - + @@ -510,7 +510,7 @@ _The repo's best-in-class instance to imitate before writing new code (picked by $ ./build/ripwire . --exemplar="format byte sizes for humans" - + - + + + + + + - - - - - ... [17 more line(s); run it to see the whole thing] ``` @@ -708,14 +713,14 @@ $ ./build/ripwire . --order=stable --top-k=5 - + - - + + ... [17 more line(s); run it to see the whole thing] @@ -739,14 +744,14 @@ $ ./build/ripwire . --no-stable --top-k=3 - - + + - - + + ... [17 more line(s); run it to see the whole thing] @@ -773,7 +778,7 @@ $ ./build/ripwire . --around=rankGraphTeleport - + @@ -823,18 +828,18 @@ _What SYM calls (1-hop out-edges)._ ``` $ ./build/ripwire . --callees=rankGraphTeleport - - + + - - - - - - + + + + + + ``` @@ -858,16 +863,16 @@ _The resolvable use-sites (call/read/write/import/extends) with file:line; count ``` $ ./build/ripwire . --uses=rankGraphTeleport - - - - + + + + - - - - - + + + + + ``` @@ -892,17 +897,17 @@ _Composable node-set query: functions within 2 caller-hops of rankGraphTeleport. ``` $ ./build/ripwire . --graph-query='and(callers(name("rankGraphTeleport"),2),kind(all,fn))' - - - - + + + + - - - + + + - + ... [17 more line(s); run it to see the whole thing] @@ -929,19 +934,19 @@ _Names referenced but never defined in-corpus (stdlib/third-party surface). The ``` $ ./build/ripwire . --external-surface - - - - - - - - - - - - - + + + + + + + + + + + + + ... [17 more line(s); run it to see the whole thing] ``` @@ -964,13 +969,13 @@ _Shortest directed call-path SRC -> DST. CHANGED: now reports from_p/to_p/from_d ``` $ ./build/ripwire . --path=main,rankGraphTeleport - - - - - - + + + + + + ... [20 more line(s); run it to see the whole thing] ``` @@ -988,14 +993,14 @@ _Which definitions each name binds, one row per definition group with sel= (the $ ./build/ripwire . --defs=main,rankGraphTeleport - + - + @@ -1016,13 +1021,13 @@ _Minimal connecting subgraph over 3 symbols (finds shared-caller joins)._ ``` $ ./build/ripwire . --connect=rankGraphTeleport,runEval,getIndex - + - - + + - + ``` @@ -1126,7 +1131,7 @@ _Test files that transitively reach the changed file._ ``` $ ./build/ripwire . --affected=src/graph.h - @@ -1137,6 +1142,7 @@ $ ./build/ripwire . --affected=src/graph.h + ``` @@ -1186,7 +1192,7 @@ _Mid-task situational report for the current git diff — recorded against a CLE $ ./build/ripwire . --situ ripwire situational-awareness — 0 changed file(s), 0 symbols in them root: . -at: b1fdfdb4e +at: b0cb13d8d (0 changed files — working tree is clean, nothing to analyze) ``` @@ -1205,18 +1211,18 @@ _The continuation packet for the NEXT session: disk truth (branch/sha ``` $ ./build/ripwire . --handoff - + - + - - - + + + + ... [1 more line(s); run it to see the whole thing] ``` @@ -1240,7 +1246,7 @@ _Pre-PR gate on a CLEAN tree: no obligations, exit 0._ ``` $ ./build/ripwire . --test-gate - ``` @@ -1265,7 +1271,7 @@ _Literal trigram-indexed search. Each hit carries its MATCHED line as the $ ./build/ripwire . --grep=DISCLOSE - + - + - + ... [17 more line(s); run it to see the whole thing] ``` @@ -1567,7 +1573,7 @@ _Importance-weighted detail: FULL bodies for top-2, signatures for the rest._ ``` $ ./build/ripwire . --for="pagerank power iteration" --detail=2 - + @@ -1604,14 +1610,14 @@ $ ./build/ripwire . --pack-signatures --top-k=10 - - + + - - + + ... [17 more line(s); run it to see the whole thing] ``` @@ -1633,7 +1639,7 @@ $ ./build/ripwire . --outline=rankGraphTeleport --top-k=0 signature rows. est_tokens=: price as emitted (an upper bound under compact). root=: p= relative to it. --> - + & p, float alpha = 0.85f ) { PROFILE_SCOPE_DESCRIBE( "rankGraph: PageRank (power iteration)" ); @@ -1664,7 +1670,7 @@ $ ./build/ripwire . --top-k=0 --expand=rankGraphTeleport - + + - - + + - + - - + + ... [17 more line(s); run it to see the whole thing] @@ -1836,16 +1842,16 @@ _File->file dependency graph (god-files, cycles)._ ``` $ ./build/ripwire . --deps - - - - - + + + + + + - @@ -1873,18 +1879,18 @@ _Complexity x recent git churn (maintenance pain)._ $ ./build/ripwire . --hotspots - - - - - - - - - + + + + + + + + + - - + + ... [17 more line(s); run it to see the whole thing] ``` @@ -1900,18 +1906,18 @@ _Token-normalized duplicate bodies._ ``` $ ./build/ripwire . --clones - - + + - + - + ... [17 more line(s); run it to see the whole thing] @@ -1932,15 +1938,15 @@ _Per-function size ranking, largest Halstead volume/token entropy/lines first ``` $ ./build/ripwire . --biggest-first --limit=8 - - - + + + - + - - - + + + ``` @@ -1965,7 +1971,7 @@ _Per function, the non-local MUTABLE state it can reach (transitively), most wri ``` $ ./build/ripwire . --nonlocal-state --limit=8 - @@ -2000,12 +2006,12 @@ _The family join: per function, which of four orthogonal evidence families fire, ``` $ ./build/ripwire . --ensemble --limit=8 - + - + @@ -2031,17 +2037,17 @@ _THE single wide-angle quality read: six families in one pass, an eligible/ranke ``` $ ./build/ripwire . --quality-panel - + - + - - + + - + ... [17 more line(s); run it to see the whole thing] @@ -2068,13 +2074,13 @@ _The local-reasoning lens: to understand this symbol, how much must you know tha ``` $ ./build/ripwire . --context-ratio --limit=8 - - - - - - + + + + + + ... [23 more line(s); run it to see the whole thing] ``` @@ -2099,19 +2105,19 @@ _Score the naming-* rules against this repo's own rename history: proxy=old/(old ``` $ ./build/ripwire . --naming-calibration - + - +

-

+

... [14 more line(s); run it to see the whole thing] ``` @@ -2134,11 +2140,11 @@ _The corpus's OWN case-convention vote per (language, kind) group; off-conventio ``` $ ./build/ripwire . --naming-consistency --limit=8 - - - - - + + + + + @@ -2171,8 +2177,8 @@ _The opt-in --lint modifier: naming predicates over LOCAL variable names too, C/ ``` $ ./build/ripwire . --lint --naming-locals - - + + @@ -2180,10 +2186,10 @@ $ ./build/ripwire . --lint --naming-locals - + - + ... [17 more line(s); run it to see the whole thing] ``` @@ -2206,13 +2212,13 @@ _Functions WITH a doc comment, most name-restating first: c_coeff (high = the co ``` $ ./build/ripwire . --comment-coherence --limit=8 - + - - - - + + + + @@ -2239,16 +2245,16 @@ _Files that change together in git (hidden coupling)._ ``` $ ./build/ripwire . --cochange - + - + - - - - + + + + ... [22 more line(s); run it to see the whole thing] ``` @@ -2271,16 +2277,16 @@ _Only pairs whose co-change RECURS in 2+ sub-windows of the mined window (sub_wi ``` $ ./build/ripwire . --cochange --cochange-recur=2 - + - - - + + + - + ... [22 more line(s); run it to see the whole thing] ``` @@ -2297,15 +2303,15 @@ _Modularity-violation GROUPS instead of pairs: "X co-changes with {A,B,C}, none ``` $ ./build/ripwire . --cochange --cochange-groups - - + + - + @@ -2326,18 +2332,18 @@ _Hotspots scoped to RECENT churn (the regression lens)._ ``` $ ./build/ripwire . --hotspots --since="2 weeks ago" - - - - - - - - - - - - + + + + + + + + + + + + ... [17 more line(s); run it to see the whole thing] ``` @@ -2451,8 +2457,8 @@ _Built-in AST checks (c-cast, goto, unsafe-c-fn, ...)._ ``` $ ./build/ripwire . --lint - - + + @@ -2460,10 +2466,10 @@ $ ./build/ripwire . --lint - + - + ... [17 more line(s); run it to see the whole thing] ``` @@ -2560,8 +2566,8 @@ _DROP two families, applied after selection; the raw select=/ignore= you passed ``` $ ./build/ripwire . --lint --lint-ignore=naming-,cache- - + @@ -2569,10 +2575,10 @@ $ ./build/ripwire . --lint --lint-ignore=naming-,cache- - + - + ... [17 more line(s); run it to see the whole thing] ``` @@ -2674,15 +2680,15 @@ _Cluster the call graph into cohesive modules._ ``` $ ./build/ripwire . --communities - + - + @@ -2705,7 +2711,7 @@ _Drill into ONE call-graph community by id — the drill= the --communities outp ``` $ ./build/ripwire . --community=0 - ``` @@ -2730,19 +2736,19 @@ _Nested module hierarchy (multi-level Louvain) + cross-module bridges — shown_ ``` $ ./build/ripwire . --zoom - - + + + + - + - - + + - - ... [17 more line(s); run it to see the whole thing] ``` @@ -2767,16 +2773,16 @@ $ ./build/ripwire . --report # ripwire architecture report -4763 files · 43356 symbols · 42475 edges · 4933 modules (20575 call-graph isolated) +4779 files · 44046 symbols · 43830 edges · 5053 modules (20765 call-graph isolated) Root: `.` -Call-graph isolate provenance: 5626 declaration, 3404 header, 4521 source, 7024 document; 0 connected Louvain singletons +Call-graph isolate provenance: 5724 declaration, 3481 header, 4519 source, 7041 document; 0 connected Louvain singletons -## Modules (call-graph clusters; showing 12 of 4933) -- **src::emitTo@infra/emit.h:53:2760 [write,run,emit]** — 1800 symbols -- **src::kindIs@infra/nodekind.h:46:3271 [push,emit,read]** — 679 symbols -- **src::DISCLOSE@infra/Diagnostics.h:622:43913 [read,compute,resolve]** — 557 symbols +## Modules (call-graph clusters; showing 12 of 5053) +- **src::emitTo@infra/emit.h:53:2760 [write,run,emit]** — 1880 symbols +- **src::kindIs@infra/nodekind.h:46:3271 [push,emit,read]** — 697 symbols +- **src::DISCLOSE@infra/Diagnostics.h:622:43913 [read,check,collect]** — 252 symbols ... [17 more line(s); run it to see the whole thing] ``` @@ -2793,9 +2799,9 @@ _Cross-module call seams no test reaches. NOW carries seam_pairs/shown/capped._ ``` $ ./build/ripwire . --seams - - + + @@ -2803,9 +2809,9 @@ $ ./build/ripwire . --seams - - - + + + ... [17 more line(s); run it to see the whole thing] ``` @@ -2824,15 +2830,15 @@ $ ./build/ripwire . --mermaid %% ripwire --mermaid: module (directory) dependency graph — node = dir (symbol count), edge = inter-module calls (>= 3). Render at mermaid.live. flowchart LR subgraph sg0 ["src"] - n105["src
14030"] - n106["src/infra
1675"] + n105["src
14596"] + n106["src/infra
1684"] end subgraph sg1 ["test"] - n107["test
6886"] + n107["test
6966"] n750["test/legochargefix
546"] n472["test/fixtures/recallpassage
314"] n491["test/fnslotcpp2
285"] - n913["test/lib
235"] + n913["test/lib
253"] n712["test/ifacepeelfix/cpp
206"] n1252["test/slotjoinfix
182"] ... [17 more line(s); run it to see the whole thing] @@ -2853,8 +2859,8 @@ _Bus-factor: recency-weighted author ownership per file._ ``` $ ./build/ripwire . --owners - - + + @@ -2884,7 +2890,7 @@ _Internal functions with no caller found in the index — a name-based graph rea ``` $ ./build/ripwire . --dead-code=src - + @@ -2892,7 +2898,7 @@ $ ./build/ripwire . --dead-code=src - + ... [20 more line(s); run it to see the whole thing] ``` @@ -2957,7 +2963,7 @@ _The same run, the same clone, the folded rows printed back: each stale acknowle ``` $ ./build/ripwire . --quality-delta --show-stale - @@ -2977,7 +2983,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) — 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, 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. **Try it** @@ -2986,7 +2992,7 @@ _The regression-free answer on a clone whose ledger holds stale acknowledgements ``` $ ./build/ripwire . --quality-delta - ``` @@ -3011,7 +3017,7 @@ _The regression-free answer on a clone whose ledger holds stale acknowledgements ``` $ ./build/ripwire . --quality-delta - ``` @@ -3031,12 +3037,12 @@ A named kind's rows are exactly its rows in a full answer (same code, same bars) **Try it** -_A ref range run for two of the twelve 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._ +_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._ ``` $ ./build/ripwire . --quality-delta=HEAD~1..HEAD --quality-kinds=complexity,dead-code -

@@ -3098,7 +3104,7 @@ $ ./build/ripwire . --quality-delta --quality-ack --ack-only=zzznope **Answers:** (with --quality-ack) ack only SOME findings — those whose KIND, canonical id or FACET matches (with --quality-ack) ack only SOME findings — those whose KIND, canonical id, or FACET contains one of these; -the pseudo-token 'gating' selects exactly what would exit 2. Bare --quality-ack accepts the WHOLE report, so accepting one deliberate change silently accepts the rest — how a ratchet turns into a rubber stamp. Prefer the facet: --ack-only=contract-change acks the deliberate arity changes WITHOUT the never-gating api-surface new-symbol rows; a defect-shape facet (format-arity, utf8-cut, dedup-first, vacuous-assert) selects that shape alone. Matching nothing refuses (exit 1) rather than falling back to acking everything. Whatever you leave unacked stays visible. +the pseudo-token 'gating' selects exactly what would exit 2. Bare --quality-ack accepts the WHOLE report, so accepting one deliberate change silently accepts the rest — how a ratchet turns into a rubber stamp. Prefer the facet: --ack-only=contract-change acks the deliberate arity changes WITHOUT the never-gating api-surface new-symbol rows; a defect-shape facet (format-arity, utf8-cut, dedup-first, vacuous-assert, unchecked-status, unhandled-arm) selects that shape alone. Matching nothing refuses (exit 1) rather than falling back to acking everything. Whatever you leave unacked stays visible. **Try it** @@ -3129,14 +3135,14 @@ _OWNERSHIP partition for a shared tree: every regression here lives in src/infra ``` $ ./build/ripwire . --quality-delta --scope=src/graph.h - - - - - - - + + + + + + ... [22 more line(s); run it to see the whole thing] ``` @@ -3159,14 +3165,14 @@ _Fast per-symbol post-edit contract check vs git HEAD (unchanged on a clean tree ``` $ ./build/ripwire . --edit-check=rankGraphTeleport - - - - - - - + + + + + + ``` @@ -3209,17 +3215,21 @@ _Insert BEFORE, with --edit-target-file pinning which same-named definition (her ``` $ ./build/ripwire . --insert-before-symbol=nonNegativeFloatDescKey --edit-payload=/aux/payload_note.h --edit-target-file=src/infra/sortutil.h -{"applied":"insert_before_symbol","symbol":"nonNegativeFloatDescKey","file":"src/infra/sortutil.h","span":{"start":3161,"end":3249},"lines":{"start":77,"end":78},"replaced_bytes":0,"old_file_bytes":8855,"new_file_bytes":8943,"file_eol":"lf","eol_normalized":false,"trailing_newline_folded":false,"sep … [line truncated: 753 more bytes on this line] +{"applied":"insert_before_symbol","symbol":"nonNegativeFloatDescKey","file":"src/infra/sortutil.h","span":{"start":3656,"end":3744},"lines":{"start":87,"end":88},"replaced_bytes":0,"old_file_bytes":9350,"new_file_bytes":9438,"file_eol":"lf","eol_normalized":false,"trailing_newline_folded":false,"sep … [line truncated: 753 more bytes on this line] {"n":"benchAdaptive","p":"bench/bench_radix_ab.cpp:157","l":[162]}, -{"n":"radixSortNonNegativeFloatsDesc","p":"src/infra/sortutil.h:108","l":[117]}, -{"n":"radixSortByScoreDescId","p":"src/infra/sortutil.h:123","l":[183]}], -"graph_ambiguous":3646,"graph_unresolved":19925,"graph_unindexed":310,"counts_floor":true},"tests_to_run":[{"p":"test/verify_radix.cpp","hops":1,"run":"bash test/greptiercheck.sh"}, +{"n":"radixSortNonNegativeFloatsDesc","p":"src/infra/sortutil.h:118","l":[127]}, +{"n":"radixSortByScoreDescId","p":"src/infra/sortutil.h:133","l":[193]}], +"graph_ambiguous":3637,"graph_unresolved":20080,"graph_unindexed":311,"counts_floor":true},"tests_to_run":[{"p":"test/verify_radix.cpp","hops":1,"run":"bash test/greptiercheck.sh"}, {"p":"test/adaptivecutshapefix/adaptive_cut_shape_test.cpp","hops":2,"run":"bash test/adaptivecutshapecheck.sh"}, +{"p":"test/connectcore_harness.cpp","hops":2,"run":"bash test/connectcorecheck.sh"}, {"p":"test/forrowfeatures_unit.cpp","hops":2,"run":"bash test/forrowfeaturescheck.sh"}, +{"p":"test/fuzz/readers/readers_domain.cpp","hops":2,"run_unknown":true}, {"p":"test/verify_csr.cpp","hops":2,"run":"bash test/a9disclosurecheck.sh"}, +{"p":"test/cloneband_harness.cpp","hops":3,"run":"bash test/clonebandcheck.sh"}, +{"p":"test/shstatus_harness.cpp","hops":3,"run":"bash test/gateexitcheck.sh"}, +{"p":"test/type3clone_harness.cpp","hops":3,"run":"bash test/type3clonecheck.sh"}, {"p":"test/includeprecise_unit.cpp","hops":4,"run":"bash test/includeprecisecheck.sh"}, -{"p":"test/rustimport_unit.cpp","hops":4,"run":"bash test/rustimportprecisecheck.sh"}], -"order":"evidence","partners":0,"run_first":1,"tests":6,"script_gates_unmodelled":941,"graph_ambiguous":3646,"graph_unresolved":19925,"graph_unindexed":310,"counts_floor":true,"next":"--uses=src/infra/sortutil.h:nonNegativeFloatDescKey"} +... [3 more line(s); run it to see the whole thing] ``` ### `--insert-after-symbol=TARGET` @@ -3234,14 +3244,20 @@ _Insert immediately AFTER one uniquely-resolved definition; replaced_bytes=0 bec ``` $ ./build/ripwire . --insert-after-symbol=lessByScoreDescId --edit-payload=/aux/payload_note.h -{"applied":"insert_after_symbol","symbol":"lessByScoreDescId","file":"src/infra/sortutil.h","span":{"start":2641,"end":2729},"lines":{"start":59,"end":61},"replaced_bytes":0,"old_file_bytes":8679,"new_file_bytes":8767,"file_eol":"lf","eol_normalized":false,"trailing_newline_folded":true,"separator_p … [line truncated: 650 more bytes on this line] -"graph_ambiguous":3646,"graph_unresolved":19925,"graph_unindexed":310,"counts_floor":true},"tests_to_run":[{"p":"test/verify_radix.cpp","hops":1,"run":"bash test/greptiercheck.sh"}, +{"applied":"insert_after_symbol","symbol":"lessByScoreDescId","file":"src/infra/sortutil.h","span":{"start":3136,"end":3224},"lines":{"start":69,"end":71},"replaced_bytes":0,"old_file_bytes":9174,"new_file_bytes":9262,"file_eol":"lf","eol_normalized":false,"trailing_newline_folded":true,"separator_p … [line truncated: 650 more bytes on this line] +"graph_ambiguous":3637,"graph_unresolved":20080,"graph_unindexed":311,"counts_floor":true},"tests_to_run":[{"p":"test/verify_radix.cpp","hops":1,"run":"bash test/greptiercheck.sh"}, {"p":"test/adaptivecutshapefix/adaptive_cut_shape_test.cpp","hops":2,"run":"bash test/adaptivecutshapecheck.sh"}, +{"p":"test/connectcore_harness.cpp","hops":2,"run":"bash test/connectcorecheck.sh"}, {"p":"test/forrowfeatures_unit.cpp","hops":2,"run":"bash test/forrowfeaturescheck.sh"}, +{"p":"test/fuzz/readers/readers_domain.cpp","hops":2,"run_unknown":true}, {"p":"test/verify_csr.cpp","hops":2,"run":"bash test/a9disclosurecheck.sh"}, +{"p":"test/cloneband_harness.cpp","hops":3,"run":"bash test/clonebandcheck.sh"}, +{"p":"test/shstatus_harness.cpp","hops":3,"run":"bash test/gateexitcheck.sh"}, +{"p":"test/type3clone_harness.cpp","hops":3,"run":"bash test/type3clonecheck.sh"}, {"p":"test/includeprecise_unit.cpp","hops":4,"run":"bash test/includeprecisecheck.sh"}, -{"p":"test/rustimport_unit.cpp","hops":4,"run":"bash test/rustimportprecisecheck.sh"}], -"order":"evidence","partners":0,"run_first":1,"tests":6,"script_gates_unmodelled":941,"graph_ambiguous":3646,"graph_unresolved":19925,"graph_unindexed":310,"counts_floor":true,"next":"bash test/greptiercheck.sh"} +{"p":"test/rustimport_unit.cpp","hops":4,"run":"bash test/rustimportprecisecheck.sh"}, +{"p":"test/fuzz/readers/readers_light.cpp","hops":5,"run_unknown":true}], +... [1 more line(s); run it to see the whole thing] ``` **Caveats (stated by the binary):** @@ -3283,17 +3299,21 @@ _Insert BEFORE, with --edit-target-file pinning which same-named definition (her ``` $ ./build/ripwire . --insert-before-symbol=nonNegativeFloatDescKey --edit-payload=/aux/payload_note.h --edit-target-file=src/infra/sortutil.h -{"applied":"insert_before_symbol","symbol":"nonNegativeFloatDescKey","file":"src/infra/sortutil.h","span":{"start":3161,"end":3249},"lines":{"start":77,"end":78},"replaced_bytes":0,"old_file_bytes":8855,"new_file_bytes":8943,"file_eol":"lf","eol_normalized":false,"trailing_newline_folded":false,"sep … [line truncated: 753 more bytes on this line] +{"applied":"insert_before_symbol","symbol":"nonNegativeFloatDescKey","file":"src/infra/sortutil.h","span":{"start":3656,"end":3744},"lines":{"start":87,"end":88},"replaced_bytes":0,"old_file_bytes":9350,"new_file_bytes":9438,"file_eol":"lf","eol_normalized":false,"trailing_newline_folded":false,"sep … [line truncated: 753 more bytes on this line] {"n":"benchAdaptive","p":"bench/bench_radix_ab.cpp:157","l":[162]}, -{"n":"radixSortNonNegativeFloatsDesc","p":"src/infra/sortutil.h:108","l":[117]}, -{"n":"radixSortByScoreDescId","p":"src/infra/sortutil.h:123","l":[183]}], -"graph_ambiguous":3646,"graph_unresolved":19925,"graph_unindexed":310,"counts_floor":true},"tests_to_run":[{"p":"test/verify_radix.cpp","hops":1,"run":"bash test/greptiercheck.sh"}, +{"n":"radixSortNonNegativeFloatsDesc","p":"src/infra/sortutil.h:118","l":[127]}, +{"n":"radixSortByScoreDescId","p":"src/infra/sortutil.h:133","l":[193]}], +"graph_ambiguous":3637,"graph_unresolved":20080,"graph_unindexed":311,"counts_floor":true},"tests_to_run":[{"p":"test/verify_radix.cpp","hops":1,"run":"bash test/greptiercheck.sh"}, {"p":"test/adaptivecutshapefix/adaptive_cut_shape_test.cpp","hops":2,"run":"bash test/adaptivecutshapecheck.sh"}, +{"p":"test/connectcore_harness.cpp","hops":2,"run":"bash test/connectcorecheck.sh"}, {"p":"test/forrowfeatures_unit.cpp","hops":2,"run":"bash test/forrowfeaturescheck.sh"}, +{"p":"test/fuzz/readers/readers_domain.cpp","hops":2,"run_unknown":true}, {"p":"test/verify_csr.cpp","hops":2,"run":"bash test/a9disclosurecheck.sh"}, +{"p":"test/cloneband_harness.cpp","hops":3,"run":"bash test/clonebandcheck.sh"}, +{"p":"test/shstatus_harness.cpp","hops":3,"run":"bash test/gateexitcheck.sh"}, +{"p":"test/type3clone_harness.cpp","hops":3,"run":"bash test/type3clonecheck.sh"}, {"p":"test/includeprecise_unit.cpp","hops":4,"run":"bash test/includeprecisecheck.sh"}, -{"p":"test/rustimport_unit.cpp","hops":4,"run":"bash test/rustimportprecisecheck.sh"}], -"order":"evidence","partners":0,"run_first":1,"tests":6,"script_gates_unmodelled":941,"graph_ambiguous":3646,"graph_unresolved":19925,"graph_unindexed":310,"counts_floor":true,"next":"--uses=src/infra/sortutil.h:nonNegativeFloatDescKey"} +... [3 more line(s); run it to see the whole thing] ``` **Shaped by:** `--insert-after-symbol` @@ -3316,7 +3336,7 @@ _The opt-out: the same insert with the folded verification skipped — lines= st ``` $ ./build/ripwire . --insert-after-symbol=lessByScoreDescId --edit-payload=/aux/payload_note.h --no-post-check -{"applied":"insert_after_symbol","symbol":"lessByScoreDescId","file":"src/infra/sortutil.h","span":{"start":2641,"end":2729},"lines":{"start":59,"end":61},"replaced_bytes":0,"old_file_bytes":8767,"new_file_bytes":8855,"file_eol":"lf","eol_normalized":false,"trailing_newline_folded":true,"separator_p … [line truncated: 570 more bytes on this line] +{"applied":"insert_after_symbol","symbol":"lessByScoreDescId","file":"src/infra/sortutil.h","span":{"start":3136,"end":3224},"lines":{"start":69,"end":71},"replaced_bytes":0,"old_file_bytes":9262,"new_file_bytes":9350,"file_eol":"lf","eol_normalized":false,"trailing_newline_folded":true,"separator_p … [line truncated: 570 more bytes on this line] ``` **Shaped by:** `--edit-target-file` @@ -3352,11 +3372,11 @@ _The same plan committed: per-file locks, re-verify-before-write, atomic rename, ``` $ ./build/ripwire . --edit-plan=/aux/edit_plan.json --apply -{"schema":"ripwire.edit-plan/v1","mode":"apply","edits":1,"files":1,"callers_union":4,"graph_ambiguous":3646,"graph_unresolved":19925,"graph_unindexed":310,"counts_floor":true,"applied":1,"atomic_files":1,"atomic_scope":"per-file","rollback_on_write_error":true,"recheck_before_each_write":true,"mult … [line truncated: 584 more bytes on this line] +{"schema":"ripwire.edit-plan/v1","mode":"apply","edits":1,"files":1,"callers_union":4,"graph_ambiguous":3637,"graph_unresolved":20080,"graph_unindexed":311,"counts_floor":true,"applied":1,"atomic_files":1,"atomic_scope":"per-file","rollback_on_write_error":true,"recheck_before_each_write":true,"mult … [line truncated: 584 more bytes on this line] {"n":"benchAdaptive","p":"bench/bench_radix_ab.cpp:157","l":[162]}, -{"n":"radixSortNonNegativeFloatsDesc","p":"src/infra/sortutil.h:110","l":[119]}, -{"n":"radixSortByScoreDescId","p":"src/infra/sortutil.h:125","l":[185]}], -"graph_ambiguous":3646,"graph_unresolved":19925,"graph_unindexed":310,"counts_floor":true}}]} +{"n":"radixSortNonNegativeFloatsDesc","p":"src/infra/sortutil.h:120","l":[129]}, +{"n":"radixSortByScoreDescId","p":"src/infra/sortutil.h:135","l":[195]}], +"graph_ambiguous":3637,"graph_unresolved":20080,"graph_unindexed":311,"counts_floor":true}}]} ``` **Shaped by:** `--edit-check` @@ -3402,19 +3422,19 @@ _Bare --slice=SYM: the INVENTORY of sliceable locals (), so a calle ``` $ ./build/ripwire . --slice=rankGraphTeleport - - - - - - - - - - - - - + + + + + + + + + + + + + ... [3 more line(s); run it to see the whole thing] ``` @@ -3439,17 +3459,17 @@ _Forward flow: which statements the seed's value reaches, at the default depth b ``` $ ./build/ripwire . --slice=rankGraphTeleport:teleport --slice-flow=fwd - - + + - + teleport( pw.begin(), pw.end() );]]> - + - + ... [22 more line(s); run it to see the whole thing] @@ -3493,10 +3513,10 @@ $ ./build/ripwire . --slice-depth=3 _Hold a LOCATION, not a name: the enclosing-definition chain at FILE:LINE (a compiler error, a diff hunk, a stack frame), outermost -> innermost._ ``` -$ ./build/ripwire . --at=src/graph.h:14281 +$ ./build/ripwire . --at=src/graph.h:14272 - - + + ``` @@ -3520,7 +3540,7 @@ _No-LLM review-evidence bundle for the working-tree diff (clean tree = empty)._ ``` $ ./build/ripwire . --pr-context - ``` @@ -3546,11 +3566,11 @@ _Pairwise cross-arm conflict sites + suggested landing order (any committish sha ``` $ ./build/ripwire . --merge-scout=HEAD~2,HEAD~1 - - + + - + @@ -3625,7 +3645,7 @@ _A second selection, the `fix/` ref family, picked at capture time from the refs ``` $ ./build/ripwire . --stray-content=fix/ - + ``` @@ -3650,19 +3670,19 @@ _Select the genuinely-unmerged refs of the `lane/` ref family and feed them to m ``` $ ./build/ripwire . --stray-content=lane/ --plan - + - - - - + + + + - - + + ... [17 more line(s); run it to see the whole thing] ``` @@ -3686,9 +3706,9 @@ _Cross-branch ABI-break gate over the `lane/` ref family: struct byte-contract d ``` $ ./build/ripwire . --stray-content=lane/ --abi - - + + @@ -3696,7 +3716,7 @@ $ ./build/ripwire . --stray-content=lane/ --abi - + ... [17 more line(s); run it to see the whole thing] @@ -3721,10 +3741,10 @@ _Which ref's tree defines or mentions SYM — HEAD first, then every local branc ``` $ ./build/ripwire . --whereis=rankGraphTeleport - + - + - + + + - + - + @@ -3895,8 +3915,8 @@ _The cache-locality lens over every aggregate: fields READ TOGETHER but declared ``` $ ./build/ripwire . --field-affinity - + @@ -3930,16 +3950,16 @@ _Which of this repo's doc claims are now false. CHANGED: row attribute at= renam ``` $ ./build/ripwire . --doc-drift - + - - - - - - - + + + + + + + ... [20 more line(s); run it to see the whole thing] ``` @@ -3964,16 +3984,16 @@ _Which of this repo's doc claims are now false. CHANGED: row attribute at= renam ``` $ ./build/ripwire . --doc-drift - + - - - - - - - + + + + + + + ... [20 more line(s); run it to see the whole thing] ``` @@ -3997,16 +4017,16 @@ _Same report, with git history splitting stale mentions into deleted-by-commit v ``` $ ./build/ripwire . --doc-drift --with-history - - + + - - - - - - + + + + + + ... [20 more line(s); run it to see the whole thing] ``` @@ -4031,7 +4051,7 @@ _The house PLAN/DESIGN format's STRUCTURE check — never semantics; exit 2 when ``` $ ./build/ripwire . --plan-lint=test/planlintfix/wave.md - + @@ -4066,10 +4086,10 @@ $ ./build/ripwire . --from-trace=- AddressSanitizer:DEADLYSIGNAL ================================================================= ==41337==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000018 (pc 0x000102f4a1c8 bp 0x00016d2f1a40 sp 0x00016d2f19e0 T0) - #0 0x102f4a1c8 in rw::rankGraphTeleport(Graph const&, std::vector const&, float) src/graph.h:14281 - #1 0x102f3e884 in rw::rankGraph(Graph const&, float) src/graph.h:14324 - #2 0x102e11f30 in runDefaultMap(MainDispatch const&) src/main.cpp:1763 - #3 0x102e01a44 in main src/main.cpp:4515 + #0 0x102f4a1c8 in rw::rankGraphTeleport(Graph const&, std::vector const&, float) src/graph.h:14272 + #1 0x102f3e884 in rw::rankGraph(Graph const&, float) src/graph.h:14315 + #2 0x102e11f30 in runDefaultMap(MainDispatch const&) src/main.cpp:1760 + #3 0x102e01a44 in main src/main.cpp:4511 #4 0x1a2b3c0dc in start+0x9dc (dyld:arm64e+0x60dc) ==41337==ABORTING ``` @@ -4096,7 +4116,7 @@ _A command that exits 0: a minimal success record (exit, measured duration, disc $ ./build/ripwire . --run-trace="true" - + ``` @@ -4186,7 +4206,7 @@ _ONE budget-shared bundle: ranking + top bodies + caller sigs + notes + tests_to ``` $ ./build/ripwire . --pack-task="add a new output format flag to the CLI" - + - + Print the authoritative CLI usage and flag catalog to the caller-provided output streaminline void printUsage( std::FILE* out ) noexcept claude's `mcp add … -- ripwire --mcp`: the flag goes on the end of that command line, ahead of its newlineinline std::string wrapCliAddPost( const AgentTarget& row, std::string_view toolsArg ) @@ -4223,13 +4243,13 @@ _Fan-out form: one shared core + 3 per-agent slices carved along call-graph comm ``` $ ./build/ripwire . --pack-task="add a new output format flag to the CLI" --partition=3 - wraps a ; bundle role=core|partition i= symbols= modules= bytes= tokens=: one agent's ctx, symbols= ids assigned, bytes= its size; tokens= = est_tokens= = bytes/2.36 (flat, the densest rate; the inner ctx est_tokens= is language-weighted). Inner ctx task= root= budget_tokens= dropped_positive=: the task, p= base, the slice's token target, ranked candidates its budget cut. of_top=: rows ranked (far) / bodies (callers); s rel=caller|callee shared=: 1-hop edge, bodies reached (absent at 1). window: shown= total= capped= (capped=1 cut). run_unknown=1: no runner derivable (a guess would be worse). est_tokens=: price as emitted (an upper bound under compact). : rank N in this ranking, rows in r= order. : cyclomatic/cognitive complexity. : N callers in the index (absent: not measured). route=: the ranker: name-exact(X) = the task names symbol X (anchors: its evidence), subtoken+body = conceptual BM25 (:broad = 1-2 plain words, plain rg may also win; :declined(...) = a name hit refused as a common name). sc=: enclosing scope; the full id is p::sc::n (p= of the row or its ) and selectors take it. next=: the one pasteable follow-up. pure=1: const/constexpr signature (Swift: non-mutating) and no transitive side effect found; a hint. partitions=/requested=: partitions carved / asked for. modules=/split=: call-graph groups found / cuts forced to split one. core_symbols=/surface=: ids in the shared core / core plus the assignable remainder. budget_per_agent_tokens=: one agent's budget, core_budget_tokens= plus partition_budget_tokens=. total_bytes=N: bytes of all bundles together. overlap_mean=/overlap_max=: pairwise Jaccard over the ids partitions name, before trimming. shared_symbols=/union_symbols=: ids two or more partitions name / ids any partition names. core_overlap=: share of the core surface a partition reaches anyway. layer=: built-in arch layer (game|infra|render|math|audio|ai|test) from a dir name in p=; absent if none. c p=: the file a body callee's l= is in, printed when it is not the b row's own (no p=: the b's file). --> - + - + Print the authoritative CLI usage and flag catalog to the caller-provided output streaminline void printUsage( std::FILE* out ) noexcept claude's `mcp add … -- ripwire --mcp`: the flag goes on the end of that command line, ahead of…inline std::string wrapCliAddPost( const AgentTarget& row, std::string_view toolsArg ) @@ -4256,7 +4276,7 @@ _Task lens + a compact Mermaid flowchart of the top anchors' 1-hop edges._ ``` $ ./build/ripwire . --for="pagerank power iteration" --with-graph - + @@ -4334,14 +4354,14 @@ _Environment self-check: binary staleness, grammars, cache dir, git, tracked-bin ``` $ ./build/ripwire . --doctor - - + - - + + - - + @@ -4368,14 +4388,14 @@ _--doctor plus a LIVE integration inspection for one agent: PATH binary, install ``` $ ./build/ripwire . --doctor --agent=claude - - + - - + + - - + @@ -4404,7 +4424,7 @@ $ ./build/ripwire . --skipped - @@ -4493,10 +4513,10 @@ $ ./build/ripwire . --rank-by=churn --top-k=5 - - + + - + @@ -4524,22 +4544,22 @@ a trailing slash is ignored; absolute paths and '..' are refused). The global block stays byte-identical, a second page follows it — n=/of= are its counts (of= IS the total, so the paging half carries no total=), capped="1" has_more="1" next_offset= offset= limit= page it, and next= replays THIS run's own corpus flags (--since/--exclude) so the page it names is a page of the same answer. The symbol map collapses to a disclosed stub — the map was not asked for and was not ranked at all, which is why the header carries no pr_iters=. merge_bombs_skipped= stays on the global block: it counts the window's skipped commits, not the directory's._ ``` -$ ./build/ripwire . --rank-by=churn-decay --since=HEAD~9 --exclude=test --exclude=docs --exclude=skills --exclude=changelog.d --in=src --limit=3 +$ ./build/ripwire . --rank-by=churn-decay --since=HEAD~4 --exclude=test --exclude=docs --exclude=skills --exclude=changelog.d --in=src --limit=3 - - - - - - - + + + + + + + + + + - - - -... [4 more line(s); run it to see the whole thing] +... [7 more line(s); run it to see the whole thing] ``` **Shaped by:** `--external-surface`, `--doctor`, `--legend`, `--max-memory` @@ -4600,14 +4620,14 @@ _The same gating report under --legend=full — same rows, same exit 2; the defa ``` $ ./build/ripwire . --quality-delta --legend=full - - - - - - - + + + + + + + ... [23 more line(s); run it to see the whole thing] ``` @@ -4631,7 +4651,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=7138c98f32671fec entries=1167 +ripwire legend dictionary ripwire.dict/v1 dictv=ff6a8ec8438b7fe0 entries=1176 : 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=) @@ -4696,12 +4716,12 @@ _The family join: per function, which of four orthogonal evidence families fire, ``` $ ./build/ripwire . --ensemble --limit=8 - + - + @@ -4734,14 +4754,14 @@ $ ./build/ripwire . --exclude=present --exclude=bench --top-k=5 - - + + - - + + ... [17 more line(s); run it to see the whole thing] @@ -4765,17 +4785,17 @@ $ ./build/ripwire . --map-diff --top-k=5 - - + + - - + + -... [13 more line(s); run it to see the whole thing] +... [14 more line(s); run it to see the whole thing] ``` **Shaped by:** `--json`, `--limit` @@ -4799,14 +4819,14 @@ $ ./build/ripwire . --cache=/aux/warm2.ripwirecache --top-k=3 - - + + - - + + ... [17 more line(s); run it to see the whole thing] @@ -4849,14 +4869,14 @@ $ ./build/ripwire . --no-cache --top-k=3 - - + + - - + + ... [17 more line(s); run it to see the whole thing] @@ -4880,14 +4900,14 @@ $ ./build/ripwire . --no-ignore --top-k=3 - - + + - - + + ... [17 more line(s); run it to see the whole thing] @@ -4916,7 +4936,7 @@ $ ./build/ripwire . --max-file-size=8K --top-k=3 - + @@ -4996,14 +5016,14 @@ $ ./build/ripwire . --pin-census=/aux/pin_census.tsv --top-k=3 - - + + - - + + ... [17 more line(s); run it to see the whole thing] @@ -5021,7 +5041,7 @@ _initialize + tools/list: the manifest an agent host loads at session start — ``` $ ./build/ripwire '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize"}' '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | ./build/ripwire --mcp -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","serverInfo":{"name":"ripwire","version":"0.6.10-dev.99+gb1fdfdb4e"},"capabilities":{"tools":{},"resources":{}},"instructions":"Map before reading files. Start a new task with explore; use from_trace for an error; use impact plus uses … [line truncated: 759 more bytes on this line] +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","serverInfo":{"name":"ripwire","version":"0.6.10-dev.130+gb0cb13d8d"},"capabilities":{"tools":{},"resources":{}},"instructions":"Map before reading files. Start a new task with explore; use from_trace for an error; use impact plus uses … [line truncated: 760 more bytes on this line] {"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"analyze","description":"Architecture map for a directory: signatures and the call graph for the top symbols. Use when landing cold in a repo or subdir, before reading files; for a task-scoped inventory use 'for', for one symbol's neighborhood find_ … [line truncated: 742 more bytes on this line] {"name":"rank_by","description":"The SAME architecture map 'analyze' serves, ranked by a different signal instead of plain PageRank. rank_by = pagerank (default, omit it — the CLI's own unbiased --rank-by=pagerank; 'analyze' can rank differently on a tree with uncommitted changes, where it biases … [line truncated: 1077 more bytes on this line] {"name":"find_symbol","description":"A symbol's 1-hop neighborhood: the symbol (with a fetch_body handle) plus direct callers (calledBy) and callees (calls). Full transitive reach: 'impact'. Read/write/import sites, not just calls: 'uses'. JSON {symbol, calledBy, calls, defs, count, hop_tested, hop_ … [line truncated: 1181 more bytes on this line] @@ -5047,11 +5067,11 @@ _--mcp-legend=inline: every answer of the stdio session carries its own legend ( ``` $ ./build/ripwire '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize"}' '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"whereis","arguments":{"path":".","symbol":"rankGraphTeleport"}}}' '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"whereis","arguments":{"path":".","symbol":"computeOnePairOverlap"}}}' | ./build/ripwire --mcp --mcp-legend=inline -{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","serverInfo":{"name":"ripwire","version":"0.6.10-dev.99+gb1fdfdb4e"},"capabilities":{"tools":{},"resources":{}},"instructions":"Map before reading files. Start a new task with explore; use from_trace for an error; use impact plus uses … [line truncated: 756 more bytes on this line] +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","serverInfo":{"name":"ripwire","version":"0.6.10-dev.130+gb0cb13d8d"},"capabilities":{"tools":{},"resources":{}},"instructions":"Map before reading files. Start a new task with explore; use from_trace for an error; use impact plus uses … [line truncated: 757 more bytes on this line] {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [759 more display lines; full output is 26013 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --top-k=5` + +*Same map, capped to the 5 highest-ranked symbols.* + +**wall time: 1.38s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [89 more display lines; full output is 10199 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --top-k=5 --no-inventory` + +*The same capped map without its inventory tier: --top-k=5 leaves files out, so the default map appends (program entries, and the files the ranked rows left out) after its rows; --no-inventory drops that tier, and the ranked rows are the same.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --top-k=0 --expand=rankGraphTeleport` + +*NEW since the last capture: --top-k=0 means PAYLOAD-ONLY — no ranked map rides along with the body you asked for.* + +**wall time: 1.67s** + +````` + + + + + + + + + + + + +````` + +## `./build/ripwire . --token-budget=100` + +*GATE form: exit 3 if the map's own est_tokens exceeds the budget (over-budget failure shape).* + +**exit code: 3** — **wall time: 2.17s** + +````` + + +````` + +stderr: + +````` +ripwire: --token-budget exceeded: withheld_est_tokens=10482 > budget=100 +````` + +## `./build/ripwire . --for="incremental cache invalidation when a file content hash changes"` + +*The task lens: ranked signatures + quality metrics framed for the task.* + +**wall time: 9.33s** + +````` + + + + +incremental cache (--cache): per-file content hash + raw facts so a re-run re-parses ONLY c…constexpr std::uint32_t kCacheMagic = 0x4b505443 + +and every file whose content hash differs is re-parsed — so a stale or foreign blob self-heals…constexpr std::uint32_t kHeadSnapCacheScheme = 1 +inline McpRebuildBaseline mcpRebuildBaseline( const McpIndex& ix, bool isIncrementalPass ) +inline void noteFactlessMiss( ParsePoolShared& sh, std::size_t fileId, bool nestRefused ) noexcept +inline CachedRecordVerdict probeCachedRecord( const PrewarmMissPass& pass, std::size_t fi, const CachedRecordHead& record, std::string& bytes ) +inline void setTreeKey( Session& s, const std::vector<std::string>& files, std::string_view rootDir, const std::vector<std::uint64_t>& hashes, cons … [line truncated: 20 more bytes on this line] +inline bool ingestCommitTree( const std::string& root, const std::string& sha, const std::vector<std::string>& excludes, std::size_t maxFileBytes, IngestResult& ou … [line truncated: 7 more bytes on this line] +inline constexpr std::uint64_t kFnv1aLegacySeed64 = 1469598103934665603ull + +persistent in-memory index (parse once, reuse across MCP calls) ---- The MCP server is long-live…struct McpIndex +inline const McpIndex& getIndex( const std::string& root ) + + + + + + + + +inline std::uint64_t indexContentHash( const std::vector<std::string>& files, const std::vector<long long>& fileMtime, const std::vector<std::uint64_t> … [line truncated: 25 more bytes on this line] + +struct IngestFileScan + +inline std::uint64_t byteHash( const char* data, std::size_t n ) noexcept +… [217 more display lines; full output is 24497 bytes on 8 raw line(s)] +````` + +## `./build/ripwire . --for="rankGraphTeleport"` + +*Name-shaped query: the router picks name-exact BM25 (header says which/why).* + +**wall time: 6.64s** + +````` + + + + + +PageRank with an explicit teleport / personalization vector p (Σp = 1). The prior is name-quality-biased through biasPrior() so all rank modes share one weighting seam; the transition matrix (edgesinline RankedGraph rankGraphTeleport( const Graph& g, const std::vector<float>&am … [line truncated: 31 more bytes on this line] +#### The convergence disclosure contract +### Wave-2 adversarial verification (2026-08-19) — six probes against `aa97c9e` + + + + + + + + + + + + + + + + + + + + + +& p, float alpha = 0.85f ) +… [28 more display lines; full output is 6611 bytes on 29 raw line(s)] +````` + +## `./build/ripwire . --for="rankGraphTeleport" --no-route` + +*Same query with routing forced OFF (plain subtoken+body BM25) — contrast with the routed run.* + +**wall time: 7.20s** + +````` + + + + + +PageRank with an explicit teleport / personalization vector p (Σp = 1). The prior is name-quali…inline RankedGraph rankGraphTeleport( const Graph& g, const std::vector<float>& p, float alpha = 0.85f ) + +uniform-teleport PageRank (the default). A kRankFlagNotNamed unit (model.h) has no edge and a 0 …inline RankedGraph rankGraph( const Graph& g, float alpha = 0.85f ) + +The default map's PageRank — uniform teleport, the one rank that is a function of the Graph al…inline std::optional<RankedGraph>& storedDefaultRank() noexcept +inline ChurnRanking churnRankedGraph( const MainDispatch& d ) +inline constexpr const char* kChurnRankLegend = "<!-- rank_by=churn: k= is PageRank re-run with the teleport BIASED by git CHANGE-FREQUENCY over window= " "(a c… +struct RankedGraph +inline std::vector<float> takeRank( RankedGraph ranked, RankDisclosure& disclosureOut ) +inline std::vector<float> biasPrior( const Graph& g, const std::vector<float>& p ) +inline std::vector<float> churnTeleportWorkspace( const std::vector<std::string>& rootDirs, const IngestResult& ing, const char* since = "18 months ago … [line truncated: 21 more bytes on this line] +inline ChurnRanking churnDecayRanking( const MainDispatch& d, const rw::SinceScope& sinceScope, bool isScoped, const char* verbLabel ) +PageRankRun pageRankDouble( const sparseCsr<float>& inEdges, std::span<const double> weightedOutDegree, std::span<const double> teleport, std::span<double> rank… +inline std::string rankByText( const std::string& root, std::string_view mode, int topK, bool stable = false ) + + +PageRankRun pageRankDouble( const sparseCsr<float>& inEdges, std::span<const double> weightedOutDegree, std::span<const double> teleport, std::span< … [line truncated: 45 more bytes on this line] +inline std::string didYouMean( const IngestResult& ing, std::string_view name ) + +inline const McpIndex& getIndex( const std::string& root ) + +inline RankedGraph defaultRank( const Graph& g ) +#### The convergence disclosure contract +### Wave-2 adversarial verification (2026-08-19) — six probes against `aa97c9e` + +… [276 more display lines; full output is 30315 bytes on 77 raw line(s)] +````` + +## `./build/ripwire . --for="rankGraphTeleport" --signatures-only` + +*T3 opt-out: the signatures-only lens (no auto bodies, no bundle="auto" attribute) — contrast with the terminal default above.* + +**wall time: 6.92s** + +````` + + + + + +PageRank with an explicit teleport / personalization vector p (Σp = 1). The prior is name-quality-biased through biasPrior() so all rank modes share one weighting seam; the transition matrix (edgesinline RankedGraph rankGraphTeleport( const Graph& g, const std::vector<float>&am … [line truncated: 31 more bytes on this line] +#### The convergence disclosure contract +### Wave-2 adversarial verification (2026-08-19) — six probes against `aa97c9e` + + + + + + + + + + + + + +````` + +## `./build/ripwire . --for="tree-sitter parse of a source file" --adaptive` + +*Cut the result at the relevance cliff (Adaptive-k) — on a flat ranking nothing is cut and the header says so ([adaptive: kept N of N]).* + +**wall time: 7.11s** + +````` + + + + +inline bool topLevelEvidence( std::string_view source, const TSLanguage* language, const Predicate& predicate ) +The crawl's per-file byte ceiling. A text file larger than this is skipped: at this size it is o…constexpr std::size_t kDefaultMaxFileBytes = 4u * 1024u * 1024u +TSTree* parseTree( TSParser* parser, std::string_view src ) + +Exercise every registered grammar and its embedded query, reporting loaded and expected totalsinline DoctorGrammarProbe doctorProbeGrammars() +class SourceReader +constexpr std::array<LangEntry, 58> kLangTable = +struct FileHealth +struct SliceScan +explicit ParsedFile( std::string bytes ) : m_bytes( std::move( bytes ) ) +class ParsedFile + + + +inline RevSide sliceAtRev( const std::string& root, const std::string& sha, const std::string& rel, const Symbol& sym, SliceFam fam, const ::TSLanguage* grammar, st … [line truncated: 77 more bytes on this line] +std::vector<LocalNameFact> collectGatedLocalNames( std::string_view defBytes, std::uint32_t defStartLine, Lang lang ) +inline ModuleScan scanModule( std::string_view source, std::string_view path ) + +inline bool hasMainGuard( std::string_view source ) +inline bool hasPhantomScopeSeparator( TSNode qualified ) noexcept + + + + +inline void runParseWorker( ParsePoolShared& sh, unsigned t ) +… [242 more display lines; full output is 26630 bytes on 44 raw line(s)] +````` + +## `./build/ripwire . --for="why does src/lexical.h chooseForRanker pick name-exact BM25"` + +*Mention anchoring (default-on): a path and a Symbol literally named in the task get lifted; the header says what anchored.* + +**wall time: 6.53s** + +````` + + + + +The name-exact ranker AS THE RETRIEVAL LENS SERVES IT: whole-name BM25 plus the definition-over-…inline std::vector<float> lexicalScoresNameExactRanked( const IngestResult& ing, std::string_view query, const std::vector<float>* symbolScoreMul ) + +P11.12: the interpretive footer for --eval's ranker table, pulled into its own function so the 9…inline void printEvalRankerNote() + +calling agent knows to reformulate rather than trust the ranking. Calibrated empirically (2026-0…inline constexpr float kWeakLexicalScoreThreshold = 1.0f +inline RouteChoice chooseForRanker( const IngestResult& ing, std::string_view query ) +inline int runEvalRetrieval( const IngestResult& ing, const Graph& g ) +inline SubjectRoute chooseSubjectRouteUnchecked( const IngestResult& ing, const Graph& g, std::string_view task, bool servesBodiesAndCallers ) +inline std::string candidatesRootTag( std::size_t keep, std::size_t corpusCount, const CandidateProvenance& prov ) +inline std::vector<float> lexicalScoresNameExactTiered( const IngestResult& ing, std::string_view query, const std::vector<float>* symbolScoreMul ) +struct NameCorpusStats +inline SubjectRoute chooseSubjectRoute( const IngestResult& ing, const Graph& g, std::string_view task, bool servesBodiesAndCallers ) + + +inline int runEvalMined( const std::string& root, const IngestResult& ing, const Graph& g, const std::string& path ) +struct LensRanking +inline bool hasIdentifierShape( std::string_view w ) noexcept +inline int runEvalSkills( const std::string& root, const IngestResult& ing, const Graph& g, const std::string& labelsPath ) +inline std::vector<SourceSyntaxAnchor> applyAnchorHonesty( const IngestResult& ing, std::string_view task, SubjectRoute& out ) + + +inline int runEval( const std::string& root, const IngestResult& ing, const Graph& g, const std::vector<char>& currentDiff ) +inline constexpr int kLexWeightDoc = 2 +inline std::vector<float> lexicalScoresNameExact( const IngestResult& ing, std::string_view query ) +inline void hedgeOffTaskPick( const IngestResult& ing, ExemplarPick& pick ) +… [275 more display lines; full output is 31818 bytes on 18 raw line(s)] +````` + +## `./build/ripwire . --for="why does src/lexical.h chooseForRanker pick name-exact BM25" --no-mention-boost` + +*Same task with the anchor disabled — the contrast the flag exists for.* + +**wall time: 7.45s** + +````` + + + + +The name-exact ranker AS THE RETRIEVAL LENS SERVES IT: whole-name BM25 plus the definition-over-…inline std::vector<float> lexicalScoresNameExactRanked( const IngestResult& ing, std::string_view query, const std::vector<float>* symbolScoreMul ) + +P11.12: the interpretive footer for --eval's ranker table, pulled into its own function so the 9…inline void printEvalRankerNote() +inline int runEvalRetrieval( const IngestResult& ing, const Graph& g ) + +The route the subject reading picks, before the CONFIDENCE-ANCHOR check. `servesBodiesAndCallers…inline SubjectRoute chooseSubjectRouteUnchecked( const IngestResult& ing, const Graph& g, std::string_view task, bool servesBodiesAndCallers ) +inline constexpr float kWeakLexicalScoreThreshold = 1.0f +inline std::string candidatesRootTag( std::size_t keep, std::size_t corpusCount, const CandidateProvenance& prov ) +inline std::vector<float> lexicalScoresNameExactTiered( const IngestResult& ing, std::string_view query, const std::vector<float>* symbolScoreMul ) +struct NameCorpusStats +inline SubjectRoute chooseSubjectRoute( const IngestResult& ing, const Graph& g, std::string_view task, bool servesBodiesAndCallers ) +inline RouteChoice routeAnchorFallThrough( std::string_view query, const RouteChoice& anchored ) +inline int runEvalMined( const std::string& root, const IngestResult& ing, const Graph& g, const std::string& path ) +struct LensRanking +inline bool hasIdentifierShape( std::string_view w ) noexcept +inline int runEvalSkills( const std::string& root, const IngestResult& ing, const Graph& g, const std::string& labelsPath ) +inline std::vector<SourceSyntaxAnchor> applyAnchorHonesty( const IngestResult& ing, std::string_view task, SubjectRoute& out ) + + + +inline RouteChoice chooseForRanker( const IngestResult& ing, std::string_view query ) +inline int runEval( const std::string& root, const IngestResult& ing, const Graph& g, const std::vector<char>& currentDiff ) +inline constexpr int kLexWeightDoc = 2 +inline std::vector<float> lexicalScoresNameExact( const IngestResult& ing, std::string_view query ) +inline void hedgeOffTaskPick( const IngestResult& ing, ExemplarPick& pick ) +… [274 more display lines; full output is 31401 bytes on 18 raw line(s)] +````` + +## `./build/ripwire . --lego=Vehicle` + +*Interface -> implementors view: every existing impl of the named interface; the method contract is extracted for the C-family/Java/TS/Python tiers — for a Rust trait (this fixture) it discloses caveat="not-extracted-for-lang" rather than an empty list.* + +````` + + + + + + + + + +````` + +## `./build/ripwire . --exemplar="format byte sizes for humans"` + +*The repo's best-in-class instance to imitate before writing new code (picked by ROLE).* + +**wall time: 1.04s** + +````` + + + + +ripwire '.' --verify='calls(runDefaultMap, rankGraphTeleport)' + + +````` + +## `./build/ripwire . --help-task="write a cheerful release announcement"` + +*The honest half of the contract: a task with no ripwire-shaped evidence ABSTAINS with zero commands rather than guessing.* + +**wall time: 5.74s** + +````` + + + + +````` + +## `./build/ripwire . --recall="quality delta gating exit codes"` + +*Most relevant DOCS' full bodies (markdown only) — recall what is already written down.* + +````` +ripwire recall — "quality delta gating exit codes" — 139 relevant of 346 document files, best-first — total=139 shown=6 capped=1 truncated=5 generated_demoted=2 generated_demoted_paths="docs/TUNING.md,docs/LIMITS.md" max_tokens=8000 share_bytes=2792 est_tokens=5385 + +━━ docs/REFERENCE_GUIDE.md (relevance 21.975) ━━ [sections: 2 of 12 selected (27 in doc), section-granular; whole doc 43914 B; lines="405-417,418-425"; dropped_by_budget=10] +#### 6.2 Exit codes + +This is the part to wire into a script. + +| Code | Meaning | +| --- | --- | +| 0 | The command completed. | +| 1 | The command refused the request. A refusal names the reason on stderr. When `--callers`, `--callees`, `--uses`, `--impact` or `--path` refuse a selector that matches no indexed definition, they also print an answer on stdout: the verb's element with `found="0"` and the name to retry with. | +| 2 | A policy gate fired: `--arch` found a layering violation, `--scan-skill` found a CRITICAL, `--quality-delta` found new debt. | +| 3 | The output exceeded the token budget that you set. | +| 4 | `--test-gate` found an open obligation. | +| 5 | The memory guard stopped the run: over `--max-memory` (default 65% of the machine's memory) with no partial answer possible, or a verb other than the default map facing a partial index. One stderr line names the limit and the override. | + +#### 6.3 JSON output + +`--json` emits JSON instead of XML, with keys mirroring the XML attribute names one to one. It is an +allow-list: the default map, `--for`, `--pack-task`, `--callers`, `--callees`, `--impact`, +`--quality-delta`, `--test-gate`, `--metrics`, `--flags`, and `--plan-lanes`, which is JSON-native. Every other +verb refuses on stderr with exit 1 rather than silently falling back to XML, so a verb added tomorrow +refuses by default. + + + +━━ CHANGELOG.md (relevance 21.060) ━━ [sections: 1 of 129 selected (611 in doc), section-granular; whole doc 1298822 B; lines="2552-2576"; dropped_by_budget=128] [truncated: 2557 of 3826 bytes] +### Changed — `--quality-delta=A..B` answers the kinds it can under memory pressure, and exits 6 when that answer has no gating row (#387 follow-up) + +A tripped memory guard in the range form used to give exit 5 and nothing, so on a large repository a four-file change +… [141 more lines, 13749 bytes total] +````` + +stderr: + +````` +ripwire: redacted 1 secret from emitted context (keyword-gated-secret=1) — pass --no-redact to disable +````` + +## `./build/ripwire /aux/kbcorpus --recall="field affinity cache line data layout which fields are read together" --top-k=3 --max-tokens=1200` + +*The directory-as-knowledge-base pattern: --recall pointed at a 1560501-byte scratch dir of DUMPED TOOL OUTPUT (a git log, this repo's own generated command reference, --help text, an architecture doc, a fabricated JSON access log) instead of a source repo — no index to build, no daemon.* + +````` +ripwire recall — "field affinity cache line data layout which fields are read together" — 2 relevant of 2 document files, best-first — total=2 shown=1 capped=1 truncated=1 max_tokens=1200 share_bytes=2040 est_tokens=952 + +━━ commands.md (relevance 36.154) ━━ [sections: 1 of 166 selected (196 in doc), section-granular; whole doc 637312 B; lines="567-592"; dropped_by_budget=165] [truncated: 1854 of 4284 bytes] +#### Pattern: a directory of dumped tool output as a knowledge base + +**Answers:** can `--recall` serve as a zero-setup knowledge base over dumped tool output — a +`git log`, an API response dump, a fetched doc, ` --help` text — sitting in a scratch +directory, instead of a source repo? + +Yes, unmodified. `--recall` never distinguishes "a codebase" from any other directory it can +walk: point it at the scratch dir and query it. No index to build, no daemon, no mutable store +between runs — the whole cost is one cold parse. Two conditions decide whether it works at all, +and both are yours, because the file you write is the only thing that sets them: + +1. **Dump to `.md`.** `--recall` ranks DOCUMENT files: `.md`, plus the docparse'd + `.ipynb`/`.html`/`.csv` (and Office/PDF through the optional markitdown bridge). `.txt`, + `.log`, `.json` and extensionless files are **not** documents to it. A directory of those + answers `0 relevant of 0 document files` and exits 0 — which reads like "nothing matched + your terms" when what happened is "nothing was indexed at all". Redirect to `notes.md`, + never `notes.txt`. The recorded run below is that rule's own demonstration: its scratch dir + holds five dumps, and the header says `2 relevant of 2 document files` because only the two + `.md` ones are documents — the `git log`, the `--help` text and the JSON access log are not + in the population at all. + +2. **Keep `##` headings in the dump.** A headed document is served as whole ranked SECTIONS, so + an answer buried mid-file arrives at a small `--max-tokens`, and — while the served document + SET stays fixed — a larger ceiling returns a strict superset of it; the `[sections: S of R + selected (N in doc) … lines="…"; dropped_by_budget=D]` note names the ranges you actually got + and what the ceiling cost. … + +(capped: 1 of 2 relevant document files omitted — raise --max-tokens/budget_tokens or narrow the query for 1 more (~2548-byte budget)) +````` + +stderr: + +````` +ripwire: redacted 1 secret from emitted context (keyword-gated-secret=1) — pass --no-redact to disable +````` + +## `./build/ripwire . --tree` + +*File-by-file orientation map (top symbols per file).* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [365 more display lines; full output is 10973 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --html=/aux/map2.html` + +*Self-contained HTML force-directed call graph.* + +**wall time: 8.53s** + +````` +(empty) +````` + +Artifact written: + +````` + 155369 /aux/map2.html +````` + +## `./build/ripwire . --order=stable --top-k=5` + +*Stable (path/id) emit order — provider KV-cache hits across re-runs.* + +**wall time: 1.85s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [89 more display lines; full output is 10206 bytes on 1 raw line(s)] +````` + + +--- + +# navigate / answer a question + +## `./build/ripwire . --around=rankGraphTeleport` + +*Ego graph around one symbol — depth 1 BY DEFAULT now (the root's depth= says so): ~6 KB where the 2-hop neighbourhood is ~64 KB on this repo.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [170 more display lines; full output is 8460 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --around=rankGraphTeleport --around-depth=2` + +*The restoring knob: --around-depth=2 brings back the whole 2-hop neighbourhood (depth="2" on the root) — pay for it only when the 1-hop view was not enough.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [2437 more display lines; full output is 73649 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --around=rankGraphTeleport --around-fanout=4` + +*The other knob: --around-fanout=4 keeps only the 4 strongest edges per node (default 32) — the same 1-hop depth, a quarter of the rows.* + +**wall time: 1.68s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [14 more display lines; full output is 4254 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --callers=rankGraphTeleport` + +*Who calls SYM (1-hop in-edges).* + +**wall time: 1.24s** + +````` + + + + + + + + + + +````` + +## `./build/ripwire . --callers=rankGraphTeleport --legend=full` + +*The same rows under --legend=full: the default is the compact dialect (one compact comment plus schema="ripwire.callers/v1" on the root), and --legend=full restores the prose legend — every row byte and every completeness attribute (counts_floor=, graph_ambiguous=, next=) identical, ~3 KB more legend. Works on EVERY XML verb.* + +````` + + + + + + + + + + + +````` + +## `./build/ripwire . --callers=DoesNotExist` + +*Unknown-symbol REFUSAL shape (exit 1) with a did-you-mean from real edit distance.* + +**exit code: 1** — **wall time: 4.14s** + +````` + + +````` + +stderr: + +````` +ripwire: --callers symbol not found: DoesNotExist (note: the lexical definition scan stopped at its budget, 4096 files or 16 MiB, before reading every file, so this miss is not proof the bytes define nothing; --grep=DoesNotExist lists its text uses) +````` + +## `./build/ripwire . --callees=rankGraphTeleport` + +*What SYM calls (1-hop out-edges).* + +````` + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --uses=rankGraphTeleport` + +*The resolvable use-sites (call/read/write/import/extends) with file:line; count= is a floor.* + +````` + + + + + + + + + + + + +````` + +## `./build/ripwire . --graph-query='and(callers(name("rankGraphTeleport"),2),kind(all,fn))'` + +*Composable node-set query: functions within 2 caller-hops of rankGraphTeleport.* + +**wall time: 1.91s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [32 more display lines; full output is 3884 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --external-surface` + +*Names referenced but never defined in-corpus (stdlib/third-party surface). The root carries names/shown/capped; the default is a 100-row window now, so total= and a pasteable next= join them when it bites (the explicit --limit form carries the same quintet). The sh BUILTINS (cd/echo/set…) are dropped and COUNTED as builtins_excluded= — grep/sed/git stay, they ARE the surface.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [73 more display lines; full output is 5636 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --external-surface --include-builtins` + +*The restoring knob: --include-builtins keeps the shell builtins in the same 100-row window (they now compete for rows, so the window's tail differs).* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [73 more display lines; full output is 5512 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --path=main,rankGraphTeleport` + +*Shortest directed call-path SRC -> DST. CHANGED: now reports from_p/to_p/from_defs and resolves the right `main` (was reachable="0").* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --defs=main,rankGraphTeleport` + +*Which definitions each name binds, one row per definition group with sel= (the spelling that picks it alone in any verb), class=source|test and in= callers; source first.* + +**wall time: 1.02s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --connect=rankGraphTeleport,runEval,getIndex` + +*Minimal connecting subgraph over 3 symbols (finds shared-caller joins).* + +**wall time: 1.48s** + +````` + + + + + + + + + + +````` + +## `./build/ripwire . --impact=rankGraphTeleport` + +*Transitive blast radius — everything that reaches SYM. NOW carries shown/capped.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [73 more display lines; full output is 7439 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --mentions=rankGraphTeleport` + +*Markdown docs that name SYM in a backtick (doc<->code edges).* + +````` + + + + + + + + + + +````` + +## `./build/ripwire . --affected=src/graph.h` + +*Test files that transitively reach the changed file.* + +**wall time: 1.87s** + +````` + + + + + + + + + + + + + +````` + +## `./build/ripwire . --situ` + +*Mid-task situational report for the current git diff — recorded against a CLEAN tree (contrast with the sandbox run below).* + +**wall time: 5.59s** + +````` +ripwire situational-awareness — 0 changed file(s), 0 symbols in them +root: . +at: b0cb13d8d + (0 changed files — working tree is clean, nothing to analyze) +````` + +## `./build/ripwire . --test-gate` + +*Pre-PR gate on a CLEAN tree: no obligations, exit 0.* + +**wall time: 11.20s** + +````` + + +````` + +## `./build/ripwire . --grep=DISCLOSE` + +*Literal trigram-indexed search. Each hit carries its MATCHED line as the element's own CDATA (the wrapper is gone), plus shown/capped/hits_capped and a pasteable next= on the root.* + +**wall time: 1.07s** + +````` + +if data.get( "schema" ) != SCHEMA: raise SystemExit( f"{path}: unexpected schema {data.get('schema')!r} (expecte +if not str( data.get( "tasks_lock_content_sha256", "" ) ).startswith( "questions:" ): train_repos = select_tasks +if train_repos: raise SystemExit( f"{path}: records from repo(s) that re-derive to LocBench +if base and ctx and base["status"] == "ok" and ctx["status"] == "ok": paired.append( ( instance_id, base["re +if not repos: return 0.0, [] +if base["localization_hit"] is None or ctx["localization_hit"] is None: return 0.0 +if bv: ratios.append( cv / bv - 1 ) +if not ratios: return None, None +if rw is None or native is None: return None +if not paired: out["note"] = "zero complete paired (baseline,ripwire_cli) runs — nothing to analyze yet" +if contaminated: print( f" ** {contaminated} baseline run(s) invoked ripwire despite the no-ripwire contract " +if "note" in out: print( f" {out['note']}" ); return +if out["n_pairs"] != 27: failures.append( f"expected 27 paired runs, got {out['n_pairs']}" ) +if out["n_incomplete"] != 2: failures.append( f"expected 2 incomplete pairs (the orphan + the contaminated-basel +if out["n_repos"] != 3: failures.append( f"expected 3 repos, got {out['n_repos']}" ) +if out.get( "n_contaminated_baseline" ) != 1: failures.append( f"expected exactly 1 contaminated baseline run co +if not ( out["resolved_delta_mean"] > 0 ): failures.append( "expected a positive resolved-rate delta" ) +if not ( out["resolved_delta_bootstrap_95_lower"] > 0 ): failures.append( "expected a POSITIVE bootstrap 95% low +if out["tokens_out_ratio_p50"] is None or abs( out["tokens_out_ratio_p50"] - 0.08 ) > 1e-6: failures.append( f"e +if out.get( "n_resolved_pairs" ) != 27: failures.append( f"expected all 27 pairs resolution-scored, got {out.get +if out.get( "substitution_rate_baseline" ) != 0.0: failures.append( f"expected baseline substitution rate 0.0 (n +if out.get( "substitution_rate_ripwire" ) is None or abs( out["substitution_rate_ripwire"] - 0.75 ) > 1e-9: fail +if out.get( "n_substitution_ripwire" ) != 27: failures.append( f"expected 27 substitution-scored ripwire runs, g +if out3.get( "substitution_rate_ripwire" ) is not None or out3.get( "n_substitution_ripwire" ) != 0: failures.ap +if out2["n_pairs"] != 27: failures.append( f"evaluator-none: expected 27 pairs, got {out2['n_pairs']}" ) +if out2["n_resolved_pairs"] != 0: failures.append( f"evaluator-none: expected 0 resolution-scored pairs, got {ou +if out2["resolved_delta_mean"] is not None or out2["resolved_delta_bootstrap_95_lower"] is not None: failures.ap +if out2["tokens_out_ratio_p50"] is None or abs( out2["tokens_out_ratio_p50"] - 0.08 ) > 1e-6: failures.append( " +… [73 more display lines; full output is 17045 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --match='(if_statement) @i'` + +*The same shape query WITH an explicit capture — identical hits, no auto_captured= attribute.* + +**wall time: 2.42s** + +````` + +if data.get( "schema" ) != SCHEMA: raise SystemExit( f"{path}: unexpected schema {data.get('schema')!r} (expecte +if not str( data.get( "tasks_lock_content_sha256", "" ) ).startswith( "questions:" ): train_repos = select_tasks +if train_repos: raise SystemExit( f"{path}: records from repo(s) that re-derive to LocBench +if base and ctx and base["status"] == "ok" and ctx["status"] == "ok": paired.append( ( instance_id, base["re +if not repos: return 0.0, [] +if base["localization_hit"] is None or ctx["localization_hit"] is None: return 0.0 +if bv: ratios.append( cv / bv - 1 ) +if not ratios: return None, None +if rw is None or native is None: return None +if not paired: out["note"] = "zero complete paired (baseline,ripwire_cli) runs — nothing to analyze yet" +if contaminated: print( f" ** {contaminated} baseline run(s) invoked ripwire despite the no-ripwire contract " +if "note" in out: print( f" {out['note']}" ); return +if out["n_pairs"] != 27: failures.append( f"expected 27 paired runs, got {out['n_pairs']}" ) +if out["n_incomplete"] != 2: failures.append( f"expected 2 incomplete pairs (the orphan + the contaminated-basel +if out["n_repos"] != 3: failures.append( f"expected 3 repos, got {out['n_repos']}" ) +if out.get( "n_contaminated_baseline" ) != 1: failures.append( f"expected exactly 1 contaminated baseline run co +if not ( out["resolved_delta_mean"] > 0 ): failures.append( "expected a positive resolved-rate delta" ) +if not ( out["resolved_delta_bootstrap_95_lower"] > 0 ): failures.append( "expected a POSITIVE bootstrap 95% low +if out["tokens_out_ratio_p50"] is None or abs( out["tokens_out_ratio_p50"] - 0.08 ) > 1e-6: failures.append( f"e +if out.get( "n_resolved_pairs" ) != 27: failures.append( f"expected all 27 pairs resolution-scored, got {out.get +if out.get( "substitution_rate_baseline" ) != 0.0: failures.append( f"expected baseline substitution rate 0.0 (n +if out.get( "substitution_rate_ripwire" ) is None or abs( out["substitution_rate_ripwire"] - 0.75 ) > 1e-9: fail +if out.get( "n_substitution_ripwire" ) != 27: failures.append( f"expected 27 substitution-scored ripwire runs, g +if out3.get( "substitution_rate_ripwire" ) is not None or out3.get( "n_substitution_ripwire" ) != 0: failures.ap +if out2["n_pairs"] != 27: failures.append( f"evaluator-none: expected 27 pairs, got {out2['n_pairs']}" ) +if out2["n_resolved_pairs"] != 0: failures.append( f"evaluator-none: expected 0 resolution-scored pairs, got {ou +if out2["resolved_delta_mean"] is not None or out2["resolved_delta_bootstrap_95_lower"] is not None: failures.ap +if out2["tokens_out_ratio_p50"] is None or abs( out2["tokens_out_ratio_p50"] - 0.08 ) > 1e-6: failures.append( " +… [73 more display lines; full output is 16929 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --query="teleport pagerank" --top-k=5` + +*Raw BM25 ranking (debug lens; --for is the real verb).* + +**wall time: 2.51s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [23 more display lines; full output is 3783 bytes on 1 raw line(s)] +````` + + +--- + +# zoom the detail ladder + +## `./build/ripwire . --for="pagerank power iteration" --detail=2` + +*Importance-weighted detail: FULL bodies for top-2, signatures for the rest.* + +**wall time: 8.04s** + +````` + + + + + +NodeId order. Renumbering an otherwise-identical graph (the exact "same probe file, different so…inline constexpr float kScoreTieAbsEps = 1e-6f + +What a ranked document discloses about the power iteration that ordered it. `isPageRank == false…struct RankDisclosure + +The PageRank power iteration itself — the numeric kernel every ranked document's order comes f…PageRankRun pageRankDouble( const sparseCsr<float>& inEdges, std::span<const double> weightedOutDegree, std::span<const double> teleport, std::span<double> r … [line truncated: 10 more bytes on this line] +inline std::string rankByText( const std::string& root, std::string_view mode, int topK, bool stable = false ) +struct RankedGraph +inline constexpr const char* kChurnRankLegend = "<!-- rank_by=churn: k= is PageRank re-run with the teleport BIASED by git CHANGE-FREQUENCY over window= " "(a c… +inline std::uint32_t sliceRdIterationCeiling() noexcept +struct PageRankRun + +Render one form of the disclosure. Empty string whenever there is nothing to say — no power it…inline std::string renderDisclosure( const RankDisclosure& d, DiscloseAs as ) +inline std::uint32_t navRelevanceWeight( const Graph& g, NodeId n ) noexcept +inline RankedGraph rankGraphTeleport( const Graph& g, const std::vector<float>& p, float alpha = 0.85f ) +inline constexpr std::string_view kPowerShellPathPrependScope = "in PowerShell, for this window + + +inline std::string path_prepend_hint( std::string_view dir ) + +HOT_FILES = ( "src/pagerank.cpp", # the power-iteration loop — G2's no-allocation scope "src/infra/radixSort.h", # LSD radix entry points "src/infra/radixSort.inl", # the counting … [line truncated: 76 more bytes on this line] +handle_t leftmost_leaf() const +inline std::string doctorPathPrependLine( const std::string& selfPath ) + + + +… [130 more display lines; full output is 19059 bytes on 6 raw line(s)] +````` + +## `./build/ripwire . --pack-signatures --top-k=10` + +*Body-elided decl skeletons — recounted on this corpus. Measured as element bytes: the signature+doc elements --pack-signatures emits, against the SAME symbols' full bodies from --expand, with the CORPUS-ROOT PREFIX SUBTRACTED FROM BOTH SIDES. That subtraction is the whole methodology and the figure is meaningless without it: the root repeats inside every element's id= and p=, it is not what this verb elides, and counting it makes the headline a function of how deep the checkout happens to sit on disk — on one corpus, three spellings of the same root read 18.6 points apart before the subtraction and agree exactly after it. Root-neutralised on THIS repo: 89.7% fewer bytes at top-10, 88.0% at top-50, 87.8% at top-100 (re-derived 2026-10-10 when the C++ standard-member gate stopped std::vector/std::string calls such as out.push_back() and s.empty() from binding to in-tree namesakes by name: the ranked top-10/50 lost one-line container accessors (svector::push_back, WidePath::c_str, every empty) and gained one-line forwarding helpers and macros (kindIs, ASSUME, formatTo, emitTo) whose signature is nearly the whole body, so less of the set is elidable, from 92.7/88.7/87.6; before that, re-derived 2026-09-20 when the native Windows port landed: src/infra/os_win32.cpp and os_win32_logic.h are ~3,900 lines of new, heavily commented infra that the ranked top-10/50/100 now reach, and their bodies are this ratio's DENOMINATOR, so the figure rises without --pack-signatures eliding anything new, from top-50 87.1. Measured by test/showcasecapturecheck.sh's own recount arm on the combined tree, which is the gate that would otherwise report the drift; before that, re-derived 2026-09-17 at the self-check macro vocabulary rename: VERIFY/VERIFY_TEXT/VERIFY_DEBUG_ONLY/VERIFY_NOT_REACHED/VERIFY_SAME_THREAD/VERIFY_NO_ALIAS*/DYNMAP_VERIFY/DEGRADED_PATH_ALERT renamed to ASSUME/EXPECTS/ENSURES/DASSERT/UNREACHABLE/ASSUME_SAME_THREAD*/ASSUME_NO_ALIAS*/DYNMAP_ASSUME/DISCLOSE (plus new VALIDATE sites) across 839 identifier renames in 179 files, and a hand-written Diagnostics.h/diagnostics.cpp replacing the old ones outright: this moves both WHICH symbols the ranked top-10/50/100 hold and how large their bodies are, from top-50 85.2. A real re-derivation of a corpus that changed, not a tolerance edit; previously re-derived 2026-09-12 when the rows dropped the path-repeating id= for the short sc= scope: the signature side shrank, the bodies did not; before that, 89.5% / 81.8% / 84.3% re-derived 2026-09-10 at the sibs= cap raise: kMaxExpandSibs went 8 -> 100, so --expand's bodies now carry the file context the old cap hid — 89.3% of all sibling names — and the body side is this ratio's DENOMINATOR, so the figure rises without --pack-signatures eliding anything new. Measured on a fixed tree with the top-50 membership and the signature side unchanged: top-50 from 71.0. A real re-derivation of a corpus that changed, not a tolerance edit; previously re-derived 2026-09-09 at the printf-family -> std::print conversion: converting ~1,500 emitter call sites to rw::emitTo/emitRaw/formatTo across 93 files changes how large the ranked symbols' BODIES are, and the body side is this ratio's denominator — top-50 from 72.3. A real re-derivation of a corpus that changed, not a tolerance edit; previously re-derived 2026-09-08 at the confident-zero round, issues #62/#63/#66: that change adds symbols to src/graphlegend.h and the new src/preprocdead.h and re-homes two long comment blocks from call sites onto the helpers they explain, which moves both WHICH symbols the ranked top-50 holds and how large their bodies are — top-50 from 74.0. A real re-derivation of a corpus that changed, not a tolerance edit; previously re-derived 2026-09-06 at the stranger-audit fix round: the doctor, cache-sweep and html-provenance bodies grew this corpus's BODY side, moving top-50 from 75.6 — a real re-derivation, not a tolerance edit; before that, re-derived 2026-09-05 at the capture-audit close: lane L7's P16 caps --expand's sibs= at 8 names, which SHRINKS the body side of this ratio and moved the figure down from 84.5/80.2/80.6 — the V1 2026-08-15 re-center, when sibs=/inc= first grew the body side from 70.0/61.0/63.8, in reverse; both were real re-derivations, not tolerance edits). top-50 is the number to quote, because the sigs payload is top-50 regardless of --top-k and is therefore what THIS command emits. A single small/trivial body can still invert it (signature+doc bigger than the body), like the --format=columnar sibling below. test/showcasecapturecheck.sh (C) re-derives all three from this repo every run, in the same quantity, and fails if the caption and the recount drift apart.* + +**wall time: 1.90s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [143 more display lines; full output is 14928 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --outline=rankGraphTeleport --top-k=0` + +*Control-flow skeleton of one symbol, payload-only via the new --top-k=0.* + +````` + + + + +& p, float alpha = 0.85f ) +{ + PROFILE_SCOPE_DESCRIBE( "rankGraph: PageRank (power iteration)" ); + const std::vector pw = biasPrior( g, p ); + const std::size_t N = pw.size(); + std::vector teleport( pw.begin(), pw.end() ); + std::vector rankDouble( N, 0.0 ); + PageRankRun run{}; // an N == 0 graph never enters the kernel: { 0, converged } — see PageRankRun + if( N ) + { + ... + } + std::vector r( N, 0.f ); + std::transform( rankDouble.begin(), rankDouble.end(), r.begin(), []( double value ) { return float( value ); } ); + return { std::move( r ), run.iterationCount, run.hasConverged }; +} +]]> +````` + +## `./build/ripwire . --outline=rankGraphTeleport:1-10 --top-k=0` + +*CHANGED: a line range on --outline is now STRIPPED with a stderr note (it used to refuse).* + +````` + + + + +& p, float alpha = 0.85f ) +{ + PROFILE_SCOPE_DESCRIBE( "rankGraph: PageRank (power iteration)" ); + const std::vector pw = biasPrior( g, p ); + const std::size_t N = pw.size(); + std::vector teleport( pw.begin(), pw.end() ); + std::vector rankDouble( N, 0.0 ); + PageRankRun run{}; // an N == 0 graph never enters the kernel: { 0, converged } — see PageRankRun + if( N ) + { + ... + } + std::vector r( N, 0.f ); + std::transform( rankDouble.begin(), rankDouble.end(), r.begin(), []( double value ) { return float( value ); } ); + return { std::move( r ), run.iterationCount, run.hasConverged }; +} +]]> +````` + +stderr: + +````` +ripwire: --outline=rankGraphTeleport:1-10: --outline has no line-range form — outlining the whole symbol (use --expand=rankGraphTeleport:1-10 for a body slice) +````` + +## `./build/ripwire . --expand=rankGraphTeleport --top-k=0` + +*Full body + inline callee signatures.* + +**wall time: 1.25s** + +````` + + + + +: files the ranked rows show / do not (sum = files=), each named or counted below. : a program entry by its language's convention (C/Go/Rust main, Java/C# static main, a script main its module scope calls, __main__.py), callees as c rows; manifest entries not read. : n= unshown files under dir p=; f= names its code files, the rest (tests, docs, config, test/doc/example dirs) counted. declined=K: K call sites without edges, including inert Elixir quote sites after unquote/unquote_splicing re-entry. external=K: K calls proven outside the tree, no edge. locality_pinned=K: K calls pinned by locality alone (a guess). extent_suspect_syms=K: K defs failed containment, corpus-wide. macro_blanked_files=K: K files indexed from a macro-blanked re-parse. prov=scip|binding|import|split|final-segment: how that edge bound (absent: one unique name); split = one arm of an amb= pick; final-segment = a qualified type matched by last name only. files=/symbols=: files and symbols indexed; edges= distinct call edges; shown= symbols printed, a merged row counting each def; ambiguous= calls split over several defs, corpus-wide; unresolved= calls with in-tree evidence and no edge (every def language-filtered or unreachable, or binding refused); order= rows by rank (important-first, important-last; (auto:fill) = flipped past a size threshold) or by path (stable). skipped_oversize=K: K files over a size ceiling, not indexed. unindexed=ext:N: N text files of that extension no grammar reads (6 extensions at most). unindexed_exts=E: E such extensions in all, the list cut. : a non-test row an indexed test transitively reaches (absent otherwise, never 0). : that callee matched by name alone (receiver unproven); it does NOT mean the edge is false. sc=: enclosing scope; the full id is p::sc::n (p= of the row or its ) and selectors take it. amb=K: K calls split over several defs. locals_floor=1: locals= is a floor. role=hub: in= is 8 or more. s in= out= cx= ccx= loc= params= nest= cbo= lcom4= amp=: callers, callees, cyclomatic/cognitive complexity, lines, parameters, nesting depth, coupled types, class cohesion, callers + co-changed files. ev=/ev_why=: essential complexity (2+: jumps block extract-method; absent: 1) / the jumps behind it, tag:count. ev_floor=1: ev= is a FLOOR; noreturn calls, macro-hidden exits and unresolved gotos are unseen. layer=: built-in arch layer (game|infra|render|math|audio|ai|test) from a dir name in p=; absent if none. l=N: start line; only on a same-name overload's row, one row per body (bodyless decls fold into overloads=). f p=: a file; s t= n=: kind, name; c n=: a resolved callee. s k=: rank. --> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [108 more display lines; full output is 12764 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --deps` + +*File->file dependency graph (god-files, cycles).* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [913 more display lines; full output is 26182 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --hotspots` + +*Complexity x recent git churn (maintenance pain).* + +**wall time: 10.47s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [14 more display lines; full output is 5824 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --clones` + +*Token-normalized duplicate bodies.* + +**wall time: 2.58s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [309 more display lines; full output is 16373 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --cochange` + +*Files that change together in git (hidden coupling).* + +**wall time: 8.57s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --hotspots --since="2 weeks ago"` + +*Hotspots scoped to RECENT churn (the regression lens).* + +**wall time: 11.08s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [13 more display lines; full output is 5179 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --arch=test/archfix/rules.txt` + +*Enforce layering rules (exit 2 on violation) — run against the repo's own test fixture rules.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [1380 more display lines; full output is 192589 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire arch: 407 file(s) in go,swift,java,cs,php,dart,kt,gd,clj: this build resolves almost none of their imports to files, so an edge through one was mostly never judged: violations= is a floor +````` + +## `./build/ripwire . --lint` + +*Built-in AST checks (c-cast, goto, unsafe-c-fn, ...).* + +**wall time: 5.12s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [679 more display lines; full output is 70957 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --lint-rules=test/lintrulesfix/rules` + +*User lint rules (YAML, ast-grep style) from a directory.* + +**wall time: 2.29s** + +````` + + + + +use LOG() instead of printf +use LOG() instead of printf +use LOG() instead of printf +use LOG() instead of printf +use LOG() instead of printf + +````` + +stderr: + +````` +ripwire: lint-rules: test/lintrulesfix/rules/malformed.yaml:5: expected 'key: value' — file skipped +[math degraded] lint-rules: malformed rule file skipped (lintrules.h:494, auto rw::parseLintRuleFile(const std::string &, std::string_view, std::vector &)::(anonymous class)::operator()(std::size_t, const char *) const — logged once per site) +ripwire: AST query did not compile for any grammar: (this_is_not_a_real_node @x @@@ ((( ) +````` + +## `./build/ripwire . --lint --with-profile=report.txt` + +*Join MEASURED heat onto --lint findings — runs in a tiny fabricated demo corpus (one cache-pointer-chase-loop finding under a PROFILE_SCOPE site) because a real report needs a RIPWIRE_PROFILE build; the finding inside the profiled scope gains heat_* columns from the report's #PROF_TSV row.* + +**wall time: 1.12s** + +Input file: + +````` +#PROF_TSV_BEGIN one row per scope, aggregated across threads; counters are RAW integers +scope file line calls total_ms l1d_mpki +walk: chase pass x.cpp 9 12 48.500 7.250 +#PROF_TSV_END +````` + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [13 more display lines; full output is 3428 bytes on 1 raw line(s)] +````` + +The joined finding — past the display cut above, extracted so the join is visible: + +````` +p = p->next +````` + +## `./build/ripwire . --communities` + +*Cluster the call graph into cohesive modules.* + +**wall time: 1.28s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [190 more display lines; full output is 16651 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --zoom` + +*Nested module hierarchy (multi-level Louvain) + cross-module bridges — shown_levels="2" of levels= BY DEFAULT over the 40 largest top modules (~8 KB, where the whole tree is ~220 KB); a module AT the cut carries children=.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [139 more display lines; full output is 7687 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --zoom --zoom-levels=3` + +*The restoring knob: --zoom-levels=N prints N levels (0 = the whole tree); here three, ~11 KB.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [319 more display lines; full output is 14364 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --report` + +*Architecture summary (modules, god-files, cycles) as markdown.* + +````` + + +# ripwire architecture report + +4779 files · 44046 symbols · 43830 edges · 5053 modules (20765 call-graph isolated) + +Root: `.` + +Call-graph isolate provenance: 5724 declaration, 3481 header, 4519 source, 7041 document; 0 connected Louvain singletons + +## Modules (call-graph clusters; showing 12 of 5053) +- **src::emitTo@infra/emit.h:53:2760 [write,run,emit]** — 1880 symbols +- **src::kindIs@infra/nodekind.h:46:3271 [push,emit,read]** — 697 symbols +- **src::DISCLOSE@infra/Diagnostics.h:622:43913 [read,check,collect]** — 252 symbols +- **docs::`--top-k=N`@COMMANDS.md:59:9303 [pack,allow,insert]** — 185 symbols +- **src::str@infra/internedtext.h:323:16987 [resolve,write,find]** — 160 symbols +- **test/ownerhopfix/py/pkg::big_handler_001@broadcast.py:3:72** — 106 symbols +- **src/infra::fail@os_win32.cpp:63:2553 [open,get,close]** — 103 symbols +- **src::text@ingest_valuerefs.h:804:41690 [emit,open,mark]** — 91 symbols +- **src::sortUnique@infra/sortutil.h:55:2725 [connect,compute,collect]** — 87 symbols +- **src::tokIs@defectshape.h:170:8137 [scan,match,run]** — 83 symbols +- **src::unq@shstatus.h:164:6384 [visit,call,bind]** — 76 symbols +- **src::shSingleQuote@infra/shquote.h:19:960 [resolve,run,read]** — 75 symbols + +Not measured: 407 files in go,swift,java,cs,php,dart,kt,gd,clj (imports almost never resolved to files), so the god files and cycles below cover the resolved edges only. + +## God files (most depended-on; showing 10 of 310) +- `src/model.h` — 143 dependents +- `src/infra/emit.h` — 101 dependents +- `src/infra/sortutil.h` — 88 dependents +… [38 more lines, 4354 bytes total] +````` + +## `./build/ripwire . --seams` + +*Cross-module call seams no test reaches. NOW carries seam_pairs/shown/capped.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [90 more display lines; full output is 12759 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --mermaid` + +*Module (directory) dependency graph as a Mermaid diagram.* + +**wall time: 1.23s** + +````` +%% ripwire --mermaid: module (directory) dependency graph — node = dir (symbol count), edge = inter-module calls (>= 3). Render at mermaid.live. +flowchart LR + subgraph sg0 ["src"] + n105["src
14596"] + n106["src/infra
1684"] + end + subgraph sg1 ["test"] + n107["test
6966"] + n750["test/legochargefix
546"] + n472["test/fixtures/recallpassage
314"] + n491["test/fnslotcpp2
285"] + n913["test/lib
253"] + n712["test/ifacepeelfix/cpp
206"] + n1252["test/slotjoinfix
182"] + n1017["test/ownerhopfix/py/pkg
158"] + n408["test/expandmodefix
151"] + n410["test/expandsibsfix
149"] + n1222["test/rubyschemafix
99"] + n527["test/forbodyfoldfix/py
98"] + end + n77["docs
1265"] + subgraph sg3 ["bench"] + n63["bench/sectionfront
1033"] + n4["bench
558"] + n5["bench/agentloop
331"] + n50["bench/locbench/results/r5_pooling
237"] + n51["bench/locbench/results/r6_expansion
187"] + n60["bench/recalleval
113"] + n44["bench/locbench
107"] + n38["bench/headtohead/r3-headroom-2026-08-03
102"] +… [23 more lines, 1626 bytes total] +````` + +## `./build/ripwire . --owners` + +*Bus-factor: recency-weighted author ownership per file.* + +**wall time: 7.36s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [1060 more display lines; full output is 118617 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --dead-code=src` + +*Internal functions with no caller found in the index — a name-based graph reading, not a confidence score. NOTE the filter is a path-COMPONENT match: 'src' matches any .../src/... segment; use ./src to pin the root directory.* + +**wall time: 2.69s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [61 more display lines; full output is 16552 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --exercises=test/regression.sh` + +*Which symbols a TEST FILE exercises — the reverse direction of --affected.* + +**wall time: 1.20s** + +````` + + + +````` + +## `./build/ripwire . --community=0` + +*Drill into ONE call-graph community by id — the drill= the --communities output itself advertises.* + +````` + + + +````` + +## `./build/ripwire . --quality-delta` + +*The regression-free answer on a clone whose ledger holds stale acknowledgements (its HEAD's own history plus one demo row keyed to a finding that no longer measures as worse): the verdict-only document, every stale row collapsed to stale= and stale_by_kind=, with stale_next= naming the call below. Recorded in a throwaway clean clone so the contrast is structural — not a race with the release checkout's drift — and every regeneration on every machine sees the same pair.* + +**wall time: 54.98s** + +````` + + +````` + +stderr: + +````` +ripwire: no ./.ripwire_quality_baseline — auto-comparing the working tree vs git HEAD (commit the baseline with --quality-baseline to pin it) +````` + +## `./build/ripwire . --quality-delta --show-stale` + +*The same run, the same clone, the folded rows printed back: each stale acknowledgement as an row under the full header — the demo row included, and no quarter of the bytes saved by silence. Refused without --quality-delta.* + +**wall time: 39.51s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [167 more display lines; full output is 18592 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: no ./.ripwire_quality_baseline — auto-comparing the working tree vs git HEAD (commit the baseline with --quality-baseline to pin it) +````` + +## `./build/ripwire . --edit-check=rankGraphTeleport` + +*Fast per-symbol post-edit contract check vs git HEAD (unchanged on a clean tree).* + +**wall time: 25.94s** + +````` + + + + + + + + + +````` + +stderr: + +````` +ripwire: cache : over its 2048 MiB budget — evicted 139 blob(s) of other roots or other ripwire builds (this build's blobs for this root are kept) +````` + +## `./build/ripwire . --pr-context` + +*No-LLM review-evidence bundle for the working-tree diff (clean tree = empty).* + +**wall time: 4.07s** + +````` + + + +````` + +## `./build/ripwire . --pr-context=HEAD~1` + +*The BASEREF form: diffed against merge-base(BASEREF, HEAD), never the ref tip — here the previous commit on the current line (a ref with NO merge base falls back to a disclosed two-dot diff: anchor="ref-tip-two-dot").* + +**wall time: 9.71s** + +````` + + + + +````` + +## `./build/ripwire . --merge-scout=HEAD~2,HEAD~1` + +*Pairwise cross-arm conflict sites + suggested landing order (any committish sharing a merge base with HEAD works as an arm; one that does not is reported ok="0", never compared).* + +**wall time: 33.54s** + +````` + + + + + + + + + + + +````` + +## `./build/ripwire . --stray-content=lane/` + +*Which refs of the `lane/` ref family still hold divergent authored work vs HEAD, with verdicts.* + +**wall time: 14.72s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [855 more display lines; full output is 97265 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --stray-content=fix/` + +*A second selection, the `fix/` ref family, picked at capture time from the refs this checkout really has and never the selection above: merged refs are OMITTED from the rows and counted in merged=; refs sharing no merge base with HEAD (a shallow clone, or a pre-rewrite history) land in unknown= with ok="0" — the counters always reconcile against refs=.* + +**wall time: 9.43s** + +````` + + + +````` + +## `./build/ripwire . --stray-content=lane/ --plan` + +*Select the genuinely-unmerged refs of the `lane/` ref family 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).* + +**wall time: 50.18s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [282 more display lines; full output is 30962 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: warning: --plan scouted 1 of 66 unmerged branches for conflicts and landing order (limit: 12 arms, and 8192 indexed files across the arms); pass --detail=1 to scout every unmerged branch +````` + +## `./build/ripwire . --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.* + +**exit code: 1** — **wall time: 10.37s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --plan: --stray-content=zzzz-no-such-ref matches no local ref — a zero here would be a failure, not a measurement + (the filter is a substring match against refs/heads names; run bare --stray-content to list them, e.g. --stray-content=feat/) +````` + +## `./build/ripwire . --stray-content=lane/ --abi` + +*Cross-branch ABI-break gate over the `lane/` ref family: 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.* + +**exit code: 2** — **wall time: 56.42s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [565 more display lines; full output is 43815 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --whereis=rankGraphTeleport` + +*Which ref's tree defines or mentions SYM — HEAD first, then every local branch. The default lists the kind="def" rows (here the first 60, most on branches, each carrying tip= and date=) and counts the references in : on this symbol HEAD's references would fill the 60-row cap before the branch definitions arrive, so the whole list (below) shows fewer definitions, and the default serves the page that shows more of them, whatever its bytes.* + +**wall time: 30.23s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [36 more display lines; full output is 13459 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: warning: --whereis read the newest 378 of 639 local branches; 261 older were not read (limit: 2097152 tree entries across all refs, 379 refs with HEAD at this tree's size); pass --detail=1 to read every branch, or narrow the branches with a ref-name filter +ripwire: warning: --whereis left 407 branch blobs unparsed, their rows kind=text (limit: 256 blobs or 64 MB per answer); pass --detail=1 to parse every one +````` + +## `./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, so it shows far fewer definitions (here HEAD's one) than the default above (here 60). The default serves the all page only when it shows the same definitions as the defs page in strictly fewer bytes (a tie serves it too).* + +**wall time: 25.16s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [36 more display lines; full output is 13481 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: warning: --whereis read the newest 378 of 639 local branches; 261 older were not read (limit: 2097152 tree entries across all refs, 379 refs with HEAD at this tree's size); pass --detail=1 to read every branch, or narrow the branches with a ref-name filter +ripwire: warning: --whereis left 407 branch blobs unparsed, their rows kind=text (limit: 256 blobs or 64 MB per answer); pass --detail=1 to parse every one +````` + +## `./build/ripwire . --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.* + +**wall time: 33.24s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [35 more display lines; full output is 13988 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: warning: --whereis read the newest 378 of 639 local branches; 261 older were not read (limit: 2097152 tree entries across all refs, 379 refs with HEAD at this tree's size); pass --detail=1 to read every branch, or narrow the branches with a ref-name filter +ripwire: warning: --whereis left 407 branch blobs unparsed, their rows kind=text (limit: 256 blobs or 64 MB per answer); pass --detail=1 to parse every one +````` + +## `./build/ripwire . --whereis=computeOnePairOverlap --with-history` + +*Same, plus a git-history row (never / removed-by-commit) for names no tree carries.* + +**wall time: 41.75s** + +````` + + + + + + + +````` + +stderr: + +````` +ripwire: warning: --whereis read the newest 378 of 639 local branches; 261 older were not read (limit: 2097152 tree entries across all refs, 379 refs with HEAD at this tree's size); pass --detail=1 to read every branch, or narrow the branches with a ref-name filter +````` + +## `./build/ripwire . --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.* + +**wall time: 2.02s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [2400 more display lines; full output is 151078 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --flags --flip=RIPWIRE_ASAN` + +*Blast radius of turning ONE gate on: live code, symbols, transitive reach, covering tests.* + +**wall time: 2.05s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --flags --flip=RIPWIRE_ASA` + +*Unknown-gate refusal (exit 1) with a did-you-mean from a real edit distance (one character off RIPWIRE_ASAN).* + +**exit code: 1** — **wall time: 1.71s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --flip: no gate named 'RIPWIRE_ASA' in . (did you mean 'RIPWIRE_ASAN', 'RIPWIRE_ASAN_BIN', 'RIPWIRE_ASAN_PROBE_SEC', 'RIPWIRE_ASAN_PROBE_WHY'?) +ripwire: run `ripwire . --flags` for the gate table +````` + +## `./build/ripwire . --plan-lanes=3 --task="add a --since filter to the doc-drift verb and cover it with tests"` + +*NEW VERB: pre-hoc lane plan — which of 3 parallel worktrees would COLLIDE, before a line is written. JSON on stdout.* + +**wall time: 4.70s** + +````` +{"v":1,"verb":"plan-lanes","at":"b0cb13d8d","root":".","task":"add a --since filter to the doc-drift verb and cover it with tests","source":"partition","requested":3,"lane_count":3,"claim_key":"path+scope+name","on_conflict":"producing-lane-rebases","corpus":{"files":4779,"symbols":44046,"edges":438 … [line truncated: 338 more bytes on this line] +"symbols":[{"p":"./src/docdrift.h","n":"DriftResult","scope":"DriftResult","l":286,"id":"./src/docdrift.h::DriftResult::DriftResult"}, +{"p":"./src/docdrift.h","n":"computeDocDrift","scope":"docdrift","l":2441,"id":"./src/docdrift.h::docdrift::computeDocDrift"}, +{"p":"./src/docdrift.h","n":"kDocDriftLegend","scope":"docdrift","l":2739,"id":"./src/docdrift.h::docdrift::kDocDriftLegend"}, +{"p":"./src/docdrift.h","n":"writeDocDriftPage","scope":"docdrift","l":2909,"id":"./src/docdrift.h::docdrift::writeDocDriftPage"}, +{"p":"./src/mcpverbs.h","n":"docDriftText","scope":"rw","l":689,"id":"./src/mcpverbs.h::rw::docDriftText"}, +{"p":"./src/verbs_change.h","n":"runDocDrift","scope":"","l":1687,"id":null}]},"lanes":[{"id":"lane-0","task":"add a --since filter to the doc-drift verb and cover it with tests","claims":{"symbols":[{"p":"./src/editcheck.h","n":"editCheckPriceRoot","scope":"rw","key":"33219bb04158a6a8","id":"./src/ … [line truncated: 158 more bytes on this line] +{"p":"./src/docdrift.h","n":"writeGateability","scope":"docdrift","key":"42c456dfb55faee4","id":"./src/docdrift.h::docdrift::writeGateability","id_addressable":true,"id_collides_with":0,"l":2685,"ord":0,"overloads":1,"amb":2,"cx":6,"ccx":6,"churn":37,"tested":0}, +{"p":"./src/darkflags.h","n":"writeFlags","scope":"darkflags","key":"5c2c4a2b311b8dba","id":"./src/darkflags.h::darkflags::writeFlags","id_addressable":true,"id_collides_with":0,"l":3199,"ord":0,"overloads":1,"amb":1,"cx":9,"ccx":8,"churn":48,"tested":0}, +{"p":"./src/docdrift.h","n":"docDriftNextAttr","scope":"docdrift","key":"7723ed789a1c9c09","id":"./src/docdrift.h::docdrift::docDriftNextAttr","id_addressable":true,"id_collides_with":0,"l":2864,"ord":0,"overloads":1,"amb":0,"cx":6,"ccx":5,"churn":37,"tested":0}, +{"p":"./src/docdrift.h","n":"writeWeakDisclosures","scope":"docdrift","key":"7d760d428aab46d1","id":"./src/docdrift.h::docdrift::writeWeakDisclosures","id_addressable":true,"id_collides_with":0,"l":2839,"ord":0,"overloads":1,"amb":2,"cx":4,"ccx":5,"churn":37,"tested":0}, +{"p":"./src/docdrift.h","n":"recordWeakDisclosures","scope":"docdrift","key":"972779210e49c0cf","id":"./src/docdrift.h::docdrift::recordWeakDisclosures","id_addressable":true,"id_collides_with":0,"l":2430,"ord":0,"overloads":1,"amb":0,"cx":2,"ccx":1,"churn":37,"tested":0}, +{"p":"./src/testmap.h","n":"scriptGatesUnmodelledCount","scope":"rw","key":"98c4487e2e9e08bc","id":"./src/testmap.h::rw::scriptGatesUnmodelledCount","id_addressable":true,"id_collides_with":0,"l":2016,"ord":0,"overloads":1,"amb":0,"cx":4,"ccx":4,"churn":77,"tested":0}, +{"p":"./src/main.cpp","n":"scanReportVerbPrecedence","scope":"","key":"9ab981e987e8108e","id":null,"id_addressable":false,"id_collides_with":0,"l":3038,"ord":0,"overloads":1,"amb":0,"cx":8,"ccx":11,"churn":509,"tested":0}, +{"p":"./src/graphlegend.h","n":"impactTestedPartitionLegend","scope":"rw","key":"9ca0ff23a3b8620e","id":"./src/graphlegend.h::rw::impactTestedPartitionLegend","id_addressable":true,"id_collides_with":0,"l":567,"ord":0,"overloads":1,"amb":0,"cx":4,"ccx":4,"churn":241,"tested":0}, +{"p":"./src/pageview.h","n":"secondaryCutAttrs","scope":"rw","key":"a10ea8d3bdca1dfb","id":"./src/pageview.h::rw::secondaryCutAttrs","id_addressable":true,"id_collides_with":0,"l":404,"ord":0,"overloads":1,"amb":0,"cx":3,"ccx":2,"churn":29,"tested":0}, +{"p":"./src/main.cpp","n":"emitNoteAddUnprovenDefs","scope":"","key":"a950332ccfce6b8d","id":null,"id_addressable":false,"id_collides_with":0,"l":695,"ord":0,"overloads":1,"amb":1,"cx":2,"ccx":1,"churn":509,"tested":0}, +{"p":"./src/docdrift.h","n":"sortDocsByLiveDrift","scope":"docdrift","key":"d5de682411b9a9a9","id":"./src/docdrift.h::docdrift::sortDocsByLiveDrift","id_addressable":true,"id_collides_with":0,"l":2390,"ord":0,"overloads":1,"amb":0,"cx":2,"ccx":2,"churn":37,"tested":0}, +{"p":"./src/mcpverbs.h","n":"unknownSubVerbRefusal","scope":"rw","key":"e336d39b0a6addea","id":"./src/mcpverbs.h::rw::unknownSubVerbRefusal","id_addressable":true,"id_collides_with":0,"l":6305,"ord":0,"overloads":1,"amb":0,"cx":3,"ccx":2,"churn":673,"tested":0}], +"files":[{"p":"./src/darkflags.h","symbols":1,"churn":48,"ccx":8,"hotspot_rank":31}, +{"p":"./src/docdrift.h","symbols":5,"churn":37,"ccx":19,"hotspot_rank":51}, +{"p":"./src/editcheck.h","symbols":1,"churn":70,"ccx":10,"hotspot_rank":53}, +{"p":"./src/graphlegend.h","symbols":1,"churn":241,"ccx":4,"hotspot_rank":34}, +{"p":"./src/main.cpp","symbols":2,"churn":509,"ccx":12,"hotspot_rank":5}, +{"p":"./src/mcpverbs.h","symbols":1,"churn":673,"ccx":2,"hotspot_rank":4}, +{"p":"./src/pageview.h","symbols":1,"churn":29,"ccx":2,"hotspot_rank":173}, +{"p":"./src/testmap.h","symbols":1,"churn":77,"ccx":4,"hotspot_rank":36}]},"blast_radius":{"reaches":52,"files_total":17,"capped":false,"files":["./src/darkflags.h","./src/docdrift.h","./src/editcheck.h","./src/editplan.h","./src/editpreview.h","./src/flipimpact.h","./src/main.cpp","./src/mcp.h","./ … [line truncated: 202 more bytes on this line] +"tests_total":0,"tests_capped":false,"tests_granularity":"claimed-symbols","untested":52,"module_span":1,"notes":[], +"execution":{"policy":"codex-lane/v1","model":"gpt-5.6-sol","reasoning":"high","rule":"complex-or-wide","basis":"structural-only","signals":{"claims":13,"files":8,"module_span":1,"max_ccx":11,"sum_ccx":61,"ambiguous_calls":6,"blast_reaches":52,"contract_touches":0,"conflicts":0,"untested":52,"tests_ … [line truncated: 134 more bytes on this line] +{"id":"lane-1","task":"add a --since filter to the doc-drift verb and cover it with tests","claims":{"symbols":[{"p":"./src/taskroute.h","n":"classifyRoutesUncapped","scope":"rw::taskroute","key":"0c5e6053e914484d","id":"./src/taskroute.h::rw::taskroute::classifyRoutesUncapped","id_addressable":true … [line truncated: 101 more bytes on this line] +… [71 more display lines; full output is 20762 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --plan-lanes --brief=/aux/lanes_brief.txt` + +*NEW VERB, explicit form: one line per lane, lane boundaries are the ones you wrote (the defensible mode).* + +**wall time: 9.60s** + +Input file: + +````` +add a --since filter to the doc-drift verb +add the CLI parse arm and help text for the new filter +write regression tests for the new filter +````` + +````` +{"v":1,"verb":"plan-lanes","at":"b0cb13d8d","root":".","task":null,"source":"brief","requested":3,"lane_count":3,"claim_key":"path+scope+name","on_conflict":"producing-lane-rebases","corpus":{"files":4779,"symbols":44046,"edges":43830,"ambiguous":3637,"unresolved":20080},"carve":null,"core":{"files" … [line truncated: 4 more bytes on this line] +"symbols":[]},"lanes":[{"id":"lane-0","task":"add a --since filter to the doc-drift verb","claims":{"symbols":[{"p":"./src/docdrift.h","n":"recordUnchecked","scope":"docdrift","key":"12641dab14abc8fd","id":"./src/docdrift.h::docdrift::recordUnchecked","id_addressable":true,"id_collides_with":0,"l":2 … [line truncated: 72 more bytes on this line] +{"p":"./src/docdrift.h","n":"sortWeakGroupsByPath","scope":"docdrift","key":"1944ba506280ff80","id":"./src/docdrift.h::docdrift::sortWeakGroupsByPath","id_addressable":true,"id_collides_with":0,"l":2401,"ord":0,"overloads":1,"amb":0,"cx":1,"ccx":0,"churn":37,"tested":0}, +{"p":"./src/mcpverbs.h","n":"docDriftText","scope":"rw","key":"1fa68e8d93c05a59","id":"./src/mcpverbs.h::rw::docDriftText","id_addressable":true,"id_collides_with":0,"l":689,"ord":0,"overloads":1,"amb":0,"cx":1,"ccx":0,"churn":673,"tested":0}, +{"p":"./src/recall.h","n":"docFileMask","scope":"rw","key":"3149a219f599664c","id":"./src/recall.h::rw::docFileMask","id_addressable":true,"id_collides_with":0,"l":113,"ord":0,"overloads":1,"amb":0,"cx":4,"ccx":4,"churn":49,"tested":0}, +{"p":"./src/docdrift.h","n":"writeDocDriftPage","scope":"docdrift","key":"380b7de5df1cfd73","id":"./src/docdrift.h::docdrift::writeDocDriftPage","id_addressable":true,"id_collides_with":0,"l":2909,"ord":0,"overloads":1,"amb":10,"cx":14,"ccx":15,"churn":37,"tested":0}, +{"p":"./src/docdrift.h","n":"computeDocDrift","scope":"docdrift","key":"3b19cc3d8996c3b2","id":"./src/docdrift.h::docdrift::computeDocDrift","id_addressable":true,"id_collides_with":0,"l":2441,"ord":0,"overloads":1,"amb":1,"cx":26,"ccx":38,"churn":37,"tested":0}, +{"p":"./src/docdrift.h","n":"DriftResult","scope":"DriftResult","key":"422ab39546b6e0bd","id":"./src/docdrift.h::DriftResult::DriftResult","id_addressable":true,"id_collides_with":0,"l":286,"ord":0,"overloads":1,"amb":0,"cx":0,"ccx":0,"churn":37,"tested":0}, +{"p":"./src/docdrift.h","n":"writeGateability","scope":"docdrift","key":"42c456dfb55faee4","id":"./src/docdrift.h::docdrift::writeGateability","id_addressable":true,"id_collides_with":0,"l":2685,"ord":0,"overloads":1,"amb":2,"cx":6,"ccx":6,"churn":37,"tested":0}, +{"p":"./src/verbs_change.h","n":"runDocDrift","scope":"","key":"904831e5c0f66b39","id":null,"id_addressable":false,"id_collides_with":0,"l":1687,"ord":0,"overloads":1,"amb":1,"cx":5,"ccx":4,"churn":91,"tested":0}, +{"p":"./src/ensemble.h","n":"kEnsembleChurnSince","scope":"ensemble","key":"a34fc78c05bf56a8","id":"./src/ensemble.h::ensemble::kEnsembleChurnSince","id_addressable":true,"id_collides_with":0,"l":121,"ord":0,"overloads":1,"amb":0,"cx":0,"ccx":0,"churn":24,"tested":0}, +{"p":"./src/mcpverbs.h","n":"unknownSubVerbRefusal","scope":"rw","key":"e336d39b0a6addea","id":"./src/mcpverbs.h::rw::unknownSubVerbRefusal","id_addressable":true,"id_collides_with":0,"l":6305,"ord":0,"overloads":1,"amb":0,"cx":3,"ccx":2,"churn":673,"tested":0}, +{"p":"./src/docdrift.h","n":"kDocDriftLegend","scope":"docdrift","key":"ff2ba74637bbbebf","id":"./src/docdrift.h::docdrift::kDocDriftLegend","id_addressable":true,"id_collides_with":0,"l":2739,"ord":0,"overloads":1,"amb":0,"cx":0,"ccx":0,"churn":37,"tested":0}], +"files":[{"p":"./src/docdrift.h","symbols":7,"churn":37,"ccx":60,"hotspot_rank":51}, +{"p":"./src/ensemble.h","symbols":1,"churn":24,"ccx":0,"hotspot_rank":131}, +{"p":"./src/mcpverbs.h","symbols":2,"churn":673,"ccx":2,"hotspot_rank":4}, +{"p":"./src/recall.h","symbols":1,"churn":49,"ccx":4,"hotspot_rank":48}, +{"p":"./src/verbs_change.h","symbols":1,"churn":91,"ccx":4,"hotspot_rank":35}], +"symbols_total":4253,"symbols_capped":true},"blast_radius":{"reaches":27,"files_total":8,"capped":false,"files":["./src/docdrift.h","./src/fordocbody.h","./src/main.cpp","./src/mcp.h","./src/mcpserver.h","./src/mcpverbs.h","./src/recall.h","./src/verbs_for.h"]},"tests_to_run":[], +"tests_total":0,"tests_capped":false,"tests_granularity":"claimed-symbols","untested":27,"module_span":5,"notes":[], +"execution":{"policy":"codex-lane/v1","model":"gpt-5.6-sol","reasoning":"xhigh","rule":"wide-contract-work","basis":"structural-only","signals":{"claims":12,"files":5,"module_span":5,"max_ccx":38,"sum_ccx":70,"ambiguous_calls":14,"blast_reaches":27,"contract_touches":1,"conflicts":0,"untested":27,"t … [line truncated: 139 more bytes on this line] +{"id":"lane-1","task":"add the CLI parse arm and help text for the new filter","claims":{"symbols":[{"p":"./scripts/optremarks.py","n":"main","scope":"","key":"01b3b880f77d1512","id":null,"id_addressable":false,"id_collides_with":188,"l":285,"ord":0,"overloads":1,"amb":0,"cx":23,"ccx":31,"churn":18, … [line truncated: 12 more bytes on this line] +{"p":"./scripts/merge_resolve.py","n":"main","scope":"","key":"0618162fab697309","id":null,"id_addressable":false,"id_collides_with":188,"l":208,"ord":0,"overloads":1,"amb":0,"cx":17,"ccx":34,"churn":4,"tested":0}, +{"p":"./src/cli.h","n":"HelpLine","scope":"rw","key":"1489844dbc310b82","id":"./src/cli.h::rw::HelpLine","id_addressable":true,"id_collides_with":0,"l":3144,"ord":0,"overloads":1,"amb":0,"cx":0,"ccx":0,"churn":648,"tested":0}, +{"p":"./src/cli.h","n":"HelpFilter","scope":"HelpFilter","key":"3103a5e8bfc33d38","id":"./src/cli.h::HelpFilter::HelpFilter","id_addressable":true,"id_collides_with":0,"l":3223,"ord":0,"overloads":1,"amb":0,"cx":0,"ccx":0,"churn":648,"tested":0}, +{"p":"./docs/docs_commands_build.py","n":"main","scope":"","key":"4015853681ded3bc","id":null,"id_addressable":false,"id_collides_with":188,"l":900,"ord":0,"overloads":1,"amb":0,"cx":19,"ccx":28,"churn":19,"tested":0}, +{"p":"./src/mcprefusal.h","n":"kMcpValueFields","scope":"rw::mcprefuse","key":"4a7106e488a2aa80","id":"./src/mcprefusal.h::rw::mcprefuse::kMcpValueFields","id_addressable":true,"id_collides_with":0,"l":304,"ord":0,"overloads":1,"amb":0,"cx":0,"ccx":0,"churn":51,"tested":0}, +{"p":"./src/query.h","n":"tryParsePredicateOnAll","scope":"query","key":"786acc4dbfec612b","id":"./src/query.h::query::tryParsePredicateOnAll","id_addressable":false,"id_collides_with":1,"l":114,"ord":0,"overloads":2,"amb":0,"cx":1,"ccx":0,"churn":22,"tested":0}, +{"p":"./src/cli.h","n":"printUsageTier","scope":"rw","key":"82b7af67acdca479","id":"./src/cli.h::rw::printUsageTier","id_addressable":true,"id_collides_with":0,"l":3274,"ord":0,"overloads":1,"amb":0,"cx":2,"ccx":1,"churn":648,"tested":0}, +{"p":"./src/crossref.h","n":"writeWhereisTextCut","scope":"crossref","key":"9a3ef6403f53ce21","id":"./src/crossref.h::crossref::writeWhereisTextCut","id_addressable":true,"id_collides_with":0,"l":5162,"ord":0,"overloads":1,"amb":1,"cx":3,"ccx":3,"churn":110,"tested":0}, +… [59 more display lines; full output is 18377 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --plan-lanes=99 --task=x` + +*Out-of-range refusal shape for the lane count.* + +**exit code: 1** — **wall time: 1.48s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --plan-lanes=99 is out of range — N must be 2..16 (1 is not a fan-out) +````` + +## `./build/ripwire . --layout=Symbol` + +*CPU/GPU contract view of one struct: computed offsets/sizes/padding + mirror check.* + +**wall time: 1.50s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + +
+ + + + + + + + + + + + + +… [262 more display lines; full output is 25845 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --doc-drift --gateability` + +*The finishable to-do list: docs whose LIVE failing anchors a date-stamp would reclassify.* + +**wall time: 3.02s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [293 more display lines; full output is 27272 bytes on 1 raw line(s)] +````` + +Tail of the same output — the `` section: + +````` + + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --doc-drift --with-history` + +*Same report, with git history splitting stale mentions into deleted-by-commit vs never-existed.* + +**wall time: 5.50s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [238 more display lines; full output is 25895 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --from-trace=-` + +*Map a pasted stack trace onto indexed symbols. CHANGED: in_corpus= now reports the real count (was 0).* + +Input file: + +````` +AddressSanitizer:DEADLYSIGNAL +================================================================= +==41337==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000018 (pc 0x000102f4a1c8 bp 0x00016d2f1a40 sp 0x00016d2f19e0 T0) + #0 0x102f4a1c8 in rw::rankGraphTeleport(Graph const&, std::vector const&, float) src/graph.h:14272 + #1 0x102f3e884 in rw::rankGraph(Graph const&, float) src/graph.h:14315 + #2 0x102e11f30 in runDefaultMap(MainDispatch const&) src/main.cpp:1760 + #3 0x102e01a44 in main src/main.cpp:4511 + #4 0x1a2b3c0dc in start+0x9dc (dyld:arm64e+0x60dc) +==41337==ABORTING +````` + +````` + + + + + + + + + + + +PageRank with an explicit teleport / personalization vector p (Σp = 1). The prior is name-quality-biased through biasPrior() so all rank modes share one weighting seam; the transition matrix (edgesinline RankedGraph rankGraphTeleport( const Graph& g, const std::vector<float>&am … [line truncated: 31 more bytes on this line] + +uniform-teleport PageRank (the default). A kRankFlagNotNamed unit (model.h) has no edge and a 0 prior weight, so the uniform share is over the ranked nodes: every other node's teleport is the value itinline RankedGraph rankGraph( const Graph& g, float alpha = 0.85f ) +int runDefaultMap( const MainDispatch& d ) +int main( int argc, char** argv ) + + + +& p, float alpha = 0.85f ) +{ + PROFILE_SCOPE_DESCRIBE( "rankGraph: PageRank (power iteration)" ); + const std::vector pw = biasPrior( g, p ); + const std::size_t N = pw.size(); + std::vector teleport( pw.begin(), pw.end() ); + std::vector rankDouble( N, 0.0 ); + PageRankRun run{}; // an N == 0 graph never enters the kernel: { 0, converged } — see PageRankRun + if( N ) + { + double teleportMass = 0.0; +… [18 more display lines; full output is 5279 bytes on 29 raw line(s)] +````` + +## `./build/ripwire . --notes` + +*List all field notes (write-side memory) — the committed .ripwire_notes at the repo root, each with the sha/branch it was recorded at.* + +````` + + + + + + + + + + + gate scripts' claim (~line 1305) is NOT enforced — the derived-vs-stated sibling loop here covers docs/EVALS.md only. It drifted 407→451 unnoticed (fixed 2026-08-23). To close: grep both files ('file:line:' parsing) in the gateCountClaims arm.]]> + + + + +````` + +## `./build/ripwire . --pack-task="add a new output format flag to the CLI"` + +*ONE budget-shared bundle: ranking + top bodies + caller sigs + notes + tests_to_run. CHANGED: rows now carry n=/id=.* + +**wall time: 3.18s** + +````` + + + + +Print the authoritative CLI usage and flag catalog to the caller-provided output streaminline void printUsage( std::FILE* out ) noexcept + +claude's `mcp add … -- ripwire --mcp`: the flag goes on the end of that command line, ahead of its newlineinline std::string wrapCliAddPost( const AgentTarget& row, std::string_view toolsArg ) +struct AgentTarget + +ONE recipe path for every agent that can shell out, and the point is that the RECOMMENDATION does not vary by agent — only the MCP alternative does. Before this there were four near-identical CLI-fiinline void wrapEmitCliFirst( const AgentTarget& row, const std::string& token, c … [line truncated: 83 more bytes on this line] + +mcp-tools pass-through. Written into the server command only where its argument shape is known to be one more plain argument: the JSON args arrays (cursor/windsurf/gemini), opencode's command arrayinline bool wrapWritesToolsArg( const AgentTarget& row ) noexcept +inline std::string classNewGroupXml( const IngestResult& ing, std::span<const ClassNewRow> rows, std::string_view rootPrefix, EscapeFn ex ) + + + + + + + + + + +… [84 more display lines; full output is 12334 bytes on 77 raw line(s)] +````` + +## `./build/ripwire . --pack-task="add a new output format flag to the CLI" --partition=3` + +*Fan-out form: one shared core + 3 per-agent slices carved along call-graph communities.* + +**wall time: 2.38s** + +````` + wraps a ; bundle role=core|partition i= symbols= modules= bytes= tokens=: one agent's ctx, symbols= ids assigned, bytes= its size; tokens= = est_tokens= = bytes/2.36 (flat, the densest rate; the inner ctx est_tokens= is language-weighted). Inner ctx task= root= budget_tokens= dropped_positive=: the task, p= base, the slice's token target, ranked candidates its budget cut. of_top=: rows ranked (far) / bodies (callers); s rel=caller|callee shared=: 1-hop edge, bodies reached (absent at 1). window: shown= total= capped= (capped=1 cut). run_unknown=1: no runner derivable (a guess would be worse). est_tokens=: price as emitted (an upper bound under compact). : rank N in this ranking, rows in r= order. : cyclomatic/cognitive complexity. : N callers in the index (absent: not measured). route=: the ranker: name-exact(X) = the task names symbol X (anchors: its evidence), subtoken+body = conceptual BM25 (:broad = 1-2 plain words, plain rg may also win; :declined(...) = a name hit refused as a common name). sc=: enclosing scope; the full id is p::sc::n (p= of the row or its ) and selectors take it. next=: the one pasteable follow-up. pure=1: const/constexpr signature (Swift: non-mutating) and no transitive side effect found; a hint. partitions=/requested=: partitions carved / asked for. modules=/split=: call-graph groups found / cuts forced to split one. core_symbols=/surface=: ids in the shared core / core plus the assignable remainder. budget_per_agent_tokens=: one agent's budget, core_budget_tokens= plus partition_budget_tokens=. total_bytes=N: bytes of all bundles together. overlap_mean=/overlap_max=: pairwise Jaccard over the ids partitions name, before trimming. shared_symbols=/union_symbols=: ids two or more partitions name / ids any partition names. core_overlap=: share of the core surface a partition reaches anyway. layer=: built-in arch layer (game|infra|render|math|audio|ai|test) from a dir name in p=; absent if none. c p=: the file a body callee's l= is in, printed when it is not the b row's own (no p=: the b's file). --> + + + + + +Print the authoritative CLI usage and flag catalog to the caller-provided output streaminline void printUsage( std::FILE* out ) noexcept + +claude's `mcp add … -- ripwire --mcp`: the flag goes on the end of that command line, ahead of…inline std::string wrapCliAddPost( const AgentTarget& row, std::string_view toolsArg ) +struct AgentTarget + +ONE recipe path for every agent that can shell out, and the point is that the RECOMMENDATION doe…inline void wrapEmitCliFirst( const AgentTarget& row, const std::string& token, const std::string_view executablePath, const WrapListing& listing ) noexcept + + + + + +inline bool printUsageTier( std::FILE* out, HelpTier tier, std::string_view want ) noexcept + + + + + + + + +NodeId order. Renumbering an otherwise-identical graph (the exact "same probe file, different so…inline constexpr float kScoreTieAbsEps = 1e-6f + +What a ranked document discloses about the power iteration that ordered it. `isPageRank == false…struct RankDisclosure + +The PageRank power iteration itself — the numeric kernel every ranked document's order comes f…PageRankRun pageRankDouble( const sparseCsr<float>& inEdges, std::span<const double> weightedOutDegree, std::span<const double> teleport, std::span<double> r … [line truncated: 10 more bytes on this line] +inline std::string rankByText( const std::string& root, std::string_view mode, int topK, bool stable = false ) +struct RankedGraph +inline constexpr const char* kChurnRankLegend = "<!-- rank_by=churn: k= is PageRank re-run with the teleport BIASED by git CHANGE-FREQUENCY over window= " "(a c… +inline std::uint32_t sliceRdIterationCeiling() noexcept +struct PageRankRun + +Render one form of the disclosure. Empty string whenever there is nothing to say — no power it…inline std::string renderDisclosure( const RankDisclosure& d, DiscloseAs as ) +inline std::uint32_t navRelevanceWeight( const Graph& g, NodeId n ) noexcept +inline RankedGraph rankGraphTeleport( const Graph& g, const std::vector<float>& p, float alpha = 0.85f ) +inline constexpr std::string_view kPowerShellPathPrependScope = "in PowerShell, for this window + + +inline std::string path_prepend_hint( std::string_view dir ) + +HOT_FILES = ( "src/pagerank.cpp", # the power-iteration loop — G2's no-allocation scope "src/infra/radixSort.h", # LSD radix entry points "src/infra/radixSort.inl", # the counting … [line truncated: 76 more bytes on this line] +handle_t leftmost_leaf() const +inline std::string doctorPathPrependLine( const std::string& selfPath ) + + + +… [166 more display lines; full output is 20878 bytes on 15 raw line(s)] +````` + +## `./build/ripwire . --export=cc.json:/aux/ripwire2.cc.json` + +*Per-file metrics as CodeCharta cc.json.* + +**wall time: 3.85s** + +````` +(empty) +````` + +Artifact written: + +````` + 731441 /aux/ripwire2.cc.json +{"projectName":"project","apiVersion":"1.3","attributeDescriptors":{"loc":{"title":"Lines of Code","description":"Physical line count","direction":-1},"symbols":{"title":"Symbols","description":"Definitions in the file","direction":-1},"cx":{"title":"Cyclomatic Complexity","description":"Sum of per-symbol cyclomatic complexity","direction":-1},"cognitive_cx":{"title":"Cognitive Complexity","descri +````` + +## `./build/ripwire . --batch=/aux/batch2.txt` + +*One-turn sweep: 4 newline-delimited verb:arg sub-queries answered in ONE deduped .* + +**wall time: 11.34s** + +Input file: + +````` +for:incremental cache invalidation +callers:rankGraphTeleport +grep:DISCLOSE +lego:Vehicle +````` + +````` + + + + + + + + + +incremental cache (--cache): per-file content hash + raw facts so a re-run re-parses ONLY c…constexpr std::uint32_t kCacheMagic = 0x4b505443 + +Composed exactly the way every OTHER blob family is (quality.h): one fixed-width identity hex pe…inline std::string spanTierMemoPath( const std::string& diskPath ) + +P1-15 — the `_reingest` envelope field for a response whose handling ran an INCREMENTAL pass, …inline bool mcpRefreshedThisRequest( std::uint64_t passesAtEntry ) + +Ingest the tree at `sha`, materialized out of `root`'s object store. The HEAD side reuses the SA…inline bool ingestCommitTree( const std::string& root, const std::string& sha, const std::vector<std::string>& excludes, std::size_t maxFileBytes, IngestResult&… … [line truncated: 4 more bytes on this line] +struct FileHealth +inline std::vector<std::vector<NodeId>> legoImplementorsOnSurface( const IngestResult& ing, const std::vector<std::vector<NodeId>>& implementors, const std:: … [line truncated: 10 more bytes on this line] +inline std::pair<Snapshot, bool> computeHeadSnapshot( const std::string& root, const std::string_view* cacheNever = nullptr, std::size_t maxFileBytes = kDefault… +inline RawFacts runParsePool( IngestResult& result, const char* rootDir, std::string_view cacheFile, bool captureValueUses, CacheRecords& cache, const CacheLoadStats& cacheStats, IngestFileScan … [line truncated: 62 more bytes on this line] +inline McpRebuildBaseline mcpRebuildBaseline( const McpIndex& ix, bool isIncrementalPass ) +inline std::string mcpFreshFields( std::uint64_t passesAtEntry ) + + + +inline std::string receiptNextFor( const std::string& fileIdentity, const std::string& symbolName, const std::string& foldJson, const std::string& firstTestRun ) +AncestorCacheScope( TSNode root, bool enabled ) : previous( tAncestorCache ) + +const char* cacheArtifactVerdict( const std::string& path, bool captureValueUses ) +inline bool parentCacheOn() +… [236 more display lines; full output is 60648 bytes on 1 raw line(s)] +````` + + +--- + +# self-diagnosis + +## `./build/ripwire . --doctor` + +*Environment self-check: binary staleness, grammars, cache dir, git, tracked-binary staleness — exit 1 when any check fails (here: the PATH install is older than ./build).* + +**exit code: 1** — **wall time: 40.75s** + +````` + + + + + + + + + + +````` + + +--- + +# security + +## `./build/ripwire --scan-skill=skills/ripwire-orient/SKILL.md` + +*Scan a single skill file for injection/exfiltration patterns before installing.* + +````` + + + +````` + +stderr: + +````` +ripwire scan: 0 finding(s) in skills/ripwire-orient/SKILL.md +````` + +## `./build/ripwire --scan-skills=skills` + +*Scan a whole skills directory (exit 2 = CRITICAL, 1 = WARN). Explicit-DIR form only.* + +**wall time: 1.31s** + +````` + + + +````` + +stderr: + +````` +ripwire scan: 0 finding(s) total (26 skill file(s) scanned, 0 unscannable file(s) skipped, 0 denylisted subtree(s) not descended) +````` + + +--- + +# knobs / modes + +## `./build/ripwire . --rank-by=churn --top-k=5` + +*Rank by git change-frequency prior instead of PageRank.* + +**wall time: 11.19s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --rank-by=churn-decay --since=HEAD~4 --exclude=test --exclude=docs --exclude=skills --exclude=changelog.d --in=src --limit=3` + +*Scope the recent-changes answer to ONE directory. The global block stays byte-identical, a second page follows it — n=/of= are its counts (of= IS the total, so the paging half carries no total=), capped="1" has_more="1" next_offset= offset= limit= page it, and next= replays THIS run's own corpus flags (--since/--exclude) so the page it names is a page of the same answer. The symbol map collapses to a disclosed stub — the map was not asked for and was not ranked at all, which is why the header carries no pr_iters=. merge_bombs_skipped= stays on the global block: it counts the window's skipped commits, not the directory's.* + +**wall time: 8.25s** + +````` + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --rank-by=bogus --top-k=5` + +*An unknown value REFUSES (exit 1), NAMED, with the supported set listed.* + +**exit code: 1** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --rank-by: unknown value 'bogus' (supported: pagerank|authority|hub|rrf|churn|churn-decay) +````` + +## `./build/ripwire . --callers=rankGraphTeleport --format=columnar` + +*Columnar output: paths table + parallel arrays, ~15-60% fewer tokens on MANY-row lists — small results can be LARGER (the columnar legend is a fixed cost).* + +````` + + +0=src/mcpindex.h 1=src/graph.h 2=src/eval.h 3=src/main.cpp + +0,1,1,2,3,3,3 +getIndex,rankGraph,anchoredLexicalRank,runEval,churnDecayRanking,churnRankedGraph,runDefaultMap +1224,14313,14982,171,1432,1471,1758 +fn,fn,fn,fn,fn,fn,fn +0,0,0,0,0,0,0 +1340,14317,15033,328,1446,1485 1486 1500,1878 + + +````` + +## `./build/ripwire . --for="cache invalidation" --format=candidates --top-k=5` + +*Flat top-K export for an external reranker.* + +**wall time: 4.69s** + +````` + + + +inline std::string spanTierMemoPath( const std::string& diskPath ) + + +inline std::vector<std::vector<NodeId>> legoImplementorsOnSurface( const IngestResult& ing, const std::vector<std::vector<NodeId>>& implementors, const std::vector<NodeId>& surfaceIds ) + + +### See the map — not just the numbers + + +inline std::string receiptNextFor( const std::string& fileIdentity, const std::string& symbolName, const std::string& foldJson, const std::string& firstTestRun ) + + +AncestorCacheScope( TSNode root, bool enabled ) : previous( tAncestorCache ) + + +````` + +## `./build/ripwire . --callers=rankGraphTeleport --format=bogus` + +*An unknown --format value REFUSES (exit 1), named, with the supported set listed.* + +**exit code: 1** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --format: unknown value 'bogus' (supported: xml|columnar|rows|candidates) +````` + +## `./build/ripwire . --callers=rankGraphTeleport --json` + +*Machine-parseable JSON, same content, keys mirror the XML attrs.* + +````` +{"of":"rankGraphTeleport","defs":1,"count":7,"root":".","hop_tested":0,"hop_untested":7,"graph_ambiguous":3637,"graph_unresolved":20080,"graph_unindexed":311,"counts_floor":true,"callers":[{"t":"fn","n":"getIndex","p":"src/mcpindex.h:1224","sites_at":["1340"]}, +{"t":"fn","n":"rankGraph","p":"src/graph.h:14313","sites_at":["14317"]}, +{"t":"fn","n":"anchoredLexicalRank","p":"src/graph.h:14982","sites_at":["15033"]}, +{"t":"fn","n":"runEval","p":"src/eval.h:171","sites_at":["328"]}, +{"t":"fn","n":"churnDecayRanking","p":"src/main.cpp:1432","sites_at":["1446"]}, +{"t":"fn","n":"churnRankedGraph","p":"src/main.cpp:1471","sites_at":["1485","1486","1500"]}, +{"t":"fn","n":"runDefaultMap","p":"src/main.cpp:1758","sites_at":["1878"]}]} +````` + +## `./build/ripwire . --hotspots --json` + +*JSON refusal shape: an unsupported verb refuses loudly instead of silently falling back to XML.* + +**exit code: 1** — **wall time: 1.02s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --json is not yet supported for --hotspots — supported: the default map, --for, --pack-task, --callers/--callees, --impact, --quality-delta, --test-gate, --metrics, --defs, --flags, and --plan-lanes which is JSON-native (e.g. ripwire

--callers=SYM --json) +````` + +## `./build/ripwire . --hotspots --limit=3 --offset=3` + +*Pagination: 3 items, skipping the first 3 (deterministic seams).* + +**wall time: 9.00s** + +````` + + + + + + + +````` + +## `./build/ripwire . --ignore-tests --top-k=5` + +*Drop test paths from the corpus before ranking.* + +**wall time: 2.19s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [86 more display lines; full output is 9788 bytes on 1 raw line(s)] +````` + +stderr: + +````` +[validate] symbolCount == N && fileCount == ing.files.size() && referenceCount == ing.references.size() is false — warmsnap: the graph section describes another model (warmsnap_graph.h:274, std::optional rw::warmsnap::readGraph(Session &, const IngestResult &) — logged once per site) +````` + +## `./build/ripwire . --exclude=present --exclude=bench --top-k=5` + +*Drop matching paths (repeatable) before ranking.* + +**wall time: 4.46s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [87 more display lines; full output is 10042 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --map-diff --top-k=5` + +*Full map re-ranked with teleport toward git-changed files — clean tree, so changed=0 and it degrades to the plain map.* + +**wall time: 5.68s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +````` + +stderr: + +````` +[validate] symbolCount == N && fileCount == ing.files.size() && referenceCount == ing.references.size() is false — warmsnap: the graph section describes another model (warmsnap_graph.h:274, std::optional rw::warmsnap::readGraph(Session &, const IngestResult &) — logged once per site) +````` + +## `./build/ripwire . --no-cache --top-k=3` + +*Force a cold parse (bypass the warm TMPDIR cache) — shows the cold-vs-warm cost.* + +**wall time: 6.90s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [80 more display lines; full output is 10040 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --cache=/aux/warm2.ripwirecache --top-k=3` + +*Explicit incremental cache at a path OUTSIDE the repo (first call writes it).* + +**wall time: 5.55s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [80 more display lines; full output is 10040 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: cache : over its 2048 MiB budget — evicted 205 blob(s) of other roots or other ripwire builds (this build's blobs for this root are kept) +````` + +Artifact written: + +````` + 40244008 /aux/warm2.ripwirecache +````` + +## `./build/ripwire . --max-file-size=8K --top-k=3` + +*Skip files above a size bound before parsing (note the corpus shrink in the header).* + +**wall time: 2.64s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [20 more display lines; full output is 4949 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --scip=does_not_exist.scip --callers=rankGraphTeleport` + +*SCIP overlay with a missing index REFUSES (exit 1) naming the file — never silently serves the name-based map you named a precision index to improve on (it used to degrade in silence).* + +**exit code: 1** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --scip=does_not_exist.scip: cannot open the index — refusing rather than serving the name-based map you named a precision index to improve on (generate one with scip-clang/scip-python, or drop --scip) +````` + +## `./build/ripwire src test --top-k=5` + +*Multi-root workspace: ONE merged graph over two roots, paths labeled /.* + +**wall time: 9.06s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --eval` + +*Self-eval: co-change recall vs BM25.* + +**wall time: 52.91s** + +````` +ripwire --eval (co-change recovery, averaged over 80 historical commits) + ranker recall@5 recall@10 recall@20 + ripwire 8.5% 9.4% 16.3% + BM25 8.7% 9.8% 11.9% + BM25sub 7.4% 10.1% 13.5% + BM25body 10.9% 12.7% 22.6% + fused 5.7% 7.4% 14.7% + anchored 10.9% 12.7% 21.6% + same-dir 0.3% 0.9% 2.0% + random 0.1% 0.2% 0.4% <- floor (random ranking over F=4779 files) + note: `ripwire` here is the DEFAULT MAP's structural-only PageRank (importance, not + relatedness) — it is NOT what a --for/--query retrieval call ranks with. BM25 / + BM25sub / BM25body are QUERY-TIME lexical rankers (whole-name / subtoken / + subtoken+body); fused = RRF(ripwire, BM25sub); anchored = BM25body + anchored PPR + expansion (--for --anchor, EXPERIMENTAL). The SHIPPED default for --for/--query is + the subtoken+body lexical family (routed to name-exact only for an identifier-shaped + query — lexical.h chooseForRanker), so a gap between the ripwire and BM25* rows here + is structural-importance-vs-lexical-relatedness on a co-change task, not the shipped + retrieval path losing to an alternative it was never running. +````` + +## `./build/ripwire . --eval-retrieval` + +*Known-item retrieval eval: MRR + recall@k per ranker per query mode.* + +**wall time: 288.35s** + +````` +ripwire --eval-retrieval (known-item, 4000 doc-commented symbols; gold is in-corpus by construction) + sample: population=11893 scored=4000 rule=smallest-key CAPPED — a SUBSET, not the population + (smallest fnv1a64(scope::name) over the population, cut on the key so an identity is never split; + path- and order-independent, but a corpus this size is NOT graded exhaustively — say so when citing it) + ingest: lex=rich (persisted subtoken stats; no per-query corpus re-tokenize) + ranker query-mode MRR recall@1 recall@5 recall@10 + subtoken name 0.660 52.7% 82.1% 87.3% + subtoken doc-phrase 0.881 85.8% 90.2% 91.3% + name-exact name 0.875 79.4% 93.7% 96.4% + name-exact doc-phrase 0.008 0.3% 1.1% 1.7% + anchored name 0.665 53.9% 81.0% 86.0% + anchored doc-phrase 0.874 84.9% 89.9% 90.5% + routed name 0.877 79.6% 93.9% 96.5% + routed doc-phrase 0.879 85.7% 90.0% 91.0% + note: routing chose name-exact on 3989/4000 NAME queries (a NAME query is always identifier-shaped); + the confidence gate routes doc-phrase queries to name-exact ONLY when EVERY content word names a symbol + (or an explicit camel/snake token appears) AND every matched name is specific enough to anchor on — + a common name (many definitions, or a subtoken carried by many symbol names) declines the route — so + conceptual prose falls back to subtoken+body; routed tracks the better ranker on BOTH modes + (routed==name-exact on name, ~=subtoken+body on doc-phrase). +````` + +## `./build/ripwire . --eval-stray=/aux/stray_labels2.tsv` + +*Labelled verdict-accuracy eval for --stray-content — three labels over REAL local refs (names resolved at capture time); exit 3 when accuracy is under the floor. Read got= against v= in the stray-content run: a ref the verb could not analyse (unknown) must never be credited as a merged hit.* + +**exit code: 3** — **wall time: 20.97s** + +Input file: + +````` +# refverdict labels for --eval-stray (the first three local branches, resolved at capture time; a missing branch is padded with a nonexistent name on purpose) +arm/for-howitworks-067-f2add merged +arm/for-howitworks-067-placebo unmerged +arm/orient-map-067-narrow merged +````` + +````` + + + + + + +````` + +stderr: + +````` +ripwire: warning: --stray-content read the newest 512 of 639 local branches; 127 older were not read (limit: 512 refs); pass --detail=1 to read every branch, or narrow the branches with a ref-name filter +````` + +## `./build/ripwire skills --eval-skills=/aux/skills_labels2.tsv` + +*Labelled skill-ROUTING eval over the repo's own skills/ directory (4 hand-labelled prompts).* + +**wall time: 2.12s** + +Input file: + +````` +orient in an unfamiliar codebase fast ripwire-orient judged +who calls this function and what is the blast radius ripwire-navigate judged +plan parallel worktrees so the lanes do not collide ripwire-change-check judged +what is the weather in Paris none neg +````` + +````` +ripwire --eval-skills (skill routing over K=16 candidate skills [ripwire-router excluded]; 3 positive + 1 negative prompts; corpus '/aux/skills_labels2.tsv'; split test=4 … [line truncated: 7 more bytes on this line] + arm hit@1 hit@2 mrr sep-auc fire/abstain@ORACLE-th (upper bound) + overlap 66.7% 66.7% 0.689 0.000 50.0% (th=-1.000) + name 33.3% 66.7% 0.537 0.667 50.0% (th=0.000) + bm25-desc 66.7% 66.7% 0.689 0.667 75.0% (th=2.867) + bm25-full 33.3% 66.7% 0.611 1.000 50.0% (th=0.427) + for-routed 33.3% 33.3% 0.556 1.000 50.0% (th=0.703) + random 6.2% 12.5% 0.211 0.500 <- floor (uniform-random ranking; auc 0.5 by definition) + provenance hit@1 (bm25-desc): router 0/0, desc 0/0, judged 2/3 (desc rows quote the descriptions - expect them easiest; judged is the honest number) + judged-only hit@1 per arm: overlap 2/3, name 1/3, bm25-desc 2/3, bm25-full 1/3, for-routed 1/3 + router-magnet: with ripwire-router ADMITTED as a candidate it takes top-1 on 1/3 positive prompts (bm25-desc arm) - why it is excluded above + per-skill (bm25-desc): name / permitted-rows / won / pos-fires / false-fires / neg-fires + ripwire-before-you-build 0 0 1 1 0 + ripwire-change-check 1 0 0 0 0 + ripwire-find-bug 0 0 0 0 0 + ripwire-fresh-eyes 0 0 0 0 1 + ripwire-graph-query 0 0 0 0 0 + ripwire-handoff 0 0 0 0 0 + ripwire-layers 0 0 0 0 0 + ripwire-mcp 0 0 0 0 0 + ripwire-navigate 1 1 1 0 0 + ripwire-opt-remarks 0 0 0 0 0 + ripwire-orient 1 1 1 0 0 + ripwire-perf-target 0 0 0 0 0 + ripwire-quality-bar 0 0 0 0 0 + ripwire-reuse-first 0 0 0 0 0 + ripwire-security-scan 0 0 0 0 0 + ripwire-write-tests 0 0 0 0 0 + misses (overlap): + line 3 want=ripwire-change-check got=ripwire-before-you-build "plan parallel worktrees so the lanes do not collide" +… [19 more lines, 3720 bytes total] +````` + +## `./build/ripwire wrap claude` + +*Print the recipe to wire ripwire into Claude Code as an MCP server.* + +````` +# ripwire -> Claude Code (CLI-first) +# RECOMMENDED — this agent can run shell commands, so call the CLI directly. It costs +# nothing until you invoke it, and it reads CLAUDE.md, so the paste block below IS the wiring: +ripwire . --for="" +# +# ...every follow-up call answers with the compact legend by default (terse definitions of only the +# attributes the answer carries; the payload is byte-identical either way). Add --legend=full when a +# definition's reasoning is needed -- `ripwire --help` carries the measured saving (one place, +# gate-held) -- this line does not repeat it, because two copies of a number is one that goes stale: +# ripwire . --callers=SYM --legend=full +# +# ALTERNATIVE — register the MCP server instead, for a warm index across calls: +claude mcp add ripwire -- ripwire --mcp --mcp-tools=no-edit +# verbs the agent can then call mid-task (30 total): +# read: analyze, rank_by, find_symbol, find_referencing_symbols, grep, cochange, memory_recall, situational_awareness, mentions, for, lego, owners, fetch_body, batch, flags, doc_drift, slice +# flagship reflex: exemplar, quality_delta, quality_baseline, impact, uses, affected, path_between, connect, explore, from_trace, edit_check, whereis, stray_content +bash skills/install.sh # deploy to ${CLAUDE_CONFIG_DIR:-~/.claude}/skills (drift-gated) +bash skills/install.sh --hook # RECOMMENDED: advisory Read/Grep -> ripwire CLI nudge + session primer (opt-in, never blocks) +# +# context wiring — a binary on PATH is invisible to an agent until its rules file says when +# to reach for it. Paste the block below into CLAUDE.md: +# --- paste into CLAUDE.md --- +## ripwire — deterministic codebase maps (on PATH as `ripwire`) +Reach for it BEFORE blind grep + whole-file reads. First call ~1s cold; after that warm, ~0.1s. +- Orient on a task: `ripwire --for=""` — ranked, quality-annotated + signatures. Paste symbol/file names from the issue verbatim; named mentions get anchored. +- One task: `--pack-task="" --legend=compact`; before parallel agents: `--plan-lanes=N --task=""`, then read `lanes[].execution`. +- Have a stack trace / build error: `ripwire --from-trace=FILE --legend=compact` (`-` = stdin) — + paste the error, don't paraphrase it into a query. +- Who calls X: `--callers=SYM --legend=compact`. "Is it safe to change X?" needs the full blast radius: +… [13 more lines, 4536 bytes total] +````` + +## `./build/ripwire --version` + +*Version + short build info.* + +````` +ripwire 0.6.10-dev.130+gb0cb13d8d (dev, AppleClang 21.0.0.21000101, emit=std::print, built_from=b0cb13d8d) +````` + + +--- + +# navigate — seeds, claims, slices, shapes + +## `./build/ripwire . --at=src/graph.h:14272` + +*Hold a LOCATION, not a name: the enclosing-definition chain at FILE:LINE (a compiler error, a diff hunk, a stack frame), outermost -> innermost.* + +````` + + + + +````` + +## `./build/ripwire . --callers=@src/graph.h:14272` + +*The same seed in a SELECTOR position: @FILE:LINE resolves to the innermost enclosing definition, then --callers runs on it.* + +````` + + + + + + + + + + +````` + +## `./build/ripwire . --at=src/graph.h:999999` + +*A seed past the end of the file — the refusal shape for a faulted location.* + +**exit code: 1** + +````` +(empty) +````` + +stderr: + +````` +ripwire: the at flag's seed 'src/graph.h:999999' named no location (./src/graph.h has only 20696 lines — the seed asked for line 999999) +````` + +## `./build/ripwire . --verify="calls(runDefaultMap, rankGraphTeleport)"` + +*VERIFY a closed claim in one call: three-valued verdict (confirmed / refuted / not-established) with the evidence rows inline.* + +````` + + + + + +````` + +## `./build/ripwire . --verify="unused(rankGraphTeleport)"` + +*A claim that is FALSE — the refuted shape, with the references that refute it.* + +**wall time: 1.07s** + +````` + + + + + + + + + + + + +````` + +## `./build/ripwire . --verify="contains(src/graph.h, \"no such literal anywhere\")"` + +*A literal-scan absence: refuted only with complete= evidence, never on a partial scan.* + +````` + + + +````` + +## `./build/ripwire . --verify="frobnicate(x)"` + +*An unparseable claim — the refusal names the accepted shapes.* + +**exit code: 1** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --verify claim not recognized: 'frobnicate(x)' — unknown shape word. The claim language is CLOSED; the shapes are: calls(A, B) does A transitively call B · uses(SYM) is SYM referenced anywhere · unused(SYM) is SYM referenced nowhere · contains(FILE, "LITERAL") do FILE's bytes contain t … [line truncated: 218 more bytes on this line] +````` + +## `./build/ripwire . --slice=rankGraphTeleport` + +*Bare --slice=SYM: the INVENTORY of sliceable locals (), so a caller can pick VAR.* + +**wall time: 3.07s** + +````` + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --slice=rankGraphTeleport:teleport` + +*Intra-procedural def-use slice of ONE variable: one row per line touching it, k=def|use|both, reaching definitions flow-sensitive (reach=cfg).* + +**wall time: 2.68s** + +````` + + + + + + + teleport( pw.begin(), pw.end() );]]> + + + + + + + + +````` + +## `./build/ripwire . --slice=rankGraphTeleport:teleport --slice-flow=back --slice-depth=3` + +*TRANSITIVE backward value-flow from the seed variable, bounded BFS (depth= disclosed; a cut frontier says flow_truncated=1).* + +**wall time: 3.05s** + +````` + + + + + + + teleport( pw.begin(), pw.end() );]]> + + + + + + + + + pw = biasPrior( g, p );]]> + + +& p, float alpha = 0.85f )]]> + + +& p, float alpha = 0.85f )]]> + + +````` + +## `./build/ripwire . --slice=rankGraphTeleport:teleport --slice-flow=fwd` + +*Forward flow: which statements the seed's value reaches, at the default depth bound.* + +**wall time: 3.44s** + +````` + + + + + + + teleport( pw.begin(), pw.end() );]]> + + + + + + + + + + + + + + + + + + + + + 0.0 )]]> + + + + + + + + +````` + +## `./build/ripwire . --slice=rankGraphTeleport:nosuchvar` + +*A variable the definition does not bind — the refusal shape, naming the inventory.* + +**exit code: 1** — **wall time: 1.15s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --slice: no occurrence of 'nosuchvar' in rankGraphTeleport — sliceable locals: alpha, g, p, pw, N, teleport, rankDouble, run, teleportMass, value, inverseMass, r (bare --slice=rankGraphTeleport lists them with first-def lines) +````` + +## `./build/ripwire . --slice-depth=3` + +*--slice-depth without --slice-flow is refused loudly rather than silently ignored.* + +**exit code: 1** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --slice-depth bounds the --slice-flow BFS — pass both (e.g. ripwire --slice=parseArgs:argIndex --slice-flow=fwd --slice-depth=4) +````` + +## `./build/ripwire . --slice=rankGraphTeleport:teleport --legend=compact` + +*The compact legend posture: rows byte-identical, a versioned schema id replaces the repeated explanatory prose — for a many-small-calls loop.* + +**wall time: 3.14s** + +````` + + + + + + + teleport( pw.begin(), pw.end() );]]> + + + + + + + + +````` + +## `./build/ripwire . --pattern='rankGraphTeleport($A, $B, $C)'` + +*Structural search written in CODE: $NAME binds one node; grammars=/shapes= disclose what the pattern became per grammar (a 3-argument call shape — the 2-argument spelling has no call site in this repo and correctly reports hits=0).* + +**wall time: 3.47s** + +````` + +rankGraphTeleport( g, std::vector<float>( N, ranked ? 1.0f / float( ranked ) : 0.f ), alpha ) + +````` + +## `./build/ripwire . --pattern='DISCLOSE(...)'` + +*The ellipsis form over a macro-shaped call site; unsupported= names the families this verb does not serve.* + +**wall time: 2.29s** + +````` + +DISCLOSE( result, AbiResult::DisclosureWhy::NoMergeBase, "abi: no merge-base for a ref (unrelated history?) — that ref +DISCLOSE( Diagnostics::answerRefused, "--arch exits 1 with path:line and the reason on stderr; no report is printed", +DISCLOSE( baseline, ArchBaselineRead::DisclosureWhy::SymlinkRefused, "arch: refusing to read the arch baseline sidecar t +DISCLOSE( Diagnostics::answerRefused, "--baseline exits 1: pathguard names the refused link on stderr and the verb says +DISCLOSE( ex, Exclusions::DisclosureWhy::ForHeaderSaturated, "atoms: the for-header exclusion stream spent its whole bud +DISCLOSE( ex, Exclusions::DisclosureWhy::StmtCrementSaturated, "atoms: the statement-crement exclusion stream spent its +DISCLOSE( ex, Exclusions::DisclosureWhy::StmtAssignSaturated, "atoms: the statement-assign exclusion stream spent its wh +DISCLOSE( ex, Exclusions::DisclosureWhy::InnerCommaSaturated, "atoms: the inner-comma exclusion stream spent its whole b +DISCLOSE( st_, Type3Stats::DisclosureWhy::PairCapHit, "clones: Type-3 pair cap hit — first N compared (both-gate-survi +DISCLOSE( scan, CommentCoherenceScan::DisclosureWhy::UnreadableFile, "comment-coherence: an indexed file could not be re +DISCLOSE( st, StreamBlobStats::DisclosureWhy::StreamEndedMidBlob, "crossref: git cat-file stream ended +DISCLOSE( st, StreamBlobStats::DisclosureWhy::ListUnwritable, "crossref: cannot write the blob-batch list — cross-bran +DISCLOSE( st, StreamBlobStats::DisclosureWhy::BatchNotStarted, "crossref: git cat-file --batch failed to start — cross +DISCLOSE( st, StreamBlobStats::DisclosureWhy::StreamEndedMidBlob, "crossref: git cat-file stream e +DISCLOSE( sink, RefEnumeration::DisclosureWhy::DateUnreadable, "crossref: for-each-ref yielded a ref with no readable co +DISCLOSE( dropSink, RefEnumeration::DisclosureWhy::TipNotObjectName, "crossref: for-each-ref yielded a ref whose tip is +DISCLOSE( "crossref: refusing a diff whose revision arguments are not resolved object names" ) +DISCLOSE( sweep, ParallelSweep::DisclosureWhy::WorkerThrew, "crossref: a git worker threw — this shard of the sweep is +DISCLOSE( stats, StreamBlobStats::DisclosureWhy::BatchNotStarted, "crossref: a blob-stream slice was never read — comp +DISCLOSE( plumb, RefPlumbing::DisclosureWhy::RevisionNotObjectName, "crossref: ref tip or HEAD is not a resolved object +DISCLOSE( plumb, RefPlumbing::DisclosureWhy::MergeBaseNotObjectName, "crossref: merge-base returned something that is no +DISCLOSE( plumb, RefPlumbing::DisclosureWhy::NoMergeBase, "crossref: no merge-base for ref (shallow clone or unrelated h +DISCLOSE( plumbing[ i ], RefPlumbing::DisclosureWhy::NoMergeBase, "crossref: no merge-base for ref (shallow clone or unr +DISCLOSE( "crossref: refusing to list a tree whose revision argument is not a resolved object name" ) +DISCLOSE( "whereis: the index's def sites match no HEAD row (working tree drifted from HEAD?) — keeping the lexical la +DISCLOSE( reads[ k ], BranchBlobReadBack::DisclosureWhy::NotReadBackWhole, "whereis: a blob the pa +DISCLOSE( scan, WorktreeScan::DisclosureWhy::ListingFailed, "whereis: git could not list the working tree's changes — +DISCLOSE( scan, WorktreeScan::DisclosureWhy::OverPathCap, "whereis: more changed paths than the overlay reads — the re +… [73 more display lines; full output is 18272 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --pattern='x'` + +*A pattern that collapses to a bare token is REFUSED — never reported as hits=0.* + +**exit code: 1** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --pattern: this pattern collapses to a single bare token, which is a TEXT search, not a structural one — a clean parse is not enough (a bare word parses fine in most grammars and means nothing structural). Give it a shape (foo($X), $A + $B, if ($C) { ... }) or use the grep flag for litera … [line truncated: 176 more bytes on this line] +````` + +## `./build/ripwire . --grep=DISCLOSE --and=cache` + +*Boolean grep: hits where BOTH literals share the matched line (--grep-scope=line is the default).* + +````` + + + +inline bool topLevelEvidence( std::string_view source, const TSLanguage* language, const Predicate& predicate ) +The crawl's per-file byte ceiling. A text file larger than this is skipped: at this size it is o…constexpr std::size_t kDefaultMaxFileBytes = 4u * 1024u * 1024u +TSTree* parseTree( TSParser* parser, std::string_view src ) + +Exercise every registered grammar and its embedded query, reporting loaded and expected totalsinline DoctorGrammarProbe doctorProbeGrammars() +class SourceReader +constexpr std::array<LangEntry, 58> kLangTable = +struct FileHealth +struct SliceScan +explicit ParsedFile( std::string bytes ) : m_bytes( std::move( bytes ) ) +class ParsedFile + + + +inline RevSide sliceAtRev( const std::string& root, const std::string& sha, const std::string& rel, const Symbol& sym, SliceFam fam, const ::TSLanguage* grammar, st … [line truncated: 77 more bytes on this line] +std::vector<LocalNameFact> collectGatedLocalNames( std::string_view defBytes, std::uint32_t defStartLine, Lang lang ) +inline ModuleScan scanModule( std::string_view source, std::string_view path ) + +inline bool hasMainGuard( std::string_view source ) +inline bool hasPhantomScopeSeparator( TSNode qualified ) noexcept + + + + +inline void runParseWorker( ParsePoolShared& sh, unsigned t ) +… [242 more display lines; full output is 26515 bytes on 44 raw line(s)] +````` + +## `./build/ripwire . --for="tree-sitter parse of a source file" --sections=lego,compose` + +*Restore the / sections the --for bundle collapses to a counted stub by default (this is the stub's own next= spelling).* + +**wall time: 4.16s** + +````` + + + + +inline bool topLevelEvidence( std::string_view source, const TSLanguage* language, const Predicate& predicate ) +The crawl's per-file byte ceiling. A text file larger than this is skipped: at this size it is o…constexpr std::size_t kDefaultMaxFileBytes = 4u * 1024u * 1024u +TSTree* parseTree( TSParser* parser, std::string_view src ) + +Exercise every registered grammar and its embedded query, reporting loaded and expected totalsinline DoctorGrammarProbe doctorProbeGrammars() +class SourceReader +constexpr std::array<LangEntry, 58> kLangTable = +struct FileHealth +struct SliceScan +explicit ParsedFile( std::string bytes ) : m_bytes( std::move( bytes ) ) +class ParsedFile + + + +inline RevSide sliceAtRev( const std::string& root, const std::string& sha, const std::string& rel, const Symbol& sym, SliceFam fam, const ::TSLanguage* grammar, st … [line truncated: 77 more bytes on this line] +std::vector<LocalNameFact> collectGatedLocalNames( std::string_view defBytes, std::uint32_t defStartLine, Lang lang ) +inline ModuleScan scanModule( std::string_view source, std::string_view path ) + +inline bool hasMainGuard( std::string_view source ) +inline bool hasPhantomScopeSeparator( TSNode qualified ) noexcept + + + + +inline void runParseWorker( ParsePoolShared& sh, unsigned t ) +… [264 more display lines; full output is 27885 bytes on 44 raw line(s)] +````` + +## `./build/ripwire . --for="tree-sitter parse of a source file" --auto-bodies` + +*Opt OUT of compact conceptual serving: restore the rank-first auto walk (bundle="auto").* + +**wall time: 5.63s** + +````` + + + + +inline bool topLevelEvidence( std::string_view source, const TSLanguage* language, const Predicate& predicate ) +The crawl's per-file byte ceiling. A text file larger than this is skipped: at this size it is o…constexpr std::size_t kDefaultMaxFileBytes = 4u * 1024u * 1024u +TSTree* parseTree( TSParser* parser, std::string_view src ) + +Exercise every registered grammar and its embedded query, reporting loaded and expected totalsinline DoctorGrammarProbe doctorProbeGrammars() +class SourceReader +constexpr std::array<LangEntry, 58> kLangTable = +struct FileHealth +struct SliceScan +explicit ParsedFile( std::string bytes ) : m_bytes( std::move( bytes ) ) +class ParsedFile + + + +inline RevSide sliceAtRev( const std::string& root, const std::string& sha, const std::string& rel, const Symbol& sym, SliceFam fam, const ::TSLanguage* grammar, st … [line truncated: 77 more bytes on this line] +std::vector<LocalNameFact> collectGatedLocalNames( std::string_view defBytes, std::uint32_t defStartLine, Lang lang ) +inline ModuleScan scanModule( std::string_view source, std::string_view path ) + +inline bool hasMainGuard( std::string_view source ) +inline bool hasPhantomScopeSeparator( TSNode qualified ) noexcept + + + + +inline void runParseWorker( ParsePoolShared& sh, unsigned t ) +… [272 more display lines; full output is 28301 bytes on 96 raw line(s)] +````` + +## `./build/ripwire . --for="quality delta acks ledger rubber stamp"` + +*Doc-mention surfacing (default ON): a markdown doc naming a top-resolved symbol in a backtick rides in below that symbol — the legend's [doc mentions: …] clause says it fired.* + +**wall time: 4.04s** + +````` + + + + + +L2 stale acks in the range form. A changed-files answer holds no whole target tree to check the …std::vector<rw::quality::StaleAck> refPairStaleAcks( const gtl::btree_map<std::string, rw::quality::AckRecord>& acks, const RefPairDelta& refs ) +inline QualityDeltaOutcome computeQualityDelta( const std::string& root ) +inline std::string staleByKindValue( const std::vector<StaleAck>& staleAcks ) +inline constexpr const char* kAtStampLegend = "<!-- at= is the git commit these numbers were computed at +std::optional<int> runForLensPosture( const MainDispatch& d, rw::ForAnswerLedger* ledger ) +inline Result computeDmm( const std::string& root, std::string_view spec, const IngestResult& wo… +inline const char* kNotesFile = ".ripwire_notes" +inline rw::pathguard::NoFollowRead openRegularFileStream( std::string_view what, const std::stri… + +The REF-PAIR floor's comparison, once loadRefPairDelta has both sides: the base snapshot is the …void refPairBasis( const rw::Config& cfg, const std::string& root, RefPairDelta& refs, DeltaBasis& out ) +std::optional<int> refuseForeignAckSelection( const rw::Config& cfg, const rw::quality::Scope& scope, const std::vector<rw::quality::Regression>& out … [line truncated: 18 more bytes on this line] +std::optional<int> runQualityDelta( const MainDispatch& d ) +int ackNothingToAccept( const std::string& acksFile, const gtl::btree_map<std::string, rw::quality::AckRecord>& acks, const rw::quality::Scope& scope, std::size… … [line truncated: 4 more bytes on this line] + + + + + +inline bool writeAckRecords( const std::string& path, const gtl::btree_map<std::string, AckRecord>& acks ) +inline std::pair<std::string, std::string> qualityDeltaJson( const std::string& root, bool showStale = false ) +inline std::string qualityAcksPath( const std::string& root ) +inline std::string staleAcksXml( const std::vector<StaleAck>& staleAcks, EscapeFn esc ) + +inline std::string gitHeadSha( const std::string& root ) + +… [321 more display lines; full output is 31603 bytes on 48 raw line(s)] +````` + +## `./build/ripwire . --for="quality delta acks ledger rubber stamp" --no-doc-mention` + +*The same task with doc-mention surfacing OFF — the contrast the flag exists for (no [doc mentions] clause, one fewer row).* + +**wall time: 4.98s** + +````` + + + + + +L2 stale acks in the range form. A changed-files answer holds no whole target tree to check the …std::vector<rw::quality::StaleAck> refPairStaleAcks( const gtl::btree_map<std::string, rw::quality::AckRecord>& acks, const RefPairDelta& refs ) +inline QualityDeltaOutcome computeQualityDelta( const std::string& root ) +inline std::string staleByKindValue( const std::vector<StaleAck>& staleAcks ) +inline constexpr const char* kAtStampLegend = "<!-- at= is the git commit these numbers were computed at +std::optional<int> runForLensPosture( const MainDispatch& d, rw::ForAnswerLedger* ledger ) +inline Result computeDmm( const std::string& root, std::string_view spec, const IngestResult& wo… +inline const char* kNotesFile = ".ripwire_notes" +inline rw::pathguard::NoFollowRead openRegularFileStream( std::string_view what, const std::stri… + +The REF-PAIR floor's comparison, once loadRefPairDelta has both sides: the base snapshot is the …void refPairBasis( const rw::Config& cfg, const std::string& root, RefPairDelta& refs, DeltaBasis& out ) +std::optional<int> refuseForeignAckSelection( const rw::Config& cfg, const rw::quality::Scope& scope, const std::vector<rw::quality::Regression>& out … [line truncated: 18 more bytes on this line] +std::optional<int> runQualityDelta( const MainDispatch& d ) +int ackNothingToAccept( const std::string& acksFile, const gtl::btree_map<std::string, rw::quality::AckRecord>& acks, const rw::quality::Scope& scope, std::size… … [line truncated: 4 more bytes on this line] + + + + + +inline bool writeAckRecords( const std::string& path, const gtl::btree_map<std::string, AckRecord>& acks ) +inline std::pair<std::string, std::string> qualityDeltaJson( const std::string& root, bool showStale = false ) +inline std::string qualityAcksPath( const std::string& root ) +inline std::string staleAcksXml( const std::vector<StaleAck>& staleAcks, EscapeFn esc ) + +inline std::string gitHeadSha( const std::string& root ) + +… [321 more display lines; full output is 31333 bytes on 48 raw line(s)] +````` + +## `./build/ripwire . --safe-delete=rankGraphTeleport` + +*"Can I delete this?" — callers + transitive impact + every use site + how much of the radius is tested, composed in ONE call; risk= names what was found, never a verdict.* + +**wall time: 1.12s** + +````` + + + + + + + + + +````` + +## `./build/ripwire . --safe-delete=DoesNotExist` + +*Unknown-symbol refusal shape for --safe-delete.* + +**exit code: 1** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --safe-delete symbol not found: DoesNotExist (note: the lexical definition scan stopped at its budget, 4096 files or 16 MiB, before reading every file, so this miss is not proof the bytes define nothing; --grep=DoesNotExist lists its text uses) +````` + +## `./build/ripwire . --handoff` + +*The continuation packet for the NEXT session: disk truth (branch/sha, changed symbols, blast radius, tests) + labeled suggestions. Recorded against a CLEAN tree.* + +**wall time: 5.84s** + +````` + + + + + + + + + + + + + +````` + +## `./build/ripwire . --handoff --token-budget=1200` + +*The same packet under a hard ceiling: heuristic rows drop tail-first (withheld= disclosed), verified rows never drop.* + +**wall time: 8.50s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [561 more display lines; full output is 59467 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --no-ignore --top-k=3` + +*Crawl paths the repo's own .gitignore covers (default honours it and discloses ignored_files=/ignored_dirs= only when it dropped anything — this repo's crawl drops nothing, so the header is identical to the default map's; --skipped's ignore_mode= says which rule applied).* + +**wall time: 2.75s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [80 more display lines; full output is 10040 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --no-stable --top-k=3` + +*--no-stable outside --mcp: what the flag does (or says) when there is no stable-by-default ordering to opt out of.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [80 more display lines; full output is 10040 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: --no-stable is read only by --mcp/--listen (it opts out of the stable ordering the server turns on) — it changed nothing here; the CLI map orders important-first unless you pass --order=stable +````` + +## `./build/ripwire . --run-trace="cat /aux/asan_trace_now.txt; exit 1"` + +*EXEC-MODE --from-trace: run a command, and on a non-zero exit map its captured output onto indexed symbols in the same call — the whole fix-loop entry. ripwire exits 4 here because the wrapped command failed, which is the signal, not an incident.* + +**exit code: 4** — **wall time: 1.32s** + +````` + + + + + + const&, float) src/graph.h:14272 + #1 0x102f3e884 in rw::rankGraph(Graph const&, float) src/graph.h:14315 + #2 0x102e11f30 in runDefaultMap(MainDispatch const&) src/main.cpp:1760 + #3 0x102e01a44 in main src/main.cpp:4511 + #4 0x1a2b3c0dc in start+0x9dc (dyld:arm64e+0x60dc)]]> pw = biasPrior( g, p ); + const std::size_t N = pw.size(); + std::vector teleport( pw.begin(), pw.end() ); + std::vector rankDouble( N, 0.0 ); + PageRankRun run{}; // an N == 0 graph never enters the kernel: { 0, converged } — see PageRankRun + if( N ) + { + double teleportMass = 0.0; + for( const double value : teleport ) + { + teleportMass += value; + } + if( teleportMass > 0.0 ) + { + const double inverseMass = 1.0 / teleportMass; + for( double& value : teleport ) + { + value *= inverseMass; + } + } + run = pageRankDouble( g.inEdges, g.wOutDeg, teleport, rankDouble, PageRankConfig{ .alpha = double( alpha ) } ); + } + std::vector r( N, 0.f ); + std::transform( rankDouble.begin(), rankDouble.end(), r.begin(), []( double value ) { return float( value ); } ); + return { std::move( r ), run.iterationCount, run.hasConverged }; +}]]>inline std::vector<float> biasPrior( const Graph& g, const std::vector<float>& p )#define PROFILE_SCOPE_DESCRIBE( desc ) + + + +````` + +## `./build/ripwire . --run-trace="sleep 30" --run-timeout=2` + +*A command still running at the cap: its process group is killed and the run reports timed_out=1 — an honest timeout, never an empty success.* + +**exit code: 4** — **wall time: 2.40s** + +````` + + + + +````` + +stderr: + +````` +ripwire: --run-trace: TIMEOUT — the command exceeded the 2 s cap; its process group was killed +````` + +## `./build/ripwire . --run-timeout=5` + +*--run-timeout alone is refused loudly (it only modifies --run-trace).* + +**exit code: 1** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --run-timeout=SECONDS modifies --run-trace — pass it too (e.g. ripwire --run-trace="make -j" --run-timeout=60) +````` + + +--- + +# assess quality — the wider lens family + +## `./build/ripwire . --quality-panel` + +*THE single wide-angle quality read: six families in one pass, an eligible/ranked shortlist rather than a firehose.* + +**wall time: 9.72s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [190 more display lines; full output is 15658 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --biggest-first --limit=8` + +*Per-function size ranking, largest Halstead volume/token entropy/lines first — a size proxy, not a readability order (withdrawn, docs/EVALS.md §8) — a RANKING lens, not a grade.* + +**wall time: 2.09s** + +````` + + + + + + + + + + + +````` + +## `./build/ripwire . --comment-coherence --limit=8` + +*Functions WITH a doc comment, most name-restating first: c_coeff (high = the comment repeats the name) and cic (Jaccard of comment vs identifier vocabulary), both reported, never collapsed.* + +**wall time: 1.01s** + +````` + + + + + + + + + + + +````` + +## `./build/ripwire . --context-ratio --limit=8` + +*The local-reasoning lens: to understand this symbol, how much must you know that is NOT in front of you (ent_ratio= edge share, read_ratio= token-weighted).* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [21 more display lines; full output is 11236 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --nonlocal-state --limit=8` + +*Per function, the non-local MUTABLE state it can reach (transitively), most writes first — unsound by construction, and the legend says where.* + +**wall time: 3.02s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [53 more display lines; full output is 8279 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --ensemble --limit=8` + +*The family join: per function, which of four orthogonal evidence families fire, ranked by how many agree.* + +**wall time: 6.52s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [36 more display lines; full output is 7516 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --field-affinity` + +*The cache-locality lens over every aggregate: fields READ TOGETHER but declared FAR APART (split-line / straddle findings, Chilimbi separation weight) — advice only, never a rewrite.* + +**wall time: 3.69s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [1639 more display lines; full output is 154933 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --field-affinity=Symbol` + +*The same lens narrowed to ONE struct — the one --layout=Symbol shows the offsets for.* + +**wall time: 2.23s** + +````` + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --naming-consistency --limit=8` + +*The corpus's OWN case-convention vote per (language, kind) group; off-convention names get a mechanical propose= (a suggestion, never a blind rename).* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [13 more display lines; full output is 4390 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --naming-calibration` + +*Score the naming-* rules against this repo's own rename history: proxy=old/(old+new) per rule, 0.50 = chance; read pairs= (sample size) first.* + +**wall time: 21.28s** + +````` + + + + + + + + + + + +

+

+

+

+

+

+

+

+

+

+

+

+

+

+

+

+… [187 more display lines; full output is 18275 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --lint --naming-locals` + +*The opt-in --lint modifier: naming predicates over LOCAL variable names too, C/C++ only, only inside functions already past a size/complexity gate.* + +**wall time: 3.69s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [640 more display lines; full output is 72767 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --lint-catalog` + +*The built-in rule registry — one row per rule with sev=/category=/rationale/lang=/since=; no corpus needed.* + +````` + + +a C-style cast — cppcoreguidelines-pro-type-cstyle-cast prefers the explicit static_cast/const_cast/reinterpret_cast +a goto statement — cppcoreguidelines-avoid-goto +a do/while loop shape (on Swift, its do/catch block shares the same grammar node and also matches) +a call to an unbounded C string function (strcpy/strcat/sprintf/gets) +a call to a broken hash or cipher (MD5/SHA1/MD4/RC4) +a doubly-parenthesized expression — readability-redundant-parentheses +an if-body that is just `;` — bugprone-suspicious-semicolon +a C-style typedef struct/union where `using` is preferred +a non-trivial numeric literal inside a function body, outside a const/constexpr init +a catch block with an empty body +x = x — almost always a copy-paste bug +a function body over 80 lines +brace nesting depth over 4 inside a function body +a bare `return;` mixed with a value-returning return in the same function +a statement after an unconditional return/break/continue/throw/raise in the same block +a 1-2 letter Function/Method/Var name — visible far beyond any tiny scope [Beniamini/Hofmeister] +more than 5 words in one name; a k or C-family g_/m_/s_ marker prefix is not a word [Butler; AlSuhaibani] +foo1/foo2/... digit-suffix siblings sharing a base name in one scope [Butler] +internal consecutive underscores, or a C-family reserved __x/_X form [Butler] +snake_case and camelCase mixed inside one name [Butler] +an is/has/can/should/was-prefixed name whose KNOWN return type is not bool-like [LAPD A2] +a set-prefixed name whose KNOWN return type is not void-like [LAPD A3] +a co-visible pair within edit distance <=2, reordered tokens, or a bare/digit-suffixed twin [Namesake] +every split subtoken is corpus-ubiquitous (BM25 idf) on a body past the size floor — fires only at the low end [Sparck Jones 1972] +the comma operator inside an expression (never a for-header comma) [Gopstein FSE 2017] +++/-- evaluated inside a larger expression (never a whole statement) [Gopstein FSE 2017] +an assignment whose VALUE is consumed (a condition, an argument, ...) [Gopstein FSE 2017] +a conditional expression inside a conditional expression [Gopstein FSE 2017] +… [12 more display lines; full output is 7847 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --legend-dict` + +*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=ff6a8ec8438b7fe0 entries=1176 +: 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=) +X_capped= (any attribute ending _capped): 1 = cut +under ref, est_tokens= and over_ceiling= price the answer with its inline legend: an upper bound +under ref, a group of n <= 8 runner-less rows prints as its n single rows, each run_unknown=1 +ripwire.map/v1 : ranked symbol map: groups rows (k= rank), resolved callees; the header comment is data +ripwire.map-diff/v1 : the ranked map anchored at at=: what the diff touched, the map's row vocabulary +ripwire.metrics/v1 : the ranked map with per-symbol metrics +ripwire.around/v1 : call neighbourhood of of=: depth= hops, fanout= kept per hop; absent rows lie outside that boundary +ripwire.query/v1 : lexical-rank map for the query term, the map's row vocabulary +ripwire.pack-signatures/v1 : the ranked map plus signature rows +ripwire.pack-top-n/v1 : the ranked map plus bodies of the top-N symbols +ripwire.skipped/v1 : why the index lacks a file ; indexed but unvouched ; census +ripwire.notes/v1 : field notes by target: holds ; the kept count comment: notes= rows, targets= rows, dangling= targets matching nothing indexed (listed, surfaced nowhere) +ripwire.lego/v1 : ONE interface/base type: , its method contract, every implementor +ripwire.expand/v1 : full bodies: of ; resolved callees (p= when not the b's file) +ripwire.expand-file/v1 : the file's own text: ; per scoped symbol; full id = p::sc::n +ripwire.candidate-page/v1 : budgeted-bundle candidate page: a resumable window over the ranked candidate set the bundle cuts, for task= under budget_tokens=, one tier per page, ranks global across pages +ripwire.pack-task/v1 : one-call task bundle for task= under budget_tokens=: ranking, ranked but over 1 hop out (of_top= ranked rows) > with callees > 1-hop from the bodies … [line truncated: 108 more bytes on this line] +ripwire.from-trace/v1 : trace frames mapped to indexed symbols, innermost first; the innermost in-corpus body included +ripwire.exemplar/v1 : the best-in-class instance of kind= for the task, chosen by role: , to imitate +ripwire.pack-task/v1 : N minimally overlapping agent bundles carved along call-graph communities plus one shared core; each wraps a ; bundle role=core|partition i= symbols= modules= bytes= tokens=: one agent's ctx, symbols= ids assigned, bytes= its size; tokens= = est_t … [line truncated: 345 more bytes on this line] +ripwire.callers/v1 : 1-hop CALLERS of of= (defs= matched, count= distinct symbols): ; hop_tested=/hop_untested= +ripwire.callees/v1 : 1-hop CALLEES of of= (defs= matched, count= distinct symbols): +ripwire.uses/v1 : resolvable use-sites of of=: +ripwire.impact/v1 : transitive blast radius of of=: reach set, importers; defs= matched, reaches= their transitive callers, radius_tested= non-tests an indexed test reaches, radius_untested= the rest; importers= files that #include/import a def's file +ripwire.defs/v1 : per the parsed definitions the name binds (defs= groups; a prototype with its definition is one): , sel= binds that one alone in any SYM verb, in= distinct callers (a floor); source first, then in=, then path +ripwire.path/v1 : one DIRECTED call path from= to to=, each a hop; reachable=0 hops=0 when none shown +… [1147 more display lines; full output is 134933 bytes on 1177 raw line(s)] +````` + +## `./build/ripwire . --lint --lint-select=cache-` + +*Run ONLY one rule family; the root carries selected="K of N" so a filtered zero is never confusable with an unfiltered one.* + +**wall time: 4.94s** + +````` + + + + + + + + + + +vector<std::vector<double>> +nodes[ perm[i] ] +nodes[ perm[ i + 1 ] ] +p = p->next +map +byName[ symN[i] ] +vector<std::vector<std::vector<std::uint32_t>>> +vector<std::vector<std::uint32_t>> +m[ symN[id] ] +vector<std::vector<double>> +m[ in.keys[ i ] ] +map +vector<std::vector<std::vector<std::uint32_t>>> +vector<std::vector<std::uint32_t>> +m[ symN[id] ] +map +m[ g_pool[ g_keyOf[i] ] ] +g_pool[ g_readOf[i] ] +g_pool[ g_readOf[i] ] +m[ g_pool[i] ] +… [612 more display lines; full output is 72931 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --lint --lint-ignore=naming-,cache-` + +*DROP two families, applied after selection; the raw select=/ignore= you passed rides on the root.* + +**wall time: 2.41s** + +````` + + + + + + + + + + + + + + + + + + + + + + + +0.5 +1023u +main (90 lines) +20 +delta < 0.02 && delta > -0.02 +0.02 +… [708 more display lines; full output is 67272 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --lint --lint-select=goto --lint-max-per-rule=4` + +*A rule that spends its own match budget (here 4, set BELOW the default 5000 so the floor shows on this repo): goto carries count_capped="1", its count= is a FLOOR, and the root names the call that counts the rest — findings_next= re-runs only the floored rules under a 10x budget.* + +**wall time: 2.74s** + +````` + + + +goto epilogue; +goto epilogue; +goto epilogue; +goto epilogue; + +````` + +## `./build/ripwire . --lint --lint-select=goto --lint-max-per-rule=40` + +*Pasting that findings_next=: the same rule under a 10x budget counts its true total — no count_capped=, no findings_next=.* + +**wall time: 2.54s** + +````` + + + +goto epilogue; +goto epilogue; +goto epilogue; +goto epilogue; +goto epilogue; +goto epilogue; +goto epilogue; +goto epilogue; +goto epilogue; +goto epilogue; +goto epilogue; +goto epilogue; +goto error; +goto error; +goto error; +goto done; +goto done; + +````` + +## `./build/ripwire . --lint --lint-select=cach-` + +*An unresolvable PREFIX refuses (exit 1) with a did-you-mean from a real edit distance (one character off cache-).* + +**exit code: 1** — **wall time: 2.63s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --lint-select: 'cach-' matches no rule or family (did you mean 'cache-'?) — see --lint-catalog for the full registry +````` + +## `./build/ripwire . --lint --lint-select=nosuchfamily` + +*A PREFIX with no near miss at all: the refusal points at --lint-catalog instead of guessing.* + +**exit code: 1** — **wall time: 2.57s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --lint-select: 'nosuchfamily' matches no rule or family — see --lint-catalog for the full registry +````` + +## `./build/ripwire . --lint --sarif` + +*The SAME findings as SARIF 2.1.0 (what github/codeql-action/upload-sarif consumes) — pure re-serialization, results count == the native run's.* + +**wall time: 2.26s** + +````` +{"version":"2.1.0","$schema":"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json","runs":[{"tool":{"driver":{"name":"ripwire","rules":[{"id":"c-style-cast","shortDescription":{"text":"c-style-cast"},"properties":{"builtin":true,"capped":false,"applicable": … [line truncated: 7 more bytes on this line] +{"id":"goto","shortDescription":{"text":"goto"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"do-while","shortDescription":{"text":"do-while"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"unsafe-c-fn","shortDescription":{"text":"unsafe-c-fn"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"weak-crypto","shortDescription":{"text":"weak-crypto"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"redundant-parens","shortDescription":{"text":"redundant-parens"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"suspicious-semicolon","shortDescription":{"text":"suspicious-semicolon"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"typedef-over-using","shortDescription":{"text":"typedef-over-using"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"magic-number","shortDescription":{"text":"magic-number"},"properties":{"builtin":true,"capped":true,"applicable":true}}, +{"id":"empty-catch","shortDescription":{"text":"empty-catch"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"self-assign","shortDescription":{"text":"self-assign"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"large-function","shortDescription":{"text":"large-function"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"deep-nesting","shortDescription":{"text":"deep-nesting"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"inconsistent-return","shortDescription":{"text":"inconsistent-return"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"unreachable-code","shortDescription":{"text":"unreachable-code"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"naming-short","shortDescription":{"text":"naming-short"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"naming-wordy","shortDescription":{"text":"naming-wordy"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"naming-series","shortDescription":{"text":"naming-series"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"naming-underscore","shortDescription":{"text":"naming-underscore"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"naming-case","shortDescription":{"text":"naming-case"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"naming-predicate","shortDescription":{"text":"naming-predicate"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"naming-setter","shortDescription":{"text":"naming-setter"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"naming-confusable","shortDescription":{"text":"naming-confusable"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"naming-uninformative","shortDescription":{"text":"naming-uninformative"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"atom-comma-operator","shortDescription":{"text":"atom-comma-operator"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"atom-embedded-crement","shortDescription":{"text":"atom-embedded-crement"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"atom-assign-as-value","shortDescription":{"text":"atom-assign-as-value"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"atom-nested-ternary","shortDescription":{"text":"atom-nested-ternary"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"atom-implicit-predicate","shortDescription":{"text":"atom-implicit-predicate"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +{"id":"atom-octal-literal","shortDescription":{"text":"atom-octal-literal"},"properties":{"builtin":true,"capped":false,"applicable":true}}, +… [17159 more display lines; full output is 2436418 bytes on 1 raw line(s)] +````` + +Parsed summary of the same SARIF (past the display cut): + +````` +sarif 2.1.0 rules= 39 results= 8575 +````` + +## `./build/ripwire . --lint --sarif --limit=5` + +*SARIF is always the FULL result set: paging alongside it refuses loudly.* + +**exit code: 1** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --sarif always emits the full result set — drop --limit=N/--offset=M +````` + +## `./build/ripwire . --dmm` + +*The Delta Maintainability Model scalar for the WORKING TREE vs HEAD — recorded against a CLEAN tree (the sandbox section shows a real delta). UNAVAILABLE is a stated reason, never 0 or 1.* + +**wall time: 10.30s** + +````` + + +

+

+ +````` + +## `./build/ripwire . --dmm=HEAD` + +*The per-commit scalar: HEAD vs its first parent, with the three separately actionable sub-scores.* + +**wall time: 18.88s** + +````` + + +

+

+ +````` + +## `./build/ripwire . --dmm=HEAD~3..HEAD` + +*The range form: tree HEAD vs tree HEAD~3.* + +**wall time: 22.47s** + +````` + + +

+

+ +````` + +## `./build/ripwire . --cochange --cochange-groups` + +*Modularity-violation GROUPS instead of pairs: "X co-changes with {A,B,C}, none of which it depends on" — a greedy cover, disclosed as greedy.* + +**wall time: 5.07s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [1002 more display lines; full output is 67536 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --cochange --cochange-recur=2` + +*Only pairs whose co-change RECURS in 2+ sub-windows of the mined window (sub_windows= is the denominator) — a one-off sprint stops reading like a structural defect.* + +**wall time: 4.95s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --html=/aux/map2.html --color-by=community` + +*The HTML graph with the initial colour mode set to community (the page embeds all five modes and keeps a live selector).* + +**wall time: 5.80s** + +````` +(empty) +````` + +Artifact written: + +````` + 155374 /aux/map2.html +````` + +## `./build/ripwire . --index-out=/aux/ci_index` + +*CI generate-and-exit: cold-parse and write BOTH committable cache families (lean + rich), no map on stdout.* + +**wall time: 8.66s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --index-out wrote /aux/ci_index.lean.ripwirecache (40244008 bytes, lean family) +ripwire: --index-out wrote /aux/ci_index.rich.ripwirecache (81040874 bytes, rich family) +````` + +Artifact written: + +````` + 40244008 /aux/ci_index.lean.ripwirecache + 81040874 /aux/ci_index.rich.ripwirecache + 121284882 total +````` + +## `./build/ripwire . --cache=/aux/ci_index.lean.ripwirecache --top-k=3` + +*Consume the lean artifact in a PR job: restore-equivalence, never blob-byte-identity.* + +**wall time: 4.48s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [80 more display lines; full output is 10040 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --pin-census=/aux/pin_census.tsv --top-k=3` + +*Eval-only: a per-call-site census of WHICH mechanism resolved each call, and the canonical id of every surviving target.* + +**wall time: 3.43s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [80 more display lines; full output is 10040 bytes on 1 raw line(s)] +````` + +Artifact written: + +````` +# ripwire pin-census v3 C=kind\tmech\tpre\tpost\tflags\tcaller_id\tcallee\ttargets(|-sep)\tline +# v3 field escape: every id and callee field is escaped, so no separator occurs inside one. A backslash is +# written \\, TAB \t, LF \n, CR \r, every other control byte 0x00-0x1f and the targets separator | as \xHH +# (lowercase hex). Split lines on LF, fields on TAB and targets on |, THEN decode. Columns are unchanged +# from v2 and an id without those bytes is spelled exactly as in v2; a C++ out-of-line template member +# whose template-argument list spans lines keeps its line break as \n instead of splitting the row. +# line is the 1-based call-site line in the caller's file (v2, appended LAST so v1 readers are unchanged): +# the key a SCIP occurrence joins on, so a coverage loss can be classified per site instead of guessed. + 179596 /aux/pin_census.tsv +````` + +## `./build/ripwire . --plan-lint=test/planlintfix/wave.md` + +*The house PLAN/DESIGN format's STRUCTURE check — never semantics; exit 2 when a card or ledger row gates.* + +**exit code: 2** — **wall time: 5.20s** + +````` + + + + + + + + + + + + + +````` + +## `./build/ripwire . --plan-lint=test/planlintfix/wave_ledger.md` + +*The ledger-shaped fixture through the same check (exit 2: one gating card).* + +**exit code: 2** — **wall time: 3.99s** + +````` + + + + + + + +````` + +## `./build/ripwire . --doctor --agent=claude` + +*--doctor plus a LIVE integration inspection for one agent: PATH binary, installed-skill manifest parity, hook executability, MCP wiring — read-only, fixed repair commands, never config contents; exit 1 when any check fails.* + +**exit code: 1** — **wall time: 36.57s** + +````` + + + + + + + + + + + + + +````` + +## `./build/ripwire . --doctor --agent=nosuch` + +*Other --agent values refuse.* + +**exit code: 1** + +````` +(empty) +````` + +stderr: + +````` +ripwire: unsupported --agent value 'nosuch' (supported: codex, claude) +````` + + +--- + +# the dirty-tree verbs (throwaway clone, NOT the read-only repo) + +Everything below runs with `cwd` = the throwaway clone at `/dirty` (`git clone --local` of this repo, then one deliberate regression in `src/infra/sortutil.h`). The read-only repo is never touched. The binary is the same `build/ripwire`, addressed absolutely. + +## `./build/ripwire . --situ` + +*Situational report for a real diff: blast radius + tests + co-change + forgotten co-change partners.* + +**wall time: 16.84s** + +````` +ripwire situational-awareness — 1 changed file(s), 14 symbols in them +root: . +at: b0cb13d8d+dirty + change_set: granularity=file changed_symbols=14 file_symbols=14 files_narrowed=0 files_file_granular=1 diff_hunks=7 diff_hunks_located=6 diff_hunks_unlocated=1 — seeds = symbols a diff -U0-vs-HEAD hunk overlaps (function/method body spans only); an unlocated hunk (module-level, deletion, rename) … [line truncated: 34 more bytes on this line] + [1] blast radius: 1043 symbols across 150 files transitively depend on these changes (showing 8 of 150 files — shown=8 total=150 capped=1 prcontext_cap=20 (--pr-context's own per-file list is cut at 20 too); next: --situ --limit=150) + counts_floor=1 graph_ambiguous=3637 graph_unresolved=20080 graph_unindexed=311 (files no grammar in this build could read at all) (the map header's own gauges) — every count above is a FLOOR, never a total: call edges are name-based, so dynamic dispatch, callbacks and macros can be missing … [line truncated: 45 more bytes on this line] + src/graph.h (59 dependent symbols) + src/mcpverbs.h (41 dependent symbols) + src/quality.h (41 dependent symbols) + src/verbs_for.h (33 dependent symbols) + src/backhops.h (31 dependent symbols) + src/slice.h (31 dependent symbols) + src/crossref.h (28 dependent symbols) + src/resolve.h (26 dependent symbols) + [2] tests to run (12) order=evidence: [changed] you edited it, [partner] named after a changed file, then hops asc (1 = direct); "(n): a, b" = n runner-less files sharing that evidence; a (run: …) is relative to root: + test/verify_radix.cpp [hops=1] (run: bash test/greptiercheck.sh) + test/adaptivecutshapefix/adaptive_cut_shape_test.cpp [hops=2] (run: bash test/adaptivecutshapecheck.sh) + test/connectcore_harness.cpp [hops=2] (run: bash test/connectcorecheck.sh) + test/forrowfeatures_unit.cpp [hops=2] (run: bash test/forrowfeaturescheck.sh) + test/fuzz/readers/readers_domain.cpp [hops=2] (run: not derivable) + test/verify_csr.cpp [hops=2] (run: bash test/a9disclosurecheck.sh) + test/cloneband_harness.cpp [hops=3] (run: bash test/clonebandcheck.sh) + test/shstatus_harness.cpp [hops=3] (run: bash test/gateexitcheck.sh) + test/type3clone_harness.cpp [hops=3] (run: bash test/type3clonecheck.sh) + test/includeprecise_unit.cpp [hops=4] (run: bash test/includeprecisecheck.sh) + test/rustimport_unit.cpp [hops=4] (run: bash test/rustimportprecisecheck.sh) + test/fuzz/readers/readers_light.cpp [hops=5] (run: not derivable) + script_gates_unmodelled=946 — test/*.sh gates never appear above: script-to-binary edges are not call edges (a path count) + [3] co-change — usually edited with these but NOT in your diff (0) window="18mo@HEAD" commits="7863": + (none — 7863 commits were mined and none co-edited a file outside your diff) + next: --test-gate +````` + +## `./build/ripwire . --test-gate` + +*The pre-PR gate with real obligations — exit 4 when tests-to-run or untested blast radius is non-empty.* + +**exit code: 4** — **wall time: 14.26s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --quality-delta` + +*Every row carries p="file:line", the gating rows are marked gating="1" and now bar= (the threshold each numeric row is judged against), and the exit-2 refusal prints a naming line on stderr; a gating row carries a pasteable next=.* + +**exit code: 2** — **wall time: 54.88s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [175 more display lines; full output is 20654 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: no ./.ripwire_quality_baseline — auto-comparing the working tree vs git HEAD (commit the baseline with --quality-baseline to pin it) +ripwire: --quality-delta gating: 5 preexisting-worse major finding(s); first: api-surface src/infra/sortutil.h::rw::sortutil::nonNegativeFloatDescKey at src/infra/sortutil.h:122 (was=1 now=2) +````` + +## `./build/ripwire . --quality-delta --legend=full` + +*The same gating report under --legend=full — same rows, same exit 2; the default compact comment (schema="ripwire.quality-delta/v1", the shape an agent's edit loop should run) becomes ~4 KB of prose legend.* + +**exit code: 2** — **wall time: 30.82s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [175 more display lines; full output is 26130 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: no ./.ripwire_quality_baseline — auto-comparing the working tree vs git HEAD (commit the baseline with --quality-baseline to pin it) +ripwire: --quality-delta gating: 5 preexisting-worse major finding(s); first: api-surface src/infra/sortutil.h::rw::sortutil::nonNegativeFloatDescKey at src/infra/sortutil.h:122 (was=1 now=2) +````` + +## `./build/ripwire . --quality-delta --json` + +*The same findings as JSON (one of the CI/scripting verbs --json supports) — same exit 2 as the XML form.* + +**exit code: 2** — **wall time: 29.88s** + +````` +{"baseline":"git-HEAD","regressions":9,"minor":1,"acked":0,"stale":193,"preexisting-worse":6,"new-symbol":3,"gating":5,"register-macro-excluded":63,"api-new-surface":2,"at":"b0cb13d8d+dirty","renames":68,"rename_window_commits":400,"acked_by_rename":0,"acked_by_content":0,"renames_window_truncated": … [line truncated: 240 more bytes on this line] +{"kind":"complexity","sym":"src/infra/sortutil.h::rw::sortutil::lessByScoreDescId","was":1,"now":67,"p":"src/infra/sortutil.h:62","gating":true}, +{"kind":"dead-code","sym":"src/infra/sortutil.h::rw::sortutil::nonNegativeFloatAscKeyCopy","p":"src/infra/sortutil.h:132","origin":"new-symbol"}, +{"kind":"dead-code","sym":"src/infra/sortutil.h::rw::sortutil::sortScoredIdsWithOptions","p":"src/infra/sortutil.h:142","origin":"new-symbol"}, +{"kind":"duplication","members":"src/infra/sortutil.h::rw::sortutil::nonNegativeFloatAscKeyCopy | src/infra/sortutil.h::rw::sortutil::nonNegativeFloatDescKey","tokens":59,"p":"src/infra/sortutil.h:132","gating":true}, +{"kind":"nesting","sym":"src/infra/sortutil.h::rw::sortutil::lessByScoreDescId","was":1,"now":6,"p":"src/infra/sortutil.h:62","gating":true}, +{"kind":"new-clone-of-reused-helper","sym":"src/infra/sortutil.h::rw::sortutil::nonNegativeFloatAscKeyCopy | src/infra/sortutil.h::rw::sortutil::nonNegativeFloatDescKey","was":0,"now":4,"p":"src/infra/sortutil.h:132","gating":true}, +{"kind":"params","sym":"src/infra/sortutil.h::rw::sortutil::sortScoredIdsWithOptions","was":0,"now":8,"p":"src/infra/sortutil.h:142","origin":"new-symbol"}, +{"kind":"verbosity","sym":"src/infra/sortutil.h::rw::sortutil::lessByScoreDescId","was":8,"now":47,"p":"src/infra/sortutil.h:62","sev":"minor"}], +"sa":[{"kind":"api-surface","key":"085e3d408c2c4a35","why":"target-gone"}, +{"kind":"api-surface","key":"155d74d341a49f3c","why":"target-gone"}, +{"kind":"api-surface","key":"1a15386c2d1e47af","why":"target-gone"}, +{"kind":"api-surface","key":"298e798c7f075715","why":"target-gone"}, +{"kind":"api-surface","key":"56acdf9b5c314a14","why":"target-gone"}, +{"kind":"api-surface","key":"5a07390012b46e06","why":"target-gone"}, +{"kind":"api-surface","key":"6eef859578c8c376","why":"target-gone"}, +{"kind":"api-surface","key":"6f2394762f82a855","why":"target-gone"}, +{"kind":"api-surface","key":"7f2c3eefdf6e512e","why":"target-gone"}, +{"kind":"api-surface","key":"802e513731103806","why":"target-gone"}, +{"kind":"api-surface","key":"b6a24afef32a68a8","why":"target-gone"}, +{"kind":"api-surface","key":"c923e661c197b265","why":"target-gone"}, +{"kind":"api-surface:new-symbol","key":"1926b0d9e94541a0","why":"target-gone"}, +{"kind":"api-surface:new-symbol","key":"1d3814ba687a4aef","why":"target-gone"}, +{"kind":"api-surface:new-symbol","key":"1db76028879244ef","why":"target-gone"}, +{"kind":"api-surface:new-symbol","key":"25c9f0504fd376a4","why":"target-gone"}, +{"kind":"api-surface:new-symbol","key":"26aa7c55d54c4341","why":"target-gone"}, +{"kind":"api-surface:new-symbol","key":"26e3f9a6bff9ea57","why":"target-gone"}, +{"kind":"api-surface:new-symbol","key":"36e39c7ab0fc1686","why":"target-gone"}, +{"kind":"api-surface:new-symbol","key":"4bce64bd920de0c3","why":"target-gone"}, +{"kind":"api-surface:new-symbol","key":"61f0e361ef7dee27","why":"target-gone"}, +… [172 more display lines; full output is 19311 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: no ./.ripwire_quality_baseline — auto-comparing the working tree vs git HEAD (commit the baseline with --quality-baseline to pin it) +ripwire: --quality-delta gating: 5 preexisting-worse major finding(s); first: api-surface src/infra/sortutil.h::rw::sortutil::nonNegativeFloatDescKey at src/infra/sortutil.h:122 (was=1 now=2) +````` + +## `./build/ripwire . --quality-delta --quality-ack --ack-only=zzznope` + +*NEW FLAG: --ack-only matching nothing REFUSES rather than falling back to acking everything.* + +**exit code: 1** — **wall time: 22.88s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: no ./.ripwire_quality_baseline — auto-comparing the working tree vs git HEAD (commit the baseline with --quality-baseline to pin it) +ripwire: ack provenance backfill — 0 clone row(s) reconstructed from the current tree, 196 re-derived, 39 left UNVERIFIED (their group was not found here — a floor, not proof it is gone), 55 left legacy (member set not found cloning here — a floor, not proof it is gone), 1297 ineligible (no cu … [line truncated: 200 more bytes on this line] +ripwire: --ack-only=zzznope matched none of the 9 finding(s) — nothing written +````` + +## `./build/ripwire . --quality-delta --quality-ack --ack-only=api-surface` + +*NEW FLAG: ack only the api-surface findings — a per-finding ratchet instead of a rubber stamp.* + +**wall time: 25.71s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: no ./.ripwire_quality_baseline — auto-comparing the working tree vs git HEAD (commit the baseline with --quality-baseline to pin it) +ripwire: ack provenance backfill — 0 clone row(s) reconstructed from the current tree, 196 re-derived, 39 left UNVERIFIED (their group was not found here — a floor, not proof it is gone), 55 left legacy (member set not found cloning here — a floor, not proof it is gone), 1297 ineligible (no cu … [line truncated: 200 more bytes on this line] +ripwire: acknowledged 1 of 9 finding(s) (8 left UNACKED by --ack-only, 0 already acked) → ./.ripwire_quality_acks +````` + +## `./build/ripwire . --quality-delta` + +*Re-run after the partial ack: acked=3, the rest still gate (exit 2).* + +**exit code: 2** — **wall time: 35.34s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [174 more display lines; full output is 20357 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: no ./.ripwire_quality_baseline — auto-comparing the working tree vs git HEAD (commit the baseline with --quality-baseline to pin it) +ripwire: --quality-delta gating: 4 preexisting-worse major finding(s); first: complexity src/infra/sortutil.h::rw::sortutil::lessByScoreDescId at src/infra/sortutil.h:62 (was=1 now=67) +````` + +## `./build/ripwire . --ack-only=gating` + +*--ack-only WITHOUT --quality-ack REFUSES loudly (exit 1, the pairing named) — it used to be silently ignored.* + +**exit code: 1** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --ack-only=SUBSTR narrows --quality-ack — pass both (e.g. ripwire

--quality-delta --ack-only=contract-change --quality-ack="reason") +````` + +## `./build/ripwire . --edit-check=nonNegativeFloatDescKey` + +*A real contract-change: was=1 now=2 params, with the call sites that are now provably incompatible, and a pasteable next= (--uses=SYM) on the root.* + +**wall time: 5.05s** + +````` + + + + + + +````` + +## `./build/ripwire . --edit-check=nonNegativeFloatDescKey --legend=full` + +*The same verdict under --legend=full: the default's one compact comment (the post-edit reflex at its cheapest) becomes ~5.7 KB of prose legend, every row identical.* + +**wall time: 5.57s** + +````` + + + + + + +````` + +## `./build/ripwire . --pr-context` + +*The review-evidence bundle with an actual changed file.* + +**wall time: 10.91s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [107 more display lines; full output is 10223 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --map-diff --top-k=5` + +*The map re-ranked with a teleport toward the changed file (changed=1 here, not 0).* + +**wall time: 6.26s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --clones` + +*The duplicated helper the sandbox edit introduced shows up as a clone group.* + +**wall time: 2.44s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [309 more display lines; full output is 16373 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --stray-content=zz-orphan` + +*CHANGED: a ref with NO merge base with HEAD now reports v="unknown" ok="0" in its own bucket — the absence of an answer, never a claim it is merged. (The sandbox carries a deliberately parentless branch built with `git commit-tree`; a shallow CI clone puts every ref here.)* + +**wall time: 6.71s** + +````` + + + + + +````` + +stderr: + +````` +[math degraded] crossref: no merge-base for ref (shallow clone or unrelated history?) — verdict is unknown, not merged (crossref.h:1750, std::vector rw::crossref::probeRefBases(const std::string &, const std::vector &, const std::string &) — logged once per site) +````` + +## `./build/ripwire . --stray-content=zz-orphan --plan` + +*CHANGED: --plan surfaces those same refs as an row rather than silently dropping them.* + +**wall time: 8.27s** + +````` + + + + +````` + +stderr: + +````` +[math degraded] crossref: no merge-base for ref (shallow clone or unrelated history?) — verdict is unknown, not merged (crossref.h:1750, std::vector rw::crossref::probeRefBases(const std::string &, const std::vector &, const std::string &) — logged once per site) +````` + +## `./build/ripwire . --dmm` + +*The DMM scalar on a REAL delta: the sandbox edit grew one unit past the nesting/complexity thresholds and added an 8-parameter one, so dmm is low and the three sub-scores say which property moved.* + +**wall time: 15.21s** + +````` + + +

+

+ +````` + +## `./build/ripwire . --quality-delta --scope=src/graph.h` + +*OWNERSHIP partition for a shared tree: every regression here lives in src/infra/, so under a scope naming src/graph.h they ALL print under with a do-not-ack banner and never gate — scoped-out-gating= says how many would have.* + +**wall time: 35.35s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [177 more display lines; full output is 20624 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: no ./.ripwire_quality_baseline — auto-comparing the working tree vs git HEAD (commit the baseline with --quality-baseline to pin it) +````` + +## `./build/ripwire . --quality-delta --quality-ack --scope=src/graph.h --ack-only=api-surface` + +*The rubber-stamp guard: an --ack-only that names an OUT-OF-SCOPE row refuses (exit 1) and writes nothing.* + +**exit code: 1** — **wall time: 25.15s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: no ./.ripwire_quality_baseline — auto-comparing the working tree vs git HEAD (commit the baseline with --quality-baseline to pin it) +ripwire: --ack-only=api-surface selects 1 finding(s) OUT OF SCOPE for --scope=src/graph.h — refusing, and writing nothing at all: + api-surface src/infra/sortutil.h::rw::sortutil::nonNegativeFloatDescKey at src/infra/sortutil.h:122 + those rows belong to whoever is editing those paths. Acking them here writes their debt into a committed ledger under YOUR + reason string, which is how a per-finding ratchet becomes a rubber stamp. Narrow the pattern, or widen the scope if they really are yours. +````` + +## `./build/ripwire . --handoff` + +*The continuation packet with a REAL diff: verified changed symbols + blast radius + tests-to-run, then the heuristic rows.* + +**wall time: 12.34s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [11 more display lines; full output is 2681 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --note-add="lessByScoreDescId: keep this branch-free — it sits inside the PageRank sort comparator"` + +*Pin a field note (write-side memory) to a symbol; committed to .ripwire_notes in the sandbox. The BARE name is resolved through the same resolver the read verbs use and stored as the canonical id — the rewrite is echoed on stderr, because a silent one is not a disclosure.* + +**wall time: 3.01s** + +````` +src/infra/sortutil.h::rw::sortutil::lessByScoreDescId 2026-11-20 keep this branch-free — it sits inside the PageRank sort comparator b0cb13d8d80ed7a0219eca835d53a9e97ec1613d integration/train-ge2 +````` + +stderr: + +````` +ripwire: --note-add: tip: notes that say "chose X over Y because Z" surface better — consider adding the why +ripwire: --note-add: target 'lessByScoreDescId' canonicalised to 'src/infra/sortutil.h::rw::sortutil::lessByScoreDescId' — that is the id --for/--expand key notes by +````` + +## `./build/ripwire . --notes` + +*The note is listed under the canonical id, dangling="0" — i.e. it will actually surface. (Before the H1 fix the bare name was stored verbatim and read dangling="1": recorded, and surfaced nowhere.)* + +**wall time: 1.49s** + +````` + + + + + + + + + + + + + + + + gate scripts' claim (~line 1305) is NOT enforced — the derived-vs-stated sibling loop here covers docs/EVALS.md only. It drifted 407→451 unnoticed (fixed 2026-08-23). To close: grep both files ('file:line:' parsing) in the gateCountClaims arm.]]> + + + + +````` + +## `./build/ripwire . --note-add="gitOneLine: which one?"` + +*Two definitions carry this name, so the write REFUSES rather than pick one: a note keys ONE canonical id, and an ambiguous selector is refused, never silently narrowed. Every candidate is named, with a runnable retry.* + +**exit code: 1** — **wall time: 1.09s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --note-add: tip: notes that say "chose X over Y because Z" surface better — consider adding the why +ripwire: --note-add: target 'gitOneLine' is ambiguous — it matches 2 definitions in 2 distinct contracts, and a note keys ONE canonical id (it would surface on one of them and look absent on the rest). Qualify one: ./src/handoff.h:gitOneLine, ./src/quality.h:gitOneLine — e.g. --note-add="./src/h … [line truncated: 33 more bytes on this line] +````` + +## `./build/ripwire . --note-add="lessByScoreDescIdd: typo"` + +*A name that resolves to nothing is refused with the read verbs' own did-you-mean — never written as a dead note.* + +**exit code: 1** — **wall time: 3.23s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --note-add: tip: notes that say "chose X over Y because Z" surface better — consider adding the why +ripwire: --note-add: target not found: lessByScoreDescIdd (did you mean 'lessByScoreDescId'?) (note: the lexical definition scan stopped at its budget, 4096 files or 16 MiB, before reading every file, so this miss is not proof the bytes define nothing; --grep=lessByScoreDescIdd lists its text uses) … [line truncated: 170 more bytes on this line] +````` + +## `./build/ripwire . --note-add="src/infra/sortutil.h::rw::sortutil::lessByScoreDescId: chose the flat two-branch compare over the nested ladder because the comparator sits inside the PageRank sort"` + +*The same symbol addressed by its CANONICAL id: already canonical, so nothing is rewritten and both notes land on ONE target.* + +**wall time: 2.37s** + +````` +src/infra/sortutil.h::rw::sortutil::lessByScoreDescId 2026-11-20 chose the flat two-branch compare over the nested ladder because the comparator sits inside the PageRank sort b0cb13d8d80ed7a0219eca835d53a9e97ec1613d integration/train-ge2 +````` + +## `./build/ripwire . --expand=lessByScoreDescId --top-k=0` + +*Both notes riding along with the symbol's body — the elements follow the body, past the display cut, so they are extracted below.* + +**wall time: 1.78s** + +````` + + + + + + + + + +````` + +## `./build/ripwire . --replace-symbol-body=lessByScoreDescId --edit-payload=/aux/empty_payload.h` + +*An EMPTY payload refuses — it never implies deletion.* + +**exit code: 1** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --edit-payload is empty; empty never means delete +````` + +## `./build/ripwire . --replace-symbol-body=lessByScoreDescId --edit-payload=/aux/payload_lessByScoreDescId.h` + +*Whole-symbol replace without a whole-file read: the payload is the ORIGINAL flat body, so this edit undoes the sandbox's deep-nesting regression. The receipt's span is the POST-edit byte range; replaced_bytes counts the old bytes overwritten.* + +**wall time: 16.85s** + +Input file: + +````` +inline bool lessByScoreDescId( const std::vector& scores, std::uint32_t a, std::uint32_t b ) noexcept +{ + if( scores[a] != scores[b] ) + { + return scores[a] > scores[b]; + } + return a < b; +} +````` + +````` +{"applied":"replace_symbol_body","symbol":"lessByScoreDescId","file":"src/infra/sortutil.h","span":{"start":2923,"end":3136},"lines":{"start":62,"end":69},"replaced_bytes":1718,"old_file_bytes":10679,"new_file_bytes":9174,"file_eol":"lf","eol_normalized":false,"trailing_newline_folded":true,"separat … [line truncated: 725 more bytes on this line] +"graph_ambiguous":3637,"graph_unresolved":20080,"graph_unindexed":311,"counts_floor":true},"tests_to_run":[{"p":"test/verify_radix.cpp","hops":1,"run":"bash test/greptiercheck.sh"}, +{"p":"test/adaptivecutshapefix/adaptive_cut_shape_test.cpp","hops":2,"run":"bash test/adaptivecutshapecheck.sh"}, +{"p":"test/connectcore_harness.cpp","hops":2,"run":"bash test/connectcorecheck.sh"}, +{"p":"test/forrowfeatures_unit.cpp","hops":2,"run":"bash test/forrowfeaturescheck.sh"}, +{"p":"test/fuzz/readers/readers_domain.cpp","hops":2,"run_unknown":true}, +{"p":"test/verify_csr.cpp","hops":2,"run":"bash test/a9disclosurecheck.sh"}, +{"p":"test/cloneband_harness.cpp","hops":3,"run":"bash test/clonebandcheck.sh"}, +{"p":"test/shstatus_harness.cpp","hops":3,"run":"bash test/gateexitcheck.sh"}, +{"p":"test/type3clone_harness.cpp","hops":3,"run":"bash test/type3clonecheck.sh"}, +{"p":"test/includeprecise_unit.cpp","hops":4,"run":"bash test/includeprecisecheck.sh"}, +{"p":"test/rustimport_unit.cpp","hops":4,"run":"bash test/rustimportprecisecheck.sh"}, +{"p":"test/fuzz/readers/readers_light.cpp","hops":5,"run_unknown":true}], +"order":"evidence","partners":0,"run_first":1,"tests":12,"script_gates_unmodelled":946,"graph_ambiguous":3637,"graph_unresolved":20080,"graph_unindexed":311,"counts_floor":true,"next":"bash test/greptiercheck.sh"} +````` + +stderr: + +````` +ripwire: cache : over its 2048 MiB budget — evicted 730 blob(s) of other roots or other ripwire builds (this build's blobs for this root are kept) +ripwire edit: applied atomically; receipt carries region, blob_sha, edit_check, tests_to_run; next: bash test/greptiercheck.sh +````` + +## `./build/ripwire . --edit-check=lessByScoreDescId` + +*The closed loop: contract unchanged (same params, same publicness) after the replace — nothing provably incompatible.* + +**wall time: 6.88s** + +````` + + + + + + + + + + + + +````` + +## `./build/ripwire . --insert-after-symbol=lessByScoreDescId --edit-payload=/aux/payload_note.h` + +*Insert immediately AFTER one uniquely-resolved definition; replaced_bytes=0 because the insert verbs never overwrite. The receipt carries the folded post-edit verification (lines=, edit_check, tests_to_run) so the loop closes in one call.* + +**wall time: 8.62s** + +````` +{"applied":"insert_after_symbol","symbol":"lessByScoreDescId","file":"src/infra/sortutil.h","span":{"start":3136,"end":3224},"lines":{"start":69,"end":71},"replaced_bytes":0,"old_file_bytes":9174,"new_file_bytes":9262,"file_eol":"lf","eol_normalized":false,"trailing_newline_folded":true,"separator_p … [line truncated: 650 more bytes on this line] +"graph_ambiguous":3637,"graph_unresolved":20080,"graph_unindexed":311,"counts_floor":true},"tests_to_run":[{"p":"test/verify_radix.cpp","hops":1,"run":"bash test/greptiercheck.sh"}, +{"p":"test/adaptivecutshapefix/adaptive_cut_shape_test.cpp","hops":2,"run":"bash test/adaptivecutshapecheck.sh"}, +{"p":"test/connectcore_harness.cpp","hops":2,"run":"bash test/connectcorecheck.sh"}, +{"p":"test/forrowfeatures_unit.cpp","hops":2,"run":"bash test/forrowfeaturescheck.sh"}, +{"p":"test/fuzz/readers/readers_domain.cpp","hops":2,"run_unknown":true}, +{"p":"test/verify_csr.cpp","hops":2,"run":"bash test/a9disclosurecheck.sh"}, +{"p":"test/cloneband_harness.cpp","hops":3,"run":"bash test/clonebandcheck.sh"}, +{"p":"test/shstatus_harness.cpp","hops":3,"run":"bash test/gateexitcheck.sh"}, +{"p":"test/type3clone_harness.cpp","hops":3,"run":"bash test/type3clonecheck.sh"}, +{"p":"test/includeprecise_unit.cpp","hops":4,"run":"bash test/includeprecisecheck.sh"}, +{"p":"test/rustimport_unit.cpp","hops":4,"run":"bash test/rustimportprecisecheck.sh"}, +{"p":"test/fuzz/readers/readers_light.cpp","hops":5,"run_unknown":true}], +"order":"evidence","partners":0,"run_first":1,"tests":12,"script_gates_unmodelled":946,"graph_ambiguous":3637,"graph_unresolved":20080,"graph_unindexed":311,"counts_floor":true,"next":"bash test/greptiercheck.sh"} +````` + +stderr: + +````` +ripwire edit: applied atomically; receipt carries region, blob_sha, edit_check, tests_to_run; next: bash test/greptiercheck.sh +````` + +## `./build/ripwire . --insert-after-symbol=lessByScoreDescId --edit-payload=/aux/payload_note.h --no-post-check` + +*The opt-out: the same insert with the folded verification skipped — lines= still rides (it is free), edit_check/tests_to_run do not, and the two pasteable commands stay on stderr.* + +**wall time: 4.86s** + +````` +{"applied":"insert_after_symbol","symbol":"lessByScoreDescId","file":"src/infra/sortutil.h","span":{"start":3136,"end":3224},"lines":{"start":69,"end":71},"replaced_bytes":0,"old_file_bytes":9262,"new_file_bytes":9350,"file_eol":"lf","eol_normalized":false,"trailing_newline_folded":true,"separator_p … [line truncated: 570 more bytes on this line] +````` + +stderr: + +````` +ripwire edit: applied atomically; receipt carries region, blob_sha (post-check skipped); next: --edit-check=src/infra/sortutil.h:lessByScoreDescId +````` + +## `./build/ripwire . --insert-before-symbol=nonNegativeFloatDescKey --edit-payload=/aux/payload_note.h --edit-target-file=src/infra/sortutil.h` + +*Insert BEFORE, with --edit-target-file pinning which same-named definition (here unambiguous — the disambiguator is simply honoured).* + +**wall time: 13.56s** + +````` +{"applied":"insert_before_symbol","symbol":"nonNegativeFloatDescKey","file":"src/infra/sortutil.h","span":{"start":3656,"end":3744},"lines":{"start":87,"end":88},"replaced_bytes":0,"old_file_bytes":9350,"new_file_bytes":9438,"file_eol":"lf","eol_normalized":false,"trailing_newline_folded":false,"sep … [line truncated: 753 more bytes on this line] +{"n":"benchAdaptive","p":"bench/bench_radix_ab.cpp:157","l":[162]}, +{"n":"radixSortNonNegativeFloatsDesc","p":"src/infra/sortutil.h:118","l":[127]}, +{"n":"radixSortByScoreDescId","p":"src/infra/sortutil.h:133","l":[193]}], +"graph_ambiguous":3637,"graph_unresolved":20080,"graph_unindexed":311,"counts_floor":true},"tests_to_run":[{"p":"test/verify_radix.cpp","hops":1,"run":"bash test/greptiercheck.sh"}, +{"p":"test/adaptivecutshapefix/adaptive_cut_shape_test.cpp","hops":2,"run":"bash test/adaptivecutshapecheck.sh"}, +{"p":"test/connectcore_harness.cpp","hops":2,"run":"bash test/connectcorecheck.sh"}, +{"p":"test/forrowfeatures_unit.cpp","hops":2,"run":"bash test/forrowfeaturescheck.sh"}, +{"p":"test/fuzz/readers/readers_domain.cpp","hops":2,"run_unknown":true}, +{"p":"test/verify_csr.cpp","hops":2,"run":"bash test/a9disclosurecheck.sh"}, +{"p":"test/cloneband_harness.cpp","hops":3,"run":"bash test/clonebandcheck.sh"}, +{"p":"test/shstatus_harness.cpp","hops":3,"run":"bash test/gateexitcheck.sh"}, +{"p":"test/type3clone_harness.cpp","hops":3,"run":"bash test/type3clonecheck.sh"}, +{"p":"test/includeprecise_unit.cpp","hops":4,"run":"bash test/includeprecisecheck.sh"}, +{"p":"test/rustimport_unit.cpp","hops":4,"run":"bash test/rustimportprecisecheck.sh"}, +{"p":"test/fuzz/readers/readers_light.cpp","hops":5,"run_unknown":true}], +"order":"evidence","partners":0,"run_first":1,"tests":12,"script_gates_unmodelled":946,"graph_ambiguous":3637,"graph_unresolved":20080,"graph_unindexed":311,"counts_floor":true,"next":"--uses=src/infra/sortutil.h:nonNegativeFloatDescKey"} +````` + +stderr: + +````` +ripwire edit: applied atomically; receipt carries region, blob_sha, edit_check, tests_to_run; next: --uses=src/infra/sortutil.h:nonNegativeFloatDescKey +````` + +## `./build/ripwire . --replace-symbol-body=DoesNotExist --edit-payload=/aux/payload_note.h` + +*An unknown TARGET refuses and leaves every file byte-identical.* + +**exit code: 1** — **wall time: 4.68s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --replace-symbol-body: symbol 'DoesNotExist' not found +````` + +## `./build/ripwire . --edit-plan=/aux/edit_plan.json --dry-run` + +*A versioned multi-edit TRANSACTION preflighted without writing: the receipt shows what each op would read and touch.* + +**wall time: 5.40s** + +Input file: + +````` +{ + "version": 1, + "edits": [ + { + "op": "insert_before_symbol", + "target": "nonNegativeFloatDescKey", + "payload": "plan_note.h" + } + ] +} +````` + +````` +{"schema":"ripwire.edit-plan/v1","mode":"dry-run","edits":1,"files":1,"callers_union":4,"graph_ambiguous":3637,"graph_unresolved":20080,"graph_unindexed":311,"counts_floor":true,"atomic_scope":"per-file","rollback_on_write_error":true,"recheck_before_each_write":true,"multifile_crash_atomic":false," … [line truncated: 400 more bytes on this line] +````` + +## `./build/ripwire . --edit-plan=/aux/edit_plan.json --apply` + +*The same plan committed: per-file locks, re-verify-before-write, atomic rename, rollback on a later failure.* + +**wall time: 10.17s** + +````` +{"schema":"ripwire.edit-plan/v1","mode":"apply","edits":1,"files":1,"callers_union":4,"graph_ambiguous":3637,"graph_unresolved":20080,"graph_unindexed":311,"counts_floor":true,"applied":1,"atomic_files":1,"atomic_scope":"per-file","rollback_on_write_error":true,"recheck_before_each_write":true,"mult … [line truncated: 584 more bytes on this line] +{"n":"benchAdaptive","p":"bench/bench_radix_ab.cpp:157","l":[162]}, +{"n":"radixSortNonNegativeFloatsDesc","p":"src/infra/sortutil.h:120","l":[129]}, +{"n":"radixSortByScoreDescId","p":"src/infra/sortutil.h:135","l":[195]}], +"graph_ambiguous":3637,"graph_unresolved":20080,"graph_unindexed":311,"counts_floor":true}}]} +````` + +## `./build/ripwire . --edit-plan=/aux/edit_plan.json` + +*Neither --dry-run nor --apply: the mode is explicit, so this refuses.* + +**exit code: 1** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --edit-plan requires exactly one of --dry-run or --apply +````` + +## `./build/ripwire . --quality-delta` + +*After the agent's edits: the complexity/nesting rows on lessByScoreDescId are gone (the replace undid them), the rest still gate (exit 2).* + +**exit code: 2** — **wall time: 30.95s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [171 more display lines; full output is 19726 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: no ./.ripwire_quality_baseline — auto-comparing the working tree vs git HEAD (commit the baseline with --quality-baseline to pin it) +ripwire: --quality-delta gating: 2 preexisting-worse major finding(s); first: duplication src/infra/sortutil.h::rw::sortutil::nonNegativeFloatAscKeyCopy | src/infra/sortutil.h::rw::sortutil::nonNegativeFloatDescKey at src/infra/sortutil.h:101 (was=0 now=59) +````` + +## `./build/ripwire . --quality-baseline` + +*REFUSES, exit 1: this sandbox tree is already regressed, and pinning here would swallow that debt into the floor so every later delta read clean. It names how many gating findings it would absorb, the first of them, and the way forward.* + +**exit code: 1** — **wall time: 15.51s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --quality-baseline: this tree already holds 2 gating finding(s) against HEAD — pinning here would absorb + them into the floor, and every later --quality-delta would read clean. First: duplication src/infra/sortutil.h::rw::sortutil::nonNegativeFloatAscKeyCopy | src/infra/sortutil.h::rw::sortutil::nonNegativeFloatDescKey (was=0 now=59) + Commit the tree first, or pass --allow-dirty to pin anyway (the sidecar then records the 2 absorbed, and every + report against it carries baseline_absorbed="2"). +````` + +## `./build/ripwire . --quality-baseline --allow-dirty` + +*The consent form: pin anyway. The sidecar is stamped with the dirty pin and the absorbed count, so the fact outlives the process that knew it.* + +**wall time: 23.06s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --quality-baseline --allow-dirty: pinned with 2 gating finding(s) ABSORBED into the floor (stamped in the sidecar; every --quality-delta against it carries baseline_absorbed="2") +ripwire: wrote ./.ripwire_quality_baseline (snapshot of 41900 per-symbol rows, 44048 indexed symbols total) +````` + +Artifact written: + +````` + 8766401 .ripwire_quality_baseline +# ripwire quality baseline v6 — regenerate with --quality-baseline; do not hand-edit +producer 3689f993bf0d8513a1d157e08097f94270b1cc71a98e7b42d4667d4384fd714c +head b0cb13d8d80ed7a0219eca835d53a9e97ec1613d +dirty 1 +absorbed 2 +ccx 67c15011ee8b 0 +ccx d19d7c13cbc7 2 +ccx 1f7edbff929e5 12 +ccx 6a732f6699b +````` + +## `./build/ripwire . --quality-delta` + +*Against that sidecar the same tree reads regressions=0 — but baseline_absorbed= is on the root, so this green means clean SINCE THE PIN, never clean. A baseline is a floor YOU chose, and it belongs BEFORE the change.* + +**wall time: 29.47s** + +````` + + +````` + + +--- + +# the MCP dialect — the same verbs over stdio JSON-RPC (one-shot exchange, not a persistent server) + +## `printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize"}' '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | ./build/ripwire --mcp` + +*initialize + tools/list: the manifest an agent host loads at session start — every verb's name, description and input schema.* + +````` +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","serverInfo":{"name":"ripwire","version":"0.6.10-dev.130+gb0cb13d8d"},"capabilities":{"tools":{},"resources":{}},"instructions":"Map before reading files. Start a new task with explore; use from_trace for an error; use impact plus uses … [line truncated: 760 more bytes on this line] +{"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"analyze","description":"Architecture map for a directory: signatures and the call graph for the top symbols. Use when landing cold in a repo or subdir, before reading files; for a task-scoped inventory use 'for', for one symbol's neighborhood find_ … [line truncated: 742 more bytes on this line] +{"name":"rank_by","description":"The SAME architecture map 'analyze' serves, ranked by a different signal instead of plain PageRank. rank_by = pagerank (default, omit it — the CLI's own unbiased --rank-by=pagerank; 'analyze' can rank differently on a tree with uncommitted changes, where it biases … [line truncated: 1077 more bytes on this line] +{"name":"find_symbol","description":"A symbol's 1-hop neighborhood: the symbol (with a fetch_body handle) plus direct callers (calledBy) and callees (calls). Full transitive reach: 'impact'. Read/write/import sites, not just calls: 'uses'. JSON {symbol, calledBy, calls, defs, count, hop_tested, hop_ … [line truncated: 1181 more bytes on this line] +{"name":"find_referencing_symbols","description":"Direct (1-hop) callers of a symbol, each with a fetch_body handle. For the full transitive blast radius use 'impact', for read/write/import sites 'uses'. JSON {symbol, calledBy, defs, count, hop_tested, hop_untested, declined_calls, counts_floor}; ca … [line truncated: 945 more bytes on this line] +{"name":"grep","description":"Trigram literal search; each hit annotated with its enclosing symbol (which function/class it is in). Hits carry text; enclosing rows a fetch_body handle. pattern = the literal; in=any lifts the span tiering (default: tightest non-empty tier; rest rides as suppressed_co … [line truncated: 837 more bytes on this line] +{"name":"cochange","description":"Files that historically change together with this file — the co-edit partners. Fowler's Shotgun Surgery as change coupling. dep_capable=false (sh/md/json/binary) or no_file_edges (Go, Java: imports not resolved) makes surprising undefined, not a finding. file = th … [line truncated: 705 more bytes on this line] +{"name":"memory_recall","description":"Most relevant memory notes / docs for a task, full text — the few that matter, not the whole corpus. path = docs/memory dir; task = what you're working on; top_k = docs to return, 1..1000 (default 6), refused outside that band, never clamped; budget_tokens = … [line truncated: 790 more bytes on this line] +{"name":"situational_awareness","description":"The 5 things to know about a diff, as JSON: blast_radius, tests_to_run, forgotten (usual co-change partners missing from this diff), hotspot_alert, modules_touched. forgotten = the Shotgun Surgery check. diff/files optional — defaults to 'git diff HEA … [line truncated: 1296 more bytes on this line] +{"name":"mentions","description":"Docs (markdown plans/designs) that name a code symbol in a backtick. symbol = the code symbol name; limit/offset page the files. An @FILE:LINE line-seed rebinds to the innermost definition enclosing that line and answers for it, disclosing the rebound name as 'sym' … [line truncated: 625 more bytes on this line] +{"name":"for","description":"Task-lens ranked, signatures-only inventory of the building blocks most relevant to a task (cx=complexity, in=reuse-count). task = the task in plain words; budget_tokens = an optional soft row target (the CLI --for --token-budget). The header carries route= (which ranker … [line truncated: 1061 more bytes on this line] +{"name":"lego","description":"Interface-to-impls view for ONE named interface/base: its method contract plus EVERY implementor (own-language only), each with file path. Use when implementing against a KNOWN interface (contrast 'for', which sprays top interfaces for a task). type = interface/base nam … [line truncated: 841 more bytes on this line] +{"name":"owners","description":"Bus-factor: recency-weighted (6-month half-life) author ownership per file. symbol = optional, restricts to the file that defines it; limit/offset page the rows. at= is the commit these numbers were computed at (+dirty = the working tree differed). An @FILE:LINE line- … [line truncated: 879 more bytes on this line] +{"name":"replace_symbol_body","description":"Replace a symbol's ENTIRE definition (signature through closing brace) with new_body — splices over the full def span, preserving every byte outside it verbatim; new_body must be a complete, well-formed definition. One trailing newline folds (trailing_n … [line truncated: 1323 more bytes on this line] +{"name":"insert_before_symbol","description":"Insert text immediately BEFORE a symbol's definition (its first byte); padded to the file's own blank-line seam (separator_padded=N). Same refusal contract as replace_symbol_body (not found / ambiguous / stale index / symlink / concurrent write, file unc … [line truncated: 877 more bytes on this line] +{"name":"insert_after_symbol","description":"Insert text immediately AFTER a symbol's definition (past its final byte, which is preserved exactly); padded to the file's own blank-line seam (separator_padded=N); one trailing newline folds (trailing_newline_folded). Same refusal contract as replace_sy … [line truncated: 878 more bytes on this line] +{"name":"fetch_body","description":"Full (or partial-range) source of a symbol's definition, addressed by the stable `handle` a read verb attached to it (bodies on request, not by default). start_line/end_line are optional, 1-based, INCLUSIVE and BODY-RELATIVE (line 1 = the def's first line), clampe … [line truncated: 1049 more bytes on this line] +{"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. chosen by ROLE, NEVER by text similarity to your task: candidates are first filtered to cogn … [line truncated: 1372 more bytes on this line] +{"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, acr … [line truncated: 870 more bytes on this line] +{"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, then quality_delta compares against this pinned floor … [line truncated: 445 more bytes on this line] +{"name":"impact","description":"IS IT SAFE TO CHANGE X? — the TRANSITIVE blast radius of a symbol via calls, nearest first (d= hop depth), then PageRank. Use before modifying or deleting a symbol; it beats find_referencing_symbols (direct callers only), and 'uses' catches the read/write/import sit … [line truncated: 1325 more bytes on this line] +{"name":"uses","description":"The STATICALLY RESOLVABLE use-sites of a symbol, not just calls: role (call | read | write | import | extends), file:line, and enclosing symbol. Use to see the footprint before renaming or changing a name — find_referencing_symbols and impact follow only calls. extern … [line truncated: 1146 more bytes on this line] +{"name":"affected","description":"WHICH TESTS TO RUN for a change — test files that transitively reach the changed files/symbols, ranked by evidence (edited > partner-named > hop distance). files = changed files and/or symbols, comma-separated: each item is tried as an indexed PATH pattern first, … [line truncated: 1238 more bytes on this line] +{"name":"path_between","description":"Does A REACH B, and HOW? — the shortest directed CALL path between two symbols, hop-by-hop. reachable=\"0\" hops=\"0\" is a valid 'not reachable' answer — call edges are name-based, so a missing dynamic/callback edge can hide a real path. Named path_between … [line truncated: 709 more bytes on this line] +{"name":"connect","description":"When a task touches 2..16 named symbols, returns the minimal subgraph RELATING them - terminals, the fewest joining intermediaries (with signatures), and call edges in true direction - finding the shared-caller joins a directed path_between cannot; unrelated symbols … [line truncated: 950 more bytes on this line] +{"name":"explore","description":"ONE-call task orientation: the routed+anchored ranking, full bodies of the top hits, their 1-hop callers, field notes, and tests_to_run — ALL under one deterministic byte budget, in a fixed section order (ranking > bodies > callers > notes > tests) that degrades gr … [line truncated: 2134 more bytes on this line] +{"name":"from_trace","description":"Paste a stack trace / sanitizer report / compiler error and get it mapped onto indexed symbols, ranked INNERMOST-first: the parsed frame map, the ranked suspects' signatures, and the innermost in-corpus symbol's FULL body. Out-of-corpus frames are listed a … [line truncated: 1233 more bytes on this line] +{"name":"edit_check","description":"Just edited a symbol? Did its CONTRACT (param count + publicness) change vs git HEAD, and which 1-hop callers are NOW INCOMPATIBLE with the new arity by fixed-arity evidence (not a guess — every folded definition disagrees)? This is call sites worth OPENING, not … [line truncated: 1908 more bytes on this line] +{"name":"whereis","description":"WHERE DOES THIS CONTENT LIVE? Which branch's tree defines or mentions a symbol, HEAD first, with on-head=0 naming the case this verb exists for: content that lives only on a branch (a finished fix stranded on 1 of 30 refs). Each distinct blob is read once (content-ad … [line truncated: 1475 more bytes on this line] +{"name":"stray_content","description":"Per branch: the lines its own divergent work AUTHORED (vs its merge-base with HEAD) that the live line does NOT have. Four verdicts (unmerged+superseded+merged+unknown=refs): v=unmerged is genuinely absent; v=superseded means the live line re-implemented the wo … [line truncated: 1123 more bytes on this line] +{"name":"flags","description":"WHAT IS BUILT BUT DARK here — the answer to 'why don't I see feature X?'. Harvests all three gate patterns (ifndef/define header gates, CMake option(), getenv reads) with each gate's kind, DEFAULT, the size of the code it guards, and its read sites. When a name is bo … [line truncated: 1434 more bytes on this line] +{"name":"doc_drift","description":"WHICH OF THIS REPO'S DOC CLAIMS ARE NOW FALSE. Verifies the CHECKABLE anchors in every markdown file against the live index and returns ONLY the ones that no longer hold: file:line refs (missing-file / past-eof / line-moved), backticked symbol mentions (undefined), … [line truncated: 1167 more bytes on this line] +{"name":"slice","description":"WHERE IS THIS VARIABLE DEFINED AND USED inside one function — NAME-BASED intra-procedural def-use rows of one variable inside ONE uniquely-resolved definition (the ARISE slicer, arXiv:2605.03117). symbol alone lists the sliceable locals to pick from; add var (or spel … [line truncated: 1722 more bytes on this line] +{"name":"batch","description":"ONE-TURN CONTEXT SWEEP: answer up to 16 heterogeneous READ sub-queries in a single call (the deterministic $0 counterpart of a parallel-search agent). queries = array over the SAME path, in EITHER grammar: {verb, ...args} objects, or the CLI --batch file's own \"verb:a … [line truncated: 2040 more bytes on this line] +````` + +The manifest, summarised (name / description bytes / required args) — what the host pays in context every session: + +````` +tools= 33 manifest_bytes= 47453 (~tokens at 4 bytes/token: 11863 ) +explore desc_bytes= 1339 schema_bytes= 958 required=['task'] +batch desc_bytes= 1235 schema_bytes= 962 required=['queries'] +edit_check desc_bytes= 1180 schema_bytes= 889 required=['symbol'] +slice desc_bytes= 953 schema_bytes= 932 required=['symbol'] +whereis desc_bytes= 701 schema_bytes= 941 required=['symbol'] +flags desc_bytes= 881 schema_bytes= 720 required=[] +exemplar desc_bytes= 951 schema_bytes= 591 required=[] +replace_symbol_body desc_bytes= 865 schema_bytes= 610 required=['symbol', 'new_body'] +impact desc_bytes= 821 schema_bytes= 666 required=['symbol'] +situational_awareness desc_bytes= 864 schema_bytes= 581 required=[] +affected desc_bytes= 790 schema_bytes= 610 required=['files'] +from_trace desc_bytes= 836 schema_bytes= 559 required=['trace'] +find_symbol desc_bytes= 752 schema_bytes= 590 required=['symbol'] +doc_drift desc_bytes= 728 schema_bytes= 604 required=[] +uses desc_bytes= 626 schema_bytes= 682 required=['symbol'] +stray_content desc_bytes= 678 schema_bytes= 604 required=[] +rank_by desc_bytes= 758 schema_bytes= 481 required=[] +for desc_bytes= 453 schema_bytes= 777 required=['task'] +fetch_body desc_bytes= 623 schema_bytes= 588 required=['handle'] +connect desc_bytes= 535 schema_bytes= 580 required=['symbols'] +find_referencing_symbols desc_bytes= 505 schema_bytes= 590 required=['symbol'] +insert_after_symbol desc_bytes= 458 schema_bytes= 577 required=['symbol', 'text'] +insert_before_symbol desc_bytes= 455 schema_bytes= 578 required=['symbol', 'text'] +owners desc_bytes= 425 schema_bytes= 625 required=[] +quality_delta desc_bytes= 750 schema_bytes= 279 required=[] +lego desc_bytes= 360 schema_bytes= 651 required=['type'] +grep desc_bytes= 445 schema_bytes= 562 required=['pattern'] +memory_recall desc_bytes= 447 schema_bytes= 500 required=['task'] +path_between desc_bytes= 357 schema_bytes= 506 required=['from', 'to'] +cochange desc_bytes= 393 schema_bytes= 476 required=['file'] +analyze desc_bytes= 546 schema_bytes= 318 required=[] +mentions desc_bytes= 305 schema_bytes= 486 required=['symbol'] +quality_baseline desc_bytes= 407 schema_bytes= 193 required=[] +````` + +## `printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize"}' '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | ./build/ripwire --mcp --mcp-tools=core` + +*--mcp-tools=core: the server lists only the core profile's tools (explore, batch, from_trace, impact, uses, fetch_body, edit_check, quality_delta), so a host that loads every schema at session start pays only for those.* + +````` +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","serverInfo":{"name":"ripwire","version":"0.6.10-dev.130+gb0cb13d8d"},"capabilities":{"tools":{},"resources":{}},"instructions":"Map before reading files. Start a new task with explore; use from_trace for an error; use impact plus uses … [line truncated: 977 more bytes on this line] +{"jsonrpc":"2.0","id":2,"result":{"tools":[{"name":"fetch_body","description":"Full (or partial-range) source of a symbol's definition, addressed by the stable `handle` a read verb attached to it (bodies on request, not by default). start_line/end_line are optional, 1-based, INCLUSIVE and BODY-RELAT … [line truncated: 1092 more bytes on this line] +{"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, acr … [line truncated: 870 more bytes on this line] +{"name":"impact","description":"IS IT SAFE TO CHANGE X? — the TRANSITIVE blast radius of a symbol via calls, nearest first (d= hop depth), then PageRank. Use before modifying or deleting a symbol; it beats find_referencing_symbols (direct callers only), and 'uses' catches the read/write/import sit … [line truncated: 1325 more bytes on this line] +{"name":"uses","description":"The STATICALLY RESOLVABLE use-sites of a symbol, not just calls: role (call | read | write | import | extends), file:line, and enclosing symbol. Use to see the footprint before renaming or changing a name — find_referencing_symbols and impact follow only calls. extern … [line truncated: 1146 more bytes on this line] +{"name":"explore","description":"ONE-call task orientation: the routed+anchored ranking, full bodies of the top hits, their 1-hop callers, field notes, and tests_to_run — ALL under one deterministic byte budget, in a fixed section order (ranking > bodies > callers > notes > tests) that degrades gr … [line truncated: 2134 more bytes on this line] +{"name":"from_trace","description":"Paste a stack trace / sanitizer report / compiler error and get it mapped onto indexed symbols, ranked INNERMOST-first: the parsed frame map, the ranked suspects' signatures, and the innermost in-corpus symbol's FULL body. Out-of-corpus frames are listed a … [line truncated: 1233 more bytes on this line] +{"name":"edit_check","description":"Just edited a symbol? Did its CONTRACT (param count + publicness) change vs git HEAD, and which 1-hop callers are NOW INCOMPATIBLE with the new arity by fixed-arity evidence (not a guess — every folded definition disagrees)? This is call sites worth OPENING, not … [line truncated: 1908 more bytes on this line] +{"name":"batch","description":"ONE-TURN CONTEXT SWEEP: answer up to 16 heterogeneous READ sub-queries in a single call (the deterministic $0 counterpart of a parallel-search agent). queries = array over the SAME path, in EITHER grammar: {verb, ...args} objects, or the CLI --batch file's own \"verb:a … [line truncated: 2040 more bytes on this line] +````` + +The core manifest, summarised (name / description bytes / required args): + +````` +tools= 8 manifest_bytes= 14193 (~tokens at 4 bytes/token: 3548 ) +explore desc_bytes= 1339 schema_bytes= 958 required=['task'] +batch desc_bytes= 1235 schema_bytes= 962 required=['queries'] +edit_check desc_bytes= 1180 schema_bytes= 889 required=['symbol'] +impact desc_bytes= 821 schema_bytes= 666 required=['symbol'] +from_trace desc_bytes= 836 schema_bytes= 559 required=['trace'] +uses desc_bytes= 626 schema_bytes= 682 required=['symbol'] +fetch_body desc_bytes= 623 schema_bytes= 588 required=['handle'] +quality_delta desc_bytes= 750 schema_bytes= 279 required=[] +````` + +## `printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize"}' '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"for","arguments":{"path":".","task":"pagerank power iteration"}}}' | ./build/ripwire --mcp` + +*MCP `for`: always bundle=sigs (never the CLI's compact route), the same ranked signatures as --for.* + +**wall time: 7.01s** + +````` +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","serverInfo":{"name":"ripwire","version":"0.6.10-dev.130+gb0cb13d8d"},"capabilities":{"tools":{},"resources":{}},"instructions":"Map before reading files. Start a new task with explore; use from_trace for an error; use impact plus uses … [line truncated: 760 more bytes on this line] +{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":". window: shown= total= capped= has_more= next_offset= offset= limit= (ca … [line truncated: 13902 more bytes on this line] +"_index":"[index: files=4779 symbols=44046 hash=3fa167a7]","_fresh":"ok"}} +{"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"