diff --git a/.ripwire_quality_acks b/.ripwire_quality_acks index 0c0360f2c..fe35ab739 100644 --- a/.ripwire_quality_acks +++ b/.ripwire_quality_acks @@ -15,6 +15,7 @@ ack api-surface 105c48e20c80c896 3 cid=720fab31ea99ebde A2: unmeasuredHintNote g ack api-surface 1085f731a3dde7c8 7 cid=b012ca29106914d1 capture-audit 2026-09-04 wave-1 close: symbols two lanes each grew past the other's acked magnitude — runDoctor (L10 legend + blobs_floor=, L9 built_from=), writeEnsembleReport (L9 root=, L10 conditional unavailable=), runAffected/runVerify (L9 root-relative block, L4 gauge), writeTestGateReport (L4 gauge splice, L9 row-gated root=; the XML/JSON twins' duplication is the lockstep mcpclidiffcheck asserts, as L9 acked; graphGaugeAttrXml/Json are the same lockstep), writePanelReport (L10 conditional attrs, L4 counts_floor), printUsage/validateConfig (L1 H10 hoist + L5/L9/L10 help text). Re-acked at the merged magnitude; prior reasons kept ack api-surface 10f47dd5a3f35d86 5 fnbody-require lane: deliberate additive API widening (optional out-params, default nullptr, every existing caller unaffected) to disclose the lazy require/import distinction on --impact's importer tier; residual complexity/duplication is the twin-dialect emitter shape and the dual-mode importersOfFiles scan this feature requires, already extracted where a helper genuinely reduced it (scanImporterEdges, recordLazyPair); short-horizon-churn is this same commit's own edit history ack api-surface 1103e9ea8ace3099 5 cid=186a55a17ef44834 now=5 was=4 facet=contract-change p=src/exemplarfamily.h:2505 REDACT-TOUCH: every emitter that quotes a source, manifest or plan line takes the run's RedactCounts* (nullptr = --no-redact), the #686 pattern; the added parameter is the fix and every caller passes the tally it already holds (d.redactPtr, the MCP request's redactPtr, PathAnswerSurface::redact). +ack api-surface 11c919df1ef385d7 3 cid=d706aec64c7e594d now=3 was=2 facet=contract-change p=src/shstatus.h:502 CR712-SHSTATUS-DEPTH: shstatus.h detail:: recursion helpers (internal to the header, every caller updated in the same commit) take the one NestBudget the lexer and parser share; not a public contract ack api-surface 131068a6cedf0864 4 cid=9ead4ea91ba5d605 review of #219: the run= relativity claim is CONDITIONAL, so the predicate has to reach every site that states it — prLegendText and writeFlipHeader take rootRelativeRuns (and its root= attribute) because the legend sentence and the command spelling must be decided by ONE fact, testmap.h runsAreRootRelative; a legend that claims a relativity the spelling does not have is the defect this round fixes. The duplication row pairs that 19-token predicate with mcp.h mcpOmitsGitVerbs, which asks a different question about a different field and shares only the shape of a two-term boolean return — merging them would name neither. | prior: E1 follow-up (#214 CI): prLegendText gains the one pre-render fact that gates testmap.h's run=/run_unknown=/ clause (corpusHasTests) — its single caller writePrContext passes it; the unconditional clause put defaultceilingcheck's 120-file no-test bundle 25 tokens over its 8000 default budget ack api-surface 147451c4175d9f08 2 cid=6d5a9dab1a24c31f degrade disclosure: each read seam and the ref pool now take the DISCLOSE sink whose field the document reads ack api-surface 1520fa02411735c3 6 cid=69e2cb4c55a88771 C1 F-06/F-07/F-10 (the listing-paging round): three listing verbs learn to disclose and page their row listings, and every gating row is that one change. api-surface 14 = ONE trailing DEFAULTED parameter each (an int pageOffset, an McpPageArgs window, a SituPageArgs, or the next= invocation a header now carries) on the emitters that must be TOLD their window — writeFlags/writeGate, writeCappedRows/writeCappedList/writeFlip/writeFlipHeader/writeFlipLights, computeFlip, nearestGateNames (which gains its cap and its TOTAL, the disclosure itself), situShowingNote/writeSituation, and the three MCP twins flagsText/flipText/situationDiffJson; additive by construction, every pre-existing call site compiles unchanged, and the alternative — a second capped emitter per verb — is the drift this repo removes rather than adds, because two emitters that disagree about a window can drop the row that IS the answer. verbosity 3 = kDocDriftLegend +20 lines and writeDocDriftPage +10 are the in-band vocabulary a reader needs to read shown_failed=/failed_capped=/failed_total= where they meet it (the rationale and the next= scan were already hoisted OUT of the body into their own function and comment, which took the complexity row to zero and the LOC row from +48 to +10); dispatchMcpLine +12 is two pagedResult wrappers on a pre-existing 1376-line dispatcher this lane adds to rather than creates. complexity 1 = the same dispatcher, +9 on a base of 518. duplication 1 = flagsText | flipText at 110 tokens, down from 131 after the shared mcpRowCap fold; the residual is getIndex + compute + captureXml, the shape EVERY index-backed MCP twin in this file has, and merging two verbs that return different results behind one entry point would be worse code than the clone. short-horizon-churn 19 = this lane's own footprint across cli.h/docdrift.h/darkflags.h/flipimpact.h/situ.h/mcp*, plus cli.h symbols three other lanes touched the same day; none foreign, none thrash. @@ -54,6 +55,7 @@ ack api-surface 3478654139c90f0f 5 cid=fc086b8b559ee8c6 Review of #214, round 2. ack api-surface 3561d0281d324276 14 WAVE-2 close (2026-08-19), finding 3 of 3: the 76 remaining gating rows, ONE change. All of them are W2-E's root-relative p= landing (9beaa2c/fccea68/a271e6c/b3fe074 plus the f9108b7 correction), measured for the first time at WAVE granularity. The per-lane acks written during W2-E covered only the correction round's own diff (working-tree-vs-HEAD at that moment), so the original ~30-verb landing was never QD-acked; this ack closes that gap rather than re-accepting anything. Verified by reading the whole 20cdc04..860291c src/main.cpp diff line by line: 282 of 448 added lines match the root-relative predicate directly and every one of the remaining 127 is an existing std::printf rewritten from ing.files[...] to the root-relative rp local, plus four extracted emit helpers (computeDirModules, printJsonSymbolRows, writeOversizeRows, writeDropRows). No unrelated logic rides in. By kind: api-surface 28 = the +1 rootArg/rootPrefix parameter on the emitters that must now be TOLD their root (writeAbiCheck/Ref/Struct, emitColumnar*, packBodies/Deps/Lego/Outline/Signatures[Json], serialize[Json], writeLayout*, packConnect, buildD1Row and the report writers) - defaulted wherever a caller could stay unchanged. complexity 31 and verbosity 16 = the single-root-condition ternary and its guarded root= clause applied per emitter, with no new nesting level and no new control flow beyond that one conditional; the large absolute numbers (runStructureText 207->231, runLint 313->323, runMaintenanceViews 174->190, runCallHierarchy 71->80) are pre-existing dispatcher size the wave adds to, not creates - decomposing them is its own round and is recorded as a wave-2 follow-up. params 1 = writeNonLocalStateReport 4->6, the same contract. The three sibling lanes are individually clean: --quality-delta at f6ec56d..1732fd8 (W2-J), 1732fd8..9a41c74 (W2-K) and 9a41c74..20cdc04 (W2-F) each report gating=0. Full suite green at this head: gates=429 pass=427 skip=2 fail=0, ASan+LSan clean, byte-deterministic, xmllint clean. churn= is unavailable in ref-pair mode by construction (both trees materialized out of the repo), so short-horizon-churn is silent here and that silence is not evidence. ack api-surface 35e8077fb0c11e92 4 cid=f1030dd30da5863d now=4 was=3 facet=contract-change p=src/editcheck.h:733 PROVEN-SITE-KEEPS-NAMESAKES (lane edge-strays-1118): CallSiteCalleeTest/EditCheckCalleeTest take ONE trailing span, the graph's provenSites, and reaches() takes the site's ref index, so a proven call site counts only for its own targets (red-first in test/callerscheck.sh SP1-SP4); every caller passes g.provenSites and the ref index in the same commit. ack api-surface 3703c22e2f2112bd 5 cid=e07b67ecf3068d1d by=src/* Phase 5 (docs/EVALS.md): the external-name veto (@external, externalnames.h tables, ExternalVeto predicate, import-name bindings at ingest) and the receiver MRO walk (rule1BaseWalk, SuperObj); every gating row is this one change — the four deliberate contract changes (serialize/serializeJson gain externalCalls, captureIncludes gains binds, methodOnTypeOrBases gains skipSelf/unionOnMulti), the ladder's two new steps in buildGraph, the census's tenth mechanism, kParserVer 77, and the two lexical clone false-positives (a one-line binary_search vs a counts total; a key-buffer probe vs a JSON string writer) +ack api-surface 372b1abf43677adf 4 cid=c4cd86becfdabe6d now=4 was=3 facet=contract-change p=src/shstatus.h:1006 CR712-SHSTATUS-DEPTH: shstatus.h detail:: recursion helpers (internal to the header, every caller updated in the same commit) take the one NestBudget the lexer and parser share; not a public contract ack api-surface 3877dd1e9b4ae997 4 R-E (2026-08-17 harvest): narrowLegoToRenderedSigs needs an explicit rootPrefix param because packSignatures' sigsRendered rows are already root-relative while the function's own escaped path comparison was still absolute -- every comparison silently failed, narrowing legoScoped to nothing on every --for run whose rendered sigs hit this path. The +1 param (defaulted, so every other caller is unaffected) and the small cx/LOC bump on narrowLegoToRenderedSigs and its one caller runForLens are the minimal fix; caught by legobundlecheck.sh going red for the wrong reason. churn=self is this lane's own edit window. ack api-surface 39588f57bd7b46b5 6 cid=2116294439c0a50f M13 paging/budget parity: each of these nine gained exactly ONE trailing DEFAULTED parameter (an McpPageArgs window, a token budget, or the legend posture) so its MCP twin can honor the flag its CLI twin already honors. Additive by construction - every pre-existing call site compiles unchanged and was verified to - and the alternative, a second overload per verb, is the clone seam this repo removes rather than adds. ack api-surface 3a54ea98a485670c 2 W1-S2 churn-keying fix (pathQualifiedKey): bodyHashesBySym's pathQualified-param drop is the deliberate contract change (one keying, no mode); pathQualifiedKey is canonicalId/voteKey-SHAPED but a distinct key domain — canonicalId's bare-name degrade IS the bug this fixes, voteKey is a rename-vote pair with a different separator and value type; churn=self is this fix's own edit trail; gate: qualitysignalcheck.sh §1d @@ -71,10 +73,12 @@ ack api-surface 44bac7b0ded56eb7 3 one grouped astQuery walk for --lint three bu ack api-surface 451442e5d1031096 5 R-R root-relative emission lane: threading the corpus root into 8 emitters is the change itself — +1 param each (contract-change), +3 cx from each pathRel lambda, and the verbosity of the relativization plus its comments. Reviewed row by row; none is avoidable without abandoning root-relative emission. Storage keys unmoved (baseline + ack ledger byte-identical across the cure). ack api-surface 49e172c2aa455e68 6 cid=0ece6180949ad4aa C1 F-06/F-07/F-10 (the listing-paging round): three listing verbs learn to disclose and page their row listings, and every gating row is that one change. api-surface 14 = ONE trailing DEFAULTED parameter each (an int pageOffset, an McpPageArgs window, a SituPageArgs, or the next= invocation a header now carries) on the emitters that must be TOLD their window — writeFlags/writeGate, writeCappedRows/writeCappedList/writeFlip/writeFlipHeader/writeFlipLights, computeFlip, nearestGateNames (which gains its cap and its TOTAL, the disclosure itself), situShowingNote/writeSituation, and the three MCP twins flagsText/flipText/situationDiffJson; additive by construction, every pre-existing call site compiles unchanged, and the alternative — a second capped emitter per verb — is the drift this repo removes rather than adds, because two emitters that disagree about a window can drop the row that IS the answer. verbosity 3 = kDocDriftLegend +20 lines and writeDocDriftPage +10 are the in-band vocabulary a reader needs to read shown_failed=/failed_capped=/failed_total= where they meet it (the rationale and the next= scan were already hoisted OUT of the body into their own function and comment, which took the complexity row to zero and the LOC row from +48 to +10); dispatchMcpLine +12 is two pagedResult wrappers on a pre-existing 1376-line dispatcher this lane adds to rather than creates. complexity 1 = the same dispatcher, +9 on a base of 518. duplication 1 = flagsText | flipText at 110 tokens, down from 131 after the shared mcpRowCap fold; the residual is getIndex + compute + captureXml, the shape EVERY index-backed MCP twin in this file has, and merging two verbs that return different results behind one entry point would be worse code than the clone. short-horizon-churn 19 = this lane's own footprint across cli.h/docdrift.h/darkflags.h/flipimpact.h/situ.h/mcp*, plus cli.h symbols three other lanes touched the same day; none foreign, none thrash. ack api-surface 49ea9954a4e77a06 6 cid=cf442ef6cda47ce0 P4.1 grep fast path — the mechanical footprint of threading two modes through one call chain, and nothing else. FOUR api-surface contract-change rows: spanTiersOfFiles (decl+def), grepApplySpanTiers and emitGrepReport each gained exactly ONE parameter, defaulted where it has more than one caller, so every existing call site is unchanged; RIPWIRE_BASE= argvdiffcheck reports 607/610 argv vectors byte-identical (the 3 diffs are the disclosed --version sha stamp and --run-trace duration_ms), and test/grepfastcheck.sh arm 6 byte-compares the whole --grep option matrix against the same base binary. TWO short-horizon-churn churn=self rows on the same two symbols: the footprint of having edited them in this window, not new debt. ONE complexity row, spanTiersOfFiles 49 to 52: the memo consult is a single branch inside the per-file worker, at the nesting that worker already had; extracting the whole worker body would be a refactor of the pre-existing tree-sitter parse path and was deliberately NOT bundled into a change whose claim is byte-identical output. What was FIXED rather than acked in this same pass: the duplication row (spanTierMemoPath now reuses quality.h's shaKeyedCachePath/headSnapRepoHex/exclConfigHex composition instead of a fourth hand-rolled name builder), main's complexity and verbosity rows (the prefetch launch/join moved into verbs_grep.h seams), and spanTiersOfFiles' verbosity row (prose moved out of the body onto the seams). +ack api-surface 4adca5de6c27054a 5 cid=bf23095f84826b6d now=5 was=4 facet=contract-change p=src/shstatus.h:645 CR712-SHSTATUS-DEPTH: shstatus.h detail:: recursion helpers (internal to the header, every caller updated in the same commit) take the one NestBudget the lexer and parser share; not a public contract ack api-surface 4b788e6f0a75bc80 6 WAVE-2 close (2026-08-19), finding 3 of 3: the 76 remaining gating rows, ONE change. All of them are W2-E's root-relative p= landing (9beaa2c/fccea68/a271e6c/b3fe074 plus the f9108b7 correction), measured for the first time at WAVE granularity. The per-lane acks written during W2-E covered only the correction round's own diff (working-tree-vs-HEAD at that moment), so the original ~30-verb landing was never QD-acked; this ack closes that gap rather than re-accepting anything. Verified by reading the whole 20cdc04..860291c src/main.cpp diff line by line: 282 of 448 added lines match the root-relative predicate directly and every one of the remaining 127 is an existing std::printf rewritten from ing.files[...] to the root-relative rp local, plus four extracted emit helpers (computeDirModules, printJsonSymbolRows, writeOversizeRows, writeDropRows). No unrelated logic rides in. By kind: api-surface 28 = the +1 rootArg/rootPrefix parameter on the emitters that must now be TOLD their root (writeAbiCheck/Ref/Struct, emitColumnar*, packBodies/Deps/Lego/Outline/Signatures[Json], serialize[Json], writeLayout*, packConnect, buildD1Row and the report writers) - defaulted wherever a caller could stay unchanged. complexity 31 and verbosity 16 = the single-root-condition ternary and its guarded root= clause applied per emitter, with no new nesting level and no new control flow beyond that one conditional; the large absolute numbers (runStructureText 207->231, runLint 313->323, runMaintenanceViews 174->190, runCallHierarchy 71->80) are pre-existing dispatcher size the wave adds to, not creates - decomposing them is its own round and is recorded as a wave-2 follow-up. params 1 = writeNonLocalStateReport 4->6, the same contract. The three sibling lanes are individually clean: --quality-delta at f6ec56d..1732fd8 (W2-J), 1732fd8..9a41c74 (W2-K) and 9a41c74..20cdc04 (W2-F) each report gating=0. Full suite green at this head: gates=429 pass=427 skip=2 fail=0, ASan+LSan clean, byte-deterministic, xmllint clean. churn= is unavailable in ref-pair mode by construction (both trees materialized out of the repo), so short-horizon-churn is silent here and that silence is not evidence. ack api-surface 4b8467d6559779e4 3 fnbody-require lane: deliberate additive API widening (optional out-params, default nullptr, every existing caller unaffected) to disclose the lazy require/import distinction on --impact's importer tier; residual complexity/duplication is the twin-dialect emitter shape and the dual-mode importersOfFiles scan this feature requires, already extracted where a helper genuinely reduced it (scanImporterEdges, recordLazyPair); short-horizon-churn is this same commit's own edit history ack api-surface 4be283ea1e39ca3b 3 cid=711b1fede0bf0fe8 by=src/* lane/n3-a phase 3 (2026-09-03): PinCensus::addRow gains the call-site line (6 to 7 params) and addOracleRow the sentinel kind (2 to 3) — the census format v2 join keys registered in docs/EVALS.md Phase 3; eval-only struct with two call sites, both in graph.h ack api-surface 4c3f4f250744d20d 4 cid=da1d80ac704b57a2 P9 the folded edit receipt: runEditVerb gains the postCheck opt-out parameter (defaulted true, so every existing call site is source-compatible) and the line-range + post-check splice; editplan's ensureStage and receipt each gain the root parameter they need to spell one identity (M12's root-relative rule, applied to the sibling it missed) and to run the per-op post-check. The +15 LOC in runEditVerb is the copy-out-before-the-index-rebuild discipline the fold requires — every reference into ing dangles once getIndex re-ingests, and that is stated in the code. +ack api-surface 52961f8157cf72f3 4 cid=85d6402f654152eb now=4 was=3 facet=contract-change p=src/shstatus.h:503 CR712-SHSTATUS-DEPTH: shstatus.h detail:: recursion helpers (internal to the header, every caller updated in the same commit) take the one NestBudget the lexer and parser share; not a public contract ack api-surface 5361e2bced6f1988 8 cid=9cf2c52c10b9d878 M12 follow-up (capture-audit L9): --ensemble gained root=/root-relative p= — writeEnsembleReport's 3 new default-valued params (singleRoot/rootPrefix/rootAttr, back-compat) thread the caller's already-computed single-root spelling through; short-horizon-churn on the touched dispatcher. ack api-surface 5383f63ad718935c 7 cid=170e3fe466966e87 L10: printLintRuleTallyRow's compiled= param and runLintRules' uncompiled-query mapping loop disambiguate a lint-rules query that failed to compile from one that legitimately found zero matches (see docs/PLAN lane L10, finding 3) — deliberate, backward-compatible (defaulted param, incompatible=0) ack api-surface 5391ffd9aa5765bf 6 cid=8a2aed10e80ed270 P2.2 register-macro dead-code fix: additive params on computeDelta/isDeadCandidate, complexity/verbosity growth in computeDelta and runQualityViews (the --dead-code verb), and the kQSnapCacheScheme bump line sit inside the in-window churn threshold - all eight gating rows are this lane's own footprint, none foreign @@ -131,14 +135,17 @@ ack api-surface 85dd951a8f730eec 4 cid=4e0fbe2c7a019909 P7 (terminality round A, ack api-surface 861092ef53c6c2dd 4 cid=48c86b50ca49ddb4 capture-audit 2026-09-04 wave-1 close: deliberate contract changes, each --edit-check incompatible=0 in its lane report — L4 (lane-L4.md, Symbols whose contract changed): pageDisclosure/computePageDisclosure +collectionCapped (defaulted), packLego +graphCountFloorAttr (defaulted), packConnect/writePrRootOpen/writeTestGateReport/writeTestGateReportJson/memberUsesArm +const Graph& for the M15 gauge; L5: enumerateRefs +filterNameHits out-param (defaulted, three callers source-compatible); L3: emitGrepUnindexed/grepAuxJson +window (the H4 paging fix, caller updated) ack api-surface 86db2ff4e22cae54 6 cid=b9c9829a2aac834e C1 F-06/F-07/F-10 (the listing-paging round): three listing verbs learn to disclose and page their row listings, and every gating row is that one change. api-surface 14 = ONE trailing DEFAULTED parameter each (an int pageOffset, an McpPageArgs window, a SituPageArgs, or the next= invocation a header now carries) on the emitters that must be TOLD their window — writeFlags/writeGate, writeCappedRows/writeCappedList/writeFlip/writeFlipHeader/writeFlipLights, computeFlip, nearestGateNames (which gains its cap and its TOTAL, the disclosure itself), situShowingNote/writeSituation, and the three MCP twins flagsText/flipText/situationDiffJson; additive by construction, every pre-existing call site compiles unchanged, and the alternative — a second capped emitter per verb — is the drift this repo removes rather than adds, because two emitters that disagree about a window can drop the row that IS the answer. verbosity 3 = kDocDriftLegend +20 lines and writeDocDriftPage +10 are the in-band vocabulary a reader needs to read shown_failed=/failed_capped=/failed_total= where they meet it (the rationale and the next= scan were already hoisted OUT of the body into their own function and comment, which took the complexity row to zero and the LOC row from +48 to +10); dispatchMcpLine +12 is two pagedResult wrappers on a pre-existing 1376-line dispatcher this lane adds to rather than creates. complexity 1 = the same dispatcher, +9 on a base of 518. duplication 1 = flagsText | flipText at 110 tokens, down from 131 after the shared mcpRowCap fold; the residual is getIndex + compute + captureXml, the shape EVERY index-backed MCP twin in this file has, and merging two verbs that return different results behind one entry point would be worse code than the clone. short-horizon-churn 19 = this lane's own footprint across cli.h/docdrift.h/darkflags.h/flipimpact.h/situ.h/mcp*, plus cli.h symbols three other lanes touched the same day; none foreign, none thrash. ack api-surface 8a92173ded649e17 14 cid=f76e97c84ac7c168 by=src/* lane 2 of the Graft head-to-head (2026-09-07): packSignatures and packSignaturesJson each gain ONE defaulted trailing out-parameter, the ids of the sigs rows they actually emitted, so the file-grain tail can exclude those files instead of the whole 40-candidate surface (three single-file answers at candidate rank 5/10/5 were served nowhere on rocksdb). Every existing caller is byte-identical; the facet is the deliberate arity change the ack-only help names. | prior: A2 (dropped_positive, 2026-09-03): packSignatures gained one trailing droppedPositiveOut out-param and the post-ladder accounting inside the rank-adaptive branch — same shared-arithmetic reason as its JSON sibling. +ack api-surface 8d454d9290626445 2 cid=8e10fcb30385d76d now=2 was=1 facet=contract-change p=src/shstatus.h:613 CR712-SHSTATUS-DEPTH: shstatus.h detail:: recursion helpers (internal to the header, every caller updated in the same commit) take the one NestBudget the lexer and parser share; not a public contract ack api-surface 8d58de9bb922f582 4 T1 completeness claims (complete= on grep/whereis): the +1 on streamBlobs is the deliberate DEFAULTED StreamBlobStats* param (null-object sink inside, no per-site null test; every existing caller byte-identical) so whereis can prove its scan exhaustive before claiming; cx/LOC on streamBlobs/computeWhereis/writeWhereisPage/emitGrepReport is the claim computation plus its in-band legend (the honesty text IS the feature); churn=self on those plus grepCollect/dispatchMcpLine is this lane own edit window. Gated red-first by test/completecheck.sh (24 arms, 10 red pre-fix; mutation arms force cap/offset/budget/unreadable-file/regex-mode/oversized-blob and assert the attribute VANISHES); full plain suite green, 21 touched-family gates green under ASan+LSan, determinism x3, xmllint clean ack api-surface 8fa8514c421e478d 4 cid=7826a06c6d682763 now=4 was=3 facet=contract-change p=src/editcheck.h:833 train 30 fcall-forward nit N1 (d62c00e0): ONE trailing span parameter, the graph's keptForwards, so this call-site reader applies the one model.h forwardCounts rule (--uses' own) instead of counting a forward buildGraph dropped; every caller passes g.keptForwards in the same commit; red-first in test/fcallforwardcheck.sh S1-S3. ack api-surface 925094be92085dae 3 cid=714cea1e1b31a1ae A6: rollbackMessage gained a 'cause' parameter one commit after this lane introduced it (57fe5fc). It is a header-inline helper in namespace rw::editplan with two callers, both in the same function in the same file; no consumer outside this lane ever saw the 2-arg form. The parameter is what lets the concurrent-write abort reuse the rollback disposition wording instead of growing a second copy of it. +ack api-surface 92749d497bf1775c 3 cid=747ebe8bc9af81a4 now=3 was=2 facet=contract-change p=src/shstatus.h:577 CR712-SHSTATUS-DEPTH: shstatus.h detail:: recursion helpers (internal to the header, every caller updated in the same commit) take the one NestBudget the lexer and parser share; not a public contract ack api-surface 92784a33434e383d 2 cid=e19f01572dacdb87 now=2 was=1 facet=contract-change p=src/hopbody.h:121 fix1: intended internal signature changes (graph for the hop hedge, language for the comment rule, the answer-wide follow budget); every caller updated in the same commit ack api-surface 92ac9caf38b8aab0 4 root-relative coverage round (verifier E1-E4 + two gaps the widened gate exposed, 2026-08-19): every gating row here is the SAME three-line pattern every verb in the original root-relative round already pays — a singleRoot bool, a rootPrefix, a rootAttr, and one ternary per path emission (the shape clones/prcontext/situ/mcp-path all carry verbatim). --tree (runStructureText) +8 ccx / +13 LOC and --quality-panel (writePanelReport) +4 ccx / +12 LOC are those lines plus the finding comment; forTaskText and packTaskBundleText are argument threading only. packBodiesJson api-surface 3 to 4 params is a DELIBERATE contract change: a defaulted trailing rootArg, identical in name, position and default to the one packSignatures/packBodies/packLego/packOutline already take, so the emitter family stays one shape and every existing call site is unaffected. churn=self/ambient is this change's own edit window. Payoff: 1340 absolute paths removed from four surfaces (tree 1212, analyze 85, panel 40, mcp-for 3) plus 5 in the pack-task JSON tail that the gate had been scoring on an empty document, and every single-root run now discloses its root exactly once. All red-first in test/rootrelcheck.sh ack api-surface 93848617cae1fe4e 2 cid=a42863f577100fa6 A3: TestRunnerIndex takes the run's crawl root so run= is spelled relative to root= (one absolute root per document, test/rootrelemitcheck.sh ARM 9). The parameter is the fix; every caller passes the root it already holds. ack api-surface 95cc88ca4aab7039 4 cid=25c411d4871bda46 C1 F-06/F-07/F-10 (the listing-paging round): three listing verbs learn to disclose and page their row listings, and every gating row is that one change. api-surface 14 = ONE trailing DEFAULTED parameter each (an int pageOffset, an McpPageArgs window, a SituPageArgs, or the next= invocation a header now carries) on the emitters that must be TOLD their window — writeFlags/writeGate, writeCappedRows/writeCappedList/writeFlip/writeFlipHeader/writeFlipLights, computeFlip, nearestGateNames (which gains its cap and its TOTAL, the disclosure itself), situShowingNote/writeSituation, and the three MCP twins flagsText/flipText/situationDiffJson; additive by construction, every pre-existing call site compiles unchanged, and the alternative — a second capped emitter per verb — is the drift this repo removes rather than adds, because two emitters that disagree about a window can drop the row that IS the answer. verbosity 3 = kDocDriftLegend +20 lines and writeDocDriftPage +10 are the in-band vocabulary a reader needs to read shown_failed=/failed_capped=/failed_total= where they meet it (the rationale and the next= scan were already hoisted OUT of the body into their own function and comment, which took the complexity row to zero and the LOC row from +48 to +10); dispatchMcpLine +12 is two pagedResult wrappers on a pre-existing 1376-line dispatcher this lane adds to rather than creates. complexity 1 = the same dispatcher, +9 on a base of 518. duplication 1 = flagsText | flipText at 110 tokens, down from 131 after the shared mcpRowCap fold; the residual is getIndex + compute + captureXml, the shape EVERY index-backed MCP twin in this file has, and merging two verbs that return different results behind one entry point would be worse code than the clone. short-horizon-churn 19 = this lane's own footprint across cli.h/docdrift.h/darkflags.h/flipimpact.h/situ.h/mcp*, plus cli.h symbols three other lanes touched the same day; none foreign, none thrash. ack api-surface 96fdcdff2f0ff0f7 4 R-H span tiers (2026-08-19 wave-3 lane, harvest R-H / experiment E5). The nine gating rows are ONE change, read line by line before acking. (1) api-surface grepHitsJson 3->4 params + verbosity: the MCP grep verb takes the span-tier MODE, because the escape hatch has to exist on the MCP surface too — an MCP-only agent that reads suppressed_comment= has no CLI to re-ask from; deliberate contract-change. WAVE-3 VERIFIER CORRECTION (P6-1): this reason originally read 'both callers updated in the same commit' and that was FALSE - src/mcpverbs.h's batch arm still took the defaulted GrepIn::Code and read no 'in' field at all, so the hatch was closed on the ONE surface that had no CLI fallback. Closed in the wave-3 fix lane: both callers now read the value through the same closed-value reader (mcpverbs.h::grepInModeFromArg), 'in' is a declared kBatchSubQueryFields member, and greptiercheck arms (9b)/(9c) pin the batch hatch and its refusal. (2) parseArgs +6 cx / +14 LOC and dispatchMcpLine +3 cx: one new closed-value flag arm (--grep-in=code|any) and its MCP twin, the same shape --grep-scope= added; a flag cannot be added to a hand-rolled parser without them. (3) churn=self on emitGrepReport / grepHitsJson / measure_set: this change's own edit window, not a history signal. (4) emitGrepReport +20 LOC / grepHitsJson +14 LOC: the filter call plus its wiring — the six conditional appends and the legend clause were already lifted into grepTierAttrs/grepTierLegend/grepTierKeys (the grepUnindexedAttrs/grepUnindexedKeys pattern), which is why the COMPLEXITY regressions on both are gone. Nothing here is a shortcut: the tier policy lives in search.h::grepApplySpanTiers and the parse in ingest.cpp::spanTiersOfFiles, both new symbols with their own gate (test/greptiercheck.sh - 30 arms at the wave-3 fix-lane head, 18 FAIL on the clean adb0831 pre-lane binary, 0 here; this text read '22 arms, 12 red', written against an earlier revision of the gate and never refreshed - WAVE-3 VERIFIER CORRECTION P6-7, and an ack's reason is the artifact a future reader trusts instead of re-deriving). +ack api-surface 9700dd1faa4b268d 4 cid=80480bc14e175681 now=4 was=3 facet=contract-change p=src/shstatus.h:750 CR712-SHSTATUS-DEPTH: shstatus.h detail:: recursion helpers (internal to the header, every caller updated in the same commit) take the one NestBudget the lexer and parser share; not a public contract ack api-surface 983814f2b5912a90 3 cid=fe2cfa34166f503a M13 paging/budget parity: each of these nine gained exactly ONE trailing DEFAULTED parameter (an McpPageArgs window, a token budget, or the legend posture) so its MCP twin can honor the flag its CLI twin already honors. Additive by construction - every pre-existing call site compiles unchanged and was verified to - and the alternative, a second overload per verb, is the clone seam this repo removes rather than adds. ack api-surface 9b27b4a434a22d52 5 cid=d77ea26ba88a5261 now=5 was=4 facet=contract-change p=src/editcheck.h:814 train 30 fcall-forward nit N1 (d62c00e0): ONE trailing span parameter, the graph's keptForwards, so this call-site reader applies the one model.h forwardCounts rule (--uses' own) instead of counting a forward buildGraph dropped; every caller passes g.keptForwards in the same commit; red-first in test/fcallforwardcheck.sh S1-S3. ack api-surface 9ebbafddddd086b4 7 cid=50e8788010378ebe capture-audit 2026-09-04 wave-1 close, lane L5 (refusal population, lane-L5.md) + lane L0 H13: guard code and its reasoning, not accidental growth — H6 file-list refusal (writeSituation/dispatchMcpLine/runChangeViews), H7 empty-selection refusals (runCrossRef flags/stray-content, evalStray badRefs, writeWhereisPage line-seed + near-miss), M7 named-file inputs + M8 --since validated once before any verb (main), M9 edit-verb refusals (runCliEdit/nearestNames/resolveOneForEdit), M20 seed disclosure (serialize + MapAnnotations::SeedDisclosure, packLego defs=, packConnect terminal defs=), F10/F14 empty list items (runPath/packConnect). L5 left these un-acked on purpose (shared-ledger race, H10); acked at close against the lane's own ec5e3c3 measurement | prior: WAVE-2 close (2026-08-19), finding 3 of 3: the 76 remaining gating rows, ONE change. All of them are W2-E's root-relative p= landing (9beaa2c/fccea68/a271e6c/b3fe074 plus the f9108b7 correction), measured for the first time at WAVE granularity. The per-lane acks written during W2-E covered only the correction round's own diff (working-tree-vs-HEAD at that moment), so the original ~30-verb landing was never QD-acked; this ack closes that gap rather than re-accepting anything. Verified by reading the whole 20cdc04..860291c src/main.cpp diff line by line: 282 of 448 added lines match the root-relative predicate directly and every one of the remaining 127 is an existing std::printf rewritten from ing.files[...] to the root-relative rp local, plus four extracted emit helpers (computeDirModules, printJsonSymbolRows, writeOversizeRows, writeDropRows). No unrelated logic rides in. By kind: api-surface 28 = the +1 rootArg/rootPrefix parameter on the emitters that must now be TOLD their root (writeAbiCheck/Ref/Struct, emitColumnar*, packBodies/Deps/Lego/Outline/Signatures[Json], serialize[Json], writeLayout*, packConnect, buildD1Row and the report writers) - defaulted wherever a caller could stay unchanged. complexity 31 and verbosity 16 = the single-root-condition ternary and its guarded root= clause applied per emitter, with no new nesting level and no new control flow beyond that one conditional; the large absolute numbers (runStructureText 207->231, runLint 313->323, runMaintenanceViews 174->190, runCallHierarchy 71->80) are pre-existing dispatcher size the wave adds to, not creates - decomposing them is its own round and is recorded as a wave-2 follow-up. params 1 = writeNonLocalStateReport 4->6, the same contract. The three sibling lanes are individually clean: --quality-delta at f6ec56d..1732fd8 (W2-J), 1732fd8..9a41c74 (W2-K) and 9a41c74..20cdc04 (W2-F) each report gating=0. Full suite green at this head: gates=429 pass=427 skip=2 fail=0, ASan+LSan clean, byte-deterministic, xmllint clean. churn= is unavailable in ref-pair mode by construction (both trees materialized out of the repo), so short-horizon-churn is silent here and that silence is not evidence. diff --git a/README.md b/README.md index 2ccbcfa70..4ebc3e184 100644 --- a/README.md +++ b/README.md @@ -964,10 +964,11 @@ AI-authored commits, a function rewritten again inside two weeks **+15%** more l `--quality-delta`'s 13 kinds each target one measured mode like those (the eleventh, `placeholder`, lists the stubs and TODOs a change adds, and never gates; the twelfth, `defect-shape`, catches four defect shapes review kept finding by hand — -new-symbol rows never gate, except defect-shape format-arity and a new function at the ceiling, +new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling and a tangled new function, because a format/argument mismatch is a defect, not debt, and a new function at 4x the bar — ccx 60 or 240 lines — -is how a 1,000-line function starts; the thirteenth, `tangle`, is report-only: a long function's nesting, deep share and -steering locals, with length only amplifying them, so a long orchestrator of named steps stays quiet), and it reports **only what your +is how a 1,000-line function starts; the thirteenth, `tangle`, scores a long function's nesting, deep share and +steering locals, with length only amplifying them, so a long orchestrator of named steps stays quiet, and gates a function +that is new at tangle 6 or more, crossed 6, or grew while over it), and it reports **only what your change made worse** — then `--exemplar` shows the pattern in your own repo to copy, and `--test-gate` names the tests that must run before "done." @@ -1824,9 +1825,9 @@ wrong, and it has. These are the results that say so, all in-tree, all published ### In the tests
-854 gate scripts (counts snapshot 2026-11-18), five contracts no unit test can hold, and the house rule: write the gate before the code it measures +866 gate scripts (counts snapshot 2026-11-22), five contracts no unit test can hold, and the house rule: write the gate before the code it measures -`test/regression.sh` named **854 gate scripts** at the counts snapshot 2026-11-18 and is the authoritative list; +`test/regression.sh` named **866 gate scripts** at the counts snapshot 2026-11-22 and is the authoritative list; `python3 test/pargates.py . ./build/ripwire -j 6` runs the same set in parallel. On top of them sit the contracts that do not fit a unit test: two runs byte-identical, warm output identical to cold, output that pipes clean through `xmllint --noout`, a sanitizer build with `-fno-sanitize-recover=all`, and a @@ -1835,7 +1836,7 @@ and requires stdout, stderr and exit code to match on each. The gate count above are the dated counts snapshot in `docs/counts.tsv` (`python3 docs/counts_snapshot.py show` prints today's numbers beside it), so two open changes that each add a gate or a cap never conflict on a total. -Another gate derives the cap inventory. At the counts snapshot 2026-11-18 the tool had 440 compile-time caps and 10 ranking parameters. +Another gate derives the cap inventory. At the counts snapshot 2026-11-22 the tool had 454 compile-time caps and 10 ranking parameters. [`docs/LIMITS.md`](docs/LIMITS.md) lists each cap, its value, and whether the file discloses a truncation when the cap fires, and `python3 docs/limits_build.py --check` proves that list against `src/`. [`docs/TUNING.md`](docs/TUNING.md) lists the measured cost of the caps the sweep has measured, and names diff --git a/changelog.d/defect-ack-two-bit.md b/changelog.d/defect-ack-two-bit.md new file mode 100644 index 000000000..f7bf74d67 --- /dev/null +++ b/changelog.d/defect-ack-two-bit.md @@ -0,0 +1,3 @@ +### Fixed — format-arity acks written by 0.6.10 and earlier match again + +The unchecked-status facet widened the facet bits of a defect-shape site value from two to three, which changed the ack key of every row holding a site whose hash had bit 2 set (about half of all one-site rows; 4 of 8 in a fixture sample): an ack written by 0.6.10 or earlier stopped matching, the row gated again and the ack was listed stale. Such an ack is now re-filed to its current key on read (counted in `acks_rekeyed_by_scheme=`) and written back healed by the next `--quality-ack`. Only rows whose key moved are affected; acks written since are unchanged. New gate `test/defectackschemecheck.sh`, its legacy key recorded from the released 0.6.9 binary. diff --git a/changelog.d/shell-nest-budget.md b/changelog.d/shell-nest-budget.md new file mode 100644 index 000000000..7adaec24a --- /dev/null +++ b/changelog.d/shell-nest-budget.md @@ -0,0 +1,3 @@ +### Fixed — a deeply nested shell script no longer crashes `--quality-delta` + +The shell lexer and parser behind the Bash defect-shape facets recursed without a bound on subshells, brace groups, `if` and quote/substitution nesting; a test script 5,000 levels deep ended the run on SIGSEGV. One nesting budget (64 levels) now covers the lexer and the parser; a script that reaches it is cut there, and the run says so with `shell_cut=N` on the `` root (and `"shell_cut"` in `--json`): N shell files whose scan stopped, what lies deeper was not judged. The old silent 40-level substitution cap is gone. New gate `test/shellnestcheck.sh` (generated scripts, never committed). diff --git a/changelog.d/tangle-gates.md b/changelog.d/tangle-gates.md new file mode 100644 index 000000000..fce77ca4d --- /dev/null +++ b/changelog.d/tangle-gates.md @@ -0,0 +1,3 @@ +### Changed — `--quality-delta`'s tangle kind gates a new, crossing or growing tangle + +`tangle` was report-only. A row now gates (exit 2) when the function is new at tangle 6.0 or more, crossed 6.0, or its score grew against the range base while over 6.0; a moved body and test code never gate, and a row an input rose on while the score held stays `sev="minor"`. The best-since-tag ratchet is now a facet (`ratchet=`) on those rows, not a row of its own, so a function that only sits above its tag best no longer prints. Replayed on the 20 merges before 8861b0d4d (tangle kind, range form): main gated 0 rows; this gates 9 over 5 PRs, every one a function that crossed or grew in its own PR (#702 `runLsp` 2.1→11.0, eight growth rows of a tenth or more), and the four rows on functions that did not grow in their PR print nothing. What it does not mean: a function already over 6.0 that the change leaves no worse never gates. Method and table: `docs/EVALS.md`, the thirteen kinds. diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index 0a950b665..bb62706bc 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -9,7 +9,7 @@ python3 docs/docs_commands_build.py --bin build/ripwire The flag surface below is read from `ripwire --help`, so it cannot disagree with the shipped binary. `test/docscommandscheck.sh` fails if it ever does — in either direction. -Sample output is lifted from a real recorded run (`docs/captures/COMMANDS_showcase_2026-11-21.md`), trimmed to the first few lines and +Sample output is lifted from a real recorded run (`docs/captures/COMMANDS_showcase_2026-11-22.md`), trimmed to the first few lines and scrubbed of local paths. It is illustrative, not a golden: run the command yourself for the current shape. @@ -72,10 +72,10 @@ $ ./build/ripwire . --top-k=5 - - + + - + @@ -108,10 +108,10 @@ $ ./build/ripwire . --top-k=5 --no-inventory - - + + - + @@ -142,10 +142,10 @@ $ ./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,7 +356,7 @@ _Same query with routing forced OFF (plain subtoken+body BM25) — contrast with ``` $ ./build/ripwire . --for="rankGraphTeleport" --no-route - + @@ -366,7 +366,7 @@ $ ./build/ripwire . --for="rankGraphTeleport" --no-route 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,16 +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 -... [22 more line(s); run it to see the whole thing] + + +WRITE ACKS — the --quality-ack arm: fold the VISIBLE findings --ack-only selects into the ledg…int runQualityAckWrite( const rw::Config& cfg, const rw::quality::Scope& scope, const QdPartition& part, DeltaBasis& basis, const std::string& acksFile ) +inline QualityDeltaOutcome computeQualityDelta( const std::string& root ) +inline std::string staleByKindValue( const std::vector<StaleAck>& staleAcks ) +... [23 more line(s); run it to see the whole thing] ``` **Caveats (stated by the binary):** @@ -479,7 +478,7 @@ _Interface -> implementors view: every existing impl of the named interface; the $ ./build/ripwire . --lego=Vehicle - + @@ -510,7 +509,7 @@ _The repo's best-in-class instance to imitate before writing new code (picked by $ ./build/ripwire . --exemplar="format byte sizes for humans" - + @@ -713,7 +712,7 @@ $ ./build/ripwire . --order=stable --top-k=5 - + @@ -744,10 +743,10 @@ $ ./build/ripwire . --no-stable --top-k=3 - - + + - + @@ -778,7 +777,7 @@ $ ./build/ripwire . --around=rankGraphTeleport - + @@ -828,7 +827,7 @@ _What SYM calls (1-hop out-edges)._ ``` $ ./build/ripwire . --callees=rankGraphTeleport - + @@ -863,16 +862,16 @@ _The resolvable use-sites (call/read/write/import/extends) with file:line; count ``` $ ./build/ripwire . --uses=rankGraphTeleport - + - - + - - + + + ``` @@ -897,17 +896,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] @@ -934,19 +933,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] ``` @@ -969,13 +968,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] ``` @@ -998,9 +997,9 @@ $ ./build/ripwire . --defs=main,rankGraphTeleport - + - + @@ -1021,7 +1020,7 @@ _Minimal connecting subgraph over 3 symbols (finds shared-caller joins)._ ``` $ ./build/ripwire . --connect=rankGraphTeleport,runEval,getIndex - + @@ -1133,7 +1132,7 @@ _Test files that transitively reach the changed file._ ``` $ ./build/ripwire . --affected=src/graph.h - @@ -1194,7 +1193,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: ed47f82e8 +at: 147c73293 (0 changed files — working tree is clean, nothing to analyze) ``` @@ -1213,18 +1212,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] ``` @@ -1248,7 +1247,7 @@ _Pre-PR gate on a CLEAN tree: no obligations, exit 0._ ``` $ ./build/ripwire . --test-gate - ``` @@ -1273,7 +1272,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] ``` @@ -1575,7 +1574,7 @@ _Importance-weighted detail: FULL bodies for top-2, signatures for the rest._ ``` $ ./build/ripwire . --for="pagerank power iteration" --detail=2 - + @@ -1612,10 +1611,10 @@ $ ./build/ripwire . --pack-signatures --top-k=10 - - + + - + @@ -1701,25 +1700,25 @@ Disclosed per bundle as compress="1" on the element; without the flag, **Try it** -_Comments stripped + blank runs collapsed — compressBody is the function that implements --compress itself, chosen because it is comment-heavy enough to show a real reduction (the previously captioned symbol had no comments or blank runs, so before/after were byte-identical under a caption promising a difference)._ +_Comments stripped + blank runs collapsed — collapseBlankLineRuns is --compress's own second step (compressBody is now the one-line stripCommentsKeepLiterals-then-collapse pipeline, with nothing left to strip), chosen because it is comment-heavy enough to show a real reduction (a symbol with no comments or blank runs reads byte-identical, or a few bytes larger for the compress attribute, under a caption promising a difference)._ ``` -$ ./build/ripwire . --expand=compressBody --top-k=0 --compress - +$ ./build/ripwire . --expand=collapseBlankLineRuns --top-k=0 --compress + - - + + - + - + ... [17 more line(s); run it to see the whole thing] @@ -1844,10 +1843,10 @@ _File->file dependency graph (god-files, cycles)._ ``` $ ./build/ripwire . --deps - - - - + + + + @@ -1855,7 +1854,7 @@ $ ./build/ripwire . --deps - + ... [17 more line(s); run it to see the whole thing] ``` @@ -1881,18 +1880,18 @@ _Complexity x recent git churn (maintenance pain)._ $ ./build/ripwire . --hotspots - + - - - - + + + + - + - + ... [17 more line(s); run it to see the whole thing] ``` @@ -1909,17 +1908,17 @@ _Token-normalized duplicate bodies._ ``` $ ./build/ripwire . --clones - + - + - + ... [17 more line(s); run it to see the whole thing] @@ -1940,15 +1939,15 @@ _Per-function size ranking, largest Halstead volume/token entropy/lines first ``` $ ./build/ripwire . --biggest-first --limit=8 - + - + - - + + ``` @@ -1973,7 +1972,7 @@ _Per function, the non-local MUTABLE state it can reach (transitively), most wri ``` $ ./build/ripwire . --nonlocal-state --limit=8 - @@ -2008,7 +2007,7 @@ _The family join: per function, which of four orthogonal evidence families fire, ``` $ ./build/ripwire . --ensemble --limit=8 - @@ -2019,7 +2018,7 @@ $ ./build/ripwire . --ensemble --limit=8 - + ... [17 more line(s); run it to see the whole thing] ``` @@ -2039,7 +2038,7 @@ _THE single wide-angle quality read: six families in one pass, an eligible/ranke ``` $ ./build/ripwire . --quality-panel - @@ -2076,13 +2075,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] ``` @@ -2107,9 +2106,9 @@ _Score the naming-* rules against this repo's own rename history: proxy=old/(old ``` $ ./build/ripwire . --naming-calibration - + - + @@ -2142,11 +2141,11 @@ _The corpus's OWN case-convention vote per (language, kind) group; off-conventio ``` $ ./build/ripwire . --naming-consistency --limit=8 - - - - - + + + + + @@ -2179,8 +2178,8 @@ _The opt-in --lint modifier: naming predicates over LOCAL variable names too, C/ ``` $ ./build/ripwire . --lint --naming-locals - - + + @@ -2214,13 +2213,13 @@ _Functions WITH a doc comment, most name-restating first: c_coeff (high = the co ``` $ ./build/ripwire . --comment-coherence --limit=8 - + - + @@ -2247,16 +2246,16 @@ _Files that change together in git (hidden coupling)._ ``` $ ./build/ripwire . --cochange - - + - - + + + - - - + + + ... [22 more line(s); run it to see the whole thing] ``` @@ -2279,16 +2278,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] ``` @@ -2305,7 +2304,7 @@ _Modularity-violation GROUPS instead of pairs: "X co-changes with {A,B,C}, none ``` $ ./build/ripwire . --cochange --cochange-groups - + @@ -2313,7 +2312,7 @@ $ ./build/ripwire . --cochange --cochange-groups - + @@ -2334,18 +2333,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] ``` @@ -2377,7 +2376,7 @@ $ ./build/ripwire . --arch=test/archfix/rules.txt - + @@ -2409,7 +2408,7 @@ $ ./build/ripwire . --arch=test/archfix/rules.txt - + @@ -2436,7 +2435,7 @@ $ ./build/ripwire . --arch=test/archfix/rules.txt - + @@ -2459,8 +2458,8 @@ _Built-in AST checks (c-cast, goto, unsafe-c-fn, ...)._ ``` $ ./build/ripwire . --lint - - + + @@ -2568,8 +2567,8 @@ _DROP two families, applied after selection; the raw select=/ignore= you passed ``` $ ./build/ripwire . --lint --lint-ignore=naming-,cache- - + @@ -2682,19 +2681,19 @@ _Cluster the call graph into cohesive modules._ ``` $ ./build/ripwire . --communities - - - - - + + + + + - + + - ... [17 more line(s); run it to see the whole thing] ``` @@ -2713,7 +2712,7 @@ _Drill into ONE call-graph community by id — the drill= the --communities outp ``` $ ./build/ripwire . --community=0 - ``` @@ -2738,19 +2737,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] ``` @@ -2775,16 +2774,16 @@ $ ./build/ripwire . --report # ripwire architecture report -4842 files · 44690 symbols · 44883 edges · 5152 modules (20966 call-graph isolated) +4852 files · 45032 symbols · 45381 edges · 5247 modules (21074 call-graph isolated) Root: `.` -Call-graph isolate provenance: 5792 declaration, 3547 header, 4560 source, 7067 document; 0 connected Louvain singletons +Call-graph isolate provenance: 5832 declaration, 3601 header, 4566 source, 7075 document; 0 connected Louvain singletons -## Modules (call-graph clusters; showing 12 of 5152) -- **src::emitTo@infra/emit.h:53:2760 [write,run,emit]** — 1842 symbols -- **src::kindIs@infra/nodekind.h:46:3271 [push,emit,read]** — 720 symbols -- **src::DISCLOSE@infra/Diagnostics.h:622:43913 [read,scan,collect]** — 385 symbols +## Modules (call-graph clusters; showing 12 of 5247) +- **src::emitTo@infra/emit.h:53:2760 [write,run,emit]** — 1652 symbols +- **src::kindIs@infra/nodekind.h:46:3271 [push,emit,read]** — 733 symbols +- **src::DISCLOSE@infra/Diagnostics.h:622:43913 [read,scan,run]** — 375 symbols ... [17 more line(s); run it to see the whole thing] ``` @@ -2801,13 +2800,13 @@ _Cross-module call seams no test reaches. NOW carries seam_pairs/shown/capped._ ``` $ ./build/ripwire . --seams - - + + + - @@ -2832,15 +2831,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
14900"] - n106["src/infra
1685"] + n105["src
15178"] + n106["src/infra
1687"] end subgraph sg1 ["test"] - n107["test
7002"] + n107["test
7030"] n750["test/legochargefix
546"] n472["test/fixtures/recallpassage
314"] n491["test/fnslotcpp2
285"] - n913["test/lib
260"] + n913["test/lib
262"] n712["test/ifacepeelfix/cpp
206"] n1260["test/slotjoinfix
182"] ... [17 more line(s); run it to see the whole thing] @@ -2861,7 +2860,7 @@ _Bus-factor: recency-weighted author ownership per file._ ``` $ ./build/ripwire . --owners - + @@ -2892,7 +2891,7 @@ _Internal functions with no caller found in the index — a name-based graph rea ``` $ ./build/ripwire . --dead-code=src - + @@ -2967,8 +2966,8 @@ _The same run, the same clone, the folded rows printed back: each stale acknowle ``` $ ./build/ripwire . --quality-delta --show-stale - -, acked. value-ref-excluded=N: internal functions kept off because a table, field or argument in another function or at file scope holds them (matched by name, not a proven call); a floor. at=: commit+dirty+shallow. stale=N: ack ledger rows whose target no longer applies (sa rows); never gating. preexisting-worse=N: regressions on symbols that existed at baseline; they gate when major. new-symbol=N: NEW code; new-symbol rows never gate, except defect-shape format-arity, ceiling=, tangle. register-macro-excluded=N: symbols skipped: self-registering test/bench macros or Rust #[test]; a floor. declined-call-excluded=N: symbols kept out of dead-code only because a declined call may mean them; a floor. api-new-surface=N: new PUBLIC symbols; a count, never gates, not in regressions=. renames=/rename_window_commits=: git rename pairs read over that many commits, to re-file baseline and acks. acked_by_rename=/acked_by_content=: acked= suppressions matched via git renames / an equal body hash. renames_window_truncated=1: history is deeper than the rename window, older renames unread. acked=N: findings suppressed by the ack ledger, listed as sa rows; never gating. sa key=/why=: the stale ack's ledger hash / target-gone (names nothing now) or finding-gone (no longer fires). --> + @@ -2988,7 +2987,7 @@ $ ./build/ripwire . --quality-delta --show-stale **Answers:** before a PR: report ONLY what your change made worse, across 13 kinds — pair with --test-gate. -Each kind is measured against the baseline (complexity/verbosity/nesting/params/dup/dead/api-surface + error-masking/short-horizon-churn/new-clone-of-reused-helper + placeholder + defect-shape + tangle, report-only); every finding is classified by ORIGIN: a symbol that EXISTED at the baseline and got worse (preexisting-worse="N", no attribute on the row) vs one that exists only because the code is NEW (new-symbol="N", origin="new-symbol" on the row). A small numeric delta is additionally sev="minor". EXIT 2 ONLY on a major AND unacked row that is preexisting-worse, defect-shape format-arity (any origin) or a new function at the ceiling — the gating="N" header count. New-symbol rows are still PRINTED (they are the debt you are adding — read them); new-symbol rows never gate, except defect-shape format-arity and a new function at the ceiling (4x the bar: ccx 60 or 240 lines, not a moved body, not test code, ceiling= on the row); exit 0 means "nothing that already existed got worse", not "clean". Clone kinds classify by member set (new-symbol only if EVERY member is new); short-horizon-churn is preexisting by construction. LIMIT: origin is canonId (path::scope::name) identity; a function RENAMED or MOVED with its body unchanged (whitespace and its own name aside: one body that left its key, matched to one new key) keeps its identity and the move reports nothing (and a file rename git recorded keeps each symbol in it under its own name, twins and changed bodies included), while one whose body also changed reads as new and a regression carried in with it will not gate; a function over the ccx or line bar whose body moved with a small edit (a clone-sketch match to a body that left its key) reads origin="moved" and never gates. error-masking = a NEW empty/pass/comment-only handler, or log-only (a broad handler whose body only logs and never names the error) or rethrow-only (the sole handler re-throws it unchanged); those two gate only where their precision was measured (Python) and are sev="minor" in every other language. Empty counts Go's `if err != nil {}` on a call's err and Rust's `if let Err(..) = f() {}` / `Err(..) => {}` or `=> ()`, and gates like Python's `except: pass`; log-only counts a Rust Err arm of print/log macros and a C++ catch of `std::cerr <<`, `LOG( x ) <<` or `fprintf( stderr, … )` (sev="minor"). facet="failure-default": a read, parse or spawn failure returned as an empty success (a TypeScript catch or .catch returning []/null/{}/false/0/'' around JSON.parse/fs reads/exec/spawn/fetch, in a function typed to return an array/boolean/object; a C++ value_or( empty ) on a file read); it never gates by itself. placeholder = a stub the change ADDED (todo!()/unimplemented!(), Kotlin TODO(), NotImplementedException, a bare raise NotImplementedError as a free function's body, a throw/raise/panic/assert saying "not implemented") or a comment line opening with TODO/FIXME that names no issue (#12, ABC-12, a URL); new-symbol by construction, so it never gates. Counted per enclosing symbol, like error-masking: a file-level TODO outside every definition is not counted. defect-shape = a known defect shape the change ADDED, named by defect=: format-arity (a literal std::format/print/format_to, fmt::, rw::emitTo/formatTo or Python "literal".format whose fields do not match its arguments — GATES on any origin, a defect not debt), utf8-cut and dedup-first (C++) and vacuous-assert (Bash test scripts) and unchecked-status (a dropped pclose/rename/write/system/fflush/close/waitpid status in C/C++; Python subprocess.run without check=, subprocess.call, os.system; the row carries call=) and unhandled-arm (a C/C++ switch with no default: that leaves an in-tree enum's enumerator out, a shell case with no *) arm whose result is read, a Python if/elif or match ending a value-returning function with no else; the row carries why=) — report-only, always sev="minor". A site is new only when its text occurs more often than in the baseline: a moved one is not. Test-fixture dirs + doc sections are exempt from dead-code/churn; churn needs COMMITTED thrash evidence (rewritten across recent commits AND again by this diff), never the current edit alone WHICH FLOOR IT COMPARES AGAINST, and a side effect: the sidecar is honored only when the sha it was pinned at EQUALS the current git HEAD (strict equality — an ancestor commit describes a DIFFERENT tree, so everything committed since would read as your regression). A sidecar pinned anywhere else is STALE: this verb then DELETES it from your working tree (self-heal, so the next run does not rediscover the dead pin) and auto-compares the working tree vs git HEAD instead. Re-pin with --quality-baseline. The read-only MCP quality_delta verb applies the SAME staleness test but never deletes. A sidecar at the current HEAD that ANOTHER ripwire build pinned (its producer stamp names other sources — a dead set depends on how calls were resolved) is FOREIGN: both arms ignore it, never delete it, and auto-compare vs git HEAD. Which floor was actually used is on every report as baseline=: sidecar | git-HEAD | git-HEAD (stale sidecar removed) | git-HEAD (stale sidecar ignored) | git-HEAD (foreign sidecar ignored) — the stale two say a stale sidecar existed, and 'removed' means the file is gone. A non-git root has no HEAD to fall back to, so its sidecar is honored whenever this build pinned it; without one there, or with another build's, the verb exits 1. +Each kind is measured against the baseline (complexity/verbosity/nesting/params/dup/dead/api-surface + error-masking/short-horizon-churn/new-clone-of-reused-helper + placeholder + defect-shape + tangle); every finding is classified by ORIGIN: a symbol that EXISTED at the baseline and got worse (preexisting-worse="N", no attribute on the row) vs one that exists only because the code is NEW (new-symbol="N", origin="new-symbol" on the row). A small numeric delta is additionally sev="minor". EXIT 2 ONLY on a major AND unacked row that is preexisting-worse, defect-shape format-arity (any origin), a new function at the ceiling or a tangled new one — the gating="N" header count. New-symbol rows are still PRINTED (they are the debt you are adding — read them); new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling (4x the bar: ccx 60 or 240 lines, not a moved body, not test code, ceiling= on the row) and a new one at tangle 6 or more (not moved, not test code); exit 0 means "nothing that already existed got worse", not "clean". Clone kinds classify by member set (new-symbol only if EVERY member is new); short-horizon-churn is preexisting by construction. LIMIT: origin is canonId (path::scope::name) identity; a function RENAMED or MOVED with its body unchanged (whitespace and its own name aside: one body that left its key, matched to one new key) keeps its identity and the move reports nothing (and a file rename git recorded keeps each symbol in it under its own name, twins and changed bodies included), while one whose body also changed reads as new and a regression carried in with it will not gate; a function over the ccx or line bar whose body moved with a small edit (a clone-sketch match to a body that left its key) reads origin="moved" and never gates. error-masking = a NEW empty/pass/comment-only handler, or log-only (a broad handler whose body only logs and never names the error) or rethrow-only (the sole handler re-throws it unchanged); those two gate only where their precision was measured (Python) and are sev="minor" in every other language. Empty counts Go's `if err != nil {}` on a call's err and Rust's `if let Err(..) = f() {}` / `Err(..) => {}` or `=> ()`, and gates like Python's `except: pass`; log-only counts a Rust Err arm of print/log macros and a C++ catch of `std::cerr <<`, `LOG( x ) <<` or `fprintf( stderr, … )` (sev="minor"). facet="failure-default": a read, parse or spawn failure returned as an empty success (a TypeScript catch or .catch returning []/null/{}/false/0/'' around JSON.parse/fs reads/exec/spawn/fetch, in a function typed to return an array/boolean/object; a C++ value_or( empty ) on a file read); it never gates by itself. placeholder = a stub the change ADDED (todo!()/unimplemented!(), Kotlin TODO(), NotImplementedException, a bare raise NotImplementedError as a free function's body, a throw/raise/panic/assert saying "not implemented") or a comment line opening with TODO/FIXME that names no issue (#12, ABC-12, a URL); new-symbol by construction, so it never gates. Counted per enclosing symbol, like error-masking: a file-level TODO outside every definition is not counted. defect-shape = a known defect shape the change ADDED, named by defect=: format-arity (a literal std::format/print/format_to, fmt::, rw::emitTo/formatTo or Python "literal".format whose fields do not match its arguments — GATES on any origin, a defect not debt), utf8-cut and dedup-first (C++) and vacuous-assert (Bash test scripts) and unchecked-status (a dropped pclose/rename/write/system/fflush/close/waitpid status in C/C++; Python subprocess.run without check=, subprocess.call, os.system; the row carries call=) and unhandled-arm (a C/C++ switch with no default: that leaves an in-tree enum's enumerator out, a shell case with no *) arm whose result is read, a Python if/elif or match ending a value-returning function with no else; the row carries why=) — report-only, always sev="minor". A site is new only when its text occurs more often than in the baseline: a moved one is not. Test-fixture dirs + doc sections are exempt from dead-code/churn; churn needs COMMITTED thrash evidence (rewritten across recent commits AND again by this diff), never the current edit alone WHICH FLOOR IT COMPARES AGAINST, and a side effect: the sidecar is honored only when the sha it was pinned at EQUALS the current git HEAD (strict equality — an ancestor commit describes a DIFFERENT tree, so everything committed since would read as your regression). A sidecar pinned anywhere else is STALE: this verb then DELETES it from your working tree (self-heal, so the next run does not rediscover the dead pin) and auto-compares the working tree vs git HEAD instead. Re-pin with --quality-baseline. The read-only MCP quality_delta verb applies the SAME staleness test but never deletes. A sidecar at the current HEAD that ANOTHER ripwire build pinned (its producer stamp names other sources — a dead set depends on how calls were resolved) is FOREIGN: both arms ignore it, never delete it, and auto-compare vs git HEAD. Which floor was actually used is on every report as baseline=: sidecar | git-HEAD | git-HEAD (stale sidecar removed) | git-HEAD (stale sidecar ignored) | git-HEAD (foreign sidecar ignored) — the stale two say a stale sidecar existed, and 'removed' means the file is gone. A non-git root has no HEAD to fall back to, so its sidecar is honored whenever this build pinned it; without one there, or with another build's, the verb exits 1. **Try it** @@ -2996,8 +2995,8 @@ _The regression-free answer on a clone whose ledger holds stale acknowledgements ``` $ ./build/ripwire . --quality-delta - -, acked. value-ref-excluded=N: internal functions kept off because a table, field or argument in another function or at file scope holds them (matched by name, not a proven call); a floor. at=: commit+dirty+shallow. stale=N: ack ledger rows whose target no longer applies (sa rows); never gating. stale_by_kind=: stale= split by ack kind (kind:N,...); the sa rows are collapsed. stale_next=: the call printing the sa rows and the full header. preexisting-worse=N: regressions on symbols that existed at baseline; they gate when major. new-symbol=N: NEW code; new-symbol rows never gate, except defect-shape format-arity, ceiling=, tangle. register-macro-excluded=N: symbols skipped: self-registering test/bench macros or Rust #[test]; a floor. declined-call-excluded=N: symbols kept out of dead-code only because a declined call may mean them; a floor. api-new-surface=N: new PUBLIC symbols; a count, never gates, not in regressions=. renames=/rename_window_commits=: git rename pairs read over that many commits, to re-file baseline and acks. acked_by_rename=/acked_by_content=: acked= suppressions matched via git renames / an equal body hash. renames_window_truncated=1: history is deeper than the rename window, older renames unread. acked=N: findings suppressed by the ack ledger, listed as sa rows; never gating. --> + ``` @@ -3005,7 +3004,7 @@ $ ./build/ripwire . --quality-delta **Caveats (stated by the binary):** -- new-symbol rows never gate, except defect-shape format-arity and a new function at the ceiling (4x the bar: ccx 60 or 240 lines, not a moved body, not test code, ceiling= on the row); +- new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling (4x the bar: ccx 60 or 240 lines, not a moved body, not test code, ceiling= on the row) and a new one at tangle 6 or more (not moved, not test code); - LIMIT: origin is canonId (path::scope::name) identity; - a function over the ccx or line bar whose body moved with a small edit (a clone-sketch match to a body that left its key) reads origin="moved" and never gates. @@ -3021,8 +3020,8 @@ _The regression-free answer on a clone whose ledger holds stale acknowledgements ``` $ ./build/ripwire . --quality-delta - -, acked. value-ref-excluded=N: internal functions kept off because a table, field or argument in another function or at file scope holds them (matched by name, not a proven call); a floor. at=: commit+dirty+shallow. stale=N: ack ledger rows whose target no longer applies (sa rows); never gating. stale_by_kind=: stale= split by ack kind (kind:N,...); the sa rows are collapsed. stale_next=: the call printing the sa rows and the full header. preexisting-worse=N: regressions on symbols that existed at baseline; they gate when major. new-symbol=N: NEW code; new-symbol rows never gate, except defect-shape format-arity, ceiling=, tangle. register-macro-excluded=N: symbols skipped: self-registering test/bench macros or Rust #[test]; a floor. declined-call-excluded=N: symbols kept out of dead-code only because a declined call may mean them; a floor. api-new-surface=N: new PUBLIC symbols; a count, never gates, not in regressions=. renames=/rename_window_commits=: git rename pairs read over that many commits, to re-file baseline and acks. acked_by_rename=/acked_by_content=: acked= suppressions matched via git renames / an equal body hash. renames_window_truncated=1: history is deeper than the rename window, older renames unread. acked=N: findings suppressed by the ack ledger, listed as sa rows; never gating. --> + ``` @@ -3046,8 +3045,8 @@ _A ref range run for two of the thirteen kinds only: the named kinds' rows are e ``` $ ./build/ripwire . --quality-delta=HEAD~1..HEAD --quality-kinds=complexity,dead-code - -

@@ -3139,8 +3138,8 @@ _OWNERSHIP partition for a shared tree: every regression here lives in src/infra ``` $ ./build/ripwire . --quality-delta --scope=src/graph.h - -, acked. value-ref-excluded=N: internal functions kept off because a table, field or argument in another function or at file scope holds them (matched by name, not a proven call); a floor. at=: commit+dirty+shallow. stale=N: ack ledger rows whose target no longer applies (sa rows); never gating. preexisting-worse=N: regressions on symbols that existed at baseline; they gate when major. new-symbol=N: NEW code; new-symbol rows never gate, except defect-shape format-arity, ceiling=, tangle. register-macro-excluded=N: symbols skipped: self-registering test/bench macros or Rust #[test]; a floor. declined-call-excluded=N: symbols kept out of dead-code only because a declined call may mean them; a floor. api-new-surface=N: new PUBLIC symbols; a count, never gates, not in regressions=. renames=/rename_window_commits=: git rename pairs read over that many commits, to re-file baseline and acks. acked_by_rename=/acked_by_content=: acked= suppressions matched via git renames / an equal body hash. renames_window_truncated=1: history is deeper than the rename window, older renames unread. r surface=: the api-surface tier, new-symbol or contract-change. acked=N: findings suppressed by the ack ledger, listed as sa rows; never gating. r sev=minor: a small numeric delta, counted in minor=, never gating (absent: major). r origin=new-symbol: a finding on NEW code; moved: its body left another name or file, never gating (absent: preexisting-worse). sa key=/why=: the stale ack's ledger hash / target-gone (names nothing now) or finding-gone (no longer fires). r members=/tokens=: a duplication row's clone group (member ids) / their shared normalized-token count. --> + @@ -3170,13 +3169,13 @@ _Fast per-symbol post-edit contract check vs git HEAD (unchanged on a clean tree ``` $ ./build/ripwire . --edit-check=rankGraphTeleport - - - - + + + ``` @@ -3224,7 +3223,7 @@ $ ./build/ripwire . --insert-before-symbol=nonNegativeFloatDescKey --edit-payloa {"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":3960,"graph_unresolved":20090,"graph_unindexed":313,"counts_floor":true},"tests_to_run":[{"p":"test/verify_radix.cpp","hops":1,"run":"bash test/greptiercheck.sh"}, +"graph_ambiguous":3984,"graph_unresolved":20100,"graph_unindexed":313,"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"}, @@ -3250,7 +3249,7 @@ _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":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":3960,"graph_unresolved":20090,"graph_unindexed":313,"counts_floor":true},"tests_to_run":[{"p":"test/verify_radix.cpp","hops":1,"run":"bash test/greptiercheck.sh"}, +"graph_ambiguous":3984,"graph_unresolved":20100,"graph_unindexed":313,"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"}, @@ -3308,7 +3307,7 @@ $ ./build/ripwire . --insert-before-symbol=nonNegativeFloatDescKey --edit-payloa {"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":3960,"graph_unresolved":20090,"graph_unindexed":313,"counts_floor":true},"tests_to_run":[{"p":"test/verify_radix.cpp","hops":1,"run":"bash test/greptiercheck.sh"}, +"graph_ambiguous":3984,"graph_unresolved":20100,"graph_unindexed":313,"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"}, @@ -3377,11 +3376,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":3960,"graph_unresolved":20090,"graph_unindexed":313,"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":3984,"graph_unresolved":20100,"graph_unindexed":313,"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: 585 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":3960,"graph_unresolved":20090,"graph_unindexed":313,"counts_floor":true}}]} +"graph_ambiguous":3984,"graph_unresolved":20100,"graph_unindexed":313,"counts_floor":true},"memory_ceiling":"suspended for this check (the write is committed, so a refusal here could not be reported and a retry could insert twice); the 10649 MiB limit was not reached"}]} ``` **Shaped by:** `--edit-check` @@ -3427,7 +3426,7 @@ _Bare --slice=SYM: the INVENTORY of sliceable locals (), so a calle ``` $ ./build/ripwire . --slice=rankGraphTeleport - + @@ -3464,7 +3463,7 @@ _Forward flow: which statements the seed's value reaches, at the default depth b ``` $ ./build/ripwire . --slice=rankGraphTeleport:teleport --slice-flow=fwd - + @@ -3545,7 +3544,7 @@ _No-LLM review-evidence bundle for the working-tree diff (clean tree = empty)._ ``` $ ./build/ripwire . --pr-context - ``` @@ -3571,11 +3570,11 @@ _Pairwise cross-arm conflict sites + suggested landing order (any committish sha ``` $ ./build/ripwire . --merge-scout=HEAD~2,HEAD~1 - - + + - + @@ -3650,7 +3649,7 @@ _A second selection, the `fix/` ref family, picked at capture time from the refs ``` $ ./build/ripwire . --stray-content=fix/ - + ``` @@ -3675,19 +3674,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] ``` @@ -3711,8 +3710,8 @@ _Cross-branch ABI-break gate over the `lane/` ref family: struct byte-contract d ``` $ ./build/ripwire . --stray-content=lane/ --abi - + @@ -3721,7 +3720,7 @@ $ ./build/ripwire . --stray-content=lane/ --abi - + ... [17 more line(s); run it to see the whole thing] @@ -3745,15 +3744,14 @@ _Which ref's tree defines or mentions SYM — HEAD first, then every local branc ``` $ ./build/ripwire . --whereis=rankGraphTeleport - - - + + - - - + +... [24 more line(s); run it to see the whole thing] ``` **Shaped by:** `--no-redact`, `--whereis-full-text`, `--whereis-listing`, `--with-history`, `--legend`, `--limit` @@ -3777,8 +3775,8 @@ _The same page with every t= line whole: the page above previews each line over ``` $ ./build/ripwire . --whereis=rankGraphTeleport --whereis-listing=all --whereis-full-text - + @@ -3806,8 +3804,8 @@ _The whole hit list asked for by name: under the same 60-row cap HEAD's referenc ``` $ ./build/ripwire . --whereis=rankGraphTeleport --whereis-listing=all - + @@ -3839,7 +3837,7 @@ $ ./build/ripwire . --flags - + @@ -3920,8 +3918,8 @@ _The cache-locality lens over every aggregate: fields READ TOGETHER but declared ``` $ ./build/ripwire . --field-affinity - + @@ -3930,9 +3928,9 @@ $ ./build/ripwire . --field-affinity - - - + + + ... [17 more line(s); run it to see the whole thing] ``` @@ -3955,16 +3953,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] ``` @@ -3989,16 +3987,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] ``` @@ -4022,16 +4020,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] ``` @@ -4056,7 +4054,7 @@ _The house PLAN/DESIGN format's STRUCTURE check — never semantics; exit 2 when ``` $ ./build/ripwire . --plan-lint=test/planlintfix/wave.md - + @@ -4095,8 +4093,8 @@ 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:14923 #1 0x102f3e884 in rw::rankGraph(Graph const&, float) src/graph.h:14966 - #2 0x102e11f30 in runDefaultMap(MainDispatch const&) src/main.cpp:1760 - #3 0x102e01a44 in main src/main.cpp:4511 + #2 0x102e11f30 in runDefaultMap(MainDispatch const&) src/main.cpp:1761 + #3 0x102e01a44 in main src/main.cpp:4565 #4 0x1a2b3c0dc in start+0x9dc (dyld:arm64e+0x60dc) ==41337==ABORTING ``` @@ -4123,7 +4121,7 @@ _A command that exits 0: a minimal success record (exit, measured duration, disc $ ./build/ripwire . --run-trace="true" - + ``` @@ -4213,7 +4211,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" - + - + @@ -4283,7 +4281,7 @@ _Task lens + a compact Mermaid flowchart of the top anchors' 1-hop edges._ ``` $ ./build/ripwire . --for="pagerank power iteration" --with-graph - + @@ -4361,14 +4359,14 @@ _Environment self-check: binary staleness, grammars, cache dir, git, tracked-bin ``` $ ./build/ripwire . --doctor - - + - - + + - - + @@ -4395,14 +4393,14 @@ _--doctor plus a LIVE integration inspection for one agent: PATH binary, install ``` $ ./build/ripwire . --doctor --agent=claude - - + - - + + - - + @@ -4431,7 +4429,7 @@ $ ./build/ripwire . --skipped - @@ -4520,14 +4518,14 @@ $ ./build/ripwire . --rank-by=churn --top-k=5 - - + + - + - + ... [10 more line(s); run it to see the whole thing] @@ -4548,25 +4546,24 @@ 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._ +_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. This page holds 1 row(s), not the usual 3: no change window on this branch held enough src/ files for a larger page to cut, so the generator fell back to a smaller one (see chooseInWindow)._ ``` -$ ./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~9 --exclude=test --exclude=docs --exclude=skills --exclude=changelog.d --in=src --limit=1 - - - - - - - - + + + + + - - -... [5 more line(s); run it to see the whole thing] + + + + + ``` **Shaped by:** `--external-surface`, `--doctor`, `--legend`, `--max-memory` @@ -4627,8 +4624,8 @@ _The same gating report under --legend=full — same rows, same exit 2; the defa ``` $ ./build/ripwire . --quality-delta --legend=full - - + @@ -4658,7 +4655,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=c40ddf725e4befcb entries=1177 +ripwire legend dictionary ripwire.dict/v1 dictv=6ad237691d743450 entries=1178 : this LAST child is only the legend pointer; the root keeps every attribute it carries inline, unchanged (schema=, each count, cut and floor); rows follow it; legend="ref": a definition is sent once per session (this dictionary's core, or the first answer that needs … [line truncated: 80 more bytes on this line] schema=ripwire.KEY/v1: the line ripwire.KEY/v1 below reads the answer's rows window: shown= total= capped= has_more= next_offset= offset= limit= page a list (capped=1 cut; next_offset= pastes as offset=) @@ -4723,7 +4720,7 @@ _The family join: per function, which of four orthogonal evidence families fire, ``` $ ./build/ripwire . --ensemble --limit=8 - @@ -4734,7 +4731,7 @@ $ ./build/ripwire . --ensemble --limit=8 - + ... [17 more line(s); run it to see the whole thing] ``` @@ -4761,8 +4758,8 @@ $ ./build/ripwire . --exclude=present --exclude=bench --top-k=5 - - + + @@ -4792,10 +4789,10 @@ $ ./build/ripwire . --map-diff --top-k=5 - - + + - + @@ -4826,10 +4823,10 @@ $ ./build/ripwire . --cache=/aux/warm2.ripwirecache --top-k=3 - - + + - + @@ -4876,10 +4873,10 @@ $ ./build/ripwire . --no-cache --top-k=3 - - + + - + @@ -4907,10 +4904,10 @@ $ ./build/ripwire . --no-ignore --top-k=3 - - + + - + @@ -4943,14 +4940,14 @@ $ ./build/ripwire . --max-file-size=8K --top-k=3 - - + + - + ... [17 more line(s); run it to see the whole thing] @@ -5023,10 +5020,10 @@ $ ./build/ripwire . --pin-census=/aux/pin_census.tsv --top-k=3 - - + + - + @@ -5048,7 +5045,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.107+ged47f82e8"},"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":1,"result":{"protocolVersion":"2025-11-25","serverInfo":{"name":"ripwire","version":"0.6.10-dev.113+g147c73293"},"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] @@ -5074,11 +5071,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.107+ged47f82e8"},"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":" | +| **The gate suite** | `test/regression.sh`, `test/pargates.py` | 866 gate scripts (counts snapshot 2026-11-22) plus the determinism, cache-transparency and golden contracts. | | **`--quality-delta`** | `src/quality.h` | Ten measured code-quality failure modes, reported only where a change made them worse. | ### The labeling protocol (why the held-out eval is allowed to disagree with the ranker) @@ -5888,7 +5888,7 @@ copy here would be exactly the dialect divergence that gate exists to catch. Com tags, wrap, stable-order defaults), seven individually invoked standalone gates (`g1freshcheck`, `skillscan`, `htmlexport`, `compresscheck`, `handoffcheck`, `releaseinstallcheck`, `taskroutecheck`), and a single loop -(**854 gate scripts** at the counts snapshot 2026-11-18; `test/manifestcheck.sh` proves every listed name exists on disk). +(**866 gate scripts** at the counts snapshot 2026-11-22; `test/manifestcheck.sh` proves every listed name exists on disk). `python3 test/pargates.py . ./build/ripwire -j 6` runs the same scripts in parallel so a full verification fits in one sitting. It does not modify `regression.sh`. @@ -6199,14 +6199,24 @@ These are the exact `kind=` strings the binary emits, from `src/quality.h`: `complexity` · `verbosity` · `nesting` · `params` · `duplication` · `dead-code` · `api-surface` · `error-masking` · `short-horizon-churn` · `new-clone-of-reused-helper` · `placeholder` · `defect-shape` · `tangle` -`tangle` (QD-TANGLE, 2026-11-19) is report-only: always `sev="minor"`, a long function's nesting past 3, deep share and -steering locals amplified by length (AUC 0.986 on 44 hand labels; a long orchestrator of named steps scores 0). +`tangle` (QD-TANGLE, 2026-11-19) scores a long function's nesting past 3, deep share and steering locals amplified by +length (AUC 0.986 on 44 hand labels; a long orchestrator of named steps scores 0). It was report-only until +TANGLE-GATE-B / QD-RATCHET-BASE (2026-11-21): a row now gates when the function is new at 6.0 or more, crossed 6.0, or +its score grew against the range base while over 6.0 (not a moved body, not test code); a row an input rose on while the +score held stays `sev="minor"`, and the best-since-tag ratchet is a facet (`ratchet=`) on those rows, never a row of its +own. Replayed on the 20 merges before 8861b0d4d (range form, tangle kind only): main printed 3 minor rows and gated 0; +the lane gates 9 rows over 5 PRs — #702 `runLsp` 2.1→11.0 (crossed) and the 8 growth rows the re-census found +(#714 `serialize` 25.4→25.5 and `cc_walk` 9.1→9.7, #706 `runForLensPass` 16.4→16.5, #705 `buildGraph` 56.8→56.9, +#702 `serialize` 25.2→25.4, #688 `ElixirContext::prepare` 12.2→12.3 and `captureTagsFacts` 28.8→29.2); the four +tag-best rows on functions that did not grow in their PR (`buildGraph` #706/#714, `serialize` #705, `captureTagsFacts` +#714 29.2→29.1) print nothing. Expected effect: a PR that adds even a tenth to an over-bar function gates until it +leaves the function no worse (or acks it). The first ten each target a failure mode measured in the literature; `placeholder` (added 0.6.7) is an honesty check on "done" — a stub or TODO the change added — and never gates. `defect-shape` carries six facets in `defect=` (`format-arity`, `utf8-cut`, `dedup-first`, `vacuous-assert`, `unchecked-status`, `unhandled-arm`), shapes this project's own code review kept finding; only `format-arity` gates, and on any origin (new-symbol rows never gate, except -defect-shape format-arity; since QD-ENTRY-CEILING also a new function at the ceiling). Measured (2026-10-07): recall 7/8 on the eight review findings it was built +defect-shape format-arity, a new function at the ceiling (QD-ENTRY-CEILING) and a tangled new function (TANGLE-GATE-B)). Measured (2026-10-07): recall 7/8 on the eight review findings it was built from; with every site treated as new, 0 format-arity false positives on this tree (1,330 literal-format calls), on the Python 3.13 standard library (405 calls) and on libc++'s std::format tests (80 calls; the 24 hits are its deliberately ill-formed `.verify.cpp` calls); vacuous-assert sample precision 30/30 on this tree's gates @@ -7057,7 +7067,7 @@ Listed because the reason is more useful than the silence. shipped**. See `bench/locbench/anchorhop_calib.json`. The mention anchor's reproducible numbers are the ablations in §4. - **A single round gate-count.** Two in-tree numbers disagree (`test/pargates.py`'s docstring says - ~210; `test/argvdiffcheck.sh` says 200+), while the loop in `test/regression.sh` names 854 at the counts snapshot 2026-11-18. The + ~210; `test/argvdiffcheck.sh` says 200+), while the loop in `test/regression.sh` names 866 at the counts snapshot 2026-11-22. The loop is the authority; the stale docstrings are a known drift. Since 2026-09-10 the number is not written by hand anywhere, and since 2026-11-02 it is the dated counts snapshot `docs/counts.tsv` (so two open changes that each add a gate never conflict on it): `docs/gatecount_build.py` rewrites diff --git a/docs/LIMITS.md b/docs/LIMITS.md index d82bc37f0..8f11388cc 100644 --- a/docs/LIMITS.md +++ b/docs/LIMITS.md @@ -45,16 +45,16 @@ revived against this residual: it counted line-match attempts BETWEEN engine cal answers and still bounded nothing inside one call.) **Totals are a dated snapshot.** Every total on this page (the table below, the class counts, the -file count) is the counts snapshot taken 2026-11-18 (`docs/counts.tsv`), so two open changes that each add a +file count) is the counts snapshot taken 2026-11-22 (`docs/counts.tsv`), so two open changes that each add a cap do not both rewrite the same line; the per-file tables are re-read from `src/` on every run. `python3 docs/counts_snapshot.py show` prints today's numbers beside these. | total caps | files | caps whose file discloses | caps whose file discloses NOTHING | | --- | --- | --- | --- | -| 440 | 149 | 288 | **152** | +| 454 | 156 | 289 | **165** | Plus 10 ranking and apportionment parameters, in their own table below: they are not caps, they -are not counted as caps, and 440 + 10 is the 450 constants this generator parses out of `src/`. +are not counted as caps, and 454 + 10 is the 464 constants this generator parses out of `src/`. ## INDEXING, OUTPUT or BOUNDARY — which half of the answer a cap bounds @@ -72,8 +72,8 @@ None of them truncates anything, so none can be judged by `shown=`/`total=` and a disclosure — labelling them OUTPUT would ask for a `capped="1"` that could never honestly fire. The distinction was named in review on #108 and the rows below now carry it. -The `class` column below carries that answer where it is known. **143 of 440 caps are classified -(51 INDEXING, 46 OUTPUT, 46 BOUNDARY); the remaining 297 render `—`, which means NOT YET +The `class` column below carries that answer where it is known. **146 of 454 caps are classified +(54 INDEXING, 46 OUTPUT, 46 BOUNDARY); the remaining 308 render `—`, which means NOT YET CLASSIFIED — never "neither".** Classifications live in `docs/limits_classes.tsv`, a sidecar with a known expiry: the tag belongs on the declaration itself, and this file exists only because the round that @@ -1499,7 +1499,7 @@ Discloses: **none** | constant | value | class | note | | --- | --- | --- | --- | -| `kMaxSubDepth` | `40` | — | nested $( ) parsed past this depth are left unparsed (an empty list) | +| `kMaxShellNest` | `64` | — | shell nesting past this depth is cut and not judged; --quality-delta says shell_cut=N | ### `src/siblift.h` diff --git a/docs/TUNING.md b/docs/TUNING.md index dfb1c6913..00cf7ab70 100644 --- a/docs/TUNING.md +++ b/docs/TUNING.md @@ -13,31 +13,31 @@ invocations at the default value and at a probe value. The tunable binary is byt to production at defaults; that control is what makes these numbers mean anything. **The census is a dated snapshot.** The first two columns below and the paragraph after them are -the counts snapshot taken 2026-11-18 (`docs/counts.tsv`), so two open changes that each add a cap do not +the counts snapshot taken 2026-11-22 (`docs/counts.tsv`), so two open changes that each add a cap do not both rewrite them; the per-cap tables are re-read from `src/` on every run. `python3 docs/counts_snapshot.py show` prints today's numbers beside these. | cap declarations | distinct names | tunable | must stay `constexpr` | move >= 1 invocation | move nothing measurable | | --- | --- | --- | --- | --- | --- | -| 318 | 317 | 112 | 12 | **37** | 75 | +| 325 | 324 | 112 | 12 | **37** | 75 | -The first two columns are not the same number, and the gap is not a rounding: `src/` holds **318 cap -declarations** under **317 distinct names** (`kRowCap` declared in more than one file). The sweep +The first two columns are not the same number, and the gap is not a rounding: `src/` holds **325 cap +declarations** under **324 distinct names** (`kRowCap` declared in more than one file). The sweep patches by NAME, so its own population is NAMES and not declarations — and the two columns beside those are frozen at the commit named under Provenance while this census is re-read from `src/` on -every run, which makes them a third population again. Enumerated over the 317 names `src/` declares -today: **111 tunable**, **12 must stay `constexpr`**, and **194 declared since the sweep was +every run, which makes them a third population again. Enumerated over the 324 names `src/` declares +today: **111 tunable**, **12 must stay `constexpr`**, and **201 declared since the sweep was prepared, which no measurement has touched** (`kAliasHopDepth`, `kAliasPeelDepth`, -`kAliasTargetCap`, `kBackHopWidth`, `kBaseScopeScanCap`, `kBridgeMaxHops`, +188 more). 111 + 12 + -194 = 317, and `emit` refuses to render a partition that does not add up. The `tunable` column above -reads 112 rather than 111 because one name the sweep classified is no longer declared in `src/` at -all: `kSituTestRowsShown`. Quoting "113 of 318" would be wrong in both halves at once, which is the -shape of error a generated table exists to prevent. +`kAliasTargetCap`, `kBackHopWidth`, `kBaseScopeScanCap`, `kBestSinceMaxBlobs`, +195 more). 111 + 12 ++ 201 = 324, and `emit` refuses to render a partition that does not add up. The `tunable` column +above reads 112 rather than 111 because one name the sweep classified is no longer declared in +`src/` at all: `kSituTestRowsShown`. Quoting "113 of 325" would be wrong in both halves at once, +which is the shape of error a generated table exists to prevent. ## Read this ratio before the tables **37 of 112 tunable caps move any invocation at all. 75 move nothing measurable.** That is the -finding, and it says what NOT to do: this is not a 318-cap audit. Most of these constants are +finding, and it says what NOT to do: this is not a 325-cap audit. Most of these constants are inert on real invocations and should be left alone. The work worth doing is the small set below, plus the caps that fire SILENTLY — a cap that bites without disclosing is a defect independent of whether its value is right, and that fix is both cheaper and larger than any retuning. diff --git a/docs/captures/COMMANDS_showcase_2026-11-22.md b/docs/captures/COMMANDS_showcase_2026-11-22.md new file mode 100644 index 000000000..5dcfb81a5 --- /dev/null +++ b/docs/captures/COMMANDS_showcase_2026-11-22.md @@ -0,0 +1,7943 @@ +# ripwire — every verb, run for real + +- **Date:** 2026-11-22 (regenerated capture; supersedes any older `docs/captures/COMMANDS_showcase_*.md`) +- **Lives in `docs/captures/`** — a directory the crawl/retrieval lenses SKIP (`kCrawlSkipDirs`, src/ingest.h): a generated doc that quotes every verb's output out-scores the source for any query about the tool and was measured at 77% of `--recall` on this repo when it sat at the root. `test/argvdiffcheck.sh` harvests its `## `-heading command lines as differential vectors — keep that format. +- **Version:** `ripwire 0.6.10-dev.113+g147c73293 (dev, AppleClang 21.0.0.21000101, emit=std::print, built_from=147c73293)` +- **Repo:** the ripwire repo @ `147c73293` — **CLEAN — `git status --porcelain` is empty**. The diff-aware verbs (`--situ`/`--test-gate`/`--quality-delta`/`--pr-context`/`--map-diff`/`--edit-check`) answer a question about the WORKING TREE, so that condition is part of their answer and every one of their captions below states which tree it recorded against. A clean tree is the honest default for a showcase, so they appear TWICE: once here on the clean tree (their empty/exit-0 shape) and once in the final section against a throwaway `git clone --local` sandbox carrying one deliberate regression, so their real gating shapes are visible without writing a byte into the read-only repo. +- **Corpus:** the ripwire repo itself (dogfood), via `./build/ripwire` +- **Sandbox diff** (the last section only): `.ripwire_notes | 2 ++ + .ripwire_quality_acks | 1 + + src/infra/sortutil.h | 31 ++++++++++++++++++++++++++++--- + 3 files changed, 31 insertions(+), 3 deletions(-)` — one preexisting function made deeply nested, one function's arity changed 1 -> 2, one copy-paste duplicate helper, one new 8-parameter public function. + +**How to read the blocks:** ripwire's real XML output is minified — often ONE long line. For scanability, long minified lines are displayed re-wrapped with a line break at every tag seam (`><`). Header COMMENT lines (the legends) always appear in full — they are exempt from the per-line cut; any OTHER display line over 300 bytes is cut with a `… [line truncated: N more bytes]` marker, which can hit a long root element or row. `--plan-lanes` emits JSON and is re-wrapped at object seams the same way. Long outputs are cut to their first ~30 display lines with a `… [N more display lines; full output is M bytes]` marker giving the true size. Exit codes are recorded when non-zero; wall time when >1s. + +**Not run (and why):** `ripwire ` (network clone), `--legend-have` (a per-CALLER handshake — the caller names the legend dictionary version it already holds — so a one-shot capture has nothing to hold and nothing to show; gated by `test/legendhavecheck.sh`), `--listen` / `--mcp-token` / `--allow-remote-edits` (the HTTP-server posture; `--mcp` itself IS captured in its own section as a one-shot stdio JSON-RPC exchange, and `wrap claude` shows the wiring), `--arch --baseline[-update]` (state writer against the read-only repo — `--note-add` / `--quality-baseline` / `--quality-ack` / the three edit verbs / `--edit-plan` ARE shown, inside the throwaway sandbox clone; `--index-out` / `--pin-census` write to scratch), `--eval-mined` (needs a `minedpair.jsonl` artifact from `bench/mine_traces.py`; none present in the tree), `--refetch` (git-url only), `--lsp` / `--lsp-langmap` (the editor transport and its language-map config — their one-shot dialogues, including every map and hint arm, are gated by `test/lspcheck.sh`, not by showcase blocks), `--max-memory` (the memory guard is silent on this repo by construction; its stops are gated by `test/memguardcheck.sh`), `--force` (wrap-only modifier), `--deadline-ms` (a timing modifier on `--help-task`: a warm index prints exactly the `--help-task` blocks shown only when it finishes within the deadline (a warm run past it abstains as well), and the cold abstention depends on wall-clock timing; gated by `test/helptaskdeadlinecheck.sh`), `--scan-skills` bare form (would sweep `~/.claude/skills`; the explicit-DIR form is shown instead), `--help` (217 lines — read it from the binary). + + +--- + +# understand a codebase cold + +## `./build/ripwire .` + +*The default ranked symbol map — start here when landing cold in a repo.* + +**wall time: 1.83s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [765 more display lines; full output is 26303 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --top-k=5` + +*Same map, capped to the 5 highest-ranked symbols.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [91 more display lines; full output is 10369 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.* + +````` + + + + + + + + + + + + +````` + +## `./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** + +````` + + +````` + +stderr: + +````` +ripwire: --token-budget exceeded: withheld_est_tokens=10597 > 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: 3.56s** + +````` + + + + +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 24477 bytes on 8 raw line(s)] +````` + +stderr: + +````` +ripwire: cache : over its 2048 MiB budget — evicted 101 blob(s) of other roots or other ripwire builds (this build's blobs for this root are kept) +````` + +## `./build/ripwire . --for="rankGraphTeleport"` + +*Name-shaped query: the router picks name-exact BM25 (header says which/why).* + +**wall time: 1.47s** + +````` + + + + + +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.* + +````` + + + + + +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 30304 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: 1.25s** + +````` + + + + + +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]).* + +````` + + + + +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 + + + + + +… [243 more display lines; full output is 26577 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.* + +````` + + + + +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 ) +inline SubjectRoute chooseSubjectRoute( const IngestResult& ing, const Graph& g, std::string_view task, bool servesBodiesAndCallers ) +struct NameCorpusStats + + +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 31831 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.* + +````` + + + + +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 ) +inline SubjectRoute chooseSubjectRoute( const IngestResult& ing, const Graph& g, std::string_view task, bool servesBodiesAndCallers ) +struct NameCorpusStats +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 ) +inline std::vector<float> lexicalScoresTiered( const IngestResult& ing, const std::vector<std::uint32_t>& outOff, const std::vector<NodeId>& outTarge … [line truncated: 104 more bytes on this line] +… [275 more display lines; full output is 31784 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).* + +````` + + + + +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.* + +````` + + + + +````` + +## `./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" — 146 relevant of 359 document files, best-first — total=146 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.928) ━━ [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 20.991) ━━ [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 1502787-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.185) ━━ [sections: 1 of 166 selected (196 in doc), section-granular; whole doc 639729 B; lines="566-591"; 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 11021 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --html=/aux/map2.html` + +*Self-contained HTML force-directed call graph.* + +**wall time: 1.50s** + +````` +(empty) +````` + +Artifact written: + +````` + 155977 /aux/map2.html +````` + +## `./build/ripwire . --order=stable --top-k=5` + +*Stable (path/id) emit order — provider KV-cache hits across re-runs.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [91 more display lines; full output is 10376 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.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [169 more display lines; full output is 8418 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.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [2411 more display lines; full output is 74072 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.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [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).* + +````` + + + + + + + + + + +````` + +## `./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** + +````` + + +````` + +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.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [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 5633 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 5508 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.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --connect=rankGraphTeleport,runEval,getIndex` + +*Minimal connecting subgraph over 3 symbols (finds shared-caller joins).* + +````` + + + + + + + + + + +````` + +## `./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.* + +````` + + + + + + + + + + + + + +````` + +## `./build/ripwire . --situ` + +*Mid-task situational report for the current git diff — recorded against a CLEAN tree (contrast with the sandbox run below).* + +````` +ripwire situational-awareness — 0 changed file(s), 0 symbols in them +root: . +at: 147c73293 + (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: 4.57s** + +````` + + +````` + +## `./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.* + +````` + +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.* + +````` + +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).* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [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.* + +````` + + + + + +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 constexpr std::string_view kPowerShellPathPrependScope = "in PowerShell, for this window +inline RankedGraph rankGraphTeleport( const Graph& g, const std::vector<float>& p, float alpha = 0.85f ) + + +inline std::string path_prepend_hint( std::string_view dir ) + +handle_t leftmost_leaf() const +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] +inline std::string doctorPathPrependLine( const std::string& selfPath ) + + + +… [130 more display lines; full output is 19074 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: 88.3% fewer bytes at top-10, 87.4% at top-50, 88.6% at top-100 (re-derived 2026-11-21 when train 1118a's qualified C++ calls began binding the namespace their qualifier names (qual-ns-call-bind; with the train's other lanes this repo's graph went from 44,435 to 44,883 edges on main 5df5a26be): the ranked top-10 lost the RW_CHECK_ macro and gained enumcount.h's enumTableAt, whose signature is most of its short body, from 89.7/88.0/87.8 (main 5df5a26be recounts 90.0/88.5/88.8); before that, 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.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [145 more display lines; full output is 15210 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.* + +````` + + + + +: 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). 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. --> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [111 more display lines; full output is 12897 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --deps` + +*File->file dependency graph (god-files, cycles).* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [915 more display lines; full output is 26230 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --hotspots` + +*Complexity x recent git churn (maintenance pain).* + +**wall time: 1.40s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [14 more display lines; full output is 5835 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --clones` + +*Token-normalized duplicate bodies.* + +**wall time: 1.35s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [309 more display lines; full output is 16374 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --cochange` + +*Files that change together in git (hidden coupling).* + +**wall time: 1.45s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --hotspots --since="2 weeks ago"` + +*Hotspots scoped to RECENT churn (the regression lens).* + +**wall time: 1.28s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [13 more display lines; full output is 5212 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.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [1392 more display lines; full output is 194260 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: 1.65s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [679 more display lines; full output is 70993 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --lint-rules=test/lintrulesfix/rules` + +*User lint rules (YAML, ast-grep style) from a directory.* + +````` + + + + +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.* + +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.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [188 more display lines; full output is 16453 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 7639 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.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [325 more display lines; full output is 14516 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --report` + +*Architecture summary (modules, god-files, cycles) as markdown.* + +````` + + +# ripwire architecture report + +4852 files · 45032 symbols · 45381 edges · 5247 modules (21074 call-graph isolated) + +Root: `.` + +Call-graph isolate provenance: 5832 declaration, 3601 header, 4566 source, 7075 document; 0 connected Louvain singletons + +## Modules (call-graph clusters; showing 12 of 5247) +- **src::emitTo@infra/emit.h:53:2760 [write,run,emit]** — 1652 symbols +- **src::kindIs@infra/nodekind.h:46:3271 [push,emit,read]** — 733 symbols +- **src::DISCLOSE@infra/Diagnostics.h:622:43913 [read,scan,run]** — 375 symbols +- **docs::`--top-k=N`@COMMANDS.md:59:9303 [pack,allow,insert]** — 185 symbols +- **src::close@infra/os.h:181:9420 [open,write,read]** — 121 symbols +- **src::str@infra/internedtext.h:323:16987 [resolve,find,add]** — 118 symbols +- **src/infra::fail@os_win32.cpp:63:2553 [get,open,release]** — 111 symbols +- **src::shSingleQuote@infra/shquote.h:19:960 [read,resolve,compute]** — 109 symbols +- **test/ownerhopfix/py/pkg::big_handler_001@broadcast.py:3:72** — 106 symbols +- **src::sortUnique@infra/sortutil.h:55:2725 [connect,collect,compute]** — 84 symbols +- **src::text@ingest_valuerefs.h:804:41690 [emit,open,mark]** — 80 symbols +- **src::unq@shstatus.h:194:7733 [visit,call,bind]** — 77 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 316) +- `src/model.h` — 144 dependents +- `src/infra/emit.h` — 101 dependents +- `src/infra/sortutil.h` — 89 dependents +… [38 more lines, 4349 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 12768 bytes on 1 raw line(s)] +````` + +## `./build/ripwire . --mermaid` + +*Module (directory) dependency graph as a Mermaid diagram.* + +````` +%% 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
15178"] + n106["src/infra
1687"] + end + subgraph sg1 ["test"] + n107["test
7030"] + n750["test/legochargefix
546"] + n472["test/fixtures/recallpassage
314"] + n491["test/fnslotcpp2
285"] + n913["test/lib
262"] + n712["test/ifacepeelfix/cpp
206"] + n1260["test/slotjoinfix
182"] + n1017["test/ownerhopfix/py/pkg
158"] + n408["test/expandmodefix
151"] + n410["test/expandsibsfix
149"] + n1223["test/rubyschemafix
99"] + n527["test/forbodyfoldfix/py
98"] + end + n77["docs
1266"] + subgraph sg3 ["bench"] + n63["bench/sectionfront
1033"] + n4["bench
569"] + 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
104"] +… [23 more lines, 1626 bytes total] +````` + +## `./build/ripwire . --owners` + +*Bus-factor: recency-weighted author ownership per file.* + +**wall time: 1.48s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [1071 more display lines; full output is 119783 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: 1.45s** + +````` + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --exercises=test/regression.sh` + +*Which symbols a TEST FILE exercises — the reverse direction of --affected.* + +````` + + + +````` + +## `./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: 25.28s** + +````` + + +````` + +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: 12.49s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [176 more display lines; full output is 19650 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: 10.43s** + +````` + + + + + + + + + +````` + +## `./build/ripwire . --pr-context` + +*No-LLM review-evidence bundle for the working-tree diff (clean tree = empty).* + +````` + + + +````` + +## `./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: 2.94s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [299 more display lines; full output is 19481 bytes on 1 raw line(s)] +````` + +## `./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: 15.95s** + +````` + + + + + + + + + + + +````` + +## `./build/ripwire . --stray-content=lane/` + +*Which refs of the `lane/` ref family still hold divergent authored work vs HEAD, with verdicts.* + +**wall time: 4.77s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [837 more display lines; full output is 94631 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=.* + +````` + + + +````` + +## `./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: 11.62s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [287 more display lines; full output is 31658 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: warning: --plan scouted 1 of 62 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: 1.16s** + +````` +(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: 34.82s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [743 more display lines; full output is 54765 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 renders two pages under the same 60-row cap, the definitions page (kind="def" rows and the kind="text" lines no parse read, the references counted in ) and the whole list, and serves the definitions page when it shows more definitions, whatever its bytes, else only when it is strictly shorter. Here the branches' copies sit in blobs past the parse guard (, kind="text", never counted as definitions), so both pages show HEAD's one definition and the default serves the shorter whole list: that definition, then HEAD's references.* + +**wall time: 14.09s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [36 more display lines; full output is 19963 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: warning: --whereis read the newest 373 of 655 local branches; 282 older were not read (limit: 2097152 tree entries across all refs, 374 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 before any branch row arrives, so it can show fewer definitions than the definitions page. The default serves this page only when both show the same definitions and the definitions page is not strictly shorter (a tie serves this page), as above: here it is the default's own page, HEAD's one definition and then its references.* + +**wall time: 13.94s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [36 more display lines; full output is 13481 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: warning: --whereis read the newest 373 of 655 local branches; 282 older were not read (limit: 2097152 tree entries across all refs, 374 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: 11.72s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [35 more display lines; full output is 13988 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: warning: --whereis read the newest 373 of 655 local branches; 282 older were not read (limit: 2097152 tree entries across all refs, 374 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: 18.79s** + +````` + + + + + + + +````` + +stderr: + +````` +ripwire: warning: --whereis read the newest 373 of 655 local branches; 282 older were not read (limit: 2097152 tree entries across all refs, 374 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: 1.12s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [2404 more display lines; full output is 151283 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.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./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** + +````` +(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: 1.57s** + +````` +{"v":1,"verb":"plan-lanes","at":"147c73293","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":4852,"symbols":45032,"edges":453 … [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":1688,"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/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/graphlegend.h","n":"kRadiusTestTierLegend","scope":"rw","key":"98c48ee73bccc1a2","id":"./src/graphlegend.h::rw::kRadiusTestTierLegend","id_addressable":true,"id_collides_with":0,"l":538,"ord":0,"overloads":1,"amb":0,"cx":0,"ccx":0,"churn":242,"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":242,"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":696,"ord":0,"overloads":1,"amb":1,"cx":2,"ccx":1,"churn":514,"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":6306,"ord":0,"overloads":1,"amb":0,"cx":3,"ccx":2,"churn":676,"tested":0}], +"files":[{"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":54}, +{"p":"./src/graphlegend.h","symbols":2,"churn":242,"ccx":4,"hotspot_rank":34}, +{"p":"./src/main.cpp","symbols":1,"churn":514,"ccx":1,"hotspot_rank":5}, +{"p":"./src/mcpverbs.h","symbols":1,"churn":676,"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":37}]},"blast_radius":{"reaches":53,"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":53,"module_span":2,"notes":[], +"execution":{"policy":"codex-lane/v1","model":"gpt-5.6-sol","reasoning":"high","rule":"complex-or-wide","basis":"structural-only","signals":{"claims":12,"files":7,"module_span":2,"max_ccx":10,"sum_ccx":42,"ambiguous_calls":5,"blast_reaches":53,"contract_touches":0,"conflicts":0,"untested":53,"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] +{"p":"./src/gitmine.h","n":"gitWindowBoundarySha","scope":"rw","key":"18627516699d7062","id":"./src/gitmine.h::rw::gitWindowBoundarySha","id_addressable":true,"id_collides_with":0,"l":2179,"ord":0,"overloads":1,"amb":1,"cx":4,"ccx":3,"churn":106,"tested":0}, +{"p":"./src/jsrunner.h","n":"matchesDefaultInclude","scope":"rw::jsrunner","key":"1e885c432f6da6bb","id":"./src/jsrunner.h::rw::jsrunner::matchesDefaultInclude","id_addressable":true,"id_collides_with":0,"l":549,"ord":0,"overloads":1,"amb":0,"cx":11,"ccx":11,"churn":22,"tested":0}, +… [68 more display lines; full output is 20421 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: 1.64s** + +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":"147c73293","root":".","task":null,"source":"brief","requested":3,"lane_count":3,"claim_key":"path+scope+name","on_conflict":"producing-lane-rebases","corpus":{"files":4852,"symbols":45032,"edges":45381,"ambiguous":3984,"unresolved":20100},"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":676,"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":1688,"ord":0,"overloads":1,"amb":1,"cx":5,"ccx":4,"churn":92,"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":6306,"ord":0,"overloads":1,"amb":0,"cx":3,"ccx":2,"churn":676,"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":676,"ccx":2,"hotspot_rank":4}, +{"p":"./src/recall.h","symbols":1,"churn":49,"ccx":4,"hotspot_rank":49}, +{"p":"./src/verbs_change.h","symbols":1,"churn":92,"ccx":4,"hotspot_rank":35}], +"symbols_total":4300,"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":289,"ord":0,"overloads":1,"amb":0,"cx":23,"ccx":31,"churn":22, … [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":3148,"ord":0,"overloads":1,"amb":0,"cx":0,"ccx":0,"churn":651,"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":3227,"ord":0,"overloads":1,"amb":0,"cx":0,"ccx":0,"churn":651,"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":3278,"ord":0,"overloads":1,"amb":0,"cx":2,"ccx":1,"churn":651,"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":5163,"ord":0,"overloads":1,"amb":1,"cx":3,"ccx":3,"churn":111,"tested":0}, +… [59 more display lines; full output is 18361 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** + +````` +(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.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + +
+ + + + + + + + + + + + + +… [260 more display lines; full output is 25804 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.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [292 more display lines; full output is 27293 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.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [234 more display lines; full output is 25789 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:14923 + #1 0x102f3e884 in rw::rankGraph(Graph const&, float) src/graph.h:14966 + #2 0x102e11f30 in runDefaultMap(MainDispatch const&) src/main.cpp:1761 + #3 0x102e01a44 in main src/main.cpp:4565 + #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=.* + +````` + + + + +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 + +B1.4: the output-SHAPE members of the list above, as a table rather than a second if-chain. A flag in here selects an ENCODING for rows some verb already produced, so "--json is not supported for Xinline constexpr std::string_view kJsonShapeModifiers[] = + + + + + + + + + +… [54 more display lines; full output is 9043 bytes on 46 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.* + +````` + 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. 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 constexpr std::string_view kPowerShellPathPrependScope = "in PowerShell, for this window +inline RankedGraph rankGraphTeleport( const Graph& g, const std::vector<float>& p, float alpha = 0.85f ) + + +inline std::string path_prepend_hint( std::string_view dir ) + +handle_t leftmost_leaf() const +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] +inline std::string doctorPathPrependLine( const std::string& selfPath ) + + + +… [166 more display lines; full output is 20893 bytes on 15 raw line(s)] +````` + +## `./build/ripwire . --export=cc.json:/aux/ripwire2.cc.json` + +*Per-file metrics as CodeCharta cc.json.* + +**wall time: 1.15s** + +````` +(empty) +````` + +Artifact written: + +````` + 741947 /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: 1.91s** + +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 60641 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: 6.23s** + +````` + + + + + + + + + + +````` + + +--- + +# 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.* + +````` + + + +````` + +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: 1.58s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --rank-by=churn-decay --since=HEAD~9 --exclude=test --exclude=docs --exclude=skills --exclude=changelog.d --in=src --limit=1` + +*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. This page holds 1 row(s), not the usual 3: no change window on this branch held enough src/ files for a larger page to cut, so the generator fell back to a smaller one (see chooseInWindow).* + +**wall time: 1.86s** + +````` + + + + + + + + + + + + + + +````` + +## `./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,14964,15633,171,1433,1472,1759 +fn,fn,fn,fn,fn,fn,fn +0,0,0,0,0,0,0 +1340,14968,15684,328,1447,1486 1487 1501,1879 + + +````` + +## `./build/ripwire . --for="cache invalidation" --format=candidates --top-k=5` + +*Flat top-K export for an external reranker.* + +````` + + + +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":3984,"graph_unresolved":20100,"graph_unindexed":313,"counts_floor":true,"callers":[{"t":"fn","n":"getIndex","p":"src/mcpindex.h:1224","sites_at":["1340"]}, +{"t":"fn","n":"rankGraph","p":"src/graph.h:14964","sites_at":["14968"]}, +{"t":"fn","n":"anchoredLexicalRank","p":"src/graph.h:15633","sites_at":["15684"]}, +{"t":"fn","n":"runEval","p":"src/eval.h:171","sites_at":["328"]}, +{"t":"fn","n":"churnDecayRanking","p":"src/main.cpp:1433","sites_at":["1447"]}, +{"t":"fn","n":"churnRankedGraph","p":"src/main.cpp:1472","sites_at":["1486","1487","1501"]}, +{"t":"fn","n":"runDefaultMap","p":"src/main.cpp:1759","sites_at":["1879"]}]} +````` + +## `./build/ripwire . --hotspots --json` + +*JSON refusal shape: an unsupported verb refuses loudly instead of silently falling back to XML.* + +**exit code: 1** + +````` +(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: 1.93s** + +````` + + + + + + + +````` + +## `./build/ripwire . --ignore-tests --top-k=5` + +*Drop test paths from the corpus before ranking.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [90 more display lines; full output is 9986 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.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [89 more display lines; full output is 10212 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: 1.06s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + +````` + +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: 2.38s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [82 more display lines; full output is 10210 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: 2.76s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [82 more display lines; full output is 10210 bytes on 1 raw line(s)] +````` + +stderr: + +````` +ripwire: cache : over its 2048 MiB budget — evicted 10 blob(s) of other roots or other ripwire builds (this build's blobs for this root are kept) +````` + +Artifact written: + +````` + 40894532 /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).* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [20 more display lines; full output is 5003 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: 3.27s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --eval` + +*Self-eval: co-change recall vs BM25.* + +**wall time: 21.89s** + +````` +ripwire --eval (co-change recovery, averaged over 80 historical commits) + ranker recall@5 recall@10 recall@20 + ripwire 5.8% 6.0% 12.0% + BM25 9.0% 9.8% 11.6% + BM25sub 10.1% 11.3% 12.8% + BM25body 10.1% 14.5% 27.4% + fused 3.8% 9.2% 16.9% + anchored 9.9% 14.5% 25.3% + same-dir 0.8% 0.8% 2.1% + random 0.1% 0.2% 0.4% <- floor (random ranking over F=4852 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: 240.15s** + +````` +ripwire --eval-retrieval (known-item, 4000 doc-commented symbols; gold is in-corpus by construction) + sample: population=12348 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.658 52.3% 82.2% 87.4% + subtoken doc-phrase 0.883 86.0% 90.4% 91.5% + name-exact name 0.877 79.7% 93.9% 96.1% + name-exact doc-phrase 0.008 0.3% 1.1% 1.6% + anchored name 0.663 53.7% 81.0% 86.0% + anchored doc-phrase 0.876 85.1% 90.0% 90.8% + routed name 0.879 79.9% 94.0% 96.3% + routed doc-phrase 0.881 86.0% 90.2% 91.2% + 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: 7.44s** + +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 655 local branches; 143 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).* + +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= … [line truncated: 8 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.872) + 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, 3721 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.113+g147c73293 (dev, AppleClang 21.0.0.21000101, emit=std::print, built_from=147c73293) +````` + + +--- + +# navigate — seeds, claims, slices, shapes + +## `./build/ripwire . --at=src/graph.h:14923` + +*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:14923` + +*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 21347 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.* + +````` + + + + + + + + + + + + +````` + +## `./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: 1.14s** + +````` + + + + + + + + + + + + + + + + + +````` + +## `./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).* + +````` + + + + + + + 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).* + +````` + + + + + + + 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.* + +````` + + + + + + + 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** + +````` +(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: 1.25s** + +````` + + + + + + + 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: 1.23s** + +````` + +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: 1.40s** + +````` + +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 + + + + + +… [243 more display lines; full output is 26462 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: 2.10s** + +````` + + + + +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 + + + + + +… [265 more display lines; full output is 27832 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: 1.39s** + +````` + + + + +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 + + + + + +… [273 more display lines; full output is 28246 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: 1.65s** + +````` + + + + + +WRITE ACKS — the --quality-ack arm: fold the VISIBLE findings --ack-only selects into the ledg…int runQualityAckWrite( const rw::Config& cfg, const rw::quality::Scope& scope, const QdPartition& part, DeltaBasis& basis, const std::string& acksFile ) +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 com… +std::optional<int> runForLensPosture( const MainDispatch& d, rw::ForAnswerLedger* ledger ) +inline Result computeDmm( const std::string& root, std::string_view spec, const IngestResult& wo… + +An --ack-only that matched NO finding: refused with exit 1, and nothing accepted. M1 FOLLOW-UP (…int refuseUnmatchedAckOnly( std::string_view ackOnly, const std::string& acksFile, const gtl::btree_map<std::string, rw::quality::AckRecord>& acks, std::size_t … + +SCOPE + RATCHET — split basis.regs by --scope, then suppress what the ack ledger already accep…QdPartition applyScopeAndAcks( const rw::quality::Scope& scope, DeltaBasis& basis ) + +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 ) +std::optional<int> runQualityDelta( const MainDispatch& d ) + + +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] +QdReport computeQdReport( const QdComparison& c, std::vector<rw::quality::StaleAck> staleAcks, const std::string& baselineFile ) +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] + + +int writeAcceptedAcks( const std::string& acksFile, const gtl::btree_map<std::string, rw::quality::AckRecord>& acks, const QdAckTally& tally, const rw::quality::Sco … [line truncated: 48 more bytes on this line] + +std::optional<QdStaleFold> qdStaleFold( const QdReport& rep, const Escape& ex ) + + +… [413 more display lines; full output is 41657 bytes on 135 raw line(s)] +````` + +stderr: + +````` +ripwire: redacted 1 secret from emitted context (keyword-gated-secret=1) — pass --no-redact to disable +````` + +## `./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: 1.28s** + +````` + + + + + +WRITE ACKS — the --quality-ack arm: fold the VISIBLE findings --ack-only selects into the ledg…int runQualityAckWrite( const rw::Config& cfg, const rw::quality::Scope& scope, const QdPartition& part, DeltaBasis& basis, const std::string& acksFile ) +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 com… +std::optional<int> runForLensPosture( const MainDispatch& d, rw::ForAnswerLedger* ledger ) +inline Result computeDmm( const std::string& root, std::string_view spec, const IngestResult& wo… + +An --ack-only that matched NO finding: refused with exit 1, and nothing accepted. M1 FOLLOW-UP (…int refuseUnmatchedAckOnly( std::string_view ackOnly, const std::string& acksFile, const gtl::btree_map<std::string, rw::quality::AckRecord>& acks, std::size_t … + +SCOPE + RATCHET — split basis.regs by --scope, then suppress what the ack ledger already accep…QdPartition applyScopeAndAcks( const rw::quality::Scope& scope, DeltaBasis& basis ) + +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 ) +std::optional<int> runQualityDelta( const MainDispatch& d ) + + +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] +QdReport computeQdReport( const QdComparison& c, std::vector<rw::quality::StaleAck> staleAcks, const std::string& baselineFile ) +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] + + +int writeAcceptedAcks( const std::string& acksFile, const gtl::btree_map<std::string, rw::quality::AckRecord>& acks, const QdAckTally& tally, const rw::quality::Sco … [line truncated: 48 more bytes on this line] + +std::optional<QdStaleFold> qdStaleFold( const QdReport& rep, const Escape& ex ) + + +… [337 more display lines; full output is 31814 bytes on 60 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.* + +````` + + + + + + + + + +````` + +## `./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: 3.08s** + +````` + + + + + + + + + + + + + +````` + +## `./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: 2.78s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [565 more display lines; full output is 59879 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).* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [82 more display lines; full output is 10210 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.* + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [82 more display lines; full output is 10210 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** + +````` + + + + + + const&, float) src/graph.h:14923 + #1 0x102f3e884 in rw::rankGraph(Graph const&, float) src/graph.h:14966 + #2 0x102e11f30 in runDefaultMap(MainDispatch const&) src/main.cpp:1761 + #3 0x102e01a44 in main src/main.cpp:4565 + #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.25s** + +````` + + + + +````` + +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: 5.90s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [188 more display lines; full output is 15456 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.* + +````` + + + + + + + + + + + +````` + +## `./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.* + +````` + + + + + + + + + + + +````` + +## `./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 11281 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: 2.65s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [58 more display lines; full output is 8686 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: 3.96s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [36 more display lines; full output is 7531 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: 1.97s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [1425 more display lines; full output is 134138 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.15s** + +````` + + + + + + + + + + + + + + + + + +````` + +## `./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: 15.64s** + +````` + + + + + + + + + + + +

+

+

+

+

+

+

+

+

+

+

+

+

+

+

+

+… [199 more display lines; full output is 19232 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.91s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [640 more display lines; full output is 72804 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=6ad237691d743450 entries=1178 +: this LAST child is only the legend pointer; the root keeps every attribute it carries inline, unchanged (schema=, each count, cut and floor); rows follow it; legend="ref": a definition is sent once per session (this dictionary's core, or the first answer that needs … [line truncated: 80 more bytes on this line] +schema=ripwire.KEY/v1: the line ripwire.KEY/v1 below reads the answer's rows +window: shown= total= capped= has_more= next_offset= offset= limit= page a list (capped=1 cut; next_offset= pastes as offset=) +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 +… [1149 more display lines; full output is 135171 bytes on 1179 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: 2.16s** + +````` + + + + + + + + + + +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 72930 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.49s** + +````` + + + + + + + + + + + + + + + + + + + + + + + +0.5 +1023u +main (90 lines) +20 +delta < 0.02 && delta > -0.02 +0.02 +… [708 more display lines; full output is 67292 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: 3.26s** + +````` + + + +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: 3.07s** + +````` + + + +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.05s** + +````` +(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.15s** + +````` +(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: 3.22s** + +````` +{"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}}, +… [17285 more display lines; full output is 2454955 bytes on 1 raw line(s)] +````` + +Parsed summary of the same SARIF (past the display cut): + +````` +sarif 2.1.0 rules= 39 results= 8638 +````` + +## `./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: 4.94s** + +````` + + +

+

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

+

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

+

+ +````` + +## `./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: 1.73s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [1005 more display lines; full output is 67750 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: 2.28s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./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: 2.07s** + +````` +(empty) +````` + +Artifact written: + +````` + 155982 /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: 5.52s** + +````` +(empty) +````` + +stderr: + +````` +ripwire: --index-out wrote /aux/ci_index.lean.ripwirecache (40894532 bytes, lean family) +ripwire: --index-out wrote /aux/ci_index.rich.ripwirecache (82404940 bytes, rich family) +````` + +Artifact written: + +````` + 40894532 /aux/ci_index.lean.ripwirecache + 82404940 /aux/ci_index.rich.ripwirecache + 123299472 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: 1.53s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [82 more display lines; full output is 10210 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: 1.87s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [82 more display lines; full output is 10210 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. + 182389 /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: 2.27s** + +````` + + + + + + + + + + + + + +````` + +## `./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** + +````` + + + + + + + +````` + +## `./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: 10.68s** + +````` + + + + + + + + + + + + + +````` + +## `./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: 9.57s** + +````` +ripwire situational-awareness — 1 changed file(s), 14 symbols in them +root: . +at: 147c73293+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: 1049 symbols across 148 files transitively depend on these changes (showing 8 of 148 files — shown=8 total=148 capped=1 prcontext_cap=20 (--pr-context's own per-file list is cut at 20 too); next: --situ --limit=148) + counts_floor=1 graph_ambiguous=3984 graph_unresolved=20100 graph_unindexed=313 (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 (62 dependent symbols) + src/quality.h (44 dependent symbols) + src/mcpverbs.h (41 dependent symbols) + src/verbs_for.h (33 dependent symbols) + src/backhops.h (31 dependent symbols) + src/slice.h (31 dependent symbols) + src/verbs_quality.h (29 dependent symbols) + src/resolve.h (27 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=952 — 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="8006": + (none — 8006 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: 9.93s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./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: 39.64s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [184 more display lines; full output is 21712 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: 16.81s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [184 more display lines; full output is 27199 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: 17.15s** + +````` +{"baseline":"git-HEAD","regressions":9,"minor":1,"acked":0,"stale":202,"preexisting-worse":6,"new-symbol":3,"gating":5,"register-macro-excluded":63,"api-new-surface":2,"at":"147c73293+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"}, +… [181 more display lines; full output is 20432 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: 12.11s** + +````` +(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: 13.96s** + +````` +(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: 19.92s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [183 more display lines; full output is 21415 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: 2.41s** + +````` + + + + + + +````` + +## `./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: 1.65s** + +````` + + + + + + +````` + +## `./build/ripwire . --pr-context` + +*The review-evidence bundle with an actual changed file.* + +**wall time: 5.56s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [107 more display lines; full output is 10225 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: 3.35s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + +````` + +## `./build/ripwire . --clones` + +*The duplicated helper the sandbox edit introduced shows up as a clone group.* + +**wall time: 2.48s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [309 more display lines; full output is 16374 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: 2.73s** + +````` + + + + + +````` + +stderr: + +````` +[math degraded] crossref: no merge-base for ref (shallow clone or unrelated history?) — verdict is unknown, not merged (crossref.h:1751, 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: 3.03s** + +````` + + + + +````` + +stderr: + +````` +[math degraded] crossref: no merge-base for ref (shallow clone or unrelated history?) — verdict is unknown, not merged (crossref.h:1751, 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: 6.47s** + +````` + + +

+

+ +````` + +## `./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: 20.13s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [186 more display lines; full output is 21682 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: 14.73s** + +````` +(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: 4.82s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [11 more display lines; full output is 2697 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: 1.18s** + +````` +src/infra/sortutil.h::rw::sortutil::lessByScoreDescId 2026-11-22 keep this branch-free — it sits inside the PageRank sort comparator 147c732930f6ea42d5f4c57ff6e09108302c089b integration/train-ge3 +````` + +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.)* + +````` + + + + + + + + + + + + + + + + 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** + +````` +(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: 1.65s** + +````` +(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: 1.89s** + +````` +src/infra/sortutil.h::rw::sortutil::lessByScoreDescId 2026-11-22 chose the flat two-branch compare over the nested ladder because the comparator sits inside the PageRank sort 147c732930f6ea42d5f4c57ff6e09108302c089b integration/train-ge3 +````` + +## `./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.* + +````` + + + + + + + + + +````` + +## `./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: 9.28s** + +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":3984,"graph_unresolved":20100,"graph_unindexed":313,"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":952,"graph_ambiguous":3984,"graph_unresolved":20100,"graph_unindexed":313,"counts_floor":true,"memory_ceiling":"suspended for this check (the write is committed, so a refusal here could not be reported and a retry cou … [line truncated: 91 more bytes on this line] +````` + +stderr: + +````` +ripwire: cache : over its 2048 MiB budget — evicted 73 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: 2.57s** + +````` + + + + + + + + + + + + +````` + +## `./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: 6.59s** + +````` +{"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":3984,"graph_unresolved":20100,"graph_unindexed":313,"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":952,"graph_ambiguous":3984,"graph_unresolved":20100,"graph_unindexed":313,"counts_floor":true,"memory_ceiling":"suspended for this check (the write is committed, so a refusal here could not be reported and a retry cou … [line truncated: 91 more bytes on this line] +````` + +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: 5.10s** + +````` +{"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: 6.48s** + +````` +{"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":3984,"graph_unresolved":20100,"graph_unindexed":313,"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":952,"graph_ambiguous":3984,"graph_unresolved":20100,"graph_unindexed":313,"counts_floor":true,"memory_ceiling":"suspended for this check (the write is committed, so a refusal here could not be reported and a retry cou … [line truncated: 116 more bytes on this line] +````` + +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: 2.62s** + +````` +(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: 3.82s** + +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":3984,"graph_unresolved":20100,"graph_unindexed":313,"counts_floor":true,"atomic_scope":"per-file","rollback_on_write_error":true,"recheck_before_each_write":true,"multifile_crash_atomic":false," … [line truncated: 401 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: 8.48s** + +````` +{"schema":"ripwire.edit-plan/v1","mode":"apply","edits":1,"files":1,"callers_union":4,"graph_ambiguous":3984,"graph_unresolved":20100,"graph_unindexed":313,"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: 585 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":3984,"graph_unresolved":20100,"graph_unindexed":313,"counts_floor":true},"memory_ceiling":"suspended for this check (the write is committed, so a refusal here could not be reported and a retry could insert twice); the 10649 MiB limit was not reached"}]} +````` + +## `./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: 16.92s** + +````` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +… [180 more display lines; full output is 20784 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: 14.11s** + +````` +(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: 18.89s** + +````` +(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 42855 per-symbol rows, 45034 indexed symbols total) +````` + +Artifact written: + +````` + 8965619 .ripwire_quality_baseline +# ripwire quality baseline v6 — regenerate with --quality-baseline; do not hand-edit +producer 7f2bbf2e86d5e6116c232bed7599e37a11acce6fcf131765068af96b0e63fc52 +head 147c732930f6ea42d5f4c57ff6e09108302c089b +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: 16.58s** + +````` + + +````` + + +--- + +# 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.113+g147c73293"},"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: 869 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= 47452 (~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= 749 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.113+g147c73293"},"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: 869 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= 14192 (~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= 749 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: 3.73s** + +````` +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25","serverInfo":{"name":"ripwire","version":"0.6.10-dev.113+g147c73293"},"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: 20711 more bytes on this line] +"_index":"[index: files=4852 symbols=45032 hash=2e70d871]","_fresh":"ok"}} +{"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"" - : ""; - // EXTENT HONESTY (src/extentsuspect.h): how many definitions carry extent_suspect= corpus-wide — the header's - // extent_suspect_syms= — and the row + header readings, appended ONLY when that is non-zero, so a corpus with - // nothing flagged keeps every byte of this legend. - // MODULE-SCOPE OWNERS (issue #60): the t="modscope" kind's reading, appended ONLY when the corpus - // actually has one, under the same byte-identity rule as the two clauses below — a corpus with no - // file-scope call keeps every byte of this legend, which is what kept test/printf_parity.manifest's - // --pack-signatures and --around hashes and every est_tokens ceiling where they were. - bool hasModuleScope = false; - for( const Symbol& sym : ing.symbols ) +template +inline MapFileGroups groupMapRowsByFile( const IngestResult& ing, const MapAnnotations& ann, std::span kept, MapEmitOrder emitOrder, + const std::vector& outOff, const std::vector& outTargets, const PathRel& pathRel ) +{ + MapFileGroups groups; + groups.buckets.resize( ing.files.size() ); + std::vector shownFile( ing.files.size(), 0 ); // exactly the printed groups + for( const NodeId id : kept ) { - if( sym.kind == SymKind::ModuleScope ) { hasModuleScope = true; break; } + const std::uint32_t f = ing.symbols[ id ].fileId; + if( !shownFile[ f ] ) + { + shownFile[ f ] = 1; + groups.fileOrder.push_back( f ); + } + groups.buckets[ f ].push_back( id ); } - if( hasModuleScope ) + groups.stemPick = pickMapStemRows( ing, ann, groups.buckets, groups.fileOrder ); + if( mapInventoryWanted( ing, ann ) ) { - legend += kModScopeMapLegend; + groups.inventory = computeMapInventory( ing, outOff, outTargets, shownFile, pathRel ); } - // lane L6: a edge's reading, under the same absent-at-zero rule over the rows WRITTEN (fix round 1, N1): only - // when a kept row or an inventory entry has a one-implementor edge — never because one exists elsewhere in the graph - if( outProv != nullptr && !stubbed - && ( markedOutAny( outOff, *outProv, std::span( order.data(), std::min( keep, order.size() ) ), kProvImpl ) - || markedOutAny( outOff, *outProv, std::span( inventory.entries.data(), inventory.entries.size() ), kProvImpl ) ) ) + putMapGroupsInEmitOrder( ing, emitOrder, groups.buckets, groups.fileOrder ); + return groups; +} + +// The header's honesty gauges, counted once. Each one decides BOTH its header attribute (absent at 0) and, on the XML map, +// the legend clause that defines it — the two can no longer disagree on whether the gauge fired. +// ambiguous = the resolver guessed among >1 in-repo def (read source); unresolved = the callee name IS defined in-repo but +// EVERY def was language-filtered — a plausibly-internal, cross-language-filtered edge (NOT counted for genuine externals like +// stdlib/third-party, whose name has no in-repo def at all). +struct MapHonestyGauges +{ + std::size_t ambiguous = 0; // calls the resolver could not pin to one target + std::size_t unresolved = 0; // calls to an in-repo name, all defs lang-filtered + std::size_t localityPinned = 0; // Phase 4: calls the locality prior ALONE pinned + std::size_t external = 0; // Phase 5: calls refused as bound outside the tree + std::size_t declined = 0; // calls tier 3 declined: no edge, and no guess + std::size_t declinedByGate = 0; // of declined, the builtin-method name gate's + std::size_t declinedByStdMember = 0; // of declined, the standard-member gate's + std::size_t declinedInert = 0; // of declined, the Elixir call candidates inside inert quote AST (#380) + std::size_t extentSuspectSyms = 0; // definitions carrying extent_suspect= (src/extentsuspect.h) + std::size_t macroBlankedFiles = 0; // files whose symbols come from a member-macro re-parse (src/macroreparse.h) + std::size_t nestRefusedFiles = 0; // #157: files the nesting guard refused +}; + +// The graph's resolver counters as an emitter receives them (graph.h g.ambOut / unresolvedOut / locPinOut / declinedOut and +// the call totals); nullptr ⇒ never measured, which reads as zero (counterTotal). +struct MapResolverCounters +{ + const std::vector* ambOut = nullptr; + const std::vector* unresolvedOut = nullptr; + const std::vector* locPinOut = nullptr; + const std::vector* declinedOut = nullptr; + std::size_t externalCalls = 0; + std::size_t gateDeclinedCalls = 0; + std::size_t stdMemberDeclined = 0; + std::size_t inertDeclinedCalls = 0; +}; + +inline MapHonestyGauges countMapHonestyGauges( const IngestResult& ing, const MapResolverCounters& c ) +{ + std::size_t extentSuspect = 0; + for( const Symbol& sym : ing.symbols ) { - legend += ""; + extentSuspect += sym.extentSuspect != 0 ? 1u : 0u; } - // honesty-small-068: the Go named-type kinds' clause, under the same absent-at-zero rule as modscope's above; index-alias-const: - // a C++ (and .h) alias or function-type row (LangFacts::aliasTargetDefs) reads its own clause, so neither language's row is - // explained by the other's - const auto namedTypeKind = []( const Symbol& sym ) { return sym.kind == SymKind::NamedType || sym.kind == SymKind::Alias || sym.kind == SymKind::FuncType; }; - if( std::any_of( ing.symbols.begin(), ing.symbols.end(), [&]( const Symbol& sym ) { return namedTypeKind( sym ) && !langFacts( sym.lang ).aliasTargetDefs; } ) ) + return MapHonestyGauges{ .ambiguous = counterTotal( c.ambOut ), + .unresolved = counterTotal( c.unresolvedOut ), + .localityPinned = counterTotal( c.locPinOut ), + .external = c.externalCalls, + .declined = counterTotal( c.declinedOut ), + .declinedByGate = c.gateDeclinedCalls, + .declinedByStdMember = c.stdMemberDeclined, + .declinedInert = c.inertDeclinedCalls, + .extentSuspectSyms = extentSuspect, + .macroBlankedFiles = macroBlankedFileCount( ing ), + .nestRefusedFiles = ing.crawlSkips.nestRefusedFiles }; +} + +// Whether in=DIR's stub (MapAnnotations::stubSymbols) replaces the symbol rows. The XML map honours it; the JSON map has no +// stub spelling and always prints its rows. Named once, at the planMap call, so neither dialect re-reads the flag. +enum class MapStubPolicy : std::uint8_t +{ + HonourAnnotation, + AlwaysPrintRows, +}; + +// WHAT a map prints, decided once for both dialects (planMap): the row cap, the rank order, the byte model, the emit order, +// the file groups, the honesty gauges and the shown= count. Each dialect then only spells the plan. +struct MapPlan +{ + bool stubbed = false; // C1-b: in=DIR's stub prints no symbol row (MapStubPolicy) + std::size_t symbolCount = 0; // symbols=: the symbols the map ranks (mapSymbolCount), counted once per map + std::size_t keep = 0; // the top-K cut; under the stub, the would_show= it would have printed + RankedMapRows ranked; // empty under the stub + TokenEstimate mapEst; // the byte MODEL: the T3 order oracle and the bytes/token rate (§H7) + MapEmitOrder emitOrder = MapEmitOrder::ImportantFirst; + MapFileGroups groups; // empty under the stub + MapHonestyGauges gauges; + std::size_t shown = 0; // shown=: the kept rows plus the stem rows; 0 under the stub + + // the rows inside the top-K cut (none under the stub) + std::span kept() const noexcept { return ranked.kept( keep ); } +}; + +template +inline MapPlan planMap( const IngestResult& ing, const std::vector& rank, const std::vector& outOff, const std::vector& outTargets, + const MapAnnotations& ann, int topK, const MapOrderRequest& asked, const MapResolverCounters& counters, MapStubPolicy stubPolicy, + const PathRel& pathRel ) +{ + MapPlan plan; + plan.stubbed = stubPolicy == MapStubPolicy::HonourAnnotation && ann.stubSymbols; + plan.symbolCount = mapSymbolCount( ing ); + plan.keep = mapKeepCount( plan.symbolCount, topK ); + if( !plan.stubbed ) + { + plan.ranked = rankMapRows( ing, rank, ann, plan.keep ); + } + // T1/§H7: the byte MODEL. It decides the T3 emit order (which has to be decided before any byte exists — see §H7 at + // estimateTokens) and supplies the language-weighted bytes/token RATE, the half of it that is actually measured. It no + // longer REPORTS the size: each dialect measures est_tokens from its emitted bytes, because a model of the symbol set cannot + // see --metrics decoration or an appended payload. C1-b: under the stub the estimate is taken over no rows. + plan.mapEst = estimateTokens( ing, plan.ranked.order, plan.kept().size(), outOff, outTargets ); + plan.emitOrder = decideMapEmitOrder( asked, plan.mapEst.tokens ); + // Stable is the one order whose traits carry stablePrefix (emitOrderTraits), so every downstream --stable choice that reads + // the trait reads exactly the flag the caller passed. + ASSUME( ( plan.emitOrder == MapEmitOrder::Stable ) == asked.stable, "decideMapEmitOrder returns Stable exactly when --stable was asked" ); + if( !plan.stubbed ) + { + plan.groups = groupMapRowsByFile( ing, ann, plan.kept(), plan.emitOrder, outOff, outTargets, pathRel ); + } + plan.gauges = countMapHonestyGauges( ing, counters ); + plan.shown = plan.stubbed ? 0 : plan.keep + plan.groups.stemPick.rows.size(); + ASSUME( !plan.stubbed || ( plan.ranked.order.empty() && plan.groups.fileOrder.empty() && plan.groups.inventory.entries.empty() ), + "the stub ranks and groups no row, so no kept-row legend clause and no group can fire under it" ); + return plan; +} + +// The per-symbol facts a map row may print, gathered once from the emitter's parameters. Read-only; a nullptr source means +// that attribute is never printed. +struct MapRowSources +{ + const std::vector& rank; + const std::vector& outOff; + const std::vector& outTargets; + const std::vector* outProv; + const std::vector* outNameOnly; + const std::vector* ambOut; + const std::vector* locPinOut; + const SparseLabels* bind; + MapEmitOrder emitOrder; // k= is absent on --stable's byte-stable prefix (emitOrderTraits().stablePrefix) + bool metrics; // --metrics: the descriptive Q-compute attributes + const std::vector* fanIn; + const std::vector* cbo; + const std::vector* tested; + const std::vector* lcom4; + const std::vector* amp; +}; + +// ── the XML map's legend, as its ordered clause groups ─────────────────────────────────────────────────────────────── +// §H7: the legend is COMPOSED into a string rather than streamed, because est_tokens can only be written once the document it +// describes has been measured (PHASE 2 in serialize()) and the legend's own bytes are part of what it describes. Every clause +// after the opening dictionary follows one rule: it is appended ONLY when the document carries what it defines, so a map with +// nothing to disclose keeps every byte of the legend. + +// The opening dictionary. The prov= clause is appended ONLY under --scip (outProv present) so the default header stays +// byte-identical to the pre-overlay output (no golden churn); prov="scip" marks a SCIP-pinned precise edge. +// §A8.7: shown= (in the stats comment) counts overload-MERGED rows individually — rows + Σ(overloads-1) == shown — and +// overloads= (overloadsAttr()) is defined here, the one clause that closes that arithmetic for a reader who has only the map. +inline std::string mapOpeningLegend( bool withProv ) +{ + return withProv + ? "" + : ""; +} + +// MODULE-SCOPE OWNERS (issue #60): the t="modscope" kind's reading, ONLY when the corpus actually has one — a corpus with no +// file-scope call keeps every byte of this legend, which is what kept test/printf_parity.manifest's --pack-signatures and +// --around hashes and every est_tokens ceiling where they were. +inline std::string_view moduleScopeLegend( const IngestResult& ing ) noexcept +{ + for( const Symbol& sym : ing.symbols ) + { + if( sym.kind == SymKind::ModuleScope ) + { + return kModScopeMapLegend; + } + } + return {}; +} + +// lane L6: a edge's reading, over the rows WRITTEN (fix round 1, N1): only when a kept row or an inventory entry +// has a one-implementor edge — never because one exists elsewhere in the graph. +inline std::string keptImplEdgeLegend( const std::vector& outOff, const std::vector* outProv, + std::span kept, std::span inventoryEntries ) +{ + if( outProv == nullptr ) { - legend += kNamedTypeMapLegend; + return {}; } - if( std::any_of( ing.symbols.begin(), ing.symbols.end(), [&]( const Symbol& sym ) { return namedTypeKind( sym ) && langFacts( sym.lang ).aliasTargetDefs; } ) ) + if( markedOutAny( outOff, *outProv, kept, kProvImpl ) || markedOutAny( outOff, *outProv, inventoryEntries, kProvImpl ) ) { - legend += kCppAliasMapLegend; + return ""; } + return {}; +} - std::size_t extentSuspectTotal = 0; - for( const Symbol& sym : ing.symbols ) +// honesty-small-068: the Go named-type kinds' clause; index-alias-const: a C++ (and .h) alias or function-type row +// (LangFacts::aliasTargetDefs) reads its own clause, so neither language's row is explained by the other's. Each only when +// the corpus has such a row. +inline std::string typeKindLegend( const IngestResult& ing ) +{ + const auto namedTypeKind = []( const Symbol& sym ) { return sym.kind == SymKind::NamedType || sym.kind == SymKind::Alias || sym.kind == SymKind::FuncType; }; + std::string clauses; + if( std::any_of( ing.symbols.begin(), ing.symbols.end(), [ & ]( const Symbol& sym ) { return namedTypeKind( sym ) && !langFacts( sym.lang ).aliasTargetDefs; } ) ) { - extentSuspectTotal += sym.extentSuspect != 0 ? 1u : 0u; + clauses += kNamedTypeMapLegend; } - if( extentSuspectTotal > 0 ) + if( std::any_of( ing.symbols.begin(), ing.symbols.end(), [ & ]( const Symbol& sym ) { return namedTypeKind( sym ) && langFacts( sym.lang ).aliasTargetDefs; } ) ) { - legend += kExtentSuspectRowLegend; - legend += kExtentSuspectHdrLegend; + clauses += kCppAliasMapLegend; } - // MEMBER-MACRO RE-PARSE (src/macroreparse.h): files whose symbols come from a re-parse — the header's - // macro_blanked_files= — and its reading, appended ONLY when non-zero, under the same byte-identity rule. - const std::size_t macroBlankedFiles = macroBlankedFileCount( ing ); - if( macroBlankedFiles > 0 ) + return clauses; +} + +// Which legend clause defines which gauge, as data: a clause is charged only to the map whose header carries its gauge (> 0). +struct GaugeClause +{ + std::size_t MapHonestyGauges::* gauge; + std::string_view clause; +}; + +inline std::string gaugeLegend( const MapHonestyGauges& gauges, std::span table ) +{ + std::string clauses; + for( const GaugeClause& row : table ) { - legend += kMacroBlankedHdrLegend; + if( gauges.*row.gauge > 0 ) + { + clauses += row.clause; + } } - // #157: a file the nesting guard refused before this map was built — the header's nest_refused=, same - // absent-when-zero rule, charged only to the map that carries the attribute. - if( ing.crawlSkips.nestRefusedFiles > 0 ) + return clauses; +} + +// The parse-honesty gauges' clauses: EXTENT HONESTY (src/extentsuspect.h; the row and the header reading), MEMBER-MACRO +// RE-PARSE (src/macroreparse.h) and #157's nest_refused=. +inline constexpr GaugeClause kParseHonestyClauses[] = { + { &MapHonestyGauges::extentSuspectSyms, kExtentSuspectRowLegend }, + { &MapHonestyGauges::extentSuspectSyms, kExtentSuspectHdrLegend }, + { &MapHonestyGauges::macroBlankedFiles, kMacroBlankedHdrLegend }, + { &MapHonestyGauges::nestRefusedFiles, kNestRefusedMapLegend }, +}; + +// The tier-3 decline clauses: declined=, then the builtin-method gate's, the standard-member gate's and the Elixir quote's share. +inline constexpr GaugeClause kDeclineClauses[] = { + { &MapHonestyGauges::declined, kDeclinedMapLegend }, + { &MapHonestyGauges::declinedByGate, kDeclinedGateMapLegend }, + { &MapHonestyGauges::declinedByStdMember, kDeclinedStdMapLegend }, + { &MapHonestyGauges::declinedInert, kInertDeclinedMapLegend }, +}; + +// M20: the seeded-verb clause, emitted only on a seeded map (see MapAnnotations::SeedDisclosure). +inline std::string seedLegend( const MapAnnotations::SeedDisclosure& seed ) +{ + if( seed.of.empty() ) { - legend += kNestRefusedMapLegend; + return {}; } - // R-E fix (2026-08-19): root= was added to with nothing defining it — legendcoveragecheck's arm (A) - // named it on nine roster verbs at once (the default map, --around, and every map-* variant share this - // legend). Spelled in THIS legend's own key=meaning dialect rather than as the prose sentence - // graphlegend.h's kRootRelPathsLegend carries: the map legend is the one first screen every run pays for, - // and its whole style is one compact token per attribute. Conditional, so a multi-root map — which emits - // no root= — stays byte-identical and no golden moves for a document the clause would not describe. + std::string clauses = ""; + if( seed.reflang != nullptr ) // D4: the FULL dialect's definition for the anchor pair — legendcoveragecheck (A) flags the --legend=full row when the seed stanza is silent, + { + clauses += std::string( ""; // charged only when the row carries the attributes (seedBiteLegend's rule); kept short, the verb dict defines the pair in full + } + clauses += seedBiteLegend( seed ); // C2: charged only on a run whose root carries a bite attribute (the at= rule) + // H1: charged only on a run whose root carries unproven_defs= — the same rule, and part of the head est_tokens prices. + clauses += unprovenDefsVerbComment( UnprovenDefsVerb::Around, seed.unprovenDefs > 0, ""; + clauses += ""; } - if( churnWindow != nullptr ) + if( ann.churnWindow != nullptr ) { - legend += churnRankLegendFor( ann.churnRankLabel ); // §A9.6 / P0-4, churn-only (see the constants) + clauses += churnRankLegendFor( ann.churnRankLabel ); // §A9.6 / P0-4, churn-only (see the constants) if( ann.scopedRecent != nullptr ) { - legend += kRecentScopeLegendOpen; // C1-b: in=DIR — the scoped block, its page, and the map stub (present-only) - legend += kNextLegendClause; - legend += kRecentScopeLegendClose; + clauses += kRecentScopeLegendOpen; // C1-b: in=DIR — the scoped block, its page, and the map stub (present-only) + clauses += kNextLegendClause; + clauses += kRecentScopeLegendClose; } } - // §B2.1: the same treatment for authority/hub/rrf. Mutually exclusive with the churn arm by construction - // (main.cpp fills exactly one of the two fields), and null on the default pagerank map ⇒ zero bytes there. + // §B2.1: the same treatment for authority/hub/rrf. Mutually exclusive with the churn arm by construction (main.cpp fills + // exactly one of the two fields), and null on the default pagerank map ⇒ zero bytes there. if( const char* rbLegend = rankByLegendFor( ann.rankByLabel ) ) { - legend += rbLegend; - } - // M20: the seeded-verb clause, emitted only on a seeded map (see MapAnnotations::SeedDisclosure). - if( !ann.seed.of.empty() ) - { - legend += ""; - if( ann.seed.reflang != nullptr ) // D4: the FULL dialect's definition for the anchor pair — legendcoveragecheck (A) flags the --legend=full row when the seed stanza is silent, - legend += std::string( ""; // charged only when the row carries the attributes (seedBiteLegend's rule); kept short, the verb dict defines the pair in full - legend += seedBiteLegend( ann.seed ); // C2: charged only on a run whose root carries a bite attribute (the at= rule) - // H1: charged only on a run whose root carries unproven_defs= — the same rule, and part of the head est_tokens prices. - legend += unprovenDefsVerbComment( UnprovenDefsVerb::Around, ann.seed.unprovenDefs > 0, "`, which turns the ENTIRE - // document into one unterminated comment. Composed on std::string, the margin question disappears. - std::string stats = ""; - return stats; - }; - // --stable: volatile counts move to a TRAILING comment (out of the cacheable prefix) — unless the caller - // asked for the first-screen placement (§B6 M10, the MCP analyze verb), in which case they stay here and - // the trailing copy is suppressed. Exactly one of the two builders emits `stats`. - const auto buildHead = [ & ]( std::size_t estTokens ) -> std::string - { - std::string h = legend; - if( estimate.isModelled ) + if( fit->isUnmeasured ) { - h += kEstModelledLegend; + attrs += " fit_unmeasured=1"; } - if( !stable || statsFirstScreen ) - { - h += buildStats( estTokens ); - } - // r26-stamp Task A: ` at="..."` ONLY when the caller passed a non-empty stamp (--map-diff); every other - // caller passes nullptr, so the hot default-map path pays a pointer compare, not a git call. at= stays - // FIRST — the `empty() ) { h += " at=\""; h += *mapAtStamp; h += "\""; } - // R-E: after at= (so gitstampcheck's ` 1 ) { h += " defs=\""; h += std::to_string( ann.seed.defs ); h += "\""; } - h += unprovenDefsAttrXml( ann.seed.unprovenDefs ); // H1: beside defs=, the rest of what the seed name resolved to - h += seedBiteAttrs( ann.seed ); // C2: each bound's BITE, right after the bound it qualifies (empty when neither bit) - if( ann.seed.reflang != nullptr ) // D4: after the bite pair, same slot logic — the anchor qualifies the whole seed stanza - { - h += " reflang=\""; h += ann.seed.reflang; - h += "\" reflang-origin=\""; h += ann.seed.reflangOrigin; h += "\""; - if( !ann.seed.nextDefs.empty() ) // the corpus tie's pasteable follow-up, beside the disclosure it belongs to — - { // the ONE next= builder the house keeps (nextverb.h, darkflags/docdrift precedents) - h += nextAttrXml( nextFlag( "--defs=", ann.seed.nextDefs ) ); - } - } + } + return attrs; +} + +// The summary preamble: counts so the agent knows the map's scope + est size. §B14 — was `char stats[480]`, one new header +// attribute away from truncating (and a cut here deletes the trailing ` -->`, which turns the ENTIRE document into one +// unterminated comment). Composed on std::string, the margin question disappears. +struct MapStatsFacts +{ + const MapPlan& plan; // symbols=, shown=, the honesty gauges and order= + std::size_t files; + std::size_t edges; + std::string_view coverageAttrs; // renderMapCoverageAttrs + mapFitAttrs +}; + +inline std::string renderMapStats( const MapStatsFacts& f, std::size_t estTokens, bool estModelled ) +{ + const auto gauge = []( std::string& out, std::string_view key, std::size_t value ) + { + if( value > 0 ) // absent when 0 — zero bytes on a corpus where the gauge never fired + { + out += key; out += std::to_string( value ); } - // §A9.6: after at= (so gitstampcheck's ` 0 ) - { - h += " data_sections_cut=\""; h += std::to_string( dataSecCut.cut ); h += "\""; - h += nextAttrXml( dataSectionsNext( dataSecCut ) ); - } - if( stemPick.cut > 0 ) - { - h += " stem_cut=\""; h += std::to_string( stemPick.cut ); h += "\""; // MAP-STEM: absent unless a --max-tokens fit left stem rows out - } - h += ">"; // K51: history_unread='s definition rides the leading legend above (HISTORY-UNREAD-LEGEND), not behind this tag - return h; }; - const auto buildTail = [ & ]( std::size_t estTokens ) -> std::string + const MapHonestyGauges& g = f.plan.gauges; + std::string stats = ""; + return stats; +} + +// M20: the seeded-verb stanza on , after root= and before the ranker attributes. Absent (and therefore byte-free) on every +// map that had no seed. +inline std::string seedRootAttrs( const MapAnnotations::SeedDisclosure& seed, std::vector& esc ) +{ + if( seed.of.empty() ) { - return ( stable && !statsFirstScreen ) ? buildStats( estTokens ) : std::string{}; - }; - - // ── PHASE 1: render 's CHILDREN into a buffer ──────────────────────────────────────────────────── - // §H7: est_tokens must charge the bytes the document actually carries, not a model of the symbol set — - // the model prices neither --metrics decoration nor an appended payload, which is how one number came to - // stand for five documents. So: measure, decide, then write (the order --recall's emitRecallBudgeted and - // the --for lens's pre-rendered sigs block already impose on themselves). - // - // DEGRADE: an open_memstream failure keeps the whole map — the head goes out FIRST carrying the MODELLED - // estimate (the pre-§H7 number, so this path is no worse than the old behaviour, never a fabricated one) - // and the children stream straight to `out` behind it. - rw::MemoryStream childStream; - std::FILE* const childMem = openChargeStream( childStream ); - if( !childMem ) + return {}; + } + std::string h; + h += " of=\""; h += escapeXml( seed.of, esc ); h += "\""; + h += " depth=\""; h += std::to_string( seed.depth ); h += "\""; + h += " fanout=\""; h += std::to_string( seed.fanout ); h += "\""; + if( seed.defs > 1 ) { h += " defs=\""; h += std::to_string( seed.defs ); h += "\""; } + h += unprovenDefsAttrXml( seed.unprovenDefs ); // H1: beside defs=, the rest of what the seed name resolved to + h += seedBiteAttrs( seed ); // C2: each bound's BITE, right after the bound it qualifies (empty when neither bit) + if( seed.reflang != nullptr ) // D4: after the bite pair, same slot logic — the anchor qualifies the whole seed stanza { - DISCLOSE( estimate, MapEstimate::DisclosureWhy::ChargeBufferFailed, "serialize: open_memstream failed — est_tokens reports the MODELLED bytes, not the emitted ones" ); + h += " reflang=\""; h += seed.reflang; + h += "\" reflang-origin=\""; h += seed.reflangOrigin; h += "\""; + if( !seed.nextDefs.empty() ) // the corpus tie's pasteable follow-up, beside the disclosure it belongs to — + { // the ONE next= builder the house keeps (nextverb.h, darkflags/docdrift precedents) + h += nextAttrXml( nextFlag( "--defs=", seed.nextDefs ) ); + } } + return h; +} - const std::size_t modelledTokens = mapEstTokens + extraPayloadTokens; - // The children, as ONE renderer both paths call. This was inline code writing through a writer bound to "the buffer, - // or `out` when the buffer could not open". That serves a failed open, and cannot serve a buffer that opened and then - // lost a write: by then the children were already spent into it, and the only bytes left to print had a hole in them. - std::vector hedgedScratch; // FE-B: writeMapCalleeRows' reused buffer - const auto writeChildren = [ & ]( XmlWriter& w ) +// What the root tag states besides est_tokens: the provenance stamp in front, the row-selection disclosures behind. +struct MapRootFacts +{ + const MapAnnotations& ann; + std::string_view rootArg; + const MapPlan& plan; // the byte-stable prefix (emit order), data_sections_cut= and stem_cut= +}; + +inline std::string renderMapRootTag( const MapRootFacts& r, std::size_t estTokens, bool estModelled, std::vector& esc ) +{ + const MapAnnotations& ann = r.ann; + const bool stablePrefix = emitOrderTraits( r.plan.emitOrder ).stablePrefix; + // r26-stamp Task A: ` at="..."` ONLY when the caller passed a non-empty stamp (--map-diff); every other caller passes + // nullptr, so the hot default-map path pays a pointer compare, not a git call. at= stays FIRST — the `empty() ) { h += " at=\""; h += *ann.atStamp; h += "\""; } + // R-E: after at= (so gitstampcheck's ` 0 ) + { + h += " data_sections_cut=\""; h += std::to_string( cut.cut ); h += "\""; + h += nextAttrXml( dataSectionsNext( cut ) ); + } + if( const std::size_t stemCut = r.plan.groups.stemPick.cut; stemCut > 0 ) + { + h += " stem_cut=\""; h += std::to_string( stemCut ); h += "\""; // MAP-STEM: absent unless a --max-tokens fit left stem rows out + } + h += ">"; // K51: history_unread='s definition rides the leading legend (HISTORY-UNREAD-LEGEND), not behind this tag + return h; +} + +// ── the XML map's rows ─────────────────────────────────────────────────────────────────────────────────────────── + +// amb= (≤ 17 B) then lpin= (≤ 18 B), each absent when 0: "fast guessed K of this symbol's call targets — read source", then +// the disclosed locality pin (Phase 4). The cursor is the OUT POINTER, never a would-have-written length: lpin= is written AT +// the offset the first write ended, so a count an implementation computed rather than wrote would place it inside the +// half-written amb= attribute. Same defect class as BoundedAttrRun below. +inline std::string rowResolverGuessAttrs( const MapRowSources& src, NodeId id ) +{ + char ambs[ 48 ]; ambs[ 0 ] = '\0'; + char* ap = ambs; + char* const ae = ambs + sizeof( ambs ); + if( const std::uint32_t ambK = counterAt( src.ambOut, id ); ambK > 0 ) + { + ap = std::format_to_n( ap, ( ae - ap ) - 1, " amb=\"{}\"", ambK ).out; + *ap = '\0'; + } + if( const std::uint32_t lpinK = counterAt( src.locPinOut, id ); lpinK > 0 ) + { + ap = std::format_to_n( ap, ( ae - ap ) - 1, " lpin=\"{}\"", lpinK ).out; + *ap = '\0'; + } + return ambs; +} + +// PageRank k= is GLOBALLY volatile (any edit perturbs every rank) → omitted on --stable's byte-stable prefix so the prefix stays +// byte-identical for unedited files (provider KV-cache hits). Default keeps k=. +inline std::string rowRankAttr( const MapRowSources& src, NodeId id ) +{ + char kbuf[ 24 ]; kbuf[ 0 ] = '\0'; + if( !emitOrderTraits( src.emitOrder ).stablePrefix ) + { + rw::formatTo( kbuf, sizeof( kbuf ), " k=\"{:.4f}\"", double( src.rank[ id ] ) ); + } + return kbuf; +} + +// A fixed attribute buffer that truncates the way snprintf did, byte for byte. A4-F8: snprintf returns the WOULD-HAVE-written +// length; on truncation `qp += ret` pushed qp PAST the end, then the next size_t(qe-qp) underflowed to a huge size → unbounded +// stack write. So every append is bound by the OUT POINTER, never by a would-have-written length: std::format_to_n's `out` is +// clamped to the n it was given on any implementation; its `size` is a would-have-written count an implementation can get +// wrong. n is (end-qp)-1 so the NUL always lands in bounds — snprintf's "at most S-1 characters plus a terminator". +// +// The obvious-looking rewrite — `qp = std::format_to_n( qp, qe - qp, ... ).out` — is WRONG, and wrong in a way no fixture +// catches: format_to_n( p, S, ... ) writes up to S and terminates nothing. It buys one extra byte of room and drops the +// terminator. Measured 2026-09-09: that version emitted a row carrying amp="1" where every previous release truncated it away, +// on test/ as the corpus — only a differential run against the pre-conversion binary on a REAL tree exposed it. +// std::format_string keeps -Wformat-security's compile-time checking through the member template. +// +// 96 -> 160 (Phase 1, local-variable-indexing, docs/LOCALS_INDEXING.md): the fn/method worst case grew by locals="4294967295" +// locals_floor="1" (38 B) on top of the pre-existing loc+params+nest+cbo+amp+tested run (~88 B) — 96 would silently TRUNCATE +// (safe from a buffer-overrun standpoint, but a truncated attr run is malformed XML, not a degrade worth shipping quietly). +// 160 -> 192 (ppalt disclosure): ppalt="65535" (+14 B) put the summed fn/method worst case within a rounding error of 160; 192 +// restores the same real headroom. The fn/method group and lcom4 are mutually exclusive, so the size covers ONE group's worst case. +class BoundedAttrRun +{ +public: + BoundedAttrRun() noexcept { buf_[ 0 ] = '\0'; } + BoundedAttrRun( const BoundedAttrRun& ) = delete; + BoundedAttrRun& operator=( const BoundedAttrRun& ) = delete; + + template + void append( std::format_string fmt, A&&... args ) { - // §P8 collision: this prologue spelled its LABEL `l=`, the two characters 22 other sites use for a LINE - // NUMBER — including the rows just below. Renamed: the label had exactly two references in the - // tree (both updated here) against 15+ readers of the line-number meaning that must not move. - if( ing.rootLabels.size() >= 2 ) - { // A13 prologue: label → root path, canonical order - for( std::size_t r = 0; r < ing.rootLabels.size(); ++r ) - { - w.write( "" ); - } - } - writeRecentRows( w, ann, pathRel, esc ); // F3: rank_by=churn-decay's file-level answer, before the symbol map - // C1-b: under in=DIR the symbol map is a DISCLOSED stub (docs/METHODOLOGY.md §9.3) — the caller asked for DIR's - // recent files, not the map. - // - // NOT total=/shown=, which is what this first shipped as. Under pageview.h's vocabulary total= is THE TOTAL - // (rule 2) and capped= always rides beside a shown= (rule 3), and the stub had neither property: it printed - // total="200" — the --top-k PAGE SIZE — on a document whose own header says symbols="18457", with no capped=, - // so the one number it carried was the one number it was not allowed to mean. The stub is not a page of the map - // and it must not borrow the page vocabulary to say so. It says what it IS instead: - // stubbed="1" the symbol map was not rendered at all (the loop walks an empty order below) - // would_show="N" `keep` — the un-stubbed header's own shown=, and shown= counts symbol DEFINITIONS - // individually, not printed rows: the print loop runs collapseOverloadRows() per file - // bucket, so a const/non-const pair that both make the top-K cut prints ONE row carrying - // overloads=2. The row count therefore FOLLOWS from the identity the map legend already - // publishes for shown= — rows+sum(overloads-1)=shown — rather than being reported here. - // Measured on this repo 2026-09-14: shown=200, 193 rows, 7 at overloads=2, 193+7=200. - // IT IS A DEFINITION COUNT AND NOT A CEILING, by owner decision 2026-09-14, and the - // reason is vocabulary: in this tool a floor/ceiling marker means "we could not see - // everything" (counts_floor=, _capped, the truncation disclosures). would_show is EXACT; - // what differs from a reader's guess is the UNIT. Spending an uncertainty marker on a - // unit difference would make "ceiling" mean "exact, but not in the unit you assumed" and - // weaken every honest use of the word elsewhere in the output. Naming the quantity is - // also the stronger claim: a ceiling cannot be inverted, while a definition count plus - // the published identity yields the rows. Reporting post-collapse rows instead — the - // review's original ask — is not available at this site for any price worth paying: - // which definitions survive the cut is a fact about the RANKING, and not ranking is the - // whole point of the stub (no pr_iters= rides its header). Not the corpus total either - // (that is symbols=), so the three cannot be read as each other. - // test/recentscopecheck.sh arms 14a/14b pin the arithmetic. - // Rule 3's own sentence sanctions the shape: "If a verb emits no shown=, it emits no capped= either." - if( ann.stubSymbols ) - { - std::string stub = "( args )... ).out; + *at_ = '\0'; } - static const std::vector kNoFiles; - for( std::uint32_t f : ann.stubSymbols ? kNoFiles : fileOrder ) - { - w.write( "" ); + } + const char* c_str() const noexcept { return buf_; } - // §P6.3: see collapseOverloadRows() above — const/non-const overload pairs are already folded to - // one representative row per (kind,id) before this loop runs, so the loop body below is unchanged - // shape (no added branch): it just iterates a shorter vector. - const OverloadRows rows = overloadRowsFor( ing, buckets[f], metrics ); // --metrics: one row per definition +private: + char buf_[ 192 ]; + char* at_ = buf_; +}; - for( std::size_t i = 0; i < rows.id.size(); ++i ) - { - const NodeId id = rows.id[i]; - const Symbol& s = ing.symbols[id]; - const std::uint32_t out = outOff[id + 1] - outOff[id]; - w.write( " verbatim — 942 of 942 scoped rows on this tree - // repeated it, 11.2% of a flagless map. The row now prints ONLY the segment the wrapper does not - // carry: sc= the enclosing scope. The legend states the composition (id = p::sc::n), the selectors - // keep accepting the composed spelling, and test/scroundtripcheck.sh proves the composed multiset is - // byte-identical to the id= multiset this row used to print. Emitted ONLY when a scope exists — - // exactly when the canonical id differed from the bare name (canonicalId degrades to the name on an - // empty scope), so the row set that carries an identity attribute is unchanged. - writeScopeAttr( w, s, esc ); - if( !stemRows.empty() && std::ranges::binary_search( stemRows, id ) ) - { - w.write( " stem=\"1\"" ); // MAP-STEM: the file's stem-namesake type, added below the top-K cut - } +// A function or method row's SHAPE attributes, --metrics only: params= (a floor when countParams saturated), nest= and its +// profile, steer=/tangle=, locals=, ppalt=. Only fns/methods carry them, so a class/sec never carries a 0 it can't have. +inline void appendFnShapeAttrs( BoundedAttrRun& run, const Symbol& s ) +{ + run.append( " params=\"{}\"", unsigned( s.params ) ); + if( s.params == std::numeric_limits::max() ) + { + run.append( " params_floor=\"1\"" ); // CR #586: countParams saturates at the field width, so this count is a floor + } + run.append( " nest=\"{}\"", unsigned( s.maxNest ) ); + // The nesting PROFILE beside the max (model.h Symbol::humps/deepLoc). nest= alone cannot distinguish a long run of shallow + // scoped steps from a body that sustains depth. Omitted, never a bare 0, when no region reached quality::kNestBar: that is + // exactly nest < kNestBar, which the row already carries, so absence is lossless rather than a truncation + // (test/nestprofilecheck.sh arm 5 pins the equivalence in both directions). + if( s.humps > 0 ) + { + run.append( " humps=\"{}\" deep=\"{}\" deep_floor=\"1\"", unsigned( s.humps ), unsigned( s.deepLoc ) ); + } + run.append( "{}", tangleMetricAttrs( s, /*json=*/false ) ); // QD-TANGLE: steer= / tangle=, each absent at 0 + // Phase 1 (local-variable-indexing, docs/LOCALS_INDEXING.md): locals= is ABSENT — never a bare "0" — for every def outside + // model.h's localsCountedLang (MVP: C/C++ only), so a reader never mistakes "not counted for this language" for "counted, + // and there are none". locals_floor="1" always rides alongside a present locals=: `int a,b;` counts as ONE + // declaration-statement, not two names (see cc_isCountableLocalDecl's own comment). + if( localsCountedLang( s.lang ) ) + { + run.append( " locals=\"{}\" locals_floor=\"1\"", unsigned( s.locals ) ); + } + // ppalt disclosure: the body carries preproc branches that never coexist at compile time, so this row's structural metrics + // are sums over ALL of them (model.h Symbol::ppAlt). ABSENT when 0 — presence itself is the signal. + if( s.ppAlt > 0 ) + { + run.append( " ppalt=\"{}\"", unsigned( s.ppAlt ) ); + } +} - w.write( overloadsAttr( rows.overloads[i] ) ); // see overloadsAttr() above — empty in the common case - w.write( splitLineAttr( rows, i, s ) ); // --metrics per-definition rows only +// The Q-compute descriptive attributes (loc/params/nest/locals/cbo/lcom4/amp/tested), --metrics only — facts, never gates. +// loc first (SIZE is the master variable); lcom4 only for class-kinds with methods (kLcom4NA = 0xFFFFFFFF omits); tested only +// when 1 (lean output). +inline void appendQMetricAttrs( BoundedAttrRun& run, const Symbol& s, NodeId id, const MapRowSources& src ) +{ + if( s.loc > 0 ) + { + run.append( " loc=\"{}\"", s.loc ); + } + if( s.kind == SymKind::Function || s.kind == SymKind::Method ) + { + appendFnShapeAttrs( run, s ); + } + if( src.cbo && id < src.cbo->size() ) + { + run.append( " cbo=\"{}\"", ( *src.cbo )[ id ] ); + } + if( src.lcom4 && id < src.lcom4->size() && ( *src.lcom4 )[ id ] != 0xFFFFFFFFu ) + { + run.append( " lcom4=\"{}\"", ( *src.lcom4 )[ id ] ); + } + if( src.amp && id < src.amp->size() ) + { + run.append( " amp=\"{}\"", ( *src.amp )[ id ] ); + } + if( src.tested && id < src.tested->size() && ( *src.tested )[ id ] ) + { + run.append( " tested=\"1\"" ); + } +} - // A4-R5: bind="pkg.Cls.method" — the decoded JNI binding label (graph.h g.bindLabel), when this - // symbol has one. Unconditional (not --metrics-gated): it is an identity fact like id=, not a - // descriptive stat. Omitted whenever bind is nullptr or the per-symbol label is empty (the - // overwhelming common case) → zero token cost, byte-identical golden map on non-JNI corpora. - if( const std::string_view label = bind ? bind->labelOf( id ) : std::string_view{}; !label.empty() ) - { - w.write( " bind=\"" ); w.write( escapeXml( label, esc ) ); w.write( "\"" ); - } +// The row's --metrics run (only with fan-in): in=/out=/cx=/ccx=, role="hub" at fan-in ≥ 8, then the Q-compute run. +// EQUIVALENCE (GE-SERIALIZE round 2): this run, amb=/lpin= and k= used to share one attr[352] buffer, so a run past its width +// would have truncated across all three. None ever did: the widest is 26 B of literal + 4 × 10 digits + 11 B role + the +// BoundedAttrRun's 191 + amb=/lpin=' 35 + k=' 23 = 326 B < 351 (test/fixedbufsweep.sh's attr row), so writing the three as +// separate writes is byte-identical — and this buffer alone now has 83 B of headroom. +inline std::string rowMetricsAttrs( const Symbol& s, NodeId id, const MapRowSources& src ) +{ + if( !src.metrics || !src.fanIn ) + { + return {}; + } + BoundedAttrRun qmetrics; + appendQMetricAttrs( qmetrics, s, id, src ); + const std::uint32_t in = ( id < src.fanIn->size() ) ? ( *src.fanIn )[ id ] : 0u; + const std::uint32_t outDegree = src.outOff[ id + 1 ] - src.outOff[ id ]; + char attr[ 352 ]; + rw::formatTo( attr, sizeof( attr ), " in=\"{}\" out=\"{}\" cx=\"{}\" ccx=\"{}\"{}{}", + in, outDegree, s.cx, s.ccx, ( in >= 8 ? " role=\"hub\"" : "" ), qmetrics.c_str() ); + return attr; +} - char ambs[ 48 ]; ambs[ 0 ] = '\0'; // "fast guessed K of this symbol's call targets — read source" - // amb= (≤ 17 B) then lpin= (≤ 18 B) in ONE buffer, each absent when 0. The cursor is the OUT - // POINTER, never a would-have-written length: lpin= is written AT the offset the first write - // ended, so a count an implementation computed rather than wrote would place it inside the - // half-written amb= attribute. Same defect class as the appendf clamps below. - char* ap = ambs; - char* const ae = ambs + sizeof( ambs ); - if( const std::uint32_t ambK = counterAt( ambOut, id ); ambK > 0 ) - { - ap = std::format_to_n( ap, ( ae - ap ) - 1, " amb=\"{}\"", ambK ).out; - *ap = '\0'; - } - if( const std::uint32_t lpinK = counterAt( locPinOut, id ); lpinK > 0 ) // Phase 4: the disclosed locality pin - { - ap = std::format_to_n( ap, ( ae - ap ) - 1, " lpin=\"{}\"", lpinK ).out; - *ap = '\0'; - } +// Essential complexity (model.h Symbol::ev), --metrics only. Emitted iff ev >= 2: ev >= 1 for any walked fn/method body, so on +// a row carrying cx= ABSENT means exactly ev == 1 — lossless, and never a bare ev="1" (G4 + the honesty contract point the +// same way). Routed through evCountedLang so an uncovered language (Bash) reads as "not counted", never "counted, 1". +// ev_floor="1" always rides along: noreturn calls, macro-hidden returns and unresolvable gotos are invisible to the syntactic +// walk and can only RAISE the true value. ev_why= is the reason breakdown that keeps §10.1-Option-A honest (a guard-heavy row +// is visibly not a knot). Composed on std::string: ev_why= is variable-length text (fixedbufsweep's rule). +inline std::string rowEssentialComplexityAttrs( const Symbol& s, bool metrics ) +{ + if( !metrics || !( s.kind == SymKind::Function || s.kind == SymKind::Method ) || !evCountedLang( s.lang ) || s.ev < 2u ) + { + return {}; + } + return " ev=\"" + std::to_string( s.ev ) + "\" ev_floor=\"1\" ev_why=\"" + evWhyString( s ) + "\""; +} - // PageRank k= is GLOBALLY volatile (any edit perturbs every rank) → omit it in --stable mode - // so the prefix stays byte-identical for unedited files (provider KV-cache hits). Default keeps k=. - char kbuf[ 24 ]; kbuf[ 0 ] = '\0'; - if( !stable ) - { - rw::formatTo( kbuf, sizeof( kbuf ), " k=\"{:.4f}\"", double( rank[id] ) ); - } +// One row and its callee rows. +inline void writeMapSymbolRow( XmlWriter& w, const IngestResult& ing, const OverloadRows& rows, std::size_t i, const std::vector& stemRows, + const MapRowSources& src, std::vector& esc, std::vector& scratch ) +{ + const NodeId id = rows.id[ i ]; + const Symbol& s = ing.symbols[ id ]; + w.write( " verbatim. The row prints ONLY the segment the wrapper does not carry: sc= the enclosing scope. The + // legend states the composition (id = p::sc::n) and test/scroundtripcheck.sh proves the composed multiset is byte-identical + // to the id= multiset this row used to print. Emitted ONLY when a scope exists. + writeScopeAttr( w, s, esc ); + if( !stemRows.empty() && std::ranges::binary_search( stemRows, id ) ) + { + w.write( " stem=\"1\"" ); // MAP-STEM: the file's stem-namesake type, added below the top-K cut + } + w.write( overloadsAttr( rows.overloads[ i ] ) ); // see overloadsAttr() above — empty in the common case + w.write( splitLineAttr( rows, i, s ) ); // --metrics per-definition rows only + // A4-R5: bind="pkg.Cls.method" — the decoded JNI binding label (graph.h g.bindLabel), when this symbol has one. Not + // --metrics-gated: it is an identity fact like id=, not a descriptive stat. Omitted whenever bind is nullptr or the label is + // empty (the overwhelming common case) → zero token cost, byte-identical golden map on non-JNI corpora. + if( const std::string_view label = src.bind ? src.bind->labelOf( id ) : std::string_view{}; !label.empty() ) + { + w.write( " bind=\"" ); w.write( escapeXml( label, esc ) ); w.write( "\"" ); + } + w.write( rowMetricsAttrs( s, id, src ) ); // --metrics: in=/out=/cx=/ccx=/role= and the Q-compute run + w.write( rowResolverGuessAttrs( src, id ) ); // amb= / lpin=, each absent at 0 + w.write( rowRankAttr( src, id ) ); // k=, absent on --stable's byte-stable prefix + // EXTENT HONESTY (kExtentSuspectRowLegend): the containment checks this row's extent/scope/kind failed. After k= so every + // pre-existing adjacency holds; absent when every check held (clean corpora unchanged). + if( s.extentSuspect != 0 ) + { + w.write( " extent_suspect=\"" ); + w.write( extent::extentSuspectReasons( s.extentSuspect ) ); + w.write( "\"" ); + } + w.write( rowEssentialComplexityAttrs( s, src.metrics ) ); + w.write( ">" ); + writeMapCalleeRows( w, ing, src.outOff[ id ], src.outOff[ id + 1 ], src.outTargets, src.outProv, src.outNameOnly, esc, scratch ); + w.write( "" ); +} - // Q-compute descriptive attrs (loc/params/nest/locals/cbo/lcom4/tested), built into a side buffer - // that is appended before the closing '>' of the metrics attr. ALL --metrics-only; absent by - // default so the golden map is byte-identical. params/nest/locals emitted only for fns/methods - // (kind guard) so a class/sec never carries a 0 it can't have; lcom4 only for class-kinds with - // methods (kLcom4NA sentinel omits) — mutually exclusive with the fn/method group, which is why - // the buffer sizing below only has to cover ONE of the two groups' worst case, not both summed. - // 96 -> 160 (Phase 1, local-variable-indexing, docs/LOCALS_INDEXING.md): the fn/method worst - // case grew by locals="4294967295" locals_floor="1" (38 B) on top of the pre-existing - // loc+params+nest+cbo+amp+tested run (~88 B) — 96 would silently TRUNCATE (appendf's qe-clamp - // makes truncation safe from a buffer-overrun standpoint, but a truncated attr run is malformed - // XML, not a degrade worth shipping quietly). 160 -> 192 (ppalt disclosure): ppalt="65535" - // (+14 B) put the summed fn/method worst case within a rounding error of 160; 192 restores the - // same real headroom over the recomputed worst case. - char qbuf[ 192 ]; qbuf[ 0 ] = '\0'; - if( metrics ) - { - char* qp = qbuf; char* const qe = qbuf + sizeof( qbuf ); - // A4-F8: snprintf returns the WOULD-HAVE-written length; on truncation `qp += ret` pushes qp - // PAST qe, then the next size_t(qe-qp) underflows to a huge size → unbounded stack write. Clamp - // qp to qe after every append (once full, further appends write nothing and stay clamped). - // fmt is always a string literal at every call site below — the non-literal warning is - // an artifact of routing it through the lambda parameter - // rw::formatTo reproduces snprintf's contract EXACTLY, so the A4-F8 clamp below is kept - // verbatim: it is applied to the same would-have-written length, and truncation therefore - // happens at the same byte it always did. - // - // The obvious-looking rewrite — `qp = std::format_to_n( qp, qe - qp, ... ).out` — is WRONG, - // and wrong in a way no fixture catches. snprintf( p, S, ... ) writes at most S-1 characters - // PLUS a NUL; format_to_n( p, S, ... ) writes up to S and terminates nothing. It buys one - // extra byte of room and drops the terminator. Measured 2026-09-09: that version emitted a - // row carrying amp="1" where every previous release truncated it away, on test/ as the - // corpus. The byte fence was green throughout — the fixture's attribute strings never reach - // this 80-byte buffer, so only a differential run against the pre-conversion binary on a - // REAL tree exposed it. - // - // What the conversion does keep: -Wformat-security is gone, because std::format_string - // preserves compile-time checking THROUGH the lambda parameter where a const char* fmt - // could not. - const auto appendf = [ & ]< class... A >( std::format_string fmt, A&&... args ) - { - // Bound by the OUT POINTER, never by a would-have-written length. std::format_to_n's - // `out` is clamped to the n it was given on any implementation; its `size` is a - // would-have-written count that an implementation can get wrong, and this clamp used - // to depend on it. n is (qe-qp)-1 so the NUL below always lands in bounds, which is - // snprintf's "at most S-1 characters plus a terminator", byte for byte. - if( qp < qe ) - { - const auto r = std::format_to_n( qp, ( qe - qp ) - 1, fmt, std::forward( args )... ); - qp = r.out; - *qp = '\0'; - } - }; - // loc: physical line span — always meaningful (SIZE is the master variable — report it first). - if( s.loc > 0 ) - { - appendf( " loc=\"{}\"", s.loc ); - } - const bool isFn = ( s.kind == SymKind::Function || s.kind == SymKind::Method ); - if( isFn ) - { - appendf( " params=\"{}\"", unsigned( s.params ) ); - if( s.params == std::numeric_limits::max() ) - { - appendf( " params_floor=\"1\"" ); // CR #586: countParams saturates at the field width, so this count is a floor - } - appendf( " nest=\"{}\"", unsigned( s.maxNest ) ); - // The nesting PROFILE beside the max (model.h Symbol::humps/deepLoc). nest= alone cannot - // distinguish a long run of shallow scoped steps from a body that sustains depth — both - // report their deepest line and nothing about how much of the function is that deep. - // Omitted, never a bare 0, when no region reached quality::kNestBar: that is exactly - // nest < kNestBar, which the row already carries, so absence is lossless rather than a - // truncation (test/nestprofilecheck.sh arm 5 pins the equivalence in both directions). - if( s.humps > 0 ) - { - appendf( " humps=\"{}\" deep=\"{}\" deep_floor=\"1\"", unsigned( s.humps ), unsigned( s.deepLoc ) ); - } - appendf( "{}", tangleMetricAttrs( s, /*json=*/false ) ); // QD-TANGLE: steer= / tangle=, each absent at 0 - // Phase 1 (local-variable-indexing, docs/LOCALS_INDEXING.md): locals= is ABSENT — never - // a bare "0" — for every def outside model.h's localsCountedLang (MVP: C/C++ only), so a - // reader never mistakes "not counted for this language" for "counted, and there are none". - // locals_floor="1" always rides alongside a present locals=: `int a,b;` counts as ONE - // declaration-statement, not two names (see cc_isCountableLocalDecl's own comment). - if( localsCountedLang( s.lang ) ) - { - appendf( " locals=\"{}\" locals_floor=\"1\"", unsigned( s.locals ) ); - } - // ppalt disclosure: the body carries preproc branches that never coexist at compile - // time, so this row's structural metrics are sums over ALL of them (model.h Symbol:: - // ppAlt). ABSENT when 0 — presence itself is the signal. - if( s.ppAlt > 0 ) - { - appendf( " ppalt=\"{}\"", unsigned( s.ppAlt ) ); - } - } - if( cbo && id < cbo->size() ) - { - appendf( " cbo=\"{}\"", (*cbo)[id] ); - } - if( lcom4 && id < lcom4->size() && ( *lcom4 )[id] != 0xFFFFFFFFu ) - { // 0xFFFFFFFF = kLcom4NA (graph.h) ⇒ omit - appendf( " lcom4=\"{}\"", (*lcom4)[id] ); - } - if( amp && id < amp->size() ) - { - appendf( " amp=\"{}\"", (*amp)[id] ); - } - if( tested && id < tested->size() && ( *tested )[id] ) - { // omit when 0 (lean output) - appendf( " tested=\"1\"" ); - } - } +// One group: the file's path and arch layer (P3), then its rows. §P6.3: const/non-const overload pairs are folded to one +// representative row per (kind,id) by overloadRowsFor() before the rows are written (--metrics: one row per definition). +template +inline void writeMapFileGroup( XmlWriter& w, const IngestResult& ing, std::uint32_t f, const MapFileGroups& groups, const MapRowSources& src, + const PathRel& pathRel, std::vector& esc, std::vector& scratch ) +{ + w.write( "" ); + const OverloadRows rows = overloadRowsFor( ing, groups.buckets[ f ], src.metrics ); + for( std::size_t i = 0; i < rows.id.size(); ++i ) + { + writeMapSymbolRow( w, ing, rows, i, groups.stemPick.rows, src, esc, scratch ); + } + w.write( "" ); +} - char attr[ 352 ]; // descriptive metric attrs (fan-in/out/cx/role/amb/lpin + Q-compute qbuf) — facts, never - // gates. The name quote + id= are already written above; this opens with a space. - // The closing '>' is written separately below so the ev run — composed on - // std::string, never a fixed char buffer (fixedbufsweep's own rule: ev_why= is - // variable-length text) — can sit inside the element. - if( metrics && fanIn ) - { - const std::uint32_t in = ( id < fanIn->size() ) ? (*fanIn)[id] : 0u; - rw::formatTo( attr, sizeof( attr ), " in=\"{}\" out=\"{}\" cx=\"{}\" ccx=\"{}\"{}{}{}{}", - in, out, s.cx, s.ccx, ( in >= 8 ? " role=\"hub\"" : "" ), rw::cstr( qbuf ), rw::cstr( ambs ), rw::cstr( kbuf ) ); - } - else - { - rw::formatTo( attr, sizeof( attr ), "{}{}", rw::cstr( ambs ), rw::cstr( kbuf ) ); - } - w.write( attr ); - // EXTENT HONESTY (kExtentSuspectRowLegend): the containment checks this row's extent/scope/kind failed. - // After k= so every pre-existing adjacency holds; absent when every check held (clean corpora unchanged). - if( s.extentSuspect != 0 ) - { - w.write( " extent_suspect=\"" ); - w.write( extent::extentSuspectReasons( s.extentSuspect ) ); - w.write( "\"" ); - } - // Essential complexity (model.h Symbol::ev), --metrics only. Emitted iff ev >= 2: ev >= 1 for any - // walked fn/method body, so on a row carrying cx= ABSENT means exactly ev == 1 — lossless in the - // strictest sense, and never a bare ev="1" (G4 + the honesty contract point the same way). Routed - // through evCountedLang so an uncovered language (Bash) reads as "not counted", never "counted, 1". - // ev_floor="1" always rides along: noreturn calls, macro-hidden returns and unresolvable gotos are - // invisible to the syntactic walk and can only RAISE the true value. ev_why= is the reason - // breakdown that keeps §10.1-Option-A honest (a guard-heavy row is visibly not a knot). - if( metrics && ( s.kind == SymKind::Function || s.kind == SymKind::Method ) && evCountedLang( s.lang ) && s.ev >= 2u ) - { - std::string evRun = " ev=\"" + std::to_string( s.ev ) + "\" ev_floor=\"1\" ev_why=\"" + evWhyString( s ) + "\""; - w.write( evRun ); - } - w.write( ">" ); +// C1-b: under in=DIR the symbol map is a DISCLOSED stub (docs/METHODOLOGY.md §9.3) — the caller asked for DIR's recent files, +// not the map. +// +// NOT total=/shown=, which is what this first shipped as. Under pageview.h's vocabulary total= is THE TOTAL (rule 2) and +// capped= always rides beside a shown= (rule 3), and the stub had neither property: it printed total="200" — the --top-k PAGE +// SIZE — on a document whose own header says symbols="18457", with no capped=, so the one number it carried was the one +// number it was not allowed to mean. The stub is not a page of the map and it must not borrow the page vocabulary to say so. +// It says what it IS instead: +// stubbed="1" the symbol map was not rendered at all (the stub ranks and groups no row) +// would_show="N" `keep` — the un-stubbed header's own shown=, and shown= counts symbol DEFINITIONS individually, not +// printed rows: the print loop runs collapseOverloadRows() per file bucket, so a const/non-const pair that +// both make the top-K cut prints ONE row carrying overloads=2. The row count therefore FOLLOWS from the +// identity the map legend already publishes for shown= — rows+sum(overloads-1)=shown — rather than being +// reported here. Measured on this repo 2026-09-14: shown=200, 193 rows, 7 at overloads=2, 193+7=200. +// IT IS A DEFINITION COUNT AND NOT A CEILING, by owner decision 2026-09-14, and the reason is vocabulary: +// in this tool a floor/ceiling marker means "we could not see everything" (counts_floor=, _capped, the +// truncation disclosures). would_show is EXACT; what differs from a reader's guess is the UNIT. Naming the +// quantity is also the stronger claim: a ceiling cannot be inverted, while a definition count plus the +// published identity yields the rows. Reporting post-collapse rows instead is not available at this site +// for any price worth paying: which definitions survive the cut is a fact about the RANKING, and not +// ranking is the whole point of the stub (no pr_iters= rides its header). Not the corpus total either +// (that is symbols=), so the three cannot be read as each other. +// test/recentscopecheck.sh arms 14a/14b pin the arithmetic. +// Rule 3's own sentence sanctions the shape: "If a verb emits no shown=, it emits no capped= either." +inline void writeSymbolMapStub( XmlWriter& w, std::size_t keep, std::string_view stubNext ) +{ + std::string stub = "'s children, as ONE renderer serialize()'s measured path and its degrade path both call: the multi-root prologue, F3's +// recent files (rank_by=churn-decay's file-level answer, before the symbol map), the stub or the groups, and the D7 +// inventory tier. The inventory rides the LOW-importance end of the document — after the rows, or before them when the map +// is emitted important-last, so the top-ranked rows keep the end position that order promises. That placement is the XML +// document's own: 's children are a sequence a reader meets in order, while the JSON map's "inv" is a key of one object, +// where a position carries nothing — so it stays here rather than in MapPlan (moving it would also move JSON bytes). +template +inline void writeMapChildren( XmlWriter& w, const IngestResult& ing, const MapAnnotations& ann, const MapPlan& plan, const MapRowSources& src, + const PathRel& pathRel, std::vector& esc, std::vector& scratch ) +{ + const MapFileGroups& groups = plan.groups; + writeRootLabelRows( w, ing, esc ); // A13: the multi-root prologue + writeRecentRows( w, ann, pathRel, esc ); + if( plan.stubbed ) + { + writeSymbolMapStub( w, plan.keep, ann.stubNext ); + } + const auto writeInventory = [ & ]() + { + if( groups.inventory.active ) + { + writeMapInventoryXml( w, ing, groups.inventory, pathRel, src.outOff, src.outTargets, src.outProv, src.outNameOnly, esc, scratch ); + } + }; + const bool inventoryFirst = emitOrderTraits( plan.emitOrder ).importantLast; // --stable's path order wins, as it does for the rows + if( inventoryFirst ) + { + writeInventory(); + } + for( const std::uint32_t f : groups.fileOrder ) + { + writeMapFileGroup( w, ing, f, groups, src, pathRel, esc, scratch ); + } + if( !inventoryFirst ) + { + writeInventory(); + } + w.write( "" ); +} - writeMapCalleeRows( w, ing, outOff[id], outOff[id + 1], outTargets, outProv, outNameOnly, esc, hedgedScratch ); - w.write( "" ); - } - w.write( "" ); +// The fixpoint: est_tokens covers head + children + tail, and head/tail both PRINT est_tokens, so the digit count feeds back. +// Converges in ≤2 passes in practice (each extra digit moves the estimate by <1 token); the bound is 4, matching recall.h's. +// +// WHAT THE LOOP GUARANTEES (CA4 verifier L4): the LAST built pair is always the pair returned, and ON CONVERGENCE — the number +// stopped moving — that pair's own bytes are exactly the bytes `estTokens` was measured over, so the document's stated number +// describes the document. On the BOUND (4 passes without convergence, not observed on any measured corpus) the head/tail were +// rebuilt from the last `next` while `next` was measured over the PREVIOUS pair's widths, which differ only in the digit count +// of one field: at most a few bytes, i.e. a residual well under one token, and never a fabricated number. The honest statement +// is "converged ⇒ exact; bounded ⇒ within a digit's worth of bytes", not "always exact". +struct SettledHeadTail +{ + std::size_t estTokens = 0; + std::string head; + std::string tail; +}; + +template +inline SettledHeadTail settleEstTokens( std::size_t modelledTokens, std::size_t childBytes, double bytesPerToken, std::size_t extraPayloadTokens, + const BuildHead& buildHead, const BuildTail& buildTail ) +{ + SettledHeadTail s{ modelledTokens, buildHead( modelledTokens ), buildTail( modelledTokens ) }; + for( int pass = 0; pass < 4; ++pass ) + { + const std::size_t next = tokensForEmittedBytes( s.head.size() + childBytes + s.tail.size(), bytesPerToken ) + extraPayloadTokens; + if( next == s.estTokens ) + { + break; } - if( !inventoryFirst ) + s.estTokens = next; + s.head = buildHead( next ); + s.tail = buildTail( next ); + } + return s; +} + +inline void serialize( std::FILE* out, const IngestResult& ing, const std::vector& rank, + const std::vector& outOff, const std::vector& outTargets, + int topK, bool mostImportantLast = false, + bool metrics = false, const std::vector* fanIn = nullptr, + const std::vector* ambOut = nullptr, bool stable = false, + const std::vector* outProv = nullptr, + // Q-compute per-symbol metrics — surfaced on --metrics ONLY (descriptive facts, never gates). + // All optional (nullptr ⇒ that attribute is omitted); loc/params/nest live on Symbol itself. + const std::vector* cbo = nullptr, // Q5a distinct in-repo dependency targets + const std::vector* tested = nullptr, // Q2 referenced from a test-path file + const std::vector* lcom4 = nullptr, // Q4 class cohesion (kLcom4NA ⇒ omit) + const std::vector* amp = nullptr, // Q2 change-amplification (callers + co-change partners) + const std::vector* unresolvedOut = nullptr, // honesty lever #2: per-symbol lang-filtered + // unresolved calls; summed into `unresolved=N` + const SparseLabels* bind = nullptr, // A4-R5 per-symbol cross-language binding + // label (graph.h g.bindLabel) — JNI decoded + // Java_pkg_Cls_method → "pkg.Cls.method". + // Emitted as bind="…" ONLY when non-empty + // (nullptr/empty-vector default ⇒ zero + // token cost, byte-identical golden map). + bool autoOrder = false, // T3: fill-aware auto important-last (see above) + std::size_t* outEstTokens = nullptr, // --token-budget: hand back the SAME est_tokens the + // header prints (no second counter) — nullptr ⇒ unused + std::size_t extraPayloadTokens = 0, // §H7 (was extraBodyTokens): tokens of + // EVERY block the caller appends after this map — + // , , , — each MEASURED + // from its rendered bytes by the caller (main.cpp's + // renderMapPayload) and converted through + // tokensForEmittedBytes. The old name said "body" + // and only --expand ever filled it, which is + // precisely why the four siblings went uncharged. + const MapAnnotations& ann = {}, // how THIS map was produced (see MapAnnotations + // above); defaulted ⇒ byte-identical golden map. + // §B6 M10: keep the files=/symbols=/shown=/order= stanza on the FIRST SCREEN even under + // `stable`. --stable moves it to a TRAILING comment to protect the cacheable prefix, which is + // right for a CLI map a provider KV-caches and wrong for the MCP `analyze` verb, whose result + // is ONE tool payload an agent reads top-down: there the reader met 197 of 6368 symbols with + // no denominator and no order marker until the last line. The stanza is emitted ONCE either + // way (never both places), so no count is stated twice. Only the MCP analyze front door + // passes true; every CLI caller keeps the default and stays byte-identical. + bool statsFirstScreen = false, + // R-E (2026-08-17 harvest, report-memgraph §F6 seconded): the run's OWN root argument, + // single-root callers only (empty ⇒ multi-root — already carries the roots=/ disclosure above and stays untouched — or a caller that never passes one, e.g. + // a pure sizing pass, where a root= attribute would add bytes nothing reads). Same fact + // --grep's root= states, same helper (sarif.h's rootPrefixOf/rootRelativeUri) — the two + // verbs must not diverge on what "root-relative" means. + std::string_view rootArg = {}, + // Phase 4: the S6-C locality-pin counter (graph.h g.locPinOut) → lpin="K" on the row, header + // locality_pinned=N — both absent when zero, so a pin-free corpus is byte-identical. + const std::vector* locPinOut = nullptr, + // Phase 5: the external-name veto's refusal count (graph.h g.externalCalls) → header external=N, + // absent when zero, so a veto-free corpus is byte-identical. + std::size_t externalCalls = 0, + // Tier 3's per-caller declines (graph.h g.declinedOut) → header declined=N, absent when zero, so a + // corpus where no call reached tier 3 undecided stays byte-identical. + const std::vector* declinedOut = nullptr, + // of those, the calls the builtin-method name gate declined (graph.h g.gateDeclinedCalls) → the + // kDeclinedGateMapLegend clause, absent when zero. + std::size_t gateDeclinedCalls = 0, + // FE-B: Graph::outNameOnly (parallel to outTargets) → via="name" on a row and the via legend + // comment; nullptr/empty ⇒ every edge is evidence-bound and the map is byte-identical. + const std::vector* outNameOnly = nullptr, + // of declined=, the calls the standard-member gate declined (graph.h g.stdMemberDeclinedCalls) → + // the kDeclinedStdMapLegend clause, absent when zero. + std::size_t stdMemberDeclinedCalls = 0, + // of declined=, the Elixir call candidates inside inert quote AST (g.inertDeclinedCalls, #380) → + // the kInertDeclinedMapLegend clause, absent when zero. + std::size_t inertDeclinedCalls = 0 ) +{ + // R-E: normalize once, reuse at every row — rootPrefixOf just strips a trailing '/'. + const std::string rootPrefix = rootArg.empty() ? std::string() : rw::sarif::rootPrefixOf( rootArg ); + const auto pathRel = [ & ]( std::uint32_t fileId ) -> std::string_view + { + return rootArg.empty() ? std::string_view( ing.files[ fileId ] ) : rw::sarif::rootRelativeUri( ing.files[ fileId ], rootPrefix ); + }; + + // ── WHICH rows, in WHICH order: the plan both dialects share; the XML map honours in=DIR's stub ───────────────────── + const MapPlan plan = planMap( ing, rank, outOff, outTargets, ann, topK, + MapOrderRequest{ .stable = stable, .mostImportantLast = mostImportantLast, .autoOrder = autoOrder }, + MapResolverCounters{ .ambOut = ambOut, .unresolvedOut = unresolvedOut, .locPinOut = locPinOut, + .declinedOut = declinedOut, .externalCalls = externalCalls, + .gateDeclinedCalls = gateDeclinedCalls, .stdMemberDeclined = stdMemberDeclinedCalls, + .inertDeclinedCalls = inertDeclinedCalls }, + MapStubPolicy::HonourAnnotation, pathRel ); + std::vector esc; + + // ── the legend, clause group by clause group, in the order the reader meets them ────────────────────────────── + std::string legend = mapOpeningLegend( outProv != nullptr ); + legend += moduleScopeLegend( ing ); + legend += keptImplEdgeLegend( outOff, outProv, plan.kept(), plan.groups.inventory.entries ); + legend += typeKindLegend( ing ); + legend += gaugeLegend( plan.gauges, kParseHonestyClauses ); + legend += runAnnotationLegend( ing, ann, rootArg, metrics ); + legend += rowSelectionLegend( plan.ranked.dataSecCut, plan.groups ); + // W2-F: the pr_iters= / pr_converged= definition, charged to the maps that carry the attributes — empty for a lexical or + // HITS ordering, and the prose half only on the map whose iteration stopped short. + legend += renderDisclosure( ann.prDisclosure, DiscloseAs::LegendComment ); + legend += gaugeLegend( plan.gauges, kDeclineClauses ); + legend += keptNameEdgeLegend( outOff, outNameOnly, plan.kept(), ann.viaLegendStripped ); + // K51: history_unread='s definition, the LAST leading clause, so it stands right before the root it marks and inside the + // leading block every reader (and legendcoveragecheck's full rows) meets first; absent unless the amp=/churn= walk was unread. + legend += renderHistoryUnread( DiscloseAs::LegendComment ); + + // ── the HEAD and the TAIL, as BUILDERS ───────────────────────────────────────────────────────────────────────── + // Both state est_tokens, and est_tokens describes the whole document including them, so the digit count feeds back into + // the number: PHASE 2 iterates these to a fixpoint (settleEstTokens). buildRecall (recall.h) has the identical fixpoint for + // the identical reason. Pure functions of estTokens, the values decided above and the estimate sink's state. + // --stable: the volatile counts move to a TRAILING comment (out of the cacheable prefix) — unless the caller asked for the + // first-screen placement (§B6 M10, the MCP analyze verb). Exactly one of the two builders emits the stats. + const bool statsTrail = emitOrderTraits( plan.emitOrder ).stablePrefix && !statsFirstScreen; + const std::string coverageAttrs = renderMapCoverageAttrs( ing, mapCoverageFacts( ing, outProv ), ann ) + mapFitAttrs( ann ); + const MapStatsFacts statsFacts{ .plan = plan, .files = ing.files.size(), .edges = outTargets.size(), .coverageAttrs = coverageAttrs }; + const MapRootFacts rootFacts{ .ann = ann, .rootArg = rootArg, .plan = plan }; + MapEstimate estimate{ ann.payloadUncharged }; // the est_tokens measurement's DISCLOSE sink — read by the builders + const auto buildHead = [ & ]( std::size_t estTokens ) -> std::string + { + std::string h = legend; + if( estimate.isModelled ) { - writeInventory(); + h += kEstModelledLegend; } - w.write( "" ); + if( !statsTrail ) + { + h += renderMapStats( statsFacts, estTokens, estimate.isModelled ); + } + h += renderMapRootTag( rootFacts, estTokens, estimate.isModelled, esc ); + return h; + }; + const auto buildTail = [ & ]( std::size_t estTokens ) -> std::string + { + return statsTrail ? renderMapStats( statsFacts, estTokens, estimate.isModelled ) : std::string{}; + }; + + // ── PHASE 1: render 's CHILDREN into a buffer ─────────────────────────────────────────────────────────────── + // §H7: est_tokens must charge the bytes the document actually carries, not a model of the symbol set — the model prices + // neither --metrics decoration nor an appended payload, which is how one number came to stand for five documents. So: + // measure, decide, then write (the order --recall's emitRecallBudgeted and the --for lens's pre-rendered sigs block + // already impose on themselves). + const MapRowSources rowSources{ .rank = rank, .outOff = outOff, .outTargets = outTargets, .outProv = outProv, .outNameOnly = outNameOnly, + .ambOut = ambOut, .locPinOut = locPinOut, .bind = bind, .emitOrder = plan.emitOrder, .metrics = metrics, + .fanIn = fanIn, .cbo = cbo, .tested = tested, .lcom4 = lcom4, .amp = amp }; + std::vector hedgedScratch; // FE-B: writeMapCalleeRows' reused buffer + const auto writeChildren = [ & ]( XmlWriter& w ) + { + writeMapChildren( w, ing, ann, plan, rowSources, pathRel, esc, hedgedScratch ); }; - // DEGRADE, one path for both failures: the head goes out FIRST carrying the MODELLED estimate (the pre-§H7 number, so - // no worse than the old behaviour and never a fabricated one), the children stream straight to `out` behind it, then - // the trailing summary. The whole map, uncharged. + // DEGRADE, one path for both failures (a buffer that did not open, or one that opened and then lost a write — by then the + // children were already spent into it, so they are rendered again): the head goes out FIRST carrying the MODELLED estimate + // (the pre-§H7 number, so no worse than the old behaviour and never a fabricated one), the children stream straight to + // `out` behind it, then the trailing summary. The whole map, uncharged. + const std::size_t modelledTokens = plan.mapEst.tokens + extraPayloadTokens; const auto emitModelled = [ & ]() { XmlWriter direct( out ); @@ -4243,17 +4614,19 @@ inline void serialize( std::FILE* out, const IngestResult& ing, const std::vecto *outEstTokens = modelledTokens; } }; + rw::MemoryStream childStream; + std::FILE* const childMem = openChargeStream( childStream ); if( !childMem ) { + DISCLOSE( estimate, MapEstimate::DisclosureWhy::ChargeBufferFailed, "serialize: open_memstream failed — est_tokens reports the MODELLED bytes, not the emitted ones" ); emitModelled(); return; } - // ── PHASE 2: measure, decide, then write ──────────────────────────────────────────────────────────── - // The children go into the buffer, and the writer flushes BEFORE the memstream is finished (its destructor flushes - // again at the end of the block, with nothing left to write). A buffer that did not finish whole means a write was - // lost INSIDE the children (rw::MemoryStream::finish), so those bytes are never printed: the map is rendered again, - // straight to `out`, on the modelled path a failed open takes. + // ── PHASE 2: measure, decide, then write ─────────────────────────────────────────────────────────────────────── + // The children go into the buffer, and the writer flushes BEFORE the memstream is finished (its destructor flushes again at + // the end of the block, with nothing left to write). A buffer that did not finish whole means a write was lost INSIDE the + // children (rw::MemoryStream::finish), so those bytes are never printed: the map is rendered again on the modelled path. { XmlWriter w( childMem ); writeChildren( w ); @@ -4268,44 +4641,16 @@ inline void serialize( std::FILE* out, const IngestResult& ing, const std::vecto return; } const std::string_view childrenStr = children.bytes; // owned by childStream, alive to the end of this function - - // The fixpoint: est_tokens covers head + children + tail, and head/tail both PRINT est_tokens, so the - // digit count feeds back. Converges in ≤2 passes in practice (each extra digit moves the estimate by - // <1 token); the bound is 4, matching recall.h's. - // - // WHAT THE LOOP GUARANTEES (CA4 verifier L4 — the previous wording claimed an equality this loop does not - // deliver): the LAST built pair is always the pair emitted, and ON CONVERGENCE — the `break`, i.e. the - // number stopped moving — that pair's own bytes are exactly the bytes `estTokens` was measured over, so the - // document's stated number describes the document. On the BOUND (4 passes without convergence, not observed - // on any measured corpus) the emitted head/tail were rebuilt from the last `next` while `next` was measured - // over the PREVIOUS pair's widths, which differ only in the digit count of one field: at most a few bytes, - // i.e. a residual well under one token, and never a fabricated number. The honest statement is "converged ⇒ - // exact; bounded ⇒ within a digit's worth of bytes", not "always exact". - std::size_t estTokens = modelledTokens; - std::string head = buildHead( estTokens ); - std::string tail = buildTail( estTokens ); - for( int pass = 0; pass < 4; ++pass ) - { - const std::size_t next = tokensForEmittedBytes( head.size() + childrenStr.size() + tail.size(), - mapEst.bytesPerToken() ) + extraPayloadTokens; - if( next == estTokens ) - { - break; - } - estTokens = next; - head = buildHead( estTokens ); - tail = buildTail( estTokens ); - } + const SettledHeadTail settled = settleEstTokens( modelledTokens, childrenStr.size(), plan.mapEst.bytesPerToken(), extraPayloadTokens, buildHead, buildTail ); if( outEstTokens ) { - *outEstTokens = estTokens; // --token-budget reads THIS value — never a second counter + *outEstTokens = settled.estTokens; // --token-budget reads THIS value — never a second counter } - - std::fwrite( head.data(), 1, head.size(), out ); + std::fwrite( settled.head.data(), 1, settled.head.size(), out ); std::fwrite( childrenStr.data(), 1, childrenStr.size(), out ); - if( !tail.empty() ) + if( !settled.tail.empty() ) { - std::fwrite( tail.data(), 1, tail.size(), out ); + std::fwrite( settled.tail.data(), 1, settled.tail.size(), out ); } } @@ -4680,214 +5025,183 @@ inline std::string docCommentBefore( const std::string& src, std::size_t defStar // that follow stripping (i.e. lines that contained only a comment and are now empty). // // Correctness guarantee: a "//" or "/*" that appears inside a "…" or '…' literal is NEVER treated as -// a comment. We track the lexer state through the following states: -// NORMAL → default; comments and literals start here -// IN_STRING → inside "…"; ends at an unescaped " -// IN_CHAR → inside '…'; ends at an unescaped ' -// IN_RAW → inside R"delim(…)delim" (C++ raw string); ends at )delim" -// IN_LINE_CMT → inside // …; ends at the next \n (the \n is kept so line count is preserved) -// IN_BLK_CMT → inside /* … */; the entire span including markers is consumed +// a comment. The lexer below has one step per token kind it can start on: +// copyStringLiteral "…" (ends at an unescaped "), or a C++ raw string R"delim(…)delim" (ends at )delim") +// copyQuotedLiteral '…' (ends at an unescaped ') +// skipLineComment // … (ends at the next \n, which is kept so the line count is preserved) +// skipBlockComment /* … */ (the entire span including markers is consumed; its newlines are kept) +// and every other character is copied as-is. // // NOTE: does NOT strip the doc-comment field — that is emitted separately by the call site and // is never passed into this function (only the raw body bytes [sigStartByte, endByte) are compressed). -inline std::string compressBody( std::string_view src ) -{ - // Phase 1: lex out comments, preserving content inside string/char literals. - // - // output: the source with all comment content removed; literal content intact. - // We output character-by-character into `out` for simplicity (the budget-capped - // bodies are not huge — typically <200 KB — so quadratic string appending is fine). - std::string out; - out.reserve( src.size() ); +// Copies a `quote`-delimited literal starting at src[i] (the opening quote) through its closing quote; a backslash escapes +// the next character. Returns the index just past the closing quote (N + 1 when the literal runs off the end, which ends the +// caller's scan the same way). +inline std::size_t copyQuotedLiteral( std::string_view src, std::size_t i, char quote, std::string& out ) +{ const std::size_t N = src.size(); - std::size_t i = 0; - + out += src[ i ]; // the opening quote + ++i; while( i < N ) { - const char c = src[i]; - - // ── String literal "…" ──────────────────────────────────────────────────────────── - if( c == '"' ) + const char sc = src[ i ]; + out += sc; + if( sc == '\\' && i + 1 < N ) { - // Check for C++ raw string R"delim( - if( i >= 1 && src[i - 1] == 'R' && ( i < 2 || src[i - 2] != '\\' ) ) - { - // Raw string: collect delimiter between " and ( - std::size_t j = i + 1; - std::string delim; - while( j < N && src[j] != '(' && src[j] != '\n' ) - { - delim += src[j++]; - } - if( j < N && src[j] == '(' ) - { - // We're inside R"delim(...). Copy everything verbatim until )delim" - const std::string terminator = ")" + delim + "\""; - out += src.substr( i, j - i + 1 ); // R"delim( - i = j + 1; - const std::size_t termLen = terminator.size(); - while( i < N ) - { - if( i + termLen <= N && src.substr( i, termLen ) == terminator ) - { - out += terminator; - i += termLen; - break; - } - out += src[i++]; - } - continue; - } - // Not a raw string (malformed R"... without a paren) — fall through to - // regular string literal handling below. - } - - // Regular double-quoted string literal. - out += c; // emit the opening " - ++i; - while( i < N ) - { - const char sc = src[i]; - out += sc; - if( sc == '\\' && i + 1 < N ) { out += src[++i]; } // escape: skip next char - else if( sc == '"' ) - { - break; // end of string - } - ++i; - } - ++i; // step past the closing " - continue; + out += src[ ++i ]; // escape: copy the next char too + } + else if( sc == quote ) + { + break; } + ++i; + } + return i + 1; // step past the closing quote +} - // ── Char literal '…' ────────────────────────────────────────────────────────────── - if( c == '\'' ) +// A `"` at src[i] opens a C++ raw string when an unescaped `R` precedes it. +inline bool opensRawString( std::string_view src, std::size_t i ) noexcept +{ + return i >= 1 && src[ i - 1 ] == 'R' && ( i < 2 || src[ i - 2 ] != '\\' ); +} + +// Copies a raw string R"delim(…)delim" verbatim from its `"` at src[i]; the `R` was already copied. Returns the index past +// the terminator (or N when it never comes), or nullopt — copying nothing — when no `(` follows the delimiter on its line, +// which is a malformed R"… the caller reads as a regular string literal. +inline std::optional copyRawStringLiteral( std::string_view src, std::size_t i, std::string& out ) +{ + const std::size_t N = src.size(); + std::size_t j = i + 1; + while( j < N && src[ j ] != '(' && src[ j ] != '\n' ) + { + ++j; + } + if( j >= N || src[ j ] != '(' ) + { + return std::nullopt; + } + const std::string terminator = ")" + std::string( src.substr( i + 1, j - i - 1 ) ) + "\""; + out += src.substr( i, j - i + 1 ); // "delim( + for( i = j + 1; i < N; ++i ) + { + if( src.substr( i, terminator.size() ) == terminator ) { - out += c; // opening ' - ++i; - while( i < N ) - { - const char sc = src[i]; - out += sc; - if( sc == '\\' && i + 1 < N ) { out += src[++i]; } - else if( sc == '\'' ) - { - break; - } - ++i; - } - ++i; - continue; + out += terminator; + return i + terminator.size(); } + out += src[ i ]; + } + return N; +} - // ── Comment detection (only reached OUTSIDE string/char literals) ───────────────── - if( c == '/' && i + 1 < N ) +// A "…" literal from its opening quote: a raw string when it opens one, else a regular escaped string. +inline std::size_t copyStringLiteral( std::string_view src, std::size_t i, std::string& out ) +{ + if( opensRawString( src, i ) ) + { + if( const std::optional end = copyRawStringLiteral( src, i, out ) ) { - // Line comment: // … — consume to end of line, emit a newline to preserve line count. - if( src[i + 1] == '/' ) - { - while( i < N && src[i] != '\n' ) - { - ++i; - } - // leave the \n to be emitted in the NORMAL branch below - continue; - } - // Block comment: /* … */ — consume entirely (no newline kept; blank lines handle the gap) - if( src[i + 1] == '*' ) - { - i += 2; // skip /* - while( i + 1 < N && !( src[i] == '*' && src[i + 1] == '/' ) ) - { - if( src[i] == '\n' ) - { - out += '\n'; // preserve newlines so line numbers survive - } - ++i; - } - if( i + 1 < N ) - { - i += 2; // skip */ - } - continue; - } + return *end; } + } + return copyQuotedLiteral( src, i, '"', out ); +} - // ── Normal character — emit as-is ───────────────────────────────────────────────── - out += c; +// A // comment from its first slash: consumed up to (not including) the \n, which the caller then copies so the line count +// is preserved. +inline std::size_t skipLineComment( std::string_view src, std::size_t i ) noexcept +{ + while( i < src.size() && src[ i ] != '\n' ) + { ++i; } + return i; +} - // Phase 2: post-process the comment-stripped text: - // (a) Drop lines that are now whitespace-only (previously held only a comment). - // (b) Collapse runs of 3+ blank lines → a single blank line. - // - // "Blank line" = a line whose trimmed content is empty. We preserve lines that have ANY - // non-whitespace content after comment stripping (this keeps intentional blank lines between - // logical blocks — only the *excess* is collapsed). - std::string result; - result.reserve( out.size() ); - - std::size_t pos = 0; - int blanks = 0; // consecutive blank lines seen so far - bool firstLine = true; // suppress leading blanks at the very start of a body - - const std::size_t M = out.size(); - while( pos < M ) +// A /* … */ comment from its first slash: consumed entirely, markers included, but its newlines are kept so line numbers +// survive (the blank-line pass handles the gap). An unterminated comment runs to the last character. +inline std::size_t skipBlockComment( std::string_view src, std::size_t i, std::string& out ) +{ + const std::size_t N = src.size(); + i += 2; // skip /* + while( i + 1 < N && !( src[ i ] == '*' && src[ i + 1 ] == '/' ) ) { - // Find end of line. - std::size_t eol = out.find( '\n', pos ); - if( eol == std::string::npos ) + if( src[ i ] == '\n' ) { - eol = M; + out += '\n'; } + ++i; + } + return i + 1 < N ? i + 2 : i; // skip */ +} - const std::string_view line( out.data() + pos, eol - pos ); - - // Is this line blank (all whitespace)? - bool isBlank = true; - for( char ch : line ) +// Phase 1: the source with all comment content removed and literal content intact. +inline std::string stripCommentsKeepLiterals( std::string_view src ) +{ + std::string out; + out.reserve( src.size() ); + const std::size_t N = src.size(); + std::size_t i = 0; + while( i < N ) + { + const char c = src[ i ]; + const char d = i + 1 < N ? src[ i + 1 ] : '\0'; // the comment openers are read only OUTSIDE string/char literals + if( c == '"' ) { - if( ch != ' ' && ch != '\t' && ch != '\r' ) - { - isBlank = false; - break; - } + i = copyStringLiteral( src, i, out ); } - - if( isBlank ) + else if( c == '\'' ) { - // Suppress leading blank lines at the very start of a body (artifact of stripping - // the opening comment of a function body), and collapse 3+ consecutive blanks. - if( !firstLine ) - { - ++blanks; - } - // Emit at most one blank line (we allow up to 2 accumulated before we start collapsing; - // the spec says "runs of 3+ → single blank", so blanks==1 and blanks==2 are both fine). - if( !firstLine && blanks <= 2 ) - { - result += '\n'; // the blank line itself (the \n that terminated the previous line) - } - // If blanks > 2: suppress (collapse). + i = copyQuotedLiteral( src, i, '\'', out ); + } + else if( c == '/' && d == '/' ) + { + i = skipLineComment( src, i ); + } + else if( c == '/' && d == '*' ) + { + i = skipBlockComment( src, i, out ); } else { - // Non-blank line: reset counter, emit. - blanks = 0; - firstLine = false; - result.append( out.data() + pos, eol - pos ); - if( eol < M ) + out += c; + ++i; + } + } + return out; +} + +// Phase 2: the comment-stripped text's line layout. Lines that are now whitespace-only and come before the first content line +// are dropped (an artifact of stripping the opening comment of a body); after it, at most two consecutive blank lines are +// kept and the rest of a run is dropped. Every line with ANY non-whitespace content is kept, so intentional blank lines between +// logical blocks survive and only the excess is collapsed. Trailing newlines are trimmed (cosmetic). +inline std::string collapseBlankLineRuns( std::string_view text ) +{ + std::string result; + result.reserve( text.size() ); + std::size_t blanks = 0; // consecutive blank lines since the last content line + std::size_t pos = 0; + while( pos < text.size() ) + { + const std::size_t eol = std::min( text.find( '\n', pos ), text.size() ); + const std::string_view line = text.substr( pos, eol - pos ); + if( line.find_first_not_of( " \t\r" ) != std::string_view::npos ) // the line has content + { + blanks = 0; + result.append( line ); + if( eol < text.size() ) { result += '\n'; } } - - pos = ( eol < M ) ? eol + 1 : M; + // `result` is empty exactly until the first content line is copied: a blank line is only ever written after one. + else if( !result.empty() && ++blanks <= 2 ) + { + result += '\n'; // the blank line itself (the \n that terminated the previous line) + } + pos = eol + 1; } - - // Trim a single trailing newline that may have been added (cosmetic). while( !result.empty() && result.back() == '\n' ) { result.pop_back(); @@ -4895,6 +5209,11 @@ inline std::string compressBody( std::string_view src ) return result; } +inline std::string compressBody( std::string_view src ) +{ + return collapseBlankLineRuns( stripCommentsKeepLiterals( src ) ); +} + // --pack-signatures: emit each top-N ranked definition's SIGNATURE (declaration up to // the body), bodies elided — ~70% fewer tokens than raw source while keeping the structural shape. // Grouped by file, capped at budgetBytes. Emitted AFTER , like packSource. With L2: a child. @@ -11246,35 +11565,24 @@ inline void writeJsonQMetrics( JsonWriter& w, const JsonQMetrics& q ) } // The default map's JSON header — the gauge block plus the two prologues that ride on it, in one place so -// "which gauge, in which order, on which condition" is stated once rather than smeared through the emitter. -// The XML sibling states the same set through its `stats` snprintf + the prologue in serialize(). +// "which gauge, in which order, on which condition" is stated once rather than smeared through the emitter. Its counts are the +// plan's and the coverage facts' — the same values the XML header spells (renderMapStats, renderMapCoverageAttrs, +// renderMapRootTag), never a second count. struct JsonMapHeader { - const IngestResult& ing; - std::size_t symbolCount; - std::size_t edgeCount; - std::size_t shownCount; - std::size_t estTokens; - std::size_t ambiguousCount; - std::size_t unresolvedCount; - const char* orderAttr; - const std::vector* outProv; // nullptr ⇒ no precise= (nothing was measured) - const MapAnnotations* ann; // §B1.2: how THIS map was produced — the same at/rank_by/window - // stamp the XML `` element carries. nullptr ⇒ no stamp emitted. - std::string_view rootArg; // R-E: the JSON twin of the XML `` — empty for - // multi-root (its own roots_count/roots table below already - // names every root) or a caller that never passes one. - std::size_t localityPinnedCount = 0; // Phase 4: Σ lpin — "locality_pinned":N, absent when 0 - std::size_t externalCount = 0; // Phase 5: the veto's refusals — "external":N, absent when 0 - std::size_t declinedCount = 0; // tier 3's declines — "declined":N, absent when 0 - std::size_t extentSuspectCount = 0; // extent honesty: "extent_suspect_syms":N, absent when 0 - std::size_t macroBlankedCount = 0; // member-macro re-parse: "macro_blanked_files":N, absent when 0 - std::size_t nestRefusedCount = 0; // #157: "nest_refused":N, the JSON twin of the XML nest_refused=, absent when 0 - bool isEstModelled = false; // MapEstimate: "est_measured":false, absent when measured - DataSectionsCut dataSectionsCut = {}; // the code-first pick's swaps: "data_sections_cut":N + "next", absent at N=0 - std::size_t stemCut = 0; // MAP-STEM: "stem_cut":N, the XML stem_cut=, absent at N=0 - std::string_view memoryPeakJson = {}; // buildMemoryPeakAttr( ing, true ), read ONCE per serializeJson call (the - // peak reading only rises and the seam counts calls); kept last, the struct is filled positionally + const IngestResult& ing; + const MapPlan& plan; // symbols, shown, the honesty gauges, order, data_sections_cut, stem_cut + const MapCoverageFacts& coverage; // precise, skipped_oversize, roots_count + std::size_t edgeCount; + std::size_t estTokens; + bool isEstModelled; // MapEstimate: "est_measured":false, absent when measured + const MapAnnotations& ann; // §B1.2: how THIS map was produced — the same at/rank_by/window stamp the XML `` + // element carries + std::string_view rootArg; // R-E: the JSON twin of the XML `` — empty for multi-root (its own + // roots_count/roots table below already names every root) or a caller that never + // passes one. + std::string_view memoryPeakJson; // buildMemoryPeakAttr( ing, true ), read ONCE per serializeJson call (the peak + // reading only rises and the seam counts calls) }; // §B1.2: the PROVENANCE stamp — the JSON half of the XML `` attributes. Without it @@ -11284,13 +11592,8 @@ struct JsonMapHeader // Same absent-unless-produced rule as the XML: a default map passes no annotations ⇒ zero bytes, byte- // identical output. `changed` (--map-diff) has no arm here on purpose — see the coverage note above // serializeJson: jsonUnsupportedVerb refuses --map-diff before this emitter is ever reached. -inline void writeJsonMapStamp( JsonWriter& w, std::string& esc, const MapAnnotations* ann ) +inline void writeJsonMapStamp( JsonWriter& w, std::string& esc, const MapAnnotations& ann ) { - if( !ann ) - { - return; - } - // §B12.6 (CA4): `at`'s ABSENCE had two meanings inside one dialect. Five JSON emitters (quality-delta, // test-gate, cochange, plan-lanes, the MCP quality_delta twin) write `"at":null` when the root has no // HEAD to anchor to — "we tried, there is nothing" — while this one OMITTED the key in the same state, @@ -11303,32 +11606,32 @@ inline void writeJsonMapStamp( JsonWriter& w, std::string& esc, const MapAnnotat // no churn ranking) emits no key, which is also what the XML does, so the 1:1 attr/key correspondence // holds in every state. The windowless rank_by= stamps (authority/hub/rrf) attempt no anchor and are // deliberately outside the predicate, exactly as they are on the XML side. - const bool didAttemptAtStamp = ( ann->changedCount != nullptr ) || ( ann->churnWindow != nullptr ); + const bool didAttemptAtStamp = ( ann.changedCount != nullptr ) || ( ann.churnWindow != nullptr ); if( didAttemptAtStamp ) { w.write( ",\"at\":" ); - if( ann->atStamp != nullptr && !ann->atStamp->empty() ) + if( ann.atStamp != nullptr && !ann.atStamp->empty() ) { - writeJsonStr( w, *ann->atStamp, esc ); + writeJsonStr( w, *ann.atStamp, esc ); } else { w.write( "null" ); } } - if( ann->churnWindow != nullptr ) + if( ann.churnWindow != nullptr ) { w.write( ",\"rank_by\":" ); // P0-4: which churn ranker — "churn" or "churn-decay" - writeJsonStr( w, ann->churnRankLabel, esc ); + writeJsonStr( w, ann.churnRankLabel, esc ); w.write( ",\"window\":" ); - writeJsonStr( w, *ann->churnWindow, esc ); + writeJsonStr( w, *ann.churnWindow, esc ); } // §B2.1: authority/hub/rrf carry no window, so they stamp rank_by alone — the JSON half of the XML arm // above, symmetric with it, so the two dialects still cannot disagree about how a map was produced. - else if( ann->rankByLabel != nullptr ) + else if( ann.rankByLabel != nullptr ) { w.write( ",\"rank_by\":" ); - writeJsonStr( w, std::string_view( ann->rankByLabel ), esc ); + writeJsonStr( w, std::string_view( ann.rankByLabel ), esc ); } // §C4 — the --max-tokens fit, in the dialect that was missing it. `--max-tokens=N --json` shaped the map and @@ -11345,13 +11648,13 @@ inline void writeJsonMapStamp( JsonWriter& w, std::string& esc, const MapAnnotat // without naming the dialect it was measured against would replace one silence with a false implication. // The XML needs no such key because the XML is the measured dialect. Fixing the SEARCH to measure the // emitted dialect is a main.cpp change and is recorded as a residual, not smuggled in here. - if( ann->maxTokensFit != nullptr ) + if( ann.maxTokensFit != nullptr ) { char fit[ 160 ]; rw::formatTo( fit, sizeof( fit ), ",\"max_tokens\":{},\"fit_bytes\":{},\"fit_measured_in\":\"xml\"{}{}", - ann->maxTokensFit->askedTokens, ann->maxTokensFit->ceilingBytes, - ann->maxTokensFit->isOverCeiling || ann->maxTokensFit->isUnmeasured ? ",\"over_ceiling\":true" : "", - ann->maxTokensFit->isUnmeasured ? ",\"fit_unmeasured\":true" : "" ); + ann.maxTokensFit->askedTokens, ann.maxTokensFit->ceilingBytes, + ann.maxTokensFit->isOverCeiling || ann.maxTokensFit->isUnmeasured ? ",\"over_ceiling\":true" : "", + ann.maxTokensFit->isUnmeasured ? ",\"fit_unmeasured\":true" : "" ); w.write( fit ); } } @@ -11397,55 +11700,56 @@ inline void writeJsonUnindexed( JsonWriter& w, std::string& esc, const CrawlSkip inline void writeJsonMapHeader( JsonWriter& w, std::string& esc, const JsonMapHeader& h ) { + const MapHonestyGauges& g = h.plan.gauges; char hdr[ 256 ]; // the gauge line has 7 size_t fields — wider than the per-symbol scratch rw::formatTo( hdr, sizeof( hdr ), "{{\"files\":{},\"symbols\":{},\"edges\":{},\"shown\":{},\"est_tokens\":{},\"ambiguous\":{},\"unresolved\":{},", - h.ing.files.size(), h.symbolCount, h.edgeCount, h.shownCount, h.estTokens, h.ambiguousCount, h.unresolvedCount ); + h.ing.files.size(), h.plan.symbolCount, h.edgeCount, h.plan.shown, h.estTokens, g.ambiguous, g.unresolved ); w.write( hdr ); if( h.isEstModelled ) { w.write( "\"est_measured\":false," ); // the XML est_measured="0" twin: est_tokens above is the model } // Phase 4: the S6-C locality-pin gauge — same absent-when-zero rule as the XML `locality_pinned=`. - if( h.localityPinnedCount > 0 ) + if( g.localityPinned > 0 ) { - rw::formatTo( hdr, sizeof( hdr ), "\"locality_pinned\":{},", h.localityPinnedCount ); + rw::formatTo( hdr, sizeof( hdr ), "\"locality_pinned\":{},", g.localityPinned ); w.write( hdr ); } // Phase 5: the external-name veto gauge — the JSON twin of the XML `external=`, same absent-when-zero rule. - if( h.externalCount > 0 ) + if( g.external > 0 ) { - rw::formatTo( hdr, sizeof( hdr ), "\"external\":{},", h.externalCount ); + rw::formatTo( hdr, sizeof( hdr ), "\"external\":{},", g.external ); w.write( hdr ); } // tier 3's declines — the JSON twin of the XML `declined=`, same absent-when-zero rule. - if( h.declinedCount > 0 ) + if( g.declined > 0 ) { - rw::formatTo( hdr, sizeof( hdr ), "\"declined\":{},", h.declinedCount ); + rw::formatTo( hdr, sizeof( hdr ), "\"declined\":{},", g.declined ); w.write( hdr ); } // extent honesty: the JSON twin of the XML header's extent_suspect_syms=, same absent-when-zero rule and the // XML header's order (after the call-resolution family, declined included). - if( h.extentSuspectCount > 0 ) + if( g.extentSuspectSyms > 0 ) { - w.write( "\"extent_suspect_syms\":" + std::to_string( h.extentSuspectCount ) + "," ); // composed, not a fixed buffer + w.write( "\"extent_suspect_syms\":" + std::to_string( g.extentSuspectSyms ) + "," ); // composed, not a fixed buffer } // member-macro re-parse: the JSON twin of the XML header's macro_blanked_files=, same absent-when-zero rule. - if( h.macroBlankedCount > 0 ) + if( g.macroBlankedFiles > 0 ) { - w.write( "\"macro_blanked_files\":" + std::to_string( h.macroBlankedCount ) + "," ); + w.write( "\"macro_blanked_files\":" + std::to_string( g.macroBlankedFiles ) + "," ); } // #157: the JSON twin of the XML header's nest_refused=, same absent-when-zero rule. - if( h.nestRefusedCount > 0 ) + if( g.nestRefusedFiles > 0 ) { - w.write( "\"nest_refused\":" + std::to_string( h.nestRefusedCount ) + "," ); + w.write( "\"nest_refused\":" + std::to_string( g.nestRefusedFiles ) + "," ); } // §P0.5d, JSON lane: the size-ceiling disclosure must reach --json consumers too — the XML header // gained skipped_oversize= and a JSON reader (MCP clients most of all) must not be the one audience // still shown the survivors as if they were the corpus. Same absent-when-zero rule as the XML side. - if( !h.ing.skippedOversize.empty() ) + if( h.coverage.skippedOversize > 0 ) { - rw::formatTo( hdr, sizeof( hdr ), "\"skipped_oversize\":{},", h.ing.skippedOversize.size() ); + rw::formatTo( hdr, sizeof( hdr ), "\"skipped_oversize\":{},", h.coverage.skippedOversize ); w.write( hdr ); } w.write( buildMemoryStopAttr( h.ing, true ) ); // #350, JSON lane: empty unless the memory guard stopped the ingest @@ -11461,25 +11765,16 @@ inline void writeJsonMapHeader( JsonWriter& w, std::string& esc, const JsonMapHe } writeJsonUnindexed( w, esc, h.ing.crawlSkips ); // §L1, JSON lane — see its own header - // §A4d: `precise=N` — how many out-edges the SCIP overlay actually pinned. C1 drift fix, the JSON half of - // the XML fix above and by the same argument: this counted every NONZERO provenance value, so an FFI - // binding (2) and now a k-way split arm (3) were both reported as SCIP-precise. Emitted only when the - // count is non-zero (absent ⇒ nothing was pinned, never a fabricated 0 nor a borrowed one). - if( h.outProv ) + // §A4d: `precise=N` — how many out-edges the SCIP overlay actually pinned: the ONE count both dialects state + // (scipPinnedEdgeCount, whose C1 drift note says why it names value 1 alone). Absent at 0 — nothing was pinned, never a + // fabricated 0 nor a borrowed one. + if( h.coverage.scipPinnedEdges > 0 ) { - std::size_t preciseTotal = 0; - for( std::uint8_t v : *h.outProv ) - { - preciseTotal += ( v == 1u ? 1u : 0u ); - } - if( preciseTotal > 0 ) - { - rw::formatTo( hdr, sizeof( hdr ), "\"precise\":{},", preciseTotal ); - w.write( hdr ); - } + rw::formatTo( hdr, sizeof( hdr ), "\"precise\":{},", h.coverage.scipPinnedEdges ); + w.write( hdr ); } w.write( "\"order\":" ); - writeJsonStr( w, h.orderAttr, esc ); + writeJsonStr( w, emitOrderTraits( h.plan.emitOrder ).orderAttr, esc ); // R-E (2026-08-17 harvest): the JSON twin of the XML `` — same condition (single-root only, // multi-root's own roots_count/roots table below already names every root), right after order= like the @@ -11496,29 +11791,29 @@ inline void writeJsonMapHeader( JsonWriter& w, std::string& esc, const JsonMapHe // headers carry the SAME KEYSET for the same run, so this is not an XML-side courtesy — a JSON consumer // (every MCP client) reading a truncated ranking with no key to tell it so is the exact defect the XML // side just closed. Same slot, same absent-means-converged rule. - w.write( renderDisclosure( h.ann->prDisclosure, DiscloseAs::JsonKeys ) ); + w.write( renderDisclosure( h.ann.prDisclosure, DiscloseAs::JsonKeys ) ); w.write( renderHistoryUnread( DiscloseAs::JsonKeys ) ); // K51: the JSON twin of the root's history_unread= (absent unless the amp= walk was unread) // The JSON twin of the XML root's data_sections_cut= / next= (codeFirstKeep): same keys, same absent-at-zero rule. - if( h.dataSectionsCut.cut > 0 ) + if( const DataSectionsCut& cut = h.plan.ranked.dataSecCut; cut.cut > 0 ) { - w.write( ",\"data_sections_cut\":" + std::to_string( h.dataSectionsCut.cut ) + ",\"next\":" ); // composed, not a fixed buffer - writeJsonStr( w, dataSectionsNext( h.dataSectionsCut ), esc ); + w.write( ",\"data_sections_cut\":" + std::to_string( cut.cut ) + ",\"next\":" ); // composed, not a fixed buffer + writeJsonStr( w, dataSectionsNext( cut ), esc ); } - if( h.stemCut > 0 ) + if( const std::size_t stemCut = h.plan.groups.stemPick.cut; stemCut > 0 ) { - w.write( ",\"stem_cut\":" + std::to_string( h.stemCut ) ); // the JSON twin of the XML root's stem_cut= + w.write( ",\"stem_cut\":" + std::to_string( stemCut ) ); // the JSON twin of the XML root's stem_cut= } // §A4b: the multi-root prologue (A13) — `roots_count` joins the header gauges and a // `roots` table maps each label to its root path, ONLY when N≥2 (single-root output byte-unchanged). // Without it every `"p"` in the payload is an unresolvable root-relative fragment. - if( h.ing.rootLabels.size() < 2 ) + if( h.coverage.multiRootCount == 0 ) { return; } - rw::formatTo( hdr, sizeof( hdr ), ",\"roots_count\":{},\"roots\":[", h.ing.rootLabels.size() ); + rw::formatTo( hdr, sizeof( hdr ), ",\"roots_count\":{},\"roots\":[", h.coverage.multiRootCount ); w.write( hdr ); for( std::size_t r = 0; r < h.ing.rootLabels.size(); ++r ) { @@ -11534,6 +11829,30 @@ inline void writeJsonMapHeader( JsonWriter& w, std::string& esc, const JsonMapHe w.write( "]" ); } +// One JSON row's "c" array members: the callee objects over out-edges [from, to), comma-separated. §A4d: prov mirrors the XML +// attribute 1:1 — "scip" for a SCIP-pinned edge, "binding" for a decoded FFI binding, "import" for an ES named-import edge, +// "split" (C1) for one arm of a k-way split the resolver could not choose between, "via":"impl" (L6) for the one implementor. +// outProv parallels outTargets exactly, so index `e` is the same edge. The two dialects MUST spell the same vocabulary: +// test/mcpclidiffcheck.sh is the gate that says so. The "r" rows and the inventory entries share this writer. +inline void writeJsonCalleeObjects( JsonWriter& w, const IngestResult& ing, std::uint32_t from, std::uint32_t to, const std::vector& outTargets, + const std::vector* outProv, const std::vector* outNameOnly, std::string& esc ) +{ + for( std::uint32_t e = from; e < to; ++e ) + { + w.write( e > from ? ",{\"n\":" : "{\"n\":" ); writeJsonStr( w, ing.symbols[ outTargets[ e ] ].name, esc ); + if( outProv && e < outProv->size() && ( *outProv )[ e ] ) + { + w.write( ",\"" ); w.write( provAttrName( ( *outProv )[ e ] ) ); w.write( "\":" ); writeJsonStr( w, provLabel( ( *outProv )[ e ] ), esc ); + } + if( outNameOnly && e < outNameOnly->size() ) + { + writeMapCalleeJsonKind( w, ( *outNameOnly )[ e ] ); + } + w.write( "}" ); + } +} + + // D7: the JSON twin of writeMapInventoryXml — `,"inv":{"listed":L,"unlisted":U,"entry":[{"p":…,"n":…,"c":[…]}], // "ls":[{"p":…,"n":N,"f":[…]}]}` after the "r" array. The callee objects spell exactly what a "r" row's "c" array does. template @@ -11557,19 +11876,7 @@ inline void writeMapInventoryJson( JsonWriter& w, const IngestResult& ing, const w.write( i ? ",{\"p\":" : "{\"p\":" ); writeJsonStr( w, pathRel( s.fileId ), esc ); w.write( ",\"n\":" ); writeJsonStr( w, s.name, esc ); w.write( ",\"c\":[" ); - for( std::uint32_t e = outOff[ id ]; e < outOff[ id + 1 ]; ++e ) - { - w.write( e > outOff[ id ] ? ",{\"n\":" : "{\"n\":" ); writeJsonStr( w, ing.symbols[ outTargets[ e ] ].name, esc ); - if( outProv && e < outProv->size() && ( *outProv )[ e ] ) - { - w.write( ",\"" ); w.write( provAttrName( ( *outProv )[ e ] ) ); w.write( "\":" ); writeJsonStr( w, provLabel( ( *outProv )[ e ] ), esc ); // L6: "via":"impl" - } - if( outNameOnly && e < outNameOnly->size() ) - { - writeMapCalleeJsonKind( w, ( *outNameOnly )[ e ] ); - } - w.write( "}" ); - } + writeJsonCalleeObjects( w, ing, outOff[ id ], outOff[ id + 1 ], outTargets, outProv, outNameOnly, esc ); w.write( "]}" ); } w.write( "],\"ls\":[" ); @@ -11593,30 +11900,98 @@ inline void writeMapInventoryJson( JsonWriter& w, const IngestResult& ing, const w.write( "]}" ); } -// The default-map JSON sibling of serialize() — same rank/order/bucket logic (kept a deliberate, mechanical -// duplication per the L2 seam decision: a sibling emitter, not a shared-emission refactor of the XML path, -// so the G5 byte-identical-default contract carries zero risk from this addition). Scope: the common single- -// root invocation (metrics, fan-in, ambiguity, cbo/tested/lcom4/amp Q-metrics, stable/most-important-last/ -// auto-order, bind labels, est_tokens, per-edge provenance, the multi-root prologue, and — §B1.2 — the -// at/rank_by/window PROVENANCE STAMP a churn-ranked map carries. NOT covered (documented gap, refused -// upstream by jsonUnsupportedVerb before this is ever reached in those combinations): --map-diff -// (changed=), --expand's appended token math (extraBodyTokens). +// One "s" row object: the XML row's facts, key for attribute — the same presence rules (hasScopeAttr, stem rows, the +// overload collapse, absent-at-0 counters), then the "c" callee array. +inline void writeJsonMapRow( JsonWriter& w, const IngestResult& ing, const OverloadRows& rows, std::size_t rowIndex, const std::vector& stemRows, + const MapRowSources& src, std::string& esc ) +{ + char num[ 64 ]; + const NodeId id = rows.id[ rowIndex ]; + const Symbol& s = ing.symbols[ id ]; + w.write( "{\"t\":" ); writeJsonStr( w, symTag( s.kind ), esc ); + w.write( ",\"n\":" ); writeJsonStr( w, s.name, esc ); + if( hasScopeAttr( s ) ) { w.write( ",\"sc\":" ); writeJsonStr( w, s.scope, esc ); } // row 6: the XML sibling's sc=, one presence rule (hasScopeAttr) + if( !stemRows.empty() && std::ranges::binary_search( stemRows, id ) ) { w.write( ",\"stem\":1" ); } // MAP-STEM: the XML sibling's stem="1" + if( rows.overloads[ rowIndex ] > 1 ) + { + rw::formatTo( num, sizeof( num ), ",\"overloads\":{}", rows.overloads[ rowIndex ] ); w.write( num ); + } + w.write( splitLineJson( rows, rowIndex, s ) ); // the XML l= twin: a --metrics row split out of a same-name group + if( const std::string_view label = src.bind ? src.bind->labelOf( id ) : std::string_view{}; !label.empty() ) + { + w.write( ",\"bind\":" ); writeJsonStr( w, label, esc ); + } + if( const std::uint32_t ambK = counterAt( src.ambOut, id ); ambK > 0 ) + { + rw::formatTo( num, sizeof( num ), ",\"amb\":{}", ambK ); w.write( num ); + } + if( const std::uint32_t lpinK = counterAt( src.locPinOut, id ); lpinK > 0 ) // Phase 4: the XML lpin= twin + { + rw::formatTo( num, sizeof( num ), ",\"lpin\":{}", lpinK ); w.write( num ); + } + if( s.extentSuspect != 0 ) // extent honesty: the XML extent_suspect= twin, same reason spelling + { + w.write( ",\"extent_suspect\":" ); writeJsonStr( w, extent::extentSuspectReasons( s.extentSuspect ), esc ); + } + if( !emitOrderTraits( src.emitOrder ).stablePrefix ) + { + rw::formatTo( num, sizeof( num ), ",\"k\":{:.4f}", double( src.rank[ id ] ) ); w.write( num ); + } + if( src.metrics ) + { + const std::uint32_t outDegree = src.outOff[ id + 1 ] - src.outOff[ id ]; + writeJsonQMetrics( w, JsonQMetrics{ s, id, outDegree, src.fanIn, src.cbo, src.tested, src.lcom4, src.amp } ); + } + w.write( ",\"c\":[" ); + writeJsonCalleeObjects( w, ing, src.outOff[ id ], src.outOff[ id + 1 ], src.outTargets, src.outProv, src.outNameOnly, esc ); + w.write( "]}" ); +} + +// One "r" file object: its path and arch layer, then its rows. §P6.3 / §A4d: const/non-const overloads canonicalize to the +// SAME id, so a bucket straight from the rank order printed two byte-identical JSON objects and a consumer keying on "id" +// silently dropped one. Same collapse the XML path runs (overloadRowsFor), same "overloads" count. +template +inline void writeJsonMapFileGroup( JsonWriter& w, const IngestResult& ing, std::uint32_t f, const MapFileGroups& groups, const MapRowSources& src, + const PathRel& pathRel, std::string& esc ) +{ + w.write( "{\"p\":" ); writeJsonStr( w, pathRel( f ), esc ); + if( const char* fl = builtinLayer( rootRelPath( ing, f ) ); *fl ) { w.write( ",\"layer\":" ); writeJsonStr( w, fl, esc ); } + w.write( ",\"s\":[" ); + const OverloadRows rows = overloadRowsFor( ing, groups.buckets[ f ], src.metrics ); + for( std::size_t rowIndex = 0; rowIndex < rows.id.size(); ++rowIndex ) + { + if( rowIndex > 0 ) + { + w.write( "," ); + } + writeJsonMapRow( w, ing, rows, rowIndex, groups.stemPick.rows, src, esc ); + } + w.write( "]}" ); +} + +// The default-map JSON sibling of serialize(). It shares serialize()'s decisions about WHAT the map prints — one MapPlan +// (planMap) and the same MapCoverageFacts — and writes the same groups in its own +// spelling, so a defect fixed in one dialect's selection cannot survive in the other's. Scope: the common single-root +// invocation (metrics, fan-in, ambiguity, cbo/tested/lcom4/amp Q-metrics, stable/most-important-last/auto-order, bind labels, +// est_tokens, per-edge provenance, the multi-root prologue, and — §B1.2 — the at/rank_by/window PROVENANCE STAMP a +// churn-ranked map carries. NOT covered (documented gap, refused upstream by jsonUnsupportedVerb before this is ever reached +// in those combinations): --map-diff (changed=), --expand's appended token math (extraBodyTokens). // -// §B1.2 — churn was the third XML-only honesty fact this sibling dropped, and the enumeration above used to -// omit it entirely: it read as a complete coverage statement while `--rank-by=churn --json` and -// `--rank-by=pagerank --json` emitted keyset-identical headers. serializeJson now takes the same -// `MapAnnotations` the XML path takes and emits `at`/`rank_by`/`window` from it (writeJsonMapHeader). +// §B1.2 — churn was the third XML-only honesty fact this sibling dropped, and the enumeration above used to omit it entirely: +// it read as a complete coverage statement while `--rank-by=churn --json` and `--rank-by=pagerank --json` emitted +// keyset-identical headers. serializeJson now takes the same `MapAnnotations` the XML path takes and emits +// `at`/`rank_by`/`window` from it (writeJsonMapHeader). // // §A4b/§A4d closed three XML-only honesty attributes that this sibling used to drop SILENTLY: -// * multi-root: the header comment above claimed the combination was "refused upstream by -// jsonUnsupportedVerb" — it never was (no roots-count arm exists there), so a JSON consumer got -// `"p":"src/./svector.h"` with no label→path table and no signal the graph spanned several roots. -// `"roots"`/`"roots_count"` now mirror the XML `roots=` + `` prologue exactly. -// * overloads: this emitter never called collapseOverloadRows(), so a const/non-const pair printed TWO -// byte-identical rows and a consumer keying on "id" silently lost one. Collapsed here as in the XML, -// with the same `"overloads":N` (>1 only) discriminator. -// * prov/precise: an edge the SCIP overlay or an FFI binding actually PINNED read identical to a -// name-guessed one. Same absent-unless-present rule as the XML attribute. +// * multi-root: the header comment above claimed the combination was "refused upstream by jsonUnsupportedVerb" — it never +// was (no roots-count arm exists there), so a JSON consumer got `"p":"src/./svector.h"` with no label→path table and no +// signal the graph spanned several roots. `"roots"`/`"roots_count"` now mirror the XML `roots=` + `` +// prologue exactly. +// * overloads: this emitter never called collapseOverloadRows(), so a const/non-const pair printed TWO byte-identical rows +// and a consumer keying on "id" silently lost one. Collapsed here as in the XML, with the same `"overloads":N` (>1 only) +// discriminator. +// * prov/precise: an edge the SCIP overlay or an FFI binding actually PINNED read identical to a name-guessed one. Same +// absent-unless-present rule as the XML attribute. inline void serializeJson( std::FILE* out, const IngestResult& ing, const std::vector& rank, const std::vector& outOff, const std::vector& outTargets, int topK, bool mostImportantLast, bool metrics, @@ -11639,87 +12014,26 @@ inline void serializeJson( std::FILE* out, const IngestResult& ing, const std::v const std::vector* outNameOnly = nullptr, // FE-B: same as serialize()'s → "via":"name" std::size_t /*stdMemberDeclinedCalls*/ = 0 ) // serialize()'s legend clause; JSON carries no legend, so unread here { - const std::size_t S = ing.symbols.size(); const std::string rootPrefix = rootArg.empty() ? std::string() : rw::sarif::rootPrefixOf( rootArg ); const auto pathRel = [ & ]( std::uint32_t fileId ) -> std::string_view { return rootArg.empty() ? std::string_view( ing.files[ fileId ] ) : rw::sarif::rootRelativeUri( ing.files[ fileId ], rootPrefix ); }; - std::vector order( S ); - for( NodeId i = 0; i < S; ++i ) - { - order[i] = i; - } - sortutil::radixSortByScoreDescId( order, rank ); - dropUnmappedRows( ing, order ); // serialize()'s rows, same rule - - const std::size_t mapS = mapSymbolCount( ing ); - const std::size_t keep = std::min( topK > 0 ? std::size_t( topK ) : mapS, mapS ); - const DataSectionsCut dataSecCut = ann.codeFirstRows ? codeFirstKeep( ing, order, keep ) : DataSectionsCut{}; // serialize()'s pick, same rule - - std::vector> buckets( ing.files.size() ); - std::vector fileOrder; - std::vector seen( ing.files.size(), 0 ); - for( std::size_t k = 0; k < keep; ++k ) - { - const NodeId id = order[k]; - const std::uint32_t f = ing.symbols[id].fileId; - if( !seen[f] ) { seen[f] = 1; fileOrder.push_back( f ); } - buckets[f].push_back( id ); - } - // MAP-STEM: the XML twin's reserved stem-namesake rows, the same rule over the same buckets - const MapStemPick stemPick = pickMapStemRows( ing, ann, buckets, fileOrder ); - const std::vector& stemRows = stemPick.rows; - // D7: the XML twin's inventory, the same selection (mapinventory.h) over the same printed-file set - const MapInventory inventory = mapInventoryWanted( ing, ann ) ? computeMapInventory( ing, outOff, outTargets, seen, pathRel ) - : MapInventory{}; - - // T1/§H7: SAME byte-model the XML sibling uses, in the same two roles — the fill-order oracle and the - // rate source. The REPORTED est_tokens is measured from the emitted bytes in PHASE 2 below, exactly as - // in serialize(): a defect fixed in one serialization and not the other is how the §H5 dialect - // divergences are born, and this emitter had the identical --metrics under-report (MEASURED: 1780 B - // reported as est_tokens=507, 3.51 B/tok). - const TokenEstimate mapEst = estimateTokens( ing, order, keep, outOff, outTargets ); - const std::size_t mapEstTokens = mapEst.tokens; - - const bool autoFlip = autoOrder && !stable && !mostImportantLast && mapEstTokens > kFillOrderThreshold; - const bool effImportantLast = mostImportantLast || autoFlip; - if( stable ) - { - std::sort( fileOrder.begin(), fileOrder.end(), - [ & ]( std::uint32_t a, std::uint32_t b ) { return ing.files[a] < ing.files[b]; } ); - for( std::vector& b : buckets ) - { - std::sort( b.begin(), b.end() ); - } - } - else if( effImportantLast ) - { - std::reverse( fileOrder.begin(), fileOrder.end() ); - for( std::vector& b : buckets ) - { - std::reverse( b.begin(), b.end() ); - } - } - - const std::size_t ambTotal = counterTotal( ambOut ); - const std::size_t unresolvedTotal = counterTotal( unresolvedOut ); - const std::size_t locPinTotal = counterTotal( locPinOut ); // Phase 4: Σ lpin, the JSON twin of locality_pinned= - const std::size_t declinedTotal = counterTotal( declinedOut ); // Σ declinedOut, the JSON twin of declined= - std::size_t extentSuspectTotal = 0; // extent honesty: the JSON twin of extent_suspect_syms= - for( const Symbol& sym : ing.symbols ) - { - extentSuspectTotal += sym.extentSuspect != 0 ? 1u : 0u; - } - const char* orderAttr = stable ? "stable" - : mostImportantLast ? "important-last" - : autoFlip ? "important-last(auto:fill)" - : "important-first"; - - // ── PHASE 1: render the "r" array into a buffer (§H7 — see serialize()'s PHASE 1 for the full reasoning: - // measure, decide, then write). DEGRADE: an open_memstream failure emits the header FIRST with the - // MODELLED estimate (the pre-§H7 number, never a fabricated one) and streams the array behind it. + // ── WHICH rows, in WHICH order: serialize()'s plan. This dialect has no in=DIR stub spelling; it always prints its rows. ──── + // The byte model in the plan plays the same two roles as in serialize() — the fill-order oracle and the rate source; the + // REPORTED est_tokens is measured from the emitted bytes in PHASE 2 below (this emitter had the identical --metrics + // under-report: MEASURED 1780 B reported as est_tokens=507, 3.51 B/tok). + const MapPlan plan = planMap( ing, rank, outOff, outTargets, ann, topK, + MapOrderRequest{ .stable = stable, .mostImportantLast = mostImportantLast, .autoOrder = autoOrder }, + MapResolverCounters{ .ambOut = ambOut, .unresolvedOut = unresolvedOut, .locPinOut = locPinOut, + .declinedOut = declinedOut, .externalCalls = externalCalls }, + MapStubPolicy::AlwaysPrintRows, pathRel ); + const MapCoverageFacts coverage = mapCoverageFacts( ing, outProv ); + + // ── PHASE 1: render the "r" array into a buffer (§H7 — see serialize()'s PHASE 1 for the full reasoning: measure, decide, + // then write). DEGRADE: an open_memstream failure emits the header FIRST with the MODELLED estimate (the pre-§H7 number, + // never a fabricated one) and streams the array behind it. rw::MemoryStream rowsStream; std::FILE* const rowsMem = openChargeStream( rowsStream ); MapEstimate estimate{ ann.payloadUncharged }; @@ -11728,132 +12042,51 @@ inline void serializeJson( std::FILE* out, const IngestResult& ing, const std::v DISCLOSE( estimate, MapEstimate::DisclosureWhy::ChargeBufferFailed, "serializeJson: open_memstream failed — est_tokens reports the MODELLED bytes, not the emitted ones" ); } - // ONE header emitter, used by the degrade write, the size probe and the real write, so the three can - // never disagree on the header's shape. The peak attribute is read here once for all three: a second reading may - // pass the limit the first did not, and the probe would then have priced a shorter header than the one written. + // ONE header emitter, used by the degrade write, the size probe and the real write, so the three can never disagree on the + // header's shape. The peak attribute is read here once for all three: a second reading may pass the limit the first did + // not, and the probe would then have priced a shorter header than the one written. const std::string memoryPeakJson = buildMemoryPeakAttr( ing, true ); std::string esc; const auto emitHeader = [ & ]( std::FILE* dst, std::size_t estTokens ) { JsonWriter hw( dst ); - writeJsonMapHeader( hw, esc, JsonMapHeader{ ing, mapSymbolCount( ing ), outTargets.size(), keep + stemRows.size(), estTokens, ambTotal, - unresolvedTotal, orderAttr, outProv, &ann, rootArg, locPinTotal, externalCalls, declinedTotal, - extentSuspectTotal, macroBlankedFileCount( ing ), ing.crawlSkips.nestRefusedFiles, - estimate.isModelled, dataSecCut, stemPick.cut, memoryPeakJson } ); + writeJsonMapHeader( hw, esc, JsonMapHeader{ .ing = ing, .plan = plan, .coverage = coverage, .edgeCount = outTargets.size(), .estTokens = estTokens, + .isEstModelled = estimate.isModelled, .ann = ann, .rootArg = rootArg, .memoryPeakJson = memoryPeakJson } ); hw.write( ",\"r\":[" ); }; - // The "r" array, as ONE renderer both paths call — serialize()'s writeChildren above, for the same reason: a buffer - // that opened and then lost a write has already spent the rows, so the fallback must be able to write them again. + // The "r" array, as ONE renderer both paths call — serialize()'s writeChildren, for the same reason: a buffer that opened and + // then lost a write has already spent the rows, so the fallback must be able to write them again. + const MapRowSources rowSources{ .rank = rank, .outOff = outOff, .outTargets = outTargets, .outProv = outProv, .outNameOnly = outNameOnly, + .ambOut = ambOut, .locPinOut = locPinOut, .bind = bind, .emitOrder = plan.emitOrder, .metrics = metrics, + .fanIn = fanIn, .cbo = cbo, .tested = tested, .lcom4 = lcom4, .amp = amp }; const auto writeRows = [ & ]( JsonWriter& w ) { - char num[ 64 ]; - - bool firstFile = true; - for( std::uint32_t f : fileOrder ) + for( std::size_t i = 0; i < plan.groups.fileOrder.size(); ++i ) { - if( !firstFile ) + if( i > 0 ) { w.write( "," ); } - firstFile = false; - w.write( "{\"p\":" ); writeJsonStr( w, pathRel( f ), esc ); - if( const char* fl = builtinLayer( rootRelPath( ing, f ) ); *fl ) { w.write( ",\"layer\":" ); writeJsonStr( w, fl, esc ); } - w.write( ",\"s\":[" ); - - // §P6.3 / §A4d: const/non-const overloads canonicalize to the SAME id, so a bucket straight from - // `order` printed two byte-identical JSON objects and a consumer keying on "id" silently dropped - // one. Same collapse the XML path runs (collapseOverloadRows above), same "overloads" count. - const OverloadRows rows = overloadRowsFor( ing, buckets[f], metrics ); // the XML path's per-definition rule - - bool firstSym = true; - for( std::size_t rowIndex = 0; rowIndex < rows.id.size(); ++rowIndex ) - { - const NodeId id = rows.id[ rowIndex ]; - if( !firstSym ) - { - w.write( "," ); - } - firstSym = false; - const Symbol& s = ing.symbols[id]; - const std::uint32_t out2= outOff[id + 1] - outOff[id]; - - w.write( "{\"t\":" ); writeJsonStr( w, symTag( s.kind ), esc ); - w.write( ",\"n\":" ); writeJsonStr( w, s.name, esc ); - - if( hasScopeAttr( s ) ) { w.write( ",\"sc\":" ); writeJsonStr( w, s.scope, esc ); } // row 6: the XML sibling's sc=, one presence rule (hasScopeAttr) - if( !stemRows.empty() && std::ranges::binary_search( stemRows, id ) ) { w.write( ",\"stem\":1" ); } // MAP-STEM: the XML sibling's stem="1" - - if( rows.overloads[ rowIndex ] > 1 ) - { rw::formatTo( num, sizeof( num ), ",\"overloads\":{}", rows.overloads[ rowIndex ] ); w.write( num ); } - w.write( splitLineJson( rows, rowIndex, s ) ); // the XML l= twin: a --metrics row split out of a same-name group - - if( const std::string_view label = bind ? bind->labelOf( id ) : std::string_view{}; !label.empty() ) - { w.write( ",\"bind\":" ); writeJsonStr( w, label, esc ); } - - if( const std::uint32_t ambK = counterAt( ambOut, id ); ambK > 0 ) - { rw::formatTo( num, sizeof( num ), ",\"amb\":{}", ambK ); w.write( num ); } - - if( const std::uint32_t lpinK = counterAt( locPinOut, id ); lpinK > 0 ) // Phase 4: the XML lpin= twin - { rw::formatTo( num, sizeof( num ), ",\"lpin\":{}", lpinK ); w.write( num ); } - - if( s.extentSuspect != 0 ) // extent honesty: the XML extent_suspect= twin, same reason spelling - { w.write( ",\"extent_suspect\":" ); writeJsonStr( w, extent::extentSuspectReasons( s.extentSuspect ), esc ); } - - if( !stable ) - { rw::formatTo( num, sizeof( num ), ",\"k\":{:.4f}", double( rank[id] ) ); w.write( num ); } - - if( metrics ) - { - writeJsonQMetrics( w, JsonQMetrics{ s, id, out2, fanIn, cbo, tested, lcom4, amp } ); - } - - w.write( ",\"c\":[" ); - bool firstC = true; - for( std::uint32_t e = outOff[id]; e < outOff[id + 1]; ++e ) - { - if( !firstC ) - { - w.write( "," ); - } - firstC = false; - w.write( "{\"n\":" ); writeJsonStr( w, ing.symbols[ outTargets[e] ].name, esc ); - // §A4d: prov mirrors the XML attribute 1:1 — "scip" for a SCIP-pinned edge, "binding" for a - // decoded FFI binding, "import" for an ES named-import edge, "split" (C1) for one arm of a k-way - // split the resolver could not choose between. outProv parallels outTargets exactly, so index `e` - // is the same edge. The two dialects MUST spell the same vocabulary: test/mcpclidiffcheck.sh is - // the gate that says so. - if( outProv && e < outProv->size() && (*outProv)[e] ) - { - w.write( ",\"" ); w.write( provAttrName( (*outProv)[e] ) ); w.write( "\":" ); writeJsonStr( w, provLabel( (*outProv)[e] ), esc ); // L6: "via":"impl" - } - if( outNameOnly && e < outNameOnly->size() ) - { - writeMapCalleeJsonKind( w, ( *outNameOnly )[e] ); - } - w.write( "}" ); - } - w.write( "]}" ); - } - w.write( "]}" ); + writeJsonMapFileGroup( w, ing, plan.groups.fileOrder[ i ], plan.groups, rowSources, pathRel, esc ); } w.write( "]" ); - if( inventory.active ) + if( plan.groups.inventory.active ) // after "r", always: a key of one object (see writeMapChildren on the XML placement) { - writeMapInventoryJson( w, ing, inventory, pathRel, outOff, outTargets, outProv, outNameOnly, esc ); + writeMapInventoryJson( w, ing, plan.groups.inventory, pathRel, outOff, outTargets, outProv, outNameOnly, esc ); } w.write( "}" ); }; // DEGRADE, one path for both failures: the header FIRST with the MODELLED estimate, the array streamed behind it. const auto emitModelled = [ & ]() { - emitHeader( out, mapEstTokens ); + emitHeader( out, plan.mapEst.tokens ); JsonWriter direct( out ); writeRows( direct ); direct.flush(); if( outEstTokens ) { - *outEstTokens = mapEstTokens; + *outEstTokens = plan.mapEst.tokens; } }; if( !rowsMem ) @@ -11892,7 +12125,7 @@ inline void serializeJson( std::FILE* out, const IngestResult& ing, const std::v rw::MemoryStream probe; if( std::FILE* const pm = openChargeStream( probe ) ) { - emitHeader( pm, mapEstTokens ); + emitHeader( pm, plan.mapEst.tokens ); if( const rw::MemoryStreamBytes header = probe.finish(); header.isWhole ) { headerBytes = header.bytes.size(); @@ -11911,7 +12144,7 @@ inline void serializeJson( std::FILE* out, const IngestResult& ing, const std::v } const std::size_t estTokens = tokensForEmittedBytes( headerBytes + kEstTokensFieldReserve + rowsStr.size(), - mapEst.bytesPerToken() ); + plan.mapEst.bytesPerToken() ); if( outEstTokens ) { *outEstTokens = estTokens; diff --git a/src/shstatus.h b/src/shstatus.h index 867d82e81..1229b4645 100644 --- a/src/shstatus.h +++ b/src/shstatus.h @@ -118,6 +118,36 @@ struct Tree std::vector nodes; std::vector lists; std::uint32_t top = kNone; + bool cut = false; // the nesting budget (kMaxShellNest) stopped the scan: what lies past it was not parsed +}; + +// ONE nesting budget for the lexer and the parser (CR712-SHSTATUS-DEPTH): every recursion of either — a quote or $( ) the +// lexer skips through, a compound command or a substitution the parser descends into — takes a level, so a script nested +// past kMaxShellNest is cut there (Tree::cut) instead of exhausting the stack (20,000 nested subshells crashed the scan). +inline constexpr int kMaxShellNest = 64; // shell nesting past this depth is cut and not judged; --quality-delta says shell_cut=N +struct NestBudget +{ + int depth = 0; + bool cut = false; +}; +// One level of the budget for the scope of a recursion; `over` = the budget is spent (and the cut is recorded). +class NestLevel +{ +public: + explicit NestLevel( NestBudget& b ) noexcept : b_( b ) + { + over_ = b_.depth >= kMaxShellNest; + b_.cut = b_.cut || over_; // the disclosure: Tree::cut, then the answer's shell_cut= (quality.h defectSitesOf) + ++b_.depth; + } + ~NestLevel() { --b_.depth; } + NestLevel( const NestLevel& ) = delete; + NestLevel& operator=( const NestLevel& ) = delete; + bool over() const noexcept { return over_; } + +private: + NestBudget& b_; + bool over_ = false; }; namespace detail @@ -462,8 +492,15 @@ inline bool isRedirOp( std::string_view o ) noexcept return o == "<" || o == ">" || o == ">>" || o == "&>" || o == "&>>" || o == ">&" || o == "<&" || o == "<>" || o == ">|" || o == "<<<" || o == "<<"; } -std::size_t skipParen( std::string_view s, std::size_t i ); -inline std::size_t skipQuote( std::string_view s, std::size_t i, char q ) // s[i] is the opening quote +// s[i] is an opening backquote: the index past its closing one, or the end when it never closes. +inline std::size_t pastBacktick( std::string_view s, std::size_t i ) noexcept +{ + const std::size_t j = s.find( '`', i + 1 ); + return j == std::string_view::npos ? s.size() : j + 1; +} + +std::size_t skipParen( std::string_view s, std::size_t i, NestBudget& nb ); +inline std::size_t skipQuote( std::string_view s, std::size_t i, char q, NestBudget& nb ) // s[i] is the opening quote { ++i; while( i < s.size() ) @@ -476,13 +513,12 @@ inline std::size_t skipQuote( std::string_view s, std::size_t i, char q ) // s } if( q == '"' && c == '$' && startsAt( s, i, "$(" ) ) { - i = skipParen( s, i + 1 ); + i = skipParen( s, i + 1, nb ); continue; } if( q == '"' && c == '`' ) { - const std::size_t j = s.find( '`', i + 1 ); - i = j == std::string_view::npos ? s.size() : j + 1; + i = pastBacktick( s, i ); continue; } if( c == q ) @@ -493,8 +529,15 @@ inline std::size_t skipQuote( std::string_view s, std::size_t i, char q ) // s } return i; } -inline std::size_t skipParen( std::string_view s, std::size_t i ) // s[i] == '(' +// The one budget guard of the skip trio: skipQuote and skipBrace recurse only through skipParen, so each nesting level of +// "$( … "$( … )" … )" or ${ … "$( … )" … } costs one level here. +inline std::size_t skipParen( std::string_view s, std::size_t i, NestBudget& nb ) // s[i] == '(' { + const NestLevel level( nb ); + if( level.over() ) + { + return s.size(); // past the budget: the rest is one unscanned word (Tree::cut says so) + } int depth = 0; while( i < s.size() ) { @@ -506,7 +549,7 @@ inline std::size_t skipParen( std::string_view s, std::size_t i ) // s[i] == ' } if( c == '\'' || c == '"' ) { - i = skipQuote( s, i, c ); + i = skipQuote( s, i, c, nb ); continue; } if( c == '#' && ( i == 0 || s[i - 1] == ' ' || s[i - 1] == '\t' || s[i - 1] == '\n' || s[i - 1] == ';' || s[i - 1] == '(' ) ) @@ -531,7 +574,7 @@ inline std::size_t skipParen( std::string_view s, std::size_t i ) // s[i] == ' } return i; } -inline std::size_t skipBrace( std::string_view s, std::size_t i ) // s[i] == '{' of a ${...} +inline std::size_t skipBrace( std::string_view s, std::size_t i, NestBudget& nb ) // s[i] == '{' of a ${...} { int depth = 0; while( i < s.size() ) @@ -544,7 +587,7 @@ inline std::size_t skipBrace( std::string_view s, std::size_t i ) // s[i] == ' } if( c == '\'' || c == '"' ) { - i = skipQuote( s, i, c ); + i = skipQuote( s, i, c, nb ); continue; } if( c == '{' ) @@ -567,7 +610,7 @@ inline std::size_t skipBrace( std::string_view s, std::size_t i ) // s[i] == ' // A double-quoted text with its own single quotes blanked: they are literal there ("don't"), but a quote inside a $( ) // or ` ` it holds is live ("$( grep -o '& out ) +inline void subsIn( std::string_view raw, std::uint32_t line, std::uint32_t base, std::vector& out, NestBudget& nb ) { std::size_t i = 0; while( i < raw.size() ) @@ -613,17 +655,17 @@ inline void subsIn( std::string_view raw, std::uint32_t line, std::uint32_t base } if( c == '\'' ) { - i = skipQuote( raw, i, '\'' ); + i = skipQuote( raw, i, '\'', nb ); continue; } if( startsAt( raw, i, "$((" ) ) { - i = skipParen( raw, i + 1 ); + i = skipParen( raw, i + 1, nb ); continue; } if( startsAt( raw, i, "$(" ) ) { - const std::size_t j = skipParen( raw, i + 1 ); + const std::size_t j = skipParen( raw, i + 1, nb ); out.push_back( { std::string( sliceOf( raw, i + 2, j - 1 ) ), static_cast( line + countNl( raw, 0, i ) ), static_cast( base + i + 2 ), kNone } ); i = j; continue; @@ -639,8 +681,13 @@ inline void subsIn( std::string_view raw, std::uint32_t line, std::uint32_t base if( c == '"' ) { // descend: substitutions inside double quotes are live (single quotes inside them are not quotes) - const std::size_t j = skipQuote( raw, i, '"' ); - subsIn( dqLiteralQuotes( sliceOf( raw, i + 1, j - 1 ) ), static_cast( line + countNl( raw, 0, i ) ), static_cast( base + i + 1 ), out ); + const std::size_t j = skipQuote( raw, i, '"', nb ); + const NestLevel level( nb ); // the descent is a recursion of its own + if( level.over() ) + { + return; + } + subsIn( dqLiteralQuotes( sliceOf( raw, i + 1, j - 1 ), nb ), static_cast( line + countNl( raw, 0, i ) ), static_cast( base + i + 1 ), out, nb ); i = j; continue; } @@ -703,7 +750,7 @@ inline std::size_t heredocDelim( std::string_view s, std::size_t k, std::string& class Lexer { public: - Lexer( std::string_view src, std::uint32_t line0, std::uint32_t base ) : src_( src ), n_( src.size() ), line_( line0 ), base_( base ) {} + Lexer( std::string_view src, std::uint32_t line0, std::uint32_t base, NestBudget& nb ) : src_( src ), n_( src.size() ), line_( line0 ), base_( base ), nb_( nb ) {} std::vector run() { @@ -725,6 +772,7 @@ class Lexer std::size_t i_ = 0; std::uint32_t line_; std::uint32_t base_; + NestBudget& nb_; std::vector> pending_; // heredoc delimiters waiting for the end of this line bool prevBlank_ = true; std::vector toks_; @@ -758,7 +806,7 @@ class Lexer t.word.pos = posAt( b ); if( withSubs ) { - subsIn( t.word.text, line_, t.word.pos, t.word.subs ); + subsIn( t.word.text, line_, t.word.pos, t.word.subs, nb_ ); } t.line = line_; t.pos = t.word.pos; @@ -933,36 +981,34 @@ class Lexer } if( d == '\'' || d == '"' ) { - return skipQuote( src_, i, d ); + return skipQuote( src_, i, d, nb_ ); } if( d == '`' ) { - const std::size_t j = src_.find( '`', i + 1 ); - return j == std::string_view::npos ? n_ : j + 1; + return pastBacktick( src_, i ); // n_ == src_.size() } if( startsAt( src_, i, "$(" ) ) { - return skipParen( src_, i + 1 ); + return skipParen( src_, i + 1, nb_ ); } if( startsAt( src_, i, "${" ) ) { - return skipBrace( src_, i + 1 ); + return skipBrace( src_, i + 1, nb_ ); } if( d == '(' && i > start && src_[i - 1] == '=' ) // array assignment X=( ... ) { - return skipParen( src_, i ); + return skipParen( src_, i, nb_ ); } return i + 1; } }; -inline std::vector lex( std::string_view src, std::uint32_t line0, std::uint32_t base ) +inline std::vector lex( std::string_view src, std::uint32_t line0, std::uint32_t base, NestBudget& nb ) { - return Lexer( src, line0, base ).run(); + return Lexer( src, line0, base, nb ).run(); } // ── parser ────────────────────────────────────────────────────────────────────────────────────────────────────────── -inline constexpr int kMaxSubDepth = 40; // nested $( ) parsed past this depth are left unparsed (an empty list) struct Stops { @@ -976,7 +1022,7 @@ struct Stops class Parser { public: - Parser( Tree& tree, std::vector toks, int depth ) : t_( std::move( toks ) ), tree_( tree ), depth_( depth ) {} + Parser( Tree& tree, std::vector toks, NestBudget& nb ) : t_( std::move( toks ) ), tree_( tree ), nb_( nb ) {} std::uint32_t parseAll() { @@ -1000,7 +1046,7 @@ class Parser std::vector t_; std::size_t i_ = 0; Tree& tree_; - int depth_; + NestBudget& nb_; // shared with the lexer and every nested Parser: one budget for the whole script Tok eof_{}; const Tok& peek() const noexcept @@ -1057,11 +1103,12 @@ class Parser { for( Sub& s : w.subs ) { - if( depth_ >= kMaxSubDepth ) + const NestLevel level( nb_ ); + if( level.over() ) { - continue; + continue; // past the budget: an empty list (Tree::cut says so) } - Parser p( tree_, lex( s.inner, s.line, s.pos ), depth_ + 1 ); + Parser p( tree_, lex( s.inner, s.line, s.pos, nb_ ), nb_ ); s.list = p.parseAll(); } } @@ -1146,6 +1193,12 @@ class Parser } std::uint32_t parseCommand( const Stops& stops ) { + const NestLevel level( nb_ ); // every nested list (subshell, group, if, loop, case, function body) is reached through here + if( level.over() ) + { + i_ = t_.size(); // past the budget: the rest of this token stream is not parsed (Tree::cut says so) + return kNone; + } const Tok& p = peek(); if( p.kind == TokKind::Eof || stopped( stops ) ) { @@ -1453,8 +1506,10 @@ class Parser inline Tree parse( std::string_view src ) { Tree t; - detail::Parser p( t, detail::lex( src, 1, 0 ), 0 ); + NestBudget nb; + detail::Parser p( t, detail::lex( src, 1, 0, nb ), nb ); t.top = p.parseAll(); + t.cut = nb.cut; return t; } diff --git a/src/verbs_quality.h b/src/verbs_quality.h index d0b6186af..6ebc5d8e3 100644 --- a/src/verbs_quality.h +++ b/src/verbs_quality.h @@ -1477,13 +1477,13 @@ inline constexpr const char* kQdLegendCore = "score). THIRTEEN KINDS, and kind= on every row names which one: complexity over the ccx bar, verbosity " "(LOC), nesting, params, duplication, dead-code, api-surface (new public contract drift), " "error-masking, short-horizon-churn, new-clone-of-reused-helper, placeholder (added stub/TODO), " - "defect-shape (defect= names it), tangle (a long function's nesting, deep share and steering locals; report-only). " + "defect-shape (defect= names it), tangle (a long function's nesting, deep share and steering locals). " "THREE independent axes, in this " "order: (1) acked findings are suppressed entirely (acked= counts them); (2) ORIGIN — a finding on a " "symbol that EXISTED at the baseline is preexisting-worse (no origin attribute), one that exists only " "because the code is NEW carries origin=\"new-symbol\"; (3) MATERIALITY — a small numeric delta is " "sev=\"minor\", and minor= counts them. EXIT 2 fires only on preexisting-worse AND major, the gating= count; " - "new-symbol rows never gate, except defect-shape format-arity and a new function at the ceiling, so exit 0 " + "new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling and a tangled new function, so exit 0 " "is NOT a verdict on them — nothing that existed got worse, but the new debt is yours: read them. Clone kinds are new-symbol only when EVERY member is new; short-horizon-churn is " "preexisting by construction. preexisting-worse= and new-symbol= partition regressions=. stale= is a " "FOURTH axis, never gating and never counted in regressions=: rows in the .ripwire_quality_acks ledger " @@ -1497,6 +1497,12 @@ inline constexpr const char* kQdLegendCore = // P8 (L7): the threshold beside the number "bar= on a complexity/verbosity/nesting/params row is the threshold now= is judged against (ccx 15, loc 60, nest 4, params 5). "; +// CR712-SHSTATUS-DEPTH — present-only: rides with shell_cut= on the root (QdRootFields::shellCut), absent at 0. +inline constexpr const char* kQdShellCutLegend = + "shell_cut=N: shell files whose defect-shape scan stopped at nesting depth 64; what lies deeper was not judged. "; + +static_assert( rw::shstatus::kMaxShellNest == 64, "kQdShellCutLegend's and compactlegend.h's shell_cut= sentences say depth 64" ); + // The macro FAMILIES, and why a member of one cannot be judged dead — printed only when the run actually // excluded something, because on a repo with no such macro the roster explains an empty set. inline constexpr const char* kQdRegisterMacroLegend = @@ -1647,7 +1653,10 @@ inline constexpr const char* kQdSchemeLegend = "written back under the new rule, which is the normal steady state rather than a failure. " "scheme_ambiguous= counts rows it REFUSED to move: the old key of a name that folded across N files " "maps to N new keys, so which symbol the ack was written for is unknowable from the ledger; those rows " - "keep their old key and surface under stale= rather than being fanned out to all N or guessed. "; + "keep their old key and surface under stale= rather than being fanned out to all N or guessed. " + "The same replay re-files a defect-shape ack written while a site value carried two facet bits " + "(v0.6.10 and earlier; three since the unchecked-status facet): the row's sites are re-hashed under the " + "two-bit rule and an ack at that key moves to the current one, counted in acks_rekeyed_by_scheme= too. "; // The sa ROW dictionary — emitted only when there are sa rows. The stale= axis itself is defined in the // core paragraph, because the counter is on the root of every report whether or not any row follows it. @@ -1744,23 +1753,25 @@ inline constexpr const char* kQdFailureDefaultLegend = // QD-TANGLE — emitted only when a tangle row is in the document. inline constexpr const char* kQdTangleLegend = - "tangle rows are REPORT-ONLY (always sev=\"minor\", never gating). was= and now= are the score S = T x log2(loc/50), " + "a tangle row GATES when the function is new, crossed the bar or its score grew while over it (not a moved body, not test " + "code); a row an input rose on while the score did not grow is sev=\"minor\". was= and now= are the score S = T x log2(loc/50), " "T = nesting levels past 3 + deep%/5 + steering locals per 100 lines (deep%: the share of lines inside regions at nesting 4+, " "short arms of a flat switch or else-if chain of 4+ arms left out); bar= 6. Length only AMPLIFIES: a function of 50 lines or " "fewer, a long flat body and an orchestrator of named steps all score 0. A row means the change made it so: the function is " - "new, crossed the bar, or an input rose (nesting +1, deep lines +5, a new steering local); why= names those inputs, fix= the " + "new, crossed the bar, its score grew against the baseline while over the bar (the ratchet: a tenth counts), or an input rose " + "(nesting +1, deep lines +5, a new steering local); why= names the inputs that changed, fix= the " "shape the rise calls for with its lines, locals= the steering locals: a primitive local written again after its " "declaration and read by a branch condition 10 or more statements after that write. "; // D4 — present when the ratchet read its reference point (ratchet_ref= on the root). A ratchet= facet needs that read, so this one // sentence defines both. inline constexpr const char* kQdRatchetLegend = - "ratchet_ref= is the reference point the tangle ratchet read, the last tag reachable from HEAD: each function over the tangle bar " - "whose inputs this change moved is compared with its BEST since that tag (the lowest of each input and of the score over every first-parent " + "ratchet_ref= is the reference point the tangle rows' history read, the last tag reachable from HEAD: each tangle row on a function " + "that existed at the baseline is compared with its BEST since that tag (the lowest of each input and of the score over every first-parent " "version since it, or since the function's creation); ratchet_judged= counts those that had history, ratchet_unread= versions " "that could not be measured, ratchet_cut=\"1\" that only the 512 newest versions were read. ratchet=\"TAG\" on a tangle row: " "the score is above its best since TAG and an input rose over its minimum by the rise rule, so a function that crept up across " - "changes is named; why= then adds \"best since TAG: ...\", and on a row of its own was= is that best score. Report-only. "; + "changes says so; why= then adds \"best since TAG: ...\". A facet only: it makes no row and changes no severity. "; // QD-CREDIT-ROW — present when the document carries an section. inline constexpr const char* kQdImprovedLegend = @@ -1895,6 +1906,7 @@ struct QualityDeltaLegendParts bool staleTree = false; // D3 QD-STALE-HEADER: stale_tree= is on the root bool ratchetRead = false; // D4: ratchet_ref= is on the root bool anyImproved = false; // QD-CREDIT-ROW: the section is in the document + bool shellCut = false; // CR712-SHSTATUS-DEPTH: shell_cut= is on the root }; // qd-memory-degrade — present-only: each rides only with the attributes it defines. No double dash anywhere in them @@ -2122,6 +2134,10 @@ inline void emitQualityDeltaLegend( const QualityDeltaLegendParts& p, std::FILE* { rw::emitRaw( out, kQdImprovedLegend ); // QD-CREDIT-ROW } + if( p.shellCut ) + { + rw::emitRaw( out, kQdShellCutLegend ); // CR712-SHSTATUS-DEPTH + } if( p.scoped ) { @@ -2166,15 +2182,12 @@ inline void emitQualityDeltaLegend( const QualityDeltaLegendParts& p, std::FILE* // F-13 — the one place both --dead-code and --quality-delta turn a RegisterMacroConfigDiagnostics into // output: the specific keys/names on stderr (never guessed at in the XML — a hand-edited config's tokens -// are not free text an attribute repeats), and the shared `config-warnings="N"` attribute string, present -// only when non-zero (this file's standing convention for every optional root attribute). One function so -// the two verbs cannot report the same misconfiguration two different ways. -inline std::string registerMacroConfigWarningAttr( const rw::quality::RegisterMacroConfigDiagnostics& diag ) +// are not free text an attribute repeats; emitRegisterMacroConfigWarnings), and the shared `config-warnings="N"` +// attribute, present only when non-zero (this file's standing convention for every optional root attribute; +// --quality-delta spells it as a QdRootField). One pair of functions so the two verbs cannot report the same +// misconfiguration two different ways. +inline void emitRegisterMacroConfigWarnings( const rw::quality::RegisterMacroConfigDiagnostics& diag ) { - if( diag.total() == 0 ) - { - return std::string(); - } const auto joined = [] ( const std::vector& v ) -> std::string { std::string out; @@ -2195,7 +2208,13 @@ inline std::string registerMacroConfigWarningAttr( const rw::quality::RegisterMa rw::emitTo( stderr, "ripwire: .ripwire_config's register_macros= names a macro matching no indexed symbol (typo, or unused): {}\n", joined( diag.inertNames ).c_str() ); } - return " config-warnings=\"" + std::to_string( diag.total() ) + "\""; +} + +// --dead-code's half of F-13: the stderr lines, then the attribute. +inline std::string registerMacroConfigWarningAttr( const rw::quality::RegisterMacroConfigDiagnostics& diag ) +{ + emitRegisterMacroConfigWarnings( diag ); + return diag.total() == 0 ? std::string() : " config-warnings=\"" + std::to_string( diag.total() ) + "\""; } // H10 (capture-audit 2026-09-04): the --quality-ack run that has NOTHING to accept. It used to re-serialise @@ -2294,7 +2313,7 @@ DirtyPinVerdict inspectDirtyBaselinePin( const MainDispatch& d, const std::strin if( verdict.firstRow.empty() ) { verdict.firstRow = r.kind + " " + quality::displaySym( r.sym, cfg.rootPath ) - + " (was=" + std::to_string( r.was ) + " now=" + std::to_string( r.now ) + ")"; + + " (was=" + quality::rowValueText( r, r.was ) + " now=" + quality::rowValueText( r, r.now ) + ")"; // CR721: tangle in display units } } return verdict; @@ -2546,27 +2565,39 @@ inline void emitQdGatingLine( const std::vector& regs, // M12: displaySym, not first->sym raw — the XML/JSON rows both normalize sym's path segment // for display (quality::displaySym); this stderr line was the one caller that skipped it, // so it named "./src/…::rw::…" beside a row that named the same finding "src/…::rw::…". - // a gating row on NEW code is defect-shape format-arity or a new function at the ceiling (rowGates); the line names + // a gating row on NEW code is defect-shape format-arity, a new function at the ceiling or a tangled new function (rowGates); the line names // either part only when there is one, so every run without them keeps its bytes. const std::size_t newGating = static_cast( std::count_if( regs.begin(), regs.end(), []( const quality::Regression& r ) { return r.isNewSymbol && quality::rowGates( r ); } ) ); const std::size_t ceilingGating = static_cast( std::count_if( regs.begin(), regs.end(), []( const quality::Regression& r ) { return r.ceiling != 0 && quality::rowGates( r ); } ) ); + // a new-symbol tangle row gates under rule (b) (QD-LESSONS-2); was=/now= read as every surface prints them (a tangle score's tenths) + const std::size_t newTangleGating = static_cast( std::count_if( regs.begin(), regs.end(), []( const quality::Regression& r ) + { return r.isNewSymbol && r.kind == "tangle" && quality::rowGates( r ); } ) ); + const std::string was = quality::rowValueText( *first, first->was ), now = quality::rowValueText( *first, first->now ); if( ceilingGating != 0 ) { - rw::emitTo( stderr, "ripwire: --quality-delta gating: {} gating finding(s), {} of them a new function at the ceiling (ccx {} / {} lines); first: {} {}{} (was={} now={})\n", - gatingCount, ceilingGating, quality::newSymbolCeiling( quality::kCcxBar ), quality::newSymbolCeiling( quality::kLocBar ), - first->kind.c_str(), quality::displaySym( first->sym, deltaRoot ).c_str(), at.c_str(), first->was, first->now ); + const std::string tangled = newTangleGating == 0 ? std::string() + : std::format( ", {} a tangled new function (tangle {} or more)", newTangleGating, quality::metricValueText( "tangle", rw::kTangleBar10 ) ); + rw::emitTo( stderr, "ripwire: --quality-delta gating: {} gating finding(s), {} of them a new function at the ceiling (ccx {} / {} lines){}; first: {} {}{} (was={} now={})\n", + gatingCount, ceilingGating, quality::newSymbolCeiling( quality::kCcxBar ), quality::newSymbolCeiling( quality::kLocBar ), tangled, + first->kind.c_str(), quality::displaySym( first->sym, deltaRoot ).c_str(), at.c_str(), was, now ); } else if( newGating == 0 ) { rw::emitTo( stderr, "ripwire: --quality-delta gating: {} preexisting-worse major finding(s); first: {} {}{} (was={} now={})\n", - gatingCount, first->kind.c_str(), quality::displaySym( first->sym, deltaRoot ).c_str(), at.c_str(), first->was, first->now ); + gatingCount, first->kind.c_str(), quality::displaySym( first->sym, deltaRoot ).c_str(), at.c_str(), was, now ); + } + else if( newTangleGating != 0 ) + { + rw::emitTo( stderr, "ripwire: --quality-delta gating: {} gating finding(s), {} of them a tangled new function (tangle {} or more); first: {} {}{} (was={} now={})\n", + gatingCount, newTangleGating, quality::metricValueText( "tangle", rw::kTangleBar10 ), first->kind.c_str(), + quality::displaySym( first->sym, deltaRoot ).c_str(), at.c_str(), was, now ); } else { rw::emitTo( stderr, "ripwire: --quality-delta gating: {} gating finding(s), {} of them defect-shape format-arity on new code; first: {} {}{} (was={} now={})\n", - gatingCount, newGating, first->kind.c_str(), quality::displaySym( first->sym, deltaRoot ).c_str(), at.c_str(), first->was, first->now ); + gatingCount, newGating, first->kind.c_str(), quality::displaySym( first->sym, deltaRoot ).c_str(), at.c_str(), was, now ); } } @@ -2584,749 +2615,965 @@ inline std::string presentXmlAttr( std::string_view name, const std::string& v, return v.empty() ? std::string() : " " + std::string( name ) + "=\"" + esc( v ) + "\""; } -std::optional runQualityDelta( const MainDispatch& d ) +// ── --quality-delta, in phases: SCOPE + RATCHET, then either WRITE ACKS or COMPUTE the report and RENDER it ────────────── +// GE-RUNQD: runQualityDelta used to compute the answer and render it in one 744-line body, with the JSON and XML row +// emitters written twice inside it. The phases are now named functions: applyScopeAndAcks returns what the partition and +// the ratchet decided (QdPartition); runQualityAckWrite is the --quality-ack arm; computeQdReport builds every count and +// root disclosure once, silently (QdReport, with each root attribute a QdRootField spelled for both formats); the stderr +// lines print from emitQdStderrLines; one row model (QdRowModel) decides each row's printed facts for both formats. + +// What the scope partition and the ack ratchet decided over basis.regs (applyScopeAndAcks): the rows that belong to someone +// else, the acks suppressing a finding in a session other than the one that wrote them, and the two counts they feed. +struct QdPartition { - using namespace rw; - const Config& cfg = d.cfg; - const IngestResult& ing = d.ing; - const Graph& g = d.g; - const std::string& root = d.root; - - // --quality-baseline / --quality-delta (the convergence-loop oracle): snapshot ccx + clone groups + dead - // candidates to .ripwire_quality_baseline; then report ONLY what a change made WORSE vs it. The "delta not - // absolute" discipline — a refine loop targets the regression it introduced, not absolute numbers (the - // defense against metric-gaming). exit 2 if any new debt, like --arch. - if( cfg.qualityBaseline || cfg.qualityDelta ) - { - // D1 fix (HIGH): resolve BOTH sidecars against the analyzed ROOT, not the process CWD — - // see quality::rootQualifiedSidecar's comment for why a bare relative filename is unsafe here - // (a foreign cwd's sidecar could be silently rewritten, or even deleted by the stale-baseline - // self-heal below). Computed once; every read/write/remove site in this block uses it. - const std::string baselineFile = quality::baselinePath( root ); - const std::string acksFile = quality::acksPath( root ); - - if( cfg.qualityBaseline ) - { - return runQualityBaselinePin( d, baselineFile, acksFile ); - } + std::vector outOfScope; + std::vector foreignAcks; + std::size_t scopedOutGating = 0; // out-of-scope rows that would have gated (would-gate=) + std::size_t ackedCount = 0; // in-scope rows the ack ledger suppressed (acked=) +}; - // Precedence for the baseline: (1) an explicit `.ripwire_quality_baseline` sidecar (from - // --quality-baseline) wins whenever it is pinned at the CURRENT HEAD — the mid-task convergence loop - // (baseline once, edit, re-check) is unchanged; (2) else — no sidecar, or a STALE one (see R3 below) — - // if the root is a git repo with a HEAD tree, auto-baseline against HEAD so the "before I push" loop - // works with no start-of-task ritual (T0.1); (3) else degrade to the exit-1 "run --quality-baseline - // first" guidance (non-git / unborn / detached-no-tree — unchanged). - // - // STALENESS + the self-heal now live in ONE place, quality::selectBaseline — R3 owner ruling - // (2026-07-29): a sidecar whose pinned sha != the CURRENT HEAD sha is STALE, full stop. The B10.1b - // "reachable ancestor is a deliberately-pinned floor" carve-out this arm used to apply (gitIsAncestor) - // is REVOKED: a parallel session's sidecar pinned at a commit that merely happened to be an ancestor of - // this session's HEAD made THIS arm report 31 phantom regressions while the MCP quality_delta verb — - // same binary, same repo, same second — correctly reported zero. That divergence was only possible - // because each arm carried its own copy of the test; there is now exactly one, in quality.h. - // - // What remains this arm's own POLICY is the `removeStaleFile=true` argument: the stale sidecar is - // silently UNLINKED (best-effort) so the NEXT run sees no file at all rather than rediscovering the - // same dead pin, and the ONLY record is the `baseline=` XML attribute ("git-HEAD (stale sidecar - // removed)") — no stderr spam, which is the B10.1b noise fix that survives the ruling intact. The - // read-only MCP arm passes false and reports "…ignored" instead. When the unlink FAILS (read-only - // parent dir) this arm degrades to the read-only story — marker "…ignored", one DISCLOSE - // from the seam — because the pin is still on disk; `baseSel.isStaleFileOnDisk()` is the fact, and the - // fatal message below words itself from it rather than from the intent. - // `refs` is declared HERE because it owns both materialized trees' teardown and they must outlive - // every read of `regs` (DeltaBasis's header states that rule, and why the emitters below spell every - // path and symbol against basis.deltaRoot rather than against `root`). - // F-04 (round-4 audit) — SERIALIZE THE ACK LEDGER'S READ-MODIFY-WRITE, cross-process. - // - // --quality-ack reads the whole ledger (inside resolveDeltaBasis just below — the heal has to happen - // before computeDelta), folds this run's accepted findings into that map, then rewrites the file from - // it. Nothing serialized that. Three sessions acking DISJOINT rows in one shared checkout — the exact - // scenario --scope exists for — lost two of the three acks on 8 of 8 measured runs, because whichever - // process rewrote last overwrote a map the other two had already published into. - // - // The lock therefore has to span the READ as well as the write, which is why it is taken HERE and not - // inside writeAckRecords: a lock held only around the final rewrite still lets two processes read the - // same stale map first and then take turns clobbering. Engaged ONLY under --quality-ack — a read-only - // --quality-delta never waits, never creates the lockfile, and is byte-for-byte the run it always was. - // RAII: released when this function returns, on every path including the refusals below. quality.h's - // SidecarWriteLock has the lockfile's location (per-user cache dir, never a repo-tree sidecar), the - // wait budget, and the honest limits. - std::optional ackLock; - if( cfg.qualityAck ) - { - ackLock.emplace( acksFile ); - } +// SCOPE + RATCHET — split basis.regs by --scope, then suppress what the ack ledger already accepted. basis.regs keeps only +// the in-scope, unsuppressed rows. +// Signal-to-noise round — the per-finding ACK RATCHET. Suppress findings already accepted (with a +// reason) in .ripwire_quality_acks, honestly (acked="N"); a finding that WORSENED past its acked +// magnitude survives the filter and reappears. --quality-ack merges the currently-VISIBLE findings +// into that file instead of printing the report (accepting what previous acks already hid would be +// a silent blanket ack — only what the agent can see right now is what it can accept). +// R1 IDENTITY: the ledger was read and HEALED inside resolveDeltaBasis (it had to be — the baseline +// half of the same healing has to precede computeDelta), so this step takes the already-current map +// rather than re-reading the file and undoing it. +QdPartition applyScopeAndAcks( const rw::quality::Scope& scope, DeltaBasis& basis ) +{ + using namespace rw; + std::vector& regs = basis.regs; + const gtl::btree_map& acks = basis.acks; + QdPartition out; + quality::countAckRescues( regs, acks, basis.healing.ackRemap, basis.healing.ackedByRename, basis.healing.ackedByContent ); + // P1.4 PROVENANCE — the foreign-ack sweep reads the PRE-ratchet list on purpose (computeForeignAcks' + // header states why: the question is about acks that are suppressing something right now). + out.foreignAcks = quality::computeForeignAcks( regs, acks ); + // P1 — the partition runs BEFORE the ratchet so acked="N" counts THIS scope's suppressions rather + // than the whole tree's (partitionByScope owns the rest of the rule). + out.scopedOutGating = partitionByScope( scope, regs, out.outOfScope, acks ); + out.ackedCount = quality::applyAckRatchet( regs, acks ); + return out; +} - const bool refPair = !cfg.qualityDeltaRange.empty(); - RefPairDelta refs; - DeltaBasis basis; - if( const std::optional refused = applyKindSelector( cfg, refs ) ) - { - return refused; - } - if( const std::optional refused = resolveDeltaBasis( d, baselineFile, refs, basis ) ) - { - return refused; - } - const quality::BaselineSelection& baseSel = basis.baseSel; - const std::string& deltaRoot = basis.deltaRoot; - std::vector& regs = basis.regs; - - // ── P1 SCOPE — the OWNERSHIP partition for a working tree with several writers in it ───────────── - quality::Scope scope = quality::parseScope( cfg.qualityScope ); - std::vector outOfScope; - std::size_t diffFileCount = 0; // P1.2: 0 = the reserved diff token was not used - const IngestResult& judged = refPair ? refs.target().ing : ing; - if( const std::optional refused = expandScopeDiff( scope, refPair, judged, root, deltaRoot, diffFileCount ) ) +// --ack-only=SUBSTR[,SUBSTR]: ack a SUBSET instead of everything on screen. Without it, the only way to accept one +// deliberate contract change was to accept the whole report — which is how a ratchet quietly becomes a rubber stamp. A +// finding matches if a pattern occurs in its kind, its canonical id or its FACET (so "api-surface", "src/quality.h", one +// exact id, or "format-arity" all work). The facet is what makes this precise enough to be honest: "api-surface" also +// covers the never-gating new-symbol rows, so acking by kind would sweep in 59 findings to accept 8; +// --ack-only=contract-change accepts exactly the deliberate ones. The pseudo-token "gating" selects whatever would +// actually exit 2. +// P1: `inScope` is a parameter because the predicate is asked about BOTH halves of the partition — once to choose what to +// write, once to detect an ack selection that NAMES a row belonging to someone else. It is also what keeps `gating` honest +// under a scope: an out-of-scope row does not gate, so `gating` must not select it. +bool ackOnlySelects( std::string_view ackOnly, const rw::quality::Regression& r, bool inScope ) +{ + if( ackOnly.empty() ) + { + return true; + } + const bool gates = rw::quality::rowGates( r ) && inScope; + // "gating" is RESERVED: the exact token answers only "would this row exit 2", never a substring of a symbol such as + // gatingHelper (CR721 — a substring hit acked a never-gating row, or refused the command on an out-of-scope one). + const auto patternSelects = [ & ]( std::string_view pat ) + { + if( pat == "gating" ) { - return refused; + return gates; } - if( const std::optional refused = refuseUnusableScope( cfg, scope, judged, deltaRoot, refs.scopeFiles() ) ) + return !pat.empty() && ( r.kind.find( pat ) != std::string::npos || r.sym.find( pat ) != std::string::npos + || ( !r.facet.empty() && r.facet.find( pat ) != std::string::npos ) ); + }; + for( std::string_view rest = ackOnly; !rest.empty(); ) + { + const std::size_t comma = rest.find( ',' ); + if( patternSelects( rest.substr( 0, comma ) ) ) { - return refused; + return true; } + rest = comma == std::string_view::npos ? std::string_view() : rest.substr( comma + 1 ); + } + return false; +} - // Signal-to-noise round — the per-finding ACK RATCHET. Suppress findings already accepted (with a - // reason) in .ripwire_quality_acks, honestly (acked="N"); a finding that WORSENED past its acked - // magnitude survives the filter and reappears. --quality-ack merges the currently-VISIBLE findings - // into that file instead of printing the report (accepting what previous acks already hid would be - // a silent blanket ack — only what the agent can see right now is what it can accept). - // R1 IDENTITY: the ledger was read and HEALED inside resolveDeltaBasis (it had to be — the baseline - // half of the same healing has to precede computeDelta), so this arm takes the already-current map - // rather than re-reading the file and undoing it. - gtl::btree_map& acks = basis.acks; - quality::countAckRescues( regs, acks, basis.healing.ackRemap, - basis.healing.ackedByRename, basis.healing.ackedByContent ); - // P1.4 PROVENANCE — the foreign-ack sweep reads the PRE-ratchet list on purpose (computeForeignAcks' - // header states why: the question is about acks that are suppressing something right now). - const std::vector foreignAcks = quality::computeForeignAcks( regs, acks ); - // P1 — the partition runs BEFORE the ratchet so acked="N" counts THIS scope's suppressions rather - // than the whole tree's (partitionByScope owns the rest of the rule). - const std::size_t scopedOutGating = partitionByScope( scope, regs, outOfScope, acks ); - const std::size_t ackedCount = quality::applyAckRatchet( regs, acks ); - if( cfg.qualityAck ) - { - // --ack-only=SUBSTR[,SUBSTR]: ack a SUBSET instead of everything on screen. Without it, the only - // way to accept one deliberate contract change was to accept the whole report — which is how a - // ratchet quietly becomes a rubber stamp. A finding matches if a substring occurs in its kind or - // in its canonical id (so "api-surface", "src/quality.h", or one exact id all work). - // P1: `inScope` is a parameter rather than a capture because this predicate is asked about BOTH - // halves of the partition — once to choose what to write, once to detect an ack selection that - // NAMES a row belonging to someone else. It is also what keeps the `gating` pseudo-token honest - // under a scope: an out-of-scope row does not gate, so `gating` must not select it. - const auto ackSelected = [ & ]( const quality::Regression& r, bool inScope ) -> bool - { - if( cfg.qualityAckOnly.empty() ) - { - return true; - } - std::string_view rest = cfg.qualityAckOnly; - while( !rest.empty() ) - { - const std::size_t comma = rest.find( ',' ); - const std::string_view pat = rest.substr( 0, comma ); - // kind, canonical id, or FACET. The facet is what makes this precise enough to be honest: - // "api-surface" also covers the never-gating new-symbol rows, so acking by kind would - // sweep in 59 findings to accept 8. --ack-only=contract-change accepts exactly the - // deliberate ones. The pseudo-token "gating" selects whatever would actually exit 2. - const bool gates = quality::rowGates( r ) && inScope; - if( !pat.empty() && ( r.kind.find( pat ) != std::string::npos || r.sym.find( pat ) != std::string::npos || ( !r.facet.empty() && r.facet.find( pat ) != std::string::npos ) || ( pat == "gating" && gates ) ) ) - { - return true; - } - if( comma == std::string_view::npos ) - { - break; - } - rest = rest.substr( comma + 1 ); - } - return false; - }; +// THE LEGACY-ACK BACKFILL's disclosure. A reconstructed row is a weaker claim than a measured one, so a reader is told how +// many rows just changed confidence class and how many could not be healed at all. The unresolved count is a FLOOR on +// what is missing, not a total of what is wrong: a member set that no longer clones in THIS tree is unanswerable here, +// not proven gone. Silent when the backfill touched nothing. +void discloseAckBackfill( const rw::quality::AckBackfill& backfilled ) +{ + if( backfilled.resolved == 0 && backfilled.refreshed == 0 && backfilled.unverified == 0 && backfilled.unresolved == 0 ) + { + return; + } + rw::emitTo( stderr, "ripwire: ack provenance backfill — {} clone row(s) reconstructed from the current tree, {} re-derived, {} left UNVERIFIED (their group was not found here — a floor, not proof it is gone), " + "{} left legacy (member set not found cloning here — a floor, not proof it is gone), {} ineligible (no current-tree fact answers their kind), {} already measured (left alone). " + "prov=recon is what the idiom is NOW, as of the last run that could check it — not what was measured when the row was accepted.\n", + backfilled.resolved, backfilled.refreshed, backfilled.unverified, backfilled.unresolved, backfilled.ineligible, backfilled.measured ); +} - // P1 — THE RUBBER-STAMP GUARD (refuseForeignAckSelection owns the rule and the message). - if( const std::optional refused = refuseForeignAckSelection( cfg, scope, outOfScope, deltaRoot, ackSelected ) ) - { - return refused; - } +// Fold ONE accepted finding into the ack ledger `acks`, then prove the re-score formula agrees with the live one. `cidByKey` +// is the healing pre-pass's content-id index; `scopeSpec` is the --scope this run names (nullptr: none, so an existing row +// keeps its `by`); `reason` is --quality-ack's text (empty: an existing row keeps its reason). +void acceptFinding( gtl::btree_map& acks, const gtl::btree_map& cidByKey, + const rw::quality::Regression& r, const std::string* scopeSpec, std::string_view reason ) +{ + using namespace rw; + // P0.3: the ack IDENTITY is ackKindToken, not the bare kind — a zero-magnitude finding + // (was==now==0: dead-code, api-surface tier A) acks per ORIGIN, so acking the never-gating + // new-symbol row can no longer blank-check the gating contract-change row on the same symbol. + const std::string ackKind = quality::ackKindToken( r ); + quality::AckRecord& rec = acks[ quality::ackMapKey( ackKind, r.key ) ]; + // R1 IDENTITY: stamp the finding's SCRUBBED CONTENT ID alongside the key, so this ack can + // still be found after a move git records no rename for. Absent (0) for the two clone kinds — + // their key is a member-SET hash with no single body behind it — and the row is then written + // exactly as it is today. A REFRESH, not a preserve: re-acking a finding re-reads the body, so + // the stored cid always describes the code as accepted, never as it was two edits ago. + const auto cidIt = cidByKey.find( r.key ); + const std::uint64_t cid = ( cidIt == cidByKey.end() ) ? 0u : cidIt->second; + // P1.4 PROVENANCE: `by` follows the SAME rule the reason does one line down — set from this + // run when this run supplies one, PRESERVED otherwise. A later scope-less re-ack therefore + // refreshes the magnitude without erasing the record of who accepted the row originally, + // which is the only reading under which the foreign-ack sweep means anything. + // REASON CLOBBER FIX (round 2026-08-29): a re-ack that supplies a DIFFERENT reason no longer + // overwrites the row's existing one outright — composeAckReason folds it in as + // " | prior: " (capped at one hop; a no-op when the reason is unchanged), so a + // shared row re-acked by unrelated sessions keeps both justifications instead of the last + // writer silently erasing the one before it. See quality.h's composeAckReason for the rule. + // RE-SCORE PROVENANCE: was/now/facet/path/line are a REFRESH, not a preserve, same posture as + // cid= above — a re-ack re-reads the finding, so the stored triple always describes the row AS + // JUST ACCEPTED, never as it was some earlier run. See AckRecord's doc comment for what each + // one is and why a later run can re-score from them alone. + rec = quality::AckRecord{ ackKind, r.key, std::max( rec.ackNow, r.now ), cid, + scopeSpec != nullptr ? *scopeSpec : rec.by, + r.was, r.now, r.facet, r.path, r.line, quality::AckProvenance::Measured, + reason.empty() ? rec.reason : quality::composeAckReason( rec.reason, std::string( reason ) ) }; + // SELF-CHECK, not a one-off test: every magnitude-bearing ack proves that the TABLE-DRIVEN + // re-score formula agrees with the LIVE one on the row it just built. NOT a full round trip — + // rescoreAckRecord runs here on the in-memory `rec` directly; it never goes through + // renderAckRecords/readAckRecords, so this does not exercise the ledger's text grammar (order- + // tolerant token parsing, splitAckLocator, the takeAckNamedToken family) at all — that half of + // the contract is what qackconcurrencycheck.sh's grammar arm (2) and byte-identity arm (7) pin + // instead, over the actual file. What THIS catches: rescoreNumericMajor's kMaterialityBars + // lookup (by kind name) silently drifting from the kMaterialityBars row perSymbolKind is handed + // by index (computeDelta; the static_assert beside the table pins the order) — two ways + // to reach the same constants that a future edit could break in only one place. A drift there means the live + // formula (numericRegressionIsMajor, via perSymbolKind) and the re-score formula + // (rescoreNumericMajor) have silently diverged — see quality.h's MaterialityBar table, the one + // place both are meant to agree. ENSURES, not ASSUME: this is this function's OWN postcondition + // on the row it just built, not a fact something else already guarantees. + const std::optional rescored = quality::rescoreAckRecord( rec ); + const bool rescoreAgrees = !rescored.has_value() || *rescored == !r.isMinor; // plain bool, so the promise below is a bare accessor-free read + ENSURES( rescoreAgrees, + "ack provenance re-score (in-memory, not a ledger round trip) must reproduce the just-computed severity" ); +} - // THE LEGACY-ACK BACKFILL, run on the map this process already holds the write lock over and - // BEFORE this run's own acks are folded in, so a row healed here can still be overwritten by a - // live measurement of the same finding in the loop below — measured always beats reconstructed, - // and ordering is what guarantees it rather than a check. It runs even when this run accepts - // NOTHING: healing the ledger's provenance is the same class of forward repair the identity - // remap already performs on every ack, and H10's ackNothingToAccept re-renders and notices. - // quality::backfillCloneAckProvenance owns the rule, what it refuses to touch, and why. - const quality::AckBackfill backfilled = quality::backfillCloneAckProvenance( acks, basis.cloneIdioms ); - // DISCLOSED, never silent: a reconstructed row is a weaker claim than a measured one, so a reader - // is told how many rows just changed confidence class and how many could not be healed at all. - // The unresolved count is a FLOOR on what is missing, not a total of what is wrong: a member set - // that no longer clones in THIS tree is unanswerable here, not proven gone. - if( backfilled.resolved > 0 || backfilled.refreshed > 0 || backfilled.unverified > 0 || backfilled.unresolved > 0 ) - { - rw::emitTo( stderr, "ripwire: ack provenance backfill — {} clone row(s) reconstructed from the current tree, {} re-derived, {} left UNVERIFIED (their group was not found here — a floor, not proof it is gone), " - "{} left legacy (member set not found cloning here — a floor, not proof it is gone), {} ineligible (no current-tree fact answers their kind), {} already measured (left alone). " - "prov=recon is what the idiom is NOW, as of the last run that could check it — not what was measured when the row was accepted.\n", - backfilled.resolved, backfilled.refreshed, backfilled.unverified, backfilled.unresolved, backfilled.ineligible, backfilled.measured ); - } +// An --ack-only that matched NO finding: refused with exit 1, and nothing accepted. +// M1 FOLLOW-UP (round train-18, rv-ack-provenance-backfill.md): this refusal used to discard the backfill unconditionally — +// `backfillCloneAckProvenance` already mutated `acks` in memory, but returning without ever calling writeAckRecords threw +// that healing away, so a rubber-stamp-guarded --ack-only that (correctly) refused to accept anything ALSO silently un-did +// an otherwise-independent repair to the ledger's provenance. Same canonical-bytes rule H10's ackNothingToAccept applies +// when there is nothing to accept at all: a ledger already equal to its own canonical bytes is left untouched (no spurious +// diff); a non-canonical one — including one this run's backfill just healed — is rewritten and the run says so. This +// never accepts a finding and the refusal's exit code is unchanged. +int refuseUnmatchedAckOnly( std::string_view ackOnly, const std::string& acksFile, + const gtl::btree_map& acks, std::size_t findingCount ) +{ + using namespace rw; + const bool nonCanonical = !acks.empty() + && quality::renderAckRecords( acks ) != docparse::detail::readRegularFile( "the quality-acks ledger", acksFile ).value_or( std::string() ); + if( !nonCanonical ) + { + rw::emitTo( stderr, "ripwire: --ack-only={} matched none of the {} finding(s) — nothing written\n", ackOnly, findingCount ); + return 1; + } + // A failed heal is said, not folded into "nothing written" (CodeRabbit on #331): the same "could not write" + // ackNothingToAccept prints for the same failure. writeAckRecords has already DISCLOSEd on its answerRefused sink; the + // exit code is 1 either way. + if( !quality::writeAckRecords( acksFile, acks ) ) + { + rw::emitTo( stderr, "ripwire: --ack-only={} matched none of the {} finding(s) — nothing accepted; could not write {} " + "(it was not in canonical form, and re-serialising it failed)\n", + ackOnly, findingCount, acksFile.c_str() ); + return 1; + } + rw::emitTo( stderr, "ripwire: --ack-only={} matched none of the {} finding(s) — nothing accepted, but {} was not in canonical form " + "(ack provenance backfill / legacy rows) and has been re-serialised\n", + ackOnly, findingCount, acksFile.c_str() ); + return 1; +} - std::size_t ackWritten = 0, ackSkipped = 0; - for( const quality::Regression& r : regs ) - { - if( !ackSelected( r, /*inScope=*/true ) ) { ++ackSkipped; continue; } - ++ackWritten; - // P0.3: the ack IDENTITY is ackKindToken, not the bare kind — a zero-magnitude finding - // (was==now==0: dead-code, api-surface tier A) acks per ORIGIN, so acking the never-gating - // new-symbol row can no longer blank-check the gating contract-change row on the same symbol. - const std::string ackKind = quality::ackKindToken( r ); - quality::AckRecord& rec = acks[ quality::ackMapKey( ackKind, r.key ) ]; - // R1 IDENTITY: stamp the finding's SCRUBBED CONTENT ID alongside the key, so this ack can - // still be found after a move git records no rename for. Absent (0) for the two clone kinds — - // their key is a member-SET hash with no single body behind it — and the row is then written - // exactly as it is today. A REFRESH, not a preserve: re-acking a finding re-reads the body, so - // the stored cid always describes the code as accepted, never as it was two edits ago. - const auto cidIt = basis.healing.cids.cidByKey.find( r.key ); - const std::uint64_t cid = ( cidIt == basis.healing.cids.cidByKey.end() ) ? 0u : cidIt->second; - // P1.4 PROVENANCE: `by` follows the SAME rule the reason does one line down — set from this - // run when this run supplies one, PRESERVED otherwise. A later scope-less re-ack therefore - // refreshes the magnitude without erasing the record of who accepted the row originally, - // which is the only reading under which the foreign-ack sweep means anything. - // REASON CLOBBER FIX (round 2026-08-29): a re-ack that supplies a DIFFERENT reason no longer - // overwrites the row's existing one outright — composeAckReason folds it in as - // " | prior: " (capped at one hop; a no-op when the reason is unchanged), so a - // shared row re-acked by unrelated sessions keeps both justifications instead of the last - // writer silently erasing the one before it. See quality.h's composeAckReason for the rule. - // RE-SCORE PROVENANCE: was/now/facet/path/line are a REFRESH, not a preserve, same posture as - // cid= above — a re-ack re-reads the finding, so the stored triple always describes the row AS - // JUST ACCEPTED, never as it was some earlier run. See AckRecord's doc comment for what each - // one is and why a later run can re-score from them alone. - rec = quality::AckRecord{ ackKind, r.key, std::max( rec.ackNow, r.now ), cid, - scope.active() ? scope.spec : rec.by, - r.was, r.now, r.facet, r.path, r.line, quality::AckProvenance::Measured, - cfg.qualityAckReason.empty() ? rec.reason - : quality::composeAckReason( rec.reason, std::string( cfg.qualityAckReason ) ) }; - // SELF-CHECK, not a one-off test: every magnitude-bearing ack proves that the TABLE-DRIVEN - // re-score formula agrees with the LIVE one on the row it just built. NOT a full round trip — - // rescoreAckRecord runs here on the in-memory `rec` directly; it never goes through - // renderAckRecords/readAckRecords, so this does not exercise the ledger's text grammar (order- - // tolerant token parsing, splitAckLocator, the takeAckNamedToken family) at all — that half of - // the contract is what qackconcurrencycheck.sh's grammar arm (2) and byte-identity arm (7) pin - // instead, over the actual file. What THIS catches: rescoreNumericMajor's kMaterialityBars - // lookup (by kind name) silently drifting from the kMaterialityBars row perSymbolKind is handed - // by index (computeDelta, above; the static_assert beside the table pins the order) — two ways - // to reach the same constants that a future edit could break in only one place. A drift there means the live - // formula (numericRegressionIsMajor, via perSymbolKind) and the re-score formula - // (rescoreNumericMajor) have silently diverged — see quality.h's MaterialityBar table, the one - // place both are meant to agree. ENSURES, not ASSUME: this is this function's OWN postcondition - // on the row it just built, not a fact something else already guarantees. - const std::optional rescored = quality::rescoreAckRecord( rec ); - const bool rescoreAgrees = !rescored.has_value() || *rescored == !r.isMinor; // plain bool, so the promise below is a bare accessor-free read - ENSURES( rescoreAgrees, - "ack provenance re-score (in-memory, not a ledger round trip) must reproduce the just-computed severity" ); - } - if( ackWritten == 0 && !cfg.qualityAckOnly.empty() ) - { - // M1 FOLLOW-UP (round train-18, rv-ack-provenance-backfill.md): this refusal used to discard - // the backfill above unconditionally — `backfillCloneAckProvenance` already mutated `acks` in - // memory, but returning here without ever calling writeAckRecords threw that healing away, - // so a rubber-stamp-guarded --ack-only that (correctly) refused to accept anything ALSO - // silently un-did an otherwise-independent repair to the ledger's provenance. Same - // canonical-bytes rule H10's ackNothingToAccept applies when there is nothing to accept at - // all: a ledger already equal to its own canonical bytes is left untouched (no spurious - // diff); a non-canonical one — including one this run's backfill just healed — is rewritten - // and the run says so. This never accepts a finding and the refusal's exit code is unchanged. - const bool nonCanonical = !acks.empty() - && quality::renderAckRecords( acks ) != docparse::detail::readRegularFile( "the quality-acks ledger", acksFile ).value_or( std::string() ); - if( nonCanonical ) - { - // A failed heal is said, not folded into "nothing written" (CodeRabbit on #331): the same - // "could not write" ackNothingToAccept prints for the same failure. writeAckRecords has already - // DISCLOSEd on its answerRefused sink; the exit code is 1 either way. - if( !quality::writeAckRecords( acksFile, acks ) ) - { - rw::emitTo( stderr, "ripwire: --ack-only={} matched none of the {} finding(s) — nothing accepted; could not write {} " - "(it was not in canonical form, and re-serialising it failed)\n", - std::string_view( cfg.qualityAckOnly.data(), cfg.qualityAckOnly.size() ), regs.size(), acksFile.c_str() ); - return 1; - } - rw::emitTo( stderr, "ripwire: --ack-only={} matched none of the {} finding(s) — nothing accepted, but {} was not in canonical form " - "(ack provenance backfill / legacy rows) and has been re-serialised\n", - std::string_view( cfg.qualityAckOnly.data(), cfg.qualityAckOnly.size() ), regs.size(), acksFile.c_str() ); - return 1; - } - rw::emitTo( stderr, "ripwire: --ack-only={} matched none of the {} finding(s) — nothing written\n", std::string_view( cfg.qualityAckOnly.data(), cfg.qualityAckOnly.size() ), regs.size() ); - return 1; - } - // H10: nothing to accept — leave a canonical ledger alone, heal a non-canonical one (ackNothingToAccept) - if( regs.empty() ) - { - return ackNothingToAccept( acksFile, acks, scope, outOfScope.size() ); - } - const bool wroteAcks = quality::writeAckRecords( acksFile, acks ); - if( wroteAcks && !cfg.qualityAckOnly.empty() ) - { - rw::emitTo( stderr, "ripwire: acknowledged {} of {} finding(s) ({} left UNACKED by --ack-only, {} already acked) → {}\n", - ackWritten, regs.size(), ackSkipped, ackedCount, acksFile.c_str() ); - } - else if( wroteAcks ) - { - rw::emitTo( stderr, "ripwire: acknowledged {} finding(s) ({} already acked) → {}\n", - regs.size(), ackedCount, acksFile.c_str() ); - } - else - { - rw::emitTo( stderr, "ripwire: could not write {}\n", acksFile.c_str() ); - } - // P1 — the skip is DISCLOSED, never silent: the count of rows this ack deliberately did not - // touch is the whole reason the caller passed a scope, and a quiet success would leave them - // believing the ledger now covers the report they were looking at. - if( wroteAcks && scope.active() && !outOfScope.empty() ) - { - rw::emitTo( stderr, "ripwire: {} finding(s) OUT OF SCOPE for --scope={} were left unacked — not yours to accept " - "(they are still in the report, under the out-of-scope element)\n", - outOfScope.size(), scope.spec.c_str() ); - } - return wroteAcks ? 0 : 1; - } +// What one --quality-ack run counted, for writeAcceptedAcks's report. +struct QdAckTally +{ + std::size_t findings = 0; // visible findings this run could accept + std::size_t alreadyAcked = 0; // suppressed by an earlier ack (acked=) + std::size_t accepted = 0; + std::size_t skipped = 0; // visible but not selected by --ack-only + bool narrowed = false; // --ack-only was given +}; - // L2 — stale-ack disclosure (rationale: quality.h's computeStaleAcks). Checked against the CURRENT - // tree, not the baseline above, so it costs one more computeSnapshot; skipped when the ledger is - // empty. Reported, never gated — the exit code below reads `regs` alone. - // R-I: "the CURRENT tree" is the JUDGED tree, which in the ref-pair form is tree B — checking the - // ledger against the working tree there would report acks as stale because of edits that have nothing - // to do with the comparison being made. - // qd-memory-degrade: refPairStaleAcks owns the two range-form departures (a changed-files answer judges none; a - // kind selection judges its own kinds' acks only). - const std::vector staleAcks = acks.empty() ? std::vector{} - : refPair ? refPairStaleAcks( acks, refs ) - : quality::computeStaleAcks( acks, quality::computeSnapshot( ing, g, cfg.rootPath, nullptr, {}, &basis.passes ) ); - if( std::getenv( "RIPWIRE_STATS" ) ) // QD-ENVOY-TIME cost bound: Type-3 passes this call ran (test/qdtype3oncecheck.sh) - { - rw::emitTo( stderr, "ripwire: quality-passes type3_runs={} type3_pairs={}\n", gType3PassRuns.load( std::memory_order_relaxed ), - gType3PassPairs.load( std::memory_order_relaxed ) ); - } +// Rewrite the ledger with this run's accepted findings and say what was written. Returns the exit code. +int writeAcceptedAcks( const std::string& acksFile, const gtl::btree_map& acks, const QdAckTally& tally, + const rw::quality::Scope& scope, std::size_t outOfScopeCount ) +{ + using namespace rw; + if( !quality::writeAckRecords( acksFile, acks ) ) + { + rw::emitTo( stderr, "ripwire: could not write {}\n", acksFile.c_str() ); + return 1; + } + if( tally.narrowed ) + { + rw::emitTo( stderr, "ripwire: acknowledged {} of {} finding(s) ({} left UNACKED by --ack-only, {} already acked) → {}\n", + tally.accepted, tally.findings, tally.skipped, tally.alreadyAcked, acksFile.c_str() ); + } + else + { + rw::emitTo( stderr, "ripwire: acknowledged {} finding(s) ({} already acked) → {}\n", tally.findings, tally.alreadyAcked, acksFile.c_str() ); + } + // P1 — the skip is DISCLOSED, never silent: the count of rows this ack deliberately did not + // touch is the whole reason the caller passed a scope, and a quiet success would leave them + // believing the ledger now covers the report they were looking at. + if( scope.active() && outOfScopeCount != 0 ) + { + rw::emitTo( stderr, "ripwire: {} finding(s) OUT OF SCOPE for --scope={} were left unacked — not yours to accept " + "(they are still in the report, under the out-of-scope element)\n", + outOfScopeCount, scope.spec.c_str() ); + } + return 0; +} - // P1.4 — the family now carries THREE whys, and the third is counted SEPARATELY: stale= means - // "this ack no longer applies", and a foreign ack applies fine — it is the SESSION that was wrong, - // not the target. Merging the rows into one list keeps the two emitters from growing a second loop - // each; keeping the COUNTS apart keeps stale= meaning what it has always meant. - std::vector saRows = staleAcks; - saRows.insert( saRows.end(), foreignAcks.begin(), foreignAcks.end() ); - // M21(a): name the rows the tree can still name, against the SAME tree computeStaleAcks judged - // (tree B in the ref-pair form) — naming a stale ack after the working tree would print an identity - // the verdict was never computed from. Costs one walk over ing.symbols, and only when there are rows. - quality::stampStaleAckIdentity( saRows, refPair ? refs.target().ing : ing, - refPair ? std::string_view( refs.target().root ) : std::string_view( cfg.rootPath ) ); - - // r26 ORIGIN SPLIT — three counts over the VISIBLE (post-ack) findings, one pass: - // minorCount — the materiality tier (unchanged axis). - // newSymbolCount — findings that exist only because the code is NEW (quality.h's origin axis). - // gatingCount — the EXIT PREDICATE (quality::rowGates): major AND preexisting-worse, or a defect-shape - // format-arity row of any origin. Emitted as gating= so the header alone tells you - // the exit code (it used to be "regressions > minor"). - // preexisting-worse = regressions − new-symbol by construction (the axis is a partition), so the two - // header counters always sum to regressions= — an invariant the gate asserts. - std::size_t minorCount = 0, newSymbolCount = 0, gatingCount = 0; - for( const quality::Regression& r : regs ) - { - if( r.isMinor ) - { - ++minorCount; - } - if( r.isNewSymbol ) - { - ++newSymbolCount; - } - if( quality::rowGates( r ) ) - { - ++gatingCount; - } - } - const std::size_t preexistingCount = regs.size() - newSymbolCount; - // H11 — the absorbed-debt stamp on the honored sidecar, or 0. Read ONLY when the sidecar is the floor - // in force: on the git-HEAD and ref-pair floors there is no pin whose contents could have absorbed - // anything, and printing a 0 there would define an attribute about a file this run did not use. - const std::size_t baselineAbsorbed = ( baseSel.marker == std::string_view( "sidecar" ) ) - ? quality::readBaselineAbsorbed( baselineFile ) : 0; - const std::string baselineAbsorbedAttr = baselineAbsorbed == 0 ? std::string() - : " baseline_absorbed=\"" + std::to_string( baselineAbsorbed ) + "\""; - - // R1 IDENTITY — the disclosure, built ONCE for both emitters (quality::identityDisclosure). An ack - // that follows a rename is a claim about identity, and a claim is only honest if the reader can see - // what it rested on; building the XML and JSON halves in one place is what keeps the two surfaces - // from disclosing different things about the same run. - const auto [ identityAttrs, identityJson ] = quality::identityDisclosure( basis.healing ); - // hwh-fix4 (N1): the history a gating kind could not read, one builder for every emitter (absent when all was read) - const auto [ historyAttrs, historyJson ] = quality::historyUnreadDisclosure( basis.historyUnread ); - if( gatingCount == 0 && basis.historyUnread.any() ) - { - rw::emitTo( stderr, "ripwire: --quality-delta: not a clean pass - git history a gating kind needs could not be read ({}; a partial clone " - "does not download it), so a gating row may be missing: exit 6\n", historyAttrs.substr( 1 ).c_str() ); - } +// WRITE ACKS — the --quality-ack arm: fold the VISIBLE findings --ack-only selects into the ledger (basis.acks, then the +// file) instead of printing the report. Returns the exit code. +int runQualityAckWrite( const rw::Config& cfg, const rw::quality::Scope& scope, const QdPartition& part, DeltaBasis& basis, + const std::string& acksFile ) +{ + using namespace rw; + const std::string_view ackOnly = cfg.qualityAckOnly; + const auto selected = [ & ]( const quality::Regression& r, bool inScope ) { return ackOnlySelects( ackOnly, r, inScope ); }; - // P1/P1.4 — the scope disclosure, built once for both emitters (quality::scopeDisclosure). - const auto [ scopeAttrs, scopeJson ] = quality::scopeDisclosure( scope, outOfScope.size(), scopedOutGating, foreignAcks.size(), diffFileCount ); - - // F-13 — the .ripwire_config disclosure, built once for both emitters (see the header comment on - // registerMacroConfigWarningAttr just above runQualityViews for why the stderr wording lives there). - // #387: the inert-name test reads the JUDGED tree's index, which in the ref-pair form is tree B — the working tree - // is not indexed there at all (runQualityDeltaRangeBeforeIngest). - // qd-memory-degrade: not over a changed-files index, which cannot tell an inert name from one the tree defines (also_skipped=) - const rw::quality::RegisterMacroConfigDiagnostics configDiag = refs.degraded ? rw::quality::RegisterMacroConfigDiagnostics{} - : rw::quality::diagnoseRegisterMacroConfig( judged, root ); - const std::string configWarnAttr = registerMacroConfigWarningAttr( configDiag ); - // qd-memory-degrade: the kinds this answer did not run, why, and the replay — plus the peak, read once now that the - // comparison is done (kindsDisclosure). Their stderr lines come first: an answer that is partial, or that ran past - // the limit, says so on the channel a human reads before anything else. - const KindsDisclosure kd = kindsDisclosure( cfg, refs, basis, refPair ); - emitMemoryLines( kd, refs ); - const bool deadRan = !refPair || quality::kindSelected( refs.kinds, "dead-code" ); // dead-code's side counts exist only when it ran - - // P2.5 — one stderr line NAMING the gating finding, in --token-budget's style ("ripwire: --token-budget - // exceeded: est_tokens=… > budget=…"). stdout is the machine artifact and a caller that only checks - // `$?` gets a number with no subject; this puts the WHICH on the channel a human reads, without - // touching the XML contract. Names the first gating row in the already-sorted list (deterministic). - // - // §A4 (minor): emitted BEFORE the format fork, not after the XML tail — under --json the fork returned - // first, so exactly the caller most likely to be a script reading `$?` got the bare exit=2 with no - // subject. The line is about the EXIT CODE, which both formats share, so it belongs to neither. - emitQdGatingLine( regs, gatingCount, deltaRoot ); - - // L2: --json — same regressions, keys mirror the XML attr names (kind/sym/members/tokens/was/now/ - // sev/churn/surface). jsonUnsupportedVerb already refused --quality-baseline/--quality-ack, so - // reaching here with cfg.json means the plain --quality-delta report. - if( cfg.json ) - { - const char* baseMarkerJ = baseSel.marker; // R3: the one spelling table lives in quality::selectBaseline — the XML/JSON twins cannot drift apart - // The JSON sibling of the XML at= anchor — "at":null (never a fake sha) on a non-git root, and - // null in the ref-pair form too: the list was not computed "at" any working-tree state, and the - // two refs below ARE its anchor. - const std::string atValJ = refPair ? std::string{} : gitstamp::stampAt( root ); - const std::string atJsonJ = atValJ.empty() ? std::string( "null" ) : ( "\"" + atValJ + "\"" ); - // R-I: the same two shas + the same unmeasurable-kind disclosure the XML root carries, spelled in - // JSON. Empty for the bare form, so that object stays byte-identical to before. - // F-13: config-warnings is the JSON sibling of the XML config-warnings= attribute — omitted - // (never 0) when .ripwire_config carried nothing to disclose, same "absent means never happened, - // 0 means checked and clean" rule scopeJson/identityJson already follow. - const std::string configWarnJson = configDiag.total() == 0 ? std::string() - : ",\"config-warnings\":" + std::to_string( configDiag.total() ); - // H11: the JSON twin of baseline_absorbed=, under the same absent-means-none rule as the XML half. - const std::string absorbedJson = baselineAbsorbed == 0 ? std::string() - : ",\"baseline_absorbed\":" + std::to_string( baselineAbsorbed ); - // #228: the JSON twin of head_basis=, under the same absent-means-the-ordinary-archived-tree rule. - const std::string headBasisJson = ( basis.headBasis == nullptr ? std::string() - : std::string( ",\"head_basis\":\"" ) + basis.headBasis + "\"" ) - + ( basis.declinedCallExcluded == 0 ? std::string() // the XML twin's declined-call-excluded=, absent at zero - : ",\"declined-call-excluded\":" + std::to_string( basis.declinedCallExcluded ) ) - + rw::countFieldOrEmpty( "value-ref-excluded", basis.valueRefExcluded, /*json=*/true ); - // qd-memory-degrade: stale and register-macro-excluded are absent (never 0) when their pass did not run - const std::string staleJ = refs.degraded ? std::string() : ",\"stale\":" + std::to_string( staleAcks.size() ); - const std::string rmeJ = deadRan ? ",\"register-macro-excluded\":" + std::to_string( basis.registerMacroExcluded ) : std::string(); - rw::emitTo( stdout, "{{\"baseline\":\"{}\",\"regressions\":{},\"minor\":{},\"acked\":{}{}," - "\"preexisting-worse\":{},\"new-symbol\":{},\"gating\":{}{},\"api-new-surface\":{},\"at\":{}{}{}{}{}{}{}{},\"r\":[", - jsonStr( baseMarkerJ ).c_str(), regs.size(), minorCount, ackedCount, staleJ, - preexistingCount, newSymbolCount, gatingCount, rmeJ, basis.apiNewSurface, atJsonJ.c_str(), refs.jsonAttrs.c_str(), - identityJson.c_str(), scopeJson.c_str(), configWarnJson.c_str(), absorbedJson.c_str(), headBasisJson.c_str(), kd.json + historyJson + quality::ratchetAttrsJson( basis.extras ) ); - // P1: one row emitter, called for both halves of the scope partition — the disclosed rows carry - // the identical key set, so nothing about a row changes by being someone else's. `gatingAllowed` - // is the ONE difference: an out-of-scope row is not what the exit code fires on, so claiming - // gating on it would contradict the exit code in the same document. - const auto emitJsonRow = [ & ]( const quality::Regression& r, bool gatingAllowed ) - { - rw::emitTo( stdout, "{{\"kind\":\"{}\"", jsonStr( r.kind ).c_str() ); - if( r.kind == "duplication" ) - { - rw::emitTo( stdout, ",\"members\":\"{}\",\"tokens\":{}", jsonStr( quality::displaySym( r.sym, deltaRoot ) ).c_str(), r.now ); - } - else - { - rw::emitTo( stdout, ",\"sym\":\"{}\"", jsonStr( quality::displaySym( r.sym, deltaRoot ) ).c_str() ); - if( !( r.kind == "dead-code" ) && !( r.kind == "api-surface" && r.was == r.now ) ) - { - rw::emitTo( stdout, ",\"was\":{},\"now\":{}", quality::rowValueText( r, r.was ), quality::rowValueText( r, r.now ) ); - } - } - if( !r.path.empty() ) - { - rw::emitTo( stdout, ",\"p\":\"{}:{}\"", jsonStr( r.path ).c_str(), r.line ); // P2.5 locator - } - if( gatingAllowed && quality::rowGates( r ) ) - { - rw::emitRaw( stdout, ",\"gating\":true" ); // P2.5 — the exit predicate, stated per row - } - if( r.isMinor ) - { - rw::emitRaw( stdout, ",\"sev\":\"minor\"" ); - } - if( !r.facet.empty() ) - { - const char* facetName = quality::facetAttrName( r.kind ); // ONE kind→name table (quality.h) - if( facetName ) - { - rw::emitTo( stdout, ",\"{}\":\"{}\"", facetName, jsonStr( r.facet ).c_str() ); - } - } - if( const char* origin = quality::originValue( r ) ) - { - rw::emitTo( stdout, ",\"origin\":\"{}\"", origin ); // absent = preexisting-worse (mirrors the XML) - } - if( r.ceiling != 0 ) - { - rw::emitTo( stdout, ",\"ceiling\":{}", r.ceiling ); // QD-ENTRY-CEILING (mirrors the XML) - } - rw::emitRaw( stdout, presentJsonMember( "call", r.call ).c_str() ); // QD-UNCHECKED-STATUS (mirrors the XML) - std::fputs( quality::tangleRowAttrs( r, /*json=*/true, []( std::string_view s ) { return jsonStr( s ); } ).c_str(), stdout ); // QD-TANGLE (mirrors the XML) - rw::emitRaw( stdout, "}" ); - }; - bool firstR = true; - for( const quality::Regression& r : regs ) - { - if( !firstR ) - { - rw::emitRaw( stdout, "," ); - } - firstR = false; - emitJsonRow( r, /*gatingAllowed=*/true ); - } - rw::emitRaw( stdout, "]," ); - if( scope.active() ) - { - // The JSON sibling of the XML out-of-scope element: a SEPARATE array, never a flag on a row - // in "r", so a consumer that reads "r" and checks "gating" cannot accidentally count someone - // else's debt as this run's. Emitted (possibly empty) whenever a scope was given, so its - // absence means "no scope", never "no disclosed rows". - rw::emitRaw( stdout, "\"oos\":[" ); - bool firstO = true; - for( const quality::Regression& r : outOfScope ) - { - if( !firstO ) - { - rw::emitRaw( stdout, "," ); - } - firstO = false; - emitJsonRow( r, /*gatingAllowed=*/false ); - } - rw::emitRaw( stdout, "]," ); - } - std::fputs( quality::staleAcksJsonArray( saRows ).c_str(), stdout ); // L2 — "sa":[...], same taxonomy as the XML sa= rows below - std::fputs( quality::improvedJson( basis.extras.improved, deltaRoot ).c_str(), stdout ); // QD-CREDIT-ROW (absent when none) - rw::emitRaw( stdout, "}" ); - return qualityDeltaExit( gatingCount, refs.degraded || basis.historyUnread.any() ); - } + // P1 — THE RUBBER-STAMP GUARD (refuseForeignAckSelection owns the rule and the message). + if( const std::optional refused = refuseForeignAckSelection( cfg, scope, part.outOfScope, basis.deltaRoot, selected ) ) + { + return *refused; + } - std::vector esc; - const auto ex = [ & ]( std::string_view s ) -> std::string { return std::string( escapeXml( s, esc ) ); }; - // §B7.1 (CA4) — the heading used to open "only what changed for the WORSE vs - // .ripwire_quality_baseline", which is FALSE in every state but one: three of the five floors this - // verb can use are not that file, and in one of them the file was judged stale and DELETED from the - // user's tree during this very run. The floor actually used is named by baseline= on the element - // below, so the heading points at that attribute instead of asserting a floor. - // - // 2026-09-02 (lane B): the marker states are still defined on the first screen — the only place a - // reader meets them — but ONE state per run, the one in force, rather than all five on every call. - // emitQualityDeltaLegend above holds the section table and the reasoning; it is passed the same - // values the root element below prints, so "the legend defines what the header emits" is read off - // one set of values rather than restated as a second condition that could drift from it. - // idea #11 — THE CLEAN-TREE PAYLOAD. A regression-free answer collapses its stale-ack rows to counts (stale= and - // stale_by_kind=), and stale_next= is the call that prints them; on a tree that IS its HEAD (head_basis="identity": - // the floor is this tree's own snapshot) with nothing else to disclose, the verdict is the whole answer. Foreign- - // scope rows are never collapsed: they are about findings suppressed RIGHT NOW. --show-stale restores today's - // document byte for byte, so every collapsed row and attribute is one flag away (PROCESS rule 5). - const bool collapseStale = regs.empty() && outOfScope.empty() && !cfg.showStale && !staleAcks.empty(); - std::string staleCollapseAttrs; - if( collapseStale ) - { - const std::string kinds = quality::staleByKindValue( staleAcks ); // shared with the MCP twin (lane lean2b) - std::string replay = cfg.qualityDeltaRange.empty() ? std::string( "--quality-delta" ) : rw::nextFlag( "--quality-delta=", cfg.qualityDeltaRange ); - if( scope.active() ) - { - replay += " " + rw::nextFlag( "--scope=", cfg.qualityScope ); - } - staleCollapseAttrs = " stale_by_kind=\"" + ex( kinds ) + "\"" + rw::nextAttrXml( replay + " --show-stale", "stale_next" ); - } - const bool verdictOnly = collapseStale && !refPair && basis.headBasis != nullptr && std::string_view( basis.headBasis ) == "identity" - && !scope.active() && foreignAcks.empty() && ackedCount == 0 && configDiag.total() == 0 && baselineAbsorbed == 0 - && basis.apiNewSurface == 0 && baseSel.sidecarBadLines == 0 && basis.acksBadLines == 0; - // P1: ONE row emitter for both halves of the scope partition — a disclosed row carries the identical - // attribute set, because nothing about a finding changes by belonging to someone else. `gatingAllowed` - // is the one difference: an out-of-scope row is not what the exit code fires on, and a gating - // attribute on it would contradict the header's own gating counter inside the same document. - const auto emitRow = [ & ]( std::FILE* out, const quality::Regression& r, bool gatingAllowed ) - { - // duplication carries a member LIST (members=) + token count; the per-symbol was/now kinds - // (complexity/verbosity/nesting/params) carry was/now; api-surface + dead-code are sym-only. - // sev="minor" marks a below-materiality delta (never gates); absent = major. - const char* sev = r.isMinor ? " sev=\"minor\"" : ""; - // B10.2 — the optional classification facet: attribute NAME is chosen by kind (churn= - // short-horizon-churn's self/ambient split; surface= api-surface's new-symbol/contract-change - // tier; idiom= the duplication kind's recognized clone-body shape); r.facet carries only the - // VALUE, and quality::facetAttrName is the ONE table that maps kind → attribute name for all - // three emitters (this one, the --json twin above, and the MCP one). - std::string facetAttr; - if( !r.facet.empty() ) - { - const char* facetName = quality::facetAttrName( r.kind ); - if( facetName ) - { - facetAttr = std::string( " " ) + facetName + "=\"" + ex( r.facet ) + "\""; // escaped: a ratchet facet is a tag name - } - } - // r26 — the ORIGIN axis, emitted LAST so the existing attribute order is untouched. Present only - // on new-symbol rows (absent = preexisting-worse), the same "mark the exception" convention sev= - // uses. api-surface's own surface="new-symbol" facet is the same fact narrowed to that kind; it - // stays for shape compatibility, and origin= is what the exit gate reads. - const char* origin = !r.isNewSymbol ? "" : r.isMoved ? " origin=\"moved\"" : " origin=\"new-symbol\""; // quality::originValue - // P2.5 — the two attributes that make a row ACTIONABLE, appended last so every pre-r27 attribute - // keeps its position: - // p="path:line" — sym= is a canonical id whose display tail is often a bare one-letter local - // (`sym="cc"`), i.e. ungreppable. Omitted, never faked, when no locator was resolvable. - // gating="1" — marks exactly the rows the header's gating= counts and the exit code fires on. - // Until now a gating row was identifiable ONLY by the ABSENCE of sev="minor" (and of - // origin="new-symbol") — absence-as-signal is the least machine-friendly encoding available. - std::string locAttr; - if( !r.path.empty() ) - { - locAttr = " p=\"" + ex( r.path ) + ":" + std::to_string( r.line ) + "\""; - } - const char* gatingAttr = ( gatingAllowed && quality::rowGates( r ) ) ? " gating=\"1\"" : ""; - // QD-ENTRY-CEILING: the ceiling a NEW function reached, beside the gating= it causes (present-only) - const std::string ceilingAttr = r.ceiling != 0 ? " ceiling=\"" + std::to_string( r.ceiling ) + "\"" : std::string(); - // QD-UNCHECKED-STATUS: the call whose status a defect-shape unchecked-status row drops (present-only) - const std::string callAttr = presentXmlAttr( "call", r.call, ex ); - // P8 (L7): the threshold beside the number it judges — bar= on the four numeric kinds (quality.h's - // kCcxBar/kLocBar/kNestBar/kParamBar), so was=/now= read without the legend. - const char* barAttr = qdBarAttrOf( r.kind ); - const std::string tangleAttrs = quality::tangleRowAttrs( r, /*json=*/false, ex ); // QD-TANGLE: why= / fix= / locals= - // P3 (L7, nextverb.h): a GATING row hands the agent the body to fix — --expand=FILE:NAME (the file-qualified - // selector, so a same-named symbol elsewhere cannot answer). The name is the sym key's last :: segment; - // duplication rows name a SET (members=) and carry no single body to open, nor does a FILE-anchored - // defect-shape row (top-level code: sym= is the path, and --expand=FILE:FILE matches no symbol). - std::string nextAttr; - if( *gatingAttr && !r.path.empty() && r.kind != "duplication" && !( r.kind == "defect-shape" && r.sym == r.path ) ) - { - const std::size_t sep = r.sym.rfind( "::" ); - const std::string bare = sep == std::string::npos ? r.sym : r.sym.substr( sep + 2 ); - nextAttr = rw::nextAttrXml( rw::nextFlag( "--expand=", r.path + ":" + bare ) ); - } - if( r.kind == "duplication" ) - { - rw::emitTo( out, "", ex( quality::displaySym( r.sym, deltaRoot ) ).c_str(), r.now, sev, facetAttr.c_str(), origin, locAttr.c_str(), gatingAttr, - tangleAttrs ); // QD-IDIOM-ELEMTYPE: why= when the operand path demoted it - } - else if( r.kind == "dead-code" ) - { - rw::emitTo( out, "", r.kind.c_str(), ex( quality::displaySym( r.sym, deltaRoot ) ).c_str(), sev, facetAttr.c_str(), origin, locAttr.c_str(), gatingAttr, nextAttr.c_str() ); - // B10.2e: api-surface now carries two shapes — a brand-new/newly-public symbol (was=now=0, no - // param comparison to show) and a param-count contract-change (was/now = the real counts). Print - // was/now whenever they differ from each other so the contract-change case's was=/now= is visible - // while the new-symbol case's meaningless was="0" now="0" is omitted, matching its old sym-only shape. - } - else if( r.kind == "api-surface" && r.was == r.now ) - { - rw::emitTo( out, "", r.kind.c_str(), ex( quality::displaySym( r.sym, deltaRoot ) ).c_str(), sev, facetAttr.c_str(), origin, locAttr.c_str(), gatingAttr, nextAttr.c_str() ); - } - else - { - rw::emitTo( out, "", r.kind.c_str(), ex( quality::displaySym( r.sym, deltaRoot ) ).c_str(), - quality::rowValueText( r, r.was ), quality::rowValueText( r, r.now ), barAttr, sev, facetAttr.c_str(), origin, locAttr.c_str(), gatingAttr, - ceilingAttr.c_str(), callAttr.c_str(), nextAttr.c_str(), tangleAttrs ); - } - }; - // Fix round 1 (rv-lean-trio item 5, owner ruling 5): a fold ships only when it PAYS (compactlegend.h foldPays: shorter - // by its margin, as written AND as the compact layer delivers it). The whole XML document is one renderer over a FILE*, - // so both candidates are rendered and measured, and the full document wins a fold that does not pay or a failed render - // (fx, dirty tree, one stale ack: 1512 B folded vs 1481 B full). - // `collapse` picks the stale rows' form: true serves only the foreign-scope rows and the stale_by_kind=/stale_next= counts. - // R-I: at= is OMITTED for the ref-pair form (see the root below). Read ONCE: both candidates print the same stamp. - const std::string atAttrs = refPair ? std::string() : gitstamp::atAttr( root ); - const auto emitDocument = [ & ]( std::FILE* out, bool collapse ) - { - const std::vector& served = collapse ? foreignAcks : saRows; - emitQualityDeltaLegend( { baseSel.marker, refPair, identityAttrs, !served.empty(), ackedCount > 0, - basis.registerMacroExcluded > 0, configDiag.total() > 0, regs, outOfScope, - scope.active() || !foreignAcks.empty(), !foreignAcks.empty(), baselineAbsorbed, - basis.headBasis, basis.declinedCallExcluded > 0, basis.valueRefExcluded > 0, collapse, - refs.kinds != quality::kAllKinds, refs.degraded, !refs.memoryStop.empty(), kd.peakOver != 0, - kd.memorySkipped != 0 && refs.selected != quality::kAllKinds, basis.historyUnread.any(), - basis.rustTestExcluded, refs.staleTree, !basis.extras.ratchetRef.empty(), !basis.extras.improved.empty() }, out ); - const char* baseMarker = baseSel.marker; // R3: ditto — one seam decides staleness AND names it - // 2026-09-06: what the sidecar readers skipped, on the root (absent means none) — see kQdBaseHeadUnreadable - std::string sidecarHealthAttrs; - if( baseSel.sidecarBadLines > 0 ) { sidecarHealthAttrs += " baseline_bad_lines=\"" + std::to_string( baseSel.sidecarBadLines ) + "\""; } - if( basis.acksBadLines > 0 ) { sidecarHealthAttrs += " acks_bad_lines=\"" + std::to_string( basis.acksBadLines ) + "\""; } - // #228: present-only, and its absence is the ordinary archived HEAD tree — the floor every git-HEAD - // marker named on its own before this attribute existed. - if( basis.headBasis != nullptr ) { sidecarHealthAttrs += std::string( " head_basis=\"" ) + basis.headBasis + "\""; } - if( basis.declinedCallExcluded > 0 ) { sidecarHealthAttrs += " declined-call-excluded=\"" + std::to_string( basis.declinedCallExcluded ) + "\""; } - sidecarHealthAttrs += rw::countAttrXmlOrEmpty( "value-ref-excluded", basis.valueRefExcluded ); // absent at zero, beside its sibling - // at= anchors this regression list to the commit (+dirty state) it was computed against. - // qd-memory-degrade: stale= and register-macro-excluded= are absent (never 0) when their pass did not run - const std::string staleX = refs.degraded ? std::string() : " stale=\"" + std::to_string( staleAcks.size() ) + "\""; - const std::string rmeX = deadRan ? " register-macro-excluded=\"" + std::to_string( basis.registerMacroExcluded ) + "\"" : std::string(); - rw::emitTo( out, "", - baseMarker, regs.size(), minorCount, ackedCount, staleX, preexistingCount, newSymbolCount, gatingCount, rmeX, basis.apiNewSurface, - // R-I: at= is OMITTED for the ref-pair form rather than stamped with the working tree's - // sha, which would anchor the list to a commit it was not computed from. base_ref= and - // target_ref= are the anchor there, and they carry FULL shas because a wave measurement - // gets quoted into handoffs where a 9-char prefix is one collision from unverifiable. - atAttrs.c_str(), refs.attrs.c_str(), identityAttrs.c_str(), - scopeAttrs.c_str(), configWarnAttr.c_str(), baselineAbsorbedAttr.c_str(), ( sidecarHealthAttrs + ( collapse ? staleCollapseAttrs : std::string() ) + kd.xml + historyAttrs + quality::ratchetAttrsXml( basis.extras, ex ) ).c_str() ); - for( const quality::Regression& r : regs ) - { - emitRow( out, r, /*gatingAllowed=*/true ); - } - std::fputs( quality::improvedXml( basis.extras.improved, deltaRoot, ex ).c_str(), out ); // QD-CREDIT-ROW: never a row, never gating - if( scope.active() ) - { - // P1 — the DISCLOSURE half. Dropping these rows would make a scoped report a quieter lie than - // the unscoped one it replaces: the debt is real, it is in the same tree, and it will be in - // someone's report. So they are printed, in their own element, marked non-gating, with the one - // sentence a reader needs written where they meet it. Emitted even when EMPTY — an absent - // element then means "no scope was given", never "nobody else has anything open". - rw::emitTo( out, "", - outOfScope.size(), scopedOutGating ); - for( const quality::Regression& r : outOfScope ) - { - emitRow( out, r, /*gatingAllowed=*/false ); - } - rw::emitRaw( out, "" ); - } - { // L2 — one row per stale ack (quality::staleAcksXml). M21(a): the escaper is passed in - // because sym= carries a canonical id (corpus text), unlike the closed-vocabulary kind=/why=. - std::vector saEsc; - std::fputs( quality::staleAcksXml( served, [ & ]( std::string_view t ) { return std::string( escapeXml( t, saEsc ) ); } ).c_str(), out ); - } - rw::emitRaw( out, "" ); - }; - // the identity-tree VERDICT (verdictOnly above): the root line alone - const auto emitVerdict = [ & ]( std::FILE* out ) - { - rw::emitTo( out, "" - "", - baseSel.marker, staleAcks.size(), atAttrs, staleCollapseAttrs ); - }; - if( !collapseStale ) + // THE LEGACY-ACK BACKFILL, run on the map this process already holds the write lock over and + // BEFORE this run's own acks are folded in, so a row healed here can still be overwritten by a + // live measurement of the same finding in the loop below — measured always beats reconstructed, + // and ordering is what guarantees it rather than a check. It runs even when this run accepts + // NOTHING: healing the ledger's provenance is the same class of forward repair the identity + // remap already performs on every ack, and H10's ackNothingToAccept re-renders and notices. + // quality::backfillCloneAckProvenance owns the rule, what it refuses to touch, and why. + discloseAckBackfill( quality::backfillCloneAckProvenance( basis.acks, basis.cloneIdioms ) ); + + const std::string* const scopeSpec = scope.active() ? &scope.spec : nullptr; + QdAckTally tally{ .findings = basis.regs.size(), .alreadyAcked = part.ackedCount, .narrowed = !ackOnly.empty() }; + for( const quality::Regression& r : basis.regs ) + { + if( !selected( r, /*inScope=*/true ) ) { - emitDocument( stdout, /*collapse=*/false ); - return qualityDeltaExit( gatingCount, refs.degraded || basis.historyUnread.any() ); + ++tally.skipped; + continue; } - const Rendered full = renderToString( [ & ]( std::FILE* f ) { emitDocument( f, /*collapse=*/false ); } ); - const Rendered folded = renderToString( [ & ]( std::FILE* f ) { if( verdictOnly ) { emitVerdict( f ); } else { emitDocument( f, /*collapse=*/true ); } } ); - if( !full.ok || !folded.ok ) + ++tally.accepted; + acceptFinding( basis.acks, basis.healing.cids.cidByKey, r, scopeSpec, cfg.qualityAckReason ); + } + if( tally.accepted == 0 && tally.narrowed ) + { + return refuseUnmatchedAckOnly( ackOnly, acksFile, basis.acks, tally.findings ); + } + // H10: nothing to accept — leave a canonical ledger alone, heal a non-canonical one (ackNothingToAccept) + if( basis.regs.empty() ) + { + return ackNothingToAccept( acksFile, basis.acks, scope, part.outOfScope.size() ); + } + return writeAcceptedAcks( acksFile, basis.acks, tally, scope, part.outOfScope.size() ); +} + +// r26 ORIGIN SPLIT — three counts over the VISIBLE (post-ack) findings, one pass: +// minor — the materiality tier (unchanged axis). +// newSymbol — findings that exist only because the code is NEW (quality.h's origin axis). +// gating — the EXIT PREDICATE (quality::rowGates): major AND preexisting-worse, or a defect-shape +// format-arity row of any origin. Emitted as gating= so the header alone tells you +// the exit code (it used to be "regressions > minor"). +// preexisting-worse = regressions − new-symbol by construction (the axis is a partition), so the two +// header counters always sum to regressions= — an invariant the gate asserts. +struct QdCounts +{ + std::size_t minor = 0, newSymbol = 0, gating = 0, preexisting = 0; +}; +QdCounts countQdRows( const std::vector& regs ) +{ + QdCounts c; + for( const rw::quality::Regression& r : regs ) + { + c.minor += r.isMinor ? 1 : 0; + c.newSymbol += r.isNewSymbol ? 1 : 0; + c.gating += rw::quality::rowGates( r ) ? 1 : 0; + } + c.preexisting = regs.size() - c.newSymbol; + return c; +} + +// The finished comparison every report step reads, READ-ONLY: the floor and the delta (basis), the range form's trees +// (refs), the scope and what the partition and the ratchet decided. Built once, after the last write to any of them. +// Every path and symbol downstream is spelled against basis.deltaRoot rather than against `root` (DeltaBasis's header). +struct QdComparison +{ + const rw::Config& cfg; + const std::string& root; + const RefPairDelta& refs; + const DeltaBasis& basis; + const rw::quality::Scope& scope; + const QdPartition& part; + const rw::IngestResult& judgedIndex; // the JUDGED tree's index: tree B in the range form, else the working tree + bool refPair; // the range form (--quality-delta=A..B) + std::size_t diffFileCount; // P1.2: files the reserved diff token expanded to (0 = not used) +}; + +// Which spelling of a root disclosure an emitter wants. +enum class QdFormat : std::uint8_t +{ + Xml, + Json +}; + +// One optional root disclosure of the --quality-delta answer, decided ONCE and spelled for both formats: `xml` is spliced +// into the root element, `json` into the top-level object. Both are empty when the fact is absent — absent means "never +// happened" or "not run", never 0. A field the JSON object has never carried keeps `json` empty. +struct QdRootField +{ + std::string xml, json; + + const std::string& in( QdFormat format ) const noexcept { return format == QdFormat::Xml ? xml : json; } +}; + +// A count as a root disclosure: ` name="N"` / `,"name":N` (rw::countField) when `present`, else absent. +QdRootField qdCountField( std::string_view name, std::size_t count, bool present ) +{ + return present ? QdRootField{ rw::countField( name, count, /*json=*/false ), rw::countField( name, count, /*json=*/true ) } : QdRootField{}; +} + +// Every root disclosure, each built once (qdRootFieldsOf). `stale` and `registerMacroExcluded` sit between the fixed +// counts; the rest form the root's tail in qdRootTail's order. +struct QdRootFields +{ + // qd-memory-degrade: stale= and register-macro-excluded= are absent (never 0) when their pass did not run + QdRootField stale, registerMacroExcluded; + QdRootField at; // at=: commit+dirty state; the range form omits it in XML and says null in JSON + QdRootField rangeRefs; // R-I: base_ref= target_ref= churn= (RefPairDelta::attrs / jsonAttrs) + QdRootField identity; // R1 IDENTITY: renames and acks re-filed by rename or content (quality::identityDisclosure) + QdRootField scopeDisclosure; // P1/P1.4: --scope, out-of-scope and foreign-ack counts (quality::scopeDisclosure) + QdRootField configWarnings; // F-13: .ripwire_config keys/names that did nothing + QdRootField baselineAbsorbed; // H11: debt the honored sidecar absorbed + QdRootField baselineBadLines, acksBadLines; // 2026-09-06: unparseable sidecar lines skipped (XML only, as always) + QdRootField headBasis; // #228: which basis produced a git-HEAD floor (absent = the archived HEAD tree) + QdRootField declinedCallExcluded, valueRefExcluded; // dead-code exemptions, absent at zero + QdRootField kinds; // qd-memory-degrade: kinds not run, why, the replay, the peak (kindsDisclosure) + QdRootField history; // hwh-fix4 (N1): history a gating kind could not read (unread_history=) + QdRootField ratchet; // D4: the ratchet's reference point and what it could not read + QdRootField shellCut; // CR712-SHSTATUS-DEPTH: shell files whose defect-shape scan the nesting budget cut +}; + +// The root's tail in one order for both formats. `foldAttrs` (XML only) is the stale fold's stale_by_kind=/stale_next=, +// which sits between the exclusion counts and the kinds disclosure. +std::string qdRootTail( const QdRootFields& f, QdFormat format, std::string_view foldAttrs ) +{ + std::string out; + for( const QdRootField* field : { &f.at, &f.rangeRefs, &f.identity, &f.scopeDisclosure, &f.configWarnings, &f.baselineAbsorbed, + &f.baselineBadLines, &f.acksBadLines, &f.headBasis, &f.declinedCallExcluded, &f.valueRefExcluded } ) + { + out += field->in( format ); + } + out += foldAttrs; + for( const QdRootField* field : { &f.kinds, &f.history, &f.ratchet, &f.shellCut } ) + { + out += field->in( format ); + } + return out; +} + +// Everything one --quality-delta answer renders, computed before the format is chosen (computeQdReport): the JSON and XML +// emitters read only this and the comparison it points at, so the two formats cannot disagree about a fact. +struct QdReport +{ + const QdComparison& c; + std::vector staleAcks; + std::vector saRows; // stale + foreign acks: the one / "sa" list + QdCounts counts; + std::size_t baselineAbsorbed = 0; + rw::quality::RegisterMacroConfigDiagnostics configDiag; // its stderr lines are emitQdStderrLines' + KindsDisclosure kd; + QdRootFields root; + + // The exit code every rendering returns (qualityDeltaExit): r26 — only a PREEXISTING-worse AND major regression gates + // (== gating=); a changed-files answer, or one whose gating history could not be read, is partial. + int exitCode() const noexcept { return qualityDeltaExit( counts.gating, c.refs.degraded || c.basis.historyUnread.any() ); } +}; + +// Every root disclosure of `rep`, each decided here once for both formats. +QdRootFields qdRootFieldsOf( const QdReport& rep ) +{ + using namespace rw; + const QdComparison& c = rep.c; + const DeltaBasis& basis = c.basis; + const bool deadRan = !c.refPair || quality::kindSelected( c.refs.kinds, "dead-code" ); // dead-code's side counts exist only when it ran + const auto fromPair = []( std::pair p ) { return QdRootField{ std::move( p.first ), std::move( p.second ) }; }; + std::vector esc; + QdRootFields f; + f.stale = qdCountField( "stale", rep.staleAcks.size(), !c.refs.degraded ); + f.registerMacroExcluded = qdCountField( "register-macro-excluded", basis.registerMacroExcluded, deadRan ); + // R-I: the range form's list was not computed "at" any working-tree state — base_ref= and target_ref= are its anchor, so + // XML omits at= and JSON says null (never a fake sha); a non-git root is null too. + const std::string atValue = c.refPair ? std::string() : gitstamp::stampAt( c.root ); + f.at = { atValue.empty() ? std::string() : " at=\"" + atValue + "\"", + ",\"at\":" + ( atValue.empty() ? std::string( "null" ) : "\"" + atValue + "\"" ) }; + f.rangeRefs = { c.refs.attrs, c.refs.jsonAttrs }; + f.identity = fromPair( quality::identityDisclosure( basis.healing ) ); + f.scopeDisclosure = fromPair( quality::scopeDisclosure( c.scope, c.part.outOfScope.size(), c.part.scopedOutGating, c.part.foreignAcks.size(), c.diffFileCount ) ); + f.configWarnings = qdCountField( "config-warnings", rep.configDiag.total(), rep.configDiag.total() != 0 ); + f.baselineAbsorbed = qdCountField( "baseline_absorbed", rep.baselineAbsorbed, rep.baselineAbsorbed != 0 ); + f.baselineBadLines = { qdCountField( "baseline_bad_lines", basis.baseSel.sidecarBadLines, basis.baseSel.sidecarBadLines != 0 ).xml, {} }; + f.acksBadLines = { qdCountField( "acks_bad_lines", basis.acksBadLines, basis.acksBadLines != 0 ).xml, {} }; + if( basis.headBasis != nullptr ) + { + f.headBasis = { std::string( " head_basis=\"" ) + basis.headBasis + "\"", std::string( ",\"head_basis\":\"" ) + basis.headBasis + "\"" }; + } + f.declinedCallExcluded = qdCountField( "declined-call-excluded", basis.declinedCallExcluded, basis.declinedCallExcluded != 0 ); + f.valueRefExcluded = qdCountField( "value-ref-excluded", basis.valueRefExcluded, basis.valueRefExcluded != 0 ); + f.kinds = { rep.kd.xml, rep.kd.json }; + f.history = fromPair( quality::historyUnreadDisclosure( basis.historyUnread ) ); + f.ratchet = { quality::ratchetAttrsXml( basis.extras, [ & ]( std::string_view s ) { return std::string( escapeXml( s, esc ) ); } ), + quality::ratchetAttrsJson( basis.extras ) }; + f.shellCut = qdCountField( "shell_cut", basis.extras.shellCut, basis.extras.shellCut != 0 ); + return f; +} + +// COMPUTE — the counts, the rows and every root disclosure of one answer. Prints nothing: its stderr lines are +// emitQdStderrLines'. `staleAcks` are the ledger rows the judged tree no longer supports (the caller computes them, since +// the bare form's snapshot writes the shared tree passes). +QdReport computeQdReport( const QdComparison& c, std::vector staleAcks, const std::string& baselineFile ) +{ + using namespace rw; + QdReport rep{ .c = c, .staleAcks = std::move( staleAcks ) }; + // P1.4 — the family now carries THREE whys, and the third is counted SEPARATELY: stale= means + // "this ack no longer applies", and a foreign ack applies fine — it is the SESSION that was wrong, + // not the target. Merging the rows into one list keeps the two emitters from growing a second loop + // each; keeping the COUNTS apart keeps stale= meaning what it has always meant. + rep.saRows = rep.staleAcks; + rep.saRows.insert( rep.saRows.end(), c.part.foreignAcks.begin(), c.part.foreignAcks.end() ); + // M21(a): name the rows the tree can still name, against the SAME tree computeStaleAcks judged + // (tree B in the ref-pair form) — naming a stale ack after the working tree would print an identity + // the verdict was never computed from. Costs one walk over the judged symbols, and only when there are rows. + quality::stampStaleAckIdentity( rep.saRows, c.judgedIndex, c.refPair ? std::string_view( c.refs.target().root ) : std::string_view( c.cfg.rootPath ) ); + + rep.counts = countQdRows( c.basis.regs ); + // H11 — the absorbed-debt stamp on the honored sidecar, or 0. Read ONLY when the sidecar is the floor + // in force: on the git-HEAD and ref-pair floors there is no pin whose contents could have absorbed + // anything, and printing a 0 there would define an attribute about a file this run did not use. + rep.baselineAbsorbed = ( c.basis.baseSel.marker == std::string_view( "sidecar" ) ) ? quality::readBaselineAbsorbed( baselineFile ) : 0; + // F-13 — the .ripwire_config diagnosis. #387: the inert-name test reads the JUDGED tree's index, which in the ref-pair + // form is tree B — the working tree is not indexed there at all (runQualityDeltaRangeBeforeIngest). + // qd-memory-degrade: not over a changed-files index, which cannot tell an inert name from one the tree defines (also_skipped=) + rep.configDiag = c.refs.degraded ? quality::RegisterMacroConfigDiagnostics{} : quality::diagnoseRegisterMacroConfig( c.judgedIndex, c.root ); + // qd-memory-degrade: the kinds this answer did not run, why, and the replay — plus the peak, read once now that the + // comparison is done (kindsDisclosure). + rep.kd = kindsDisclosure( c.cfg, c.refs, c.basis, c.refPair ); + rep.root = qdRootFieldsOf( rep ); + return rep; +} + +// The human channel's lines of one answer, in the order they have always printed, before stdout is written: a stdout +// answer that is partial, ran past the memory limit or gates says so first on the channel a human reads. +void emitQdStderrLines( const QdReport& rep ) +{ + using namespace rw; + const QdComparison& c = rep.c; + if( std::getenv( "RIPWIRE_STATS" ) ) // QD-ENVOY-TIME cost bound: Type-3 passes this call ran (test/qdtype3oncecheck.sh) + { + rw::emitTo( stderr, "ripwire: quality-passes type3_runs={} type3_pairs={}\n", gType3PassRuns.load( std::memory_order_relaxed ), + gType3PassPairs.load( std::memory_order_relaxed ) ); + } + if( rep.counts.gating == 0 && c.basis.historyUnread.any() ) + { + rw::emitTo( stderr, "ripwire: --quality-delta: not a clean pass - git history a gating kind needs could not be read ({}; a partial clone " + "does not download it), so a gating row may be missing: exit 6\n", rep.root.history.xml.substr( 1 ).c_str() ); + } + emitRegisterMacroConfigWarnings( rep.configDiag ); // F-13: the specific keys and names, never guessed at in the attribute + emitMemoryLines( rep.kd, c.refs ); + // P2.5 — one stderr line NAMING the gating finding, in --token-budget's style ("ripwire: --token-budget + // exceeded: est_tokens=… > budget=…"). stdout is the machine artifact and a caller that only checks + // `$?` gets a number with no subject; this puts the WHICH on the channel a human reads, without + // touching the XML contract. Names the first gating row in the already-sorted list (deterministic). + // §A4 (minor): emitted BEFORE the format fork — the line is about the EXIT CODE, which both formats share, so it + // belongs to neither (under --json the fork used to return first, and a script reading `$?` got no subject). + emitQdGatingLine( c.basis.regs, rep.counts.gating, c.basis.deltaRoot ); +} + +// ── the ROW MODEL: one --quality-delta row's printed facts, decided once for the XML and JSON emitters ───────────────── +// P1: both formats print the in-scope rows and the disclosed out-of-scope rows with this one model — a disclosed row +// carries the identical attribute set, because nothing about a finding changes by belonging to someone else. `gating` is +// the one difference: an out-of-scope row is not what the exit code fires on, and claiming gating on it would contradict +// the header's own gating counter inside the same document. +struct QdRowModel +{ + // duplication carries a member LIST (members=) + token count; dead-code and an api-surface row whose counts did not + // change are sym-only; every other kind carries was/now. + // B10.2e: api-surface carries two shapes — a brand-new/newly-public symbol (was=now=0, no param comparison to show) + // and a param-count contract-change (was/now = the real counts). was/now print whenever they differ from each other, + // so the contract-change case's was=/now= is visible while the new-symbol case's meaningless was="0" now="0" is + // omitted, matching its old sym-only shape. + enum class RowShape : std::uint8_t { Members, SymOnly, WasNow }; + RowShape shape = RowShape::WasNow; + std::string sym; // quality::displaySym, unescaped: members= for Members, sym= otherwise + bool gating = false; // P2.5: the exit predicate (quality::rowGates), stated per row; never on a disclosed row + // B10.2 — the optional classification facet: its attribute NAME is chosen by kind (quality::facetAttrName, the ONE + // kind→name table for every emitter, MCP included); r.facet carries only the VALUE. nullptr = no facet attribute. + const char* facetName = nullptr; + // r26 — the ORIGIN axis (quality::originValue): present only on new-symbol rows (absent = preexisting-worse), the same + // "mark the exception" convention sev= uses. origin= is what the exit gate reads. + const char* origin = nullptr; +}; +QdRowModel qdRowModel( const rw::quality::Regression& r, bool gatingAllowed, std::string_view deltaRoot ) +{ + using namespace rw; + QdRowModel m; + m.shape = r.kind == "duplication" ? QdRowModel::RowShape::Members + : ( r.kind == "dead-code" || ( r.kind == "api-surface" && r.was == r.now ) ) ? QdRowModel::RowShape::SymOnly + : QdRowModel::RowShape::WasNow; + m.sym = quality::displaySym( r.sym, deltaRoot ); + m.gating = gatingAllowed && quality::rowGates( r ); + m.facetName = r.facet.empty() ? nullptr : quality::facetAttrName( r.kind ); + m.origin = quality::originValue( r ); + return m; +} + +// P3 (L7, nextverb.h): a GATING row hands the agent the body to fix — --expand=FILE:NAME (the file-qualified selector, so +// a same-named symbol elsewhere cannot answer). The name is the sym key's last :: segment. Only the sym-carrying shapes ask: +// a Members row (duplication) names a SET and has no single body to open; nor does new-clone-of-reused-helper, whose sym= is +// the same member list (CR721: its "last :: segment" was "a | b", and p= belongs to the first member). Nor does a +// FILE-anchored defect-shape row (top-level code: sym= is the path, and --expand=FILE:FILE matches no symbol). Empty when +// the row offers no body. +std::string qdExpandNextAttr( const rw::quality::Regression& r, const QdRowModel& m ) +{ + if( !m.gating || r.path.empty() || r.kind == "new-clone-of-reused-helper" || ( r.kind == "defect-shape" && r.sym == r.path ) ) + { + return std::string(); + } + const std::size_t sep = r.sym.rfind( "::" ); + const std::string bare = sep == std::string::npos ? r.sym : r.sym.substr( sep + 2 ); + return rw::nextAttrXml( rw::nextFlag( "--expand=", r.path + ":" + bare ) ); +} + +// One XML row. The attribute order is the contract every gate reads: kind/sym (or members/tokens), was/now with bar=, +// then sev= facet= origin= and the P2.5 pair p= gating= (appended after every pre-r27 attribute), then the per-kind tail. +// `ex` is the document's XML escaper. +template +void emitQdXmlRow( std::FILE* out, const rw::quality::Regression& r, const QdRowModel& m, const Escape& ex ) +{ + using namespace rw; + // sev="minor" marks a below-materiality delta (never gates); absent = major. + std::string common = r.isMinor ? " sev=\"minor\"" : ""; + if( m.facetName != nullptr ) + { + common += std::string( " " ) + m.facetName + "=\"" + ex( r.facet ) + "\""; // escaped: a ratchet facet is a tag name + } + if( m.origin != nullptr ) + { + common += std::string( " origin=\"" ) + m.origin + "\""; + } + // P2.5 — p="path:line": sym= is a canonical id whose display tail is often a bare one-letter local (`sym="cc"`), i.e. + // ungreppable. Omitted, never faked, when no locator was resolvable. gating="1" marks exactly the rows the header's + // gating= counts — until r27 a gating row was identifiable only by the ABSENCE of sev="minor" and origin=. + if( !r.path.empty() ) + { + common += " p=\"" + ex( r.path ) + ":" + std::to_string( r.line ) + "\""; + } + common += m.gating ? " gating=\"1\"" : ""; + switch( m.shape ) + { + case QdRowModel::RowShape::Members: + rw::emitTo( out, "", ex( m.sym ), r.now, common, + quality::tangleRowAttrs( r, /*json=*/false, ex ) ); // QD-IDIOM-ELEMTYPE: why= when the operand path demoted it + return; + case QdRowModel::RowShape::SymOnly: + rw::emitTo( out, "", r.kind, ex( m.sym ), common, qdExpandNextAttr( r, m ) ); + return; + case QdRowModel::RowShape::WasNow: + // P8 (L7): bar= is the threshold beside the number it judges, on the four numeric kinds (quality.h's + // kCcxBar/kLocBar/kNestBar/kParamBar), so was=/now= read without the legend. QD-ENTRY-CEILING: ceiling= is the + // ceiling a NEW function reached, beside the gating= it causes; QD-UNCHECKED-STATUS: call= is the call whose + // status a defect-shape unchecked-status row drops; QD-TANGLE: why= / fix= / locals=. All present-only. + rw::emitTo( out, "", r.kind, ex( m.sym ), + quality::rowValueText( r, r.was ), quality::rowValueText( r, r.now ), qdBarAttrOf( r.kind ), common, + r.ceiling != 0 ? " ceiling=\"" + std::to_string( r.ceiling ) + "\"" : std::string(), presentXmlAttr( "call", r.call, ex ), + qdExpandNextAttr( r, m ), quality::tangleRowAttrs( r, /*json=*/false, ex ) ); + return; + } +} + +// One JSON row object: the keys mirror the XML attribute names, in the order the --json contract has always used. +void emitQdJsonRow( std::FILE* out, const rw::quality::Regression& r, const QdRowModel& m ) +{ + using namespace rw; + rw::emitTo( out, "{{\"kind\":\"{}\"", jsonStr( r.kind ) ); + if( m.shape == QdRowModel::RowShape::Members ) + { + rw::emitTo( out, ",\"members\":\"{}\",\"tokens\":{}", jsonStr( m.sym ), r.now ); + } + else + { + rw::emitTo( out, ",\"sym\":\"{}\"", jsonStr( m.sym ) ); + } + if( m.shape == QdRowModel::RowShape::WasNow ) + { + rw::emitTo( out, ",\"was\":{},\"now\":{}", quality::rowValueText( r, r.was ), quality::rowValueText( r, r.now ) ); + } + if( !r.path.empty() ) + { + rw::emitTo( out, ",\"p\":\"{}:{}\"", jsonStr( r.path ), r.line ); // P2.5 locator + } + rw::emitRaw( out, m.gating ? ",\"gating\":true" : "" ); // P2.5 — the exit predicate, stated per row + rw::emitRaw( out, r.isMinor ? ",\"sev\":\"minor\"" : "" ); + if( m.facetName != nullptr ) + { + rw::emitTo( out, ",\"{}\":\"{}\"", m.facetName, jsonStr( r.facet ) ); + } + if( m.origin != nullptr ) + { + rw::emitTo( out, ",\"origin\":\"{}\"", m.origin ); // absent = preexisting-worse (mirrors the XML) + } + if( r.ceiling != 0 ) + { + rw::emitTo( out, ",\"ceiling\":{}", r.ceiling ); // QD-ENTRY-CEILING (mirrors the XML) + } + rw::emitRaw( out, presentJsonMember( "call", r.call ).c_str() ); // QD-UNCHECKED-STATUS (mirrors the XML) + std::fputs( quality::tangleRowAttrs( r, /*json=*/true, []( std::string_view s ) { return jsonStr( s ); } ).c_str(), out ); // QD-TANGLE (mirrors the XML) + rw::emitRaw( out, "}" ); +} + +// A comma-separated run of JSON rows (the "r" array's body, or "oos"'s). +void emitQdJsonRows( std::FILE* out, const std::vector& rows, bool gatingAllowed, std::string_view deltaRoot ) +{ + bool first = true; + for( const rw::quality::Regression& r : rows ) + { + rw::emitRaw( out, first ? "" : "," ); + first = false; + emitQdJsonRow( out, r, qdRowModel( r, gatingAllowed, deltaRoot ) ); + } +} + +// RENDER, --json — same regressions, keys mirror the XML attr names (kind/sym/members/tokens/was/now/sev/churn/surface). +// jsonUnsupportedVerb already refused --quality-baseline/--quality-ack, so reaching here with cfg.json means the plain +// --quality-delta report. Every optional root member is the JSON spelling of a QdRootField. +void emitQualityDeltaJson( const QdReport& rep ) +{ + using namespace rw; + const QdComparison& c = rep.c; + const DeltaBasis& basis = c.basis; + rw::emitTo( stdout, "{{\"baseline\":\"{}\",\"regressions\":{},\"minor\":{},\"acked\":{}{}," + "\"preexisting-worse\":{},\"new-symbol\":{},\"gating\":{}{},\"api-new-surface\":{}{},\"r\":[", + jsonStr( basis.baseSel.marker ), basis.regs.size(), rep.counts.minor, c.part.ackedCount, rep.root.stale.json, + rep.counts.preexisting, rep.counts.newSymbol, rep.counts.gating, rep.root.registerMacroExcluded.json, basis.apiNewSurface, + qdRootTail( rep.root, QdFormat::Json, {} ) ); + emitQdJsonRows( stdout, basis.regs, /*gatingAllowed=*/true, basis.deltaRoot ); + rw::emitRaw( stdout, "]," ); + if( c.scope.active() ) + { + // The JSON sibling of the XML out-of-scope element: a SEPARATE array, never a flag on a row + // in "r", so a consumer that reads "r" and checks "gating" cannot accidentally count someone + // else's debt as this run's. Emitted (possibly empty) whenever a scope was given, so its + // absence means "no scope", never "no disclosed rows". + rw::emitRaw( stdout, "\"oos\":[" ); + emitQdJsonRows( stdout, c.part.outOfScope, /*gatingAllowed=*/false, basis.deltaRoot ); + rw::emitRaw( stdout, "]," ); + } + std::fputs( quality::staleAcksJsonArray( rep.saRows ).c_str(), stdout ); // L2 — "sa":[...], same taxonomy as the XML sa= rows + std::fputs( quality::improvedJson( basis.extras.improved, basis.deltaRoot ).c_str(), stdout ); // QD-CREDIT-ROW (absent when none) + rw::emitRaw( stdout, "}" ); +} + +// idea #11 — THE CLEAN-TREE PAYLOAD. A regression-free answer folds its stale-ack rows to counts (stale= and +// stale_by_kind=), and stale_next= is the call that prints them; on a tree that IS its HEAD (head_basis="identity": the +// floor is this tree's own snapshot) with nothing else to disclose, the verdict is the whole answer. Foreign-scope rows are +// never folded: they are about findings suppressed RIGHT NOW. --show-stale restores today's document byte for byte, so +// every folded row and attribute is one flag away (PROCESS rule 5). +struct QdStaleFold +{ + bool verdictOnly = false; // the identity-tree VERDICT: the root line alone (qdNothingElseToDisclose) + std::string attrs; // stale_by_kind= + stale_next=, on the folded root +}; + +// The identity-tree verdict's precondition: a working-tree answer whose floor is this tree's own snapshot +// (head_basis="identity") with no scope, foreign or accepted ack, config warning, absorbed debt, new public surface, +// unreadable sidecar line or shell scan the nesting budget cut (shell_cut=, CR721) to disclose — so the root line alone +// loses nothing. +bool qdNothingElseToDisclose( const QdReport& rep ) +{ + const QdComparison& c = rep.c; + const DeltaBasis& basis = c.basis; + return !c.refPair && basis.headBasis != nullptr && std::string_view( basis.headBasis ) == "identity" + && !c.scope.active() && c.part.foreignAcks.empty() && c.part.ackedCount == 0 && rep.configDiag.total() == 0 && rep.baselineAbsorbed == 0 + && basis.apiNewSurface == 0 && basis.baseSel.sidecarBadLines == 0 && basis.acksBadLines == 0 && basis.extras.shellCut == 0; +} + +// The stale fold this answer could ship (whether it PAYS is emitQualityDeltaXml's to measure), or nullopt when it has a +// regression, an out-of-scope row, no stale ack, or --show-stale. +template +std::optional qdStaleFold( const QdReport& rep, const Escape& ex ) +{ + using namespace rw; + const QdComparison& c = rep.c; + if( !c.basis.regs.empty() || !c.part.outOfScope.empty() || c.cfg.showStale || rep.staleAcks.empty() ) + { + return std::nullopt; + } + const std::string kinds = quality::staleByKindValue( rep.staleAcks ); // shared with the MCP twin (lane lean2b) + std::string replay = c.cfg.qualityDeltaRange.empty() ? std::string( "--quality-delta" ) : rw::nextFlag( "--quality-delta=", c.cfg.qualityDeltaRange ); + if( c.scope.active() ) + { + replay += " " + rw::nextFlag( "--scope=", c.cfg.qualityScope ); + } + return QdStaleFold{ .verdictOnly = qdNothingElseToDisclose( rep ), + .attrs = " stale_by_kind=\"" + ex( kinds ) + "\"" + rw::nextAttrXml( replay + " --show-stale", "stale_next" ) }; +} + +// The whole XML document over one FILE*: legend, root, rows, improvements, the out-of-scope disclosure and the rows. +// `fold` null renders every stale row; otherwise only the foreign-scope rows, with fold->attrs on the root. +void emitQdXmlDocument( std::FILE* out, const QdReport& rep, const QdStaleFold* fold ) +{ + using namespace rw; + const QdComparison& c = rep.c; + const DeltaBasis& basis = c.basis; + const RefPairDelta& refs = c.refs; + std::vector esc; + const auto ex = [ & ]( std::string_view s ) -> std::string { return std::string( escapeXml( s, esc ) ); }; + const std::vector& served = fold != nullptr ? c.part.foreignAcks : rep.saRows; + // the legend is passed the same values the root element below prints, so "the legend defines what the header emits" is + // read off one set of values rather than restated as a second condition that could drift from it + emitQualityDeltaLegend( { basis.baseSel.marker, c.refPair, rep.root.identity.xml, !served.empty(), c.part.ackedCount > 0, + basis.registerMacroExcluded > 0, rep.configDiag.total() > 0, basis.regs, c.part.outOfScope, + c.scope.active() || !c.part.foreignAcks.empty(), !c.part.foreignAcks.empty(), rep.baselineAbsorbed, + basis.headBasis, basis.declinedCallExcluded > 0, basis.valueRefExcluded > 0, fold != nullptr, + refs.kinds != quality::kAllKinds, refs.degraded, !refs.memoryStop.empty(), rep.kd.peakOver != 0, + rep.kd.memorySkipped != 0 && refs.selected != quality::kAllKinds, basis.historyUnread.any(), + basis.rustTestExcluded, refs.staleTree, !basis.extras.ratchetRef.empty(), !basis.extras.improved.empty(), + basis.extras.shellCut > 0 }, out ); + // at= anchors this regression list to the commit (+dirty state) it was computed against (QdRootFields::at). R-I: the range + // form's base_ref= and target_ref= carry FULL shas because a wave measurement gets quoted into handoffs where a 9-char + // prefix is one collision from unverifiable. + rw::emitTo( out, "", + basis.baseSel.marker, basis.regs.size(), rep.counts.minor, c.part.ackedCount, rep.root.stale.xml, rep.counts.preexisting, + rep.counts.newSymbol, rep.counts.gating, rep.root.registerMacroExcluded.xml, basis.apiNewSurface, + qdRootTail( rep.root, QdFormat::Xml, fold != nullptr ? std::string_view( fold->attrs ) : std::string_view() ) ); + for( const quality::Regression& r : basis.regs ) + { + emitQdXmlRow( out, r, qdRowModel( r, /*gatingAllowed=*/true, basis.deltaRoot ), ex ); + } + std::fputs( quality::improvedXml( basis.extras.improved, basis.deltaRoot, ex ).c_str(), out ); // QD-CREDIT-ROW: never a row, never gating + if( c.scope.active() ) + { + // P1 — the DISCLOSURE half. Dropping these rows would make a scoped report a quieter lie than + // the unscoped one it replaces: the debt is real, it is in the same tree, and it will be in + // someone's report. So they are printed, in their own element, marked non-gating, with the one + // sentence a reader needs written where they meet it. Emitted even when EMPTY — an absent + // element then means "no scope was given", never "nobody else has anything open". + rw::emitTo( out, "", + c.part.outOfScope.size(), c.part.scopedOutGating ); + for( const quality::Regression& r : c.part.outOfScope ) { - // renderToString DISCLOSEd the failed buffer; the full document is the superset, written straight to stdout - emitDocument( stdout, /*collapse=*/false ); - return qualityDeltaExit( gatingCount, refs.degraded || basis.historyUnread.any() ); + emitQdXmlRow( out, r, qdRowModel( r, /*gatingAllowed=*/false, basis.deltaRoot ), ex ); } - const std::string& chosen = foldPays( folded.text, full.text ) ? folded.text : full.text; // compactlegend.h: the margin and why - std::fwrite( chosen.data(), 1, chosen.size(), stdout ); - return qualityDeltaExit( gatingCount, refs.degraded || basis.historyUnread.any() ); // r26: only a PREEXISTING-worse AND major regression gates (== gating=) + rw::emitRaw( out, "" ); } - return std::nullopt; + // L2 — one row per stale ack (quality::staleAcksXml). M21(a): the escaper is passed in because sym= carries a + // canonical id (corpus text), unlike the closed-vocabulary kind=/why=. + std::vector saEsc; + std::fputs( quality::staleAcksXml( served, [ & ]( std::string_view t ) { return std::string( escapeXml( t, saEsc ) ); } ).c_str(), out ); + rw::emitRaw( out, "" ); +} + +// The identity-tree VERDICT (QdStaleFold::verdictOnly): the root line alone. +void emitQdVerdict( std::FILE* out, const QdReport& rep, const QdStaleFold& fold ) +{ + rw::emitTo( out, "" + "", + rep.c.basis.baseSel.marker, rep.staleAcks.size(), rep.root.at.xml, fold.attrs ); +} + +// RENDER, XML. +// §B7.1 (CA4) — the heading used to open "only what changed for the WORSE vs .ripwire_quality_baseline", which is FALSE in +// every state but one: three of the five floors this verb can use are not that file, and in one of them the file was judged +// stale and DELETED from the user's tree during this very run. The floor actually used is named by baseline= on the root, +// so the heading points at that attribute instead of asserting a floor. +// 2026-09-02 (lane B): the marker states are still defined on the first screen — the only place a reader meets them — but +// ONE state per run, the one in force, rather than all five on every call (emitQualityDeltaLegend). +// Fix round 1 (rv-lean-trio item 5, owner ruling 5): a fold ships only when it PAYS (compactlegend.h foldPays: shorter +// by its margin, as written AND as the compact layer delivers it). The whole XML document is one renderer over a FILE*, +// so both candidates are rendered and measured, and the full document wins a fold that does not pay or a failed render +// (fx, dirty tree, one stale ack: 1512 B folded vs 1481 B full). +void emitQualityDeltaXml( const QdReport& rep ) +{ + using namespace rw; + std::vector esc; + const std::optional fold = qdStaleFold( rep, [ & ]( std::string_view s ) -> std::string { return std::string( escapeXml( s, esc ) ); } ); + if( !fold ) + { + emitQdXmlDocument( stdout, rep, /*fold=*/nullptr ); + return; + } + const Rendered full = renderToString( [ & ]( std::FILE* f ) { emitQdXmlDocument( f, rep, /*fold=*/nullptr ); } ); + const Rendered folded = renderToString( [ & ]( std::FILE* f ) + { + if( fold->verdictOnly ) { emitQdVerdict( f, rep, *fold ); } + else { emitQdXmlDocument( f, rep, &*fold ); } + } ); + if( !full.ok || !folded.ok ) + { + // renderToString DISCLOSEd the failed buffer; the full document is the superset, written straight to stdout + emitQdXmlDocument( stdout, rep, /*fold=*/nullptr ); + return; + } + const std::string& chosen = foldPays( folded.text, full.text ) ? folded.text : full.text; // compactlegend.h: the margin and why + std::fwrite( chosen.data(), 1, chosen.size(), stdout ); +} + +// --quality-baseline / --quality-delta (the convergence-loop oracle): snapshot ccx + clone groups + dead candidates to +// .ripwire_quality_baseline; then report ONLY what a change made WORSE vs it. The "delta not absolute" discipline — a refine +// loop targets the regression it introduced, not absolute numbers (the defense against metric-gaming). exit 2 if any new +// debt, like --arch. The phases: resolve the floor and the delta (resolveDeltaBasis), the scope and the ack ratchet +// (applyScopeAndAcks), then either WRITE ACKS (runQualityAckWrite) or COMPUTE the report (computeQdReport), print its +// stderr lines (emitQdStderrLines) and RENDER it as JSON or XML. +std::optional runQualityDelta( const MainDispatch& d ) +{ + using namespace rw; + const Config& cfg = d.cfg; + if( !cfg.qualityBaseline && !cfg.qualityDelta ) + { + return std::nullopt; + } + // D1 fix (HIGH): resolve BOTH sidecars against the analyzed ROOT, not the process CWD — + // see quality::rootQualifiedSidecar's comment for why a bare relative filename is unsafe here + // (a foreign cwd's sidecar could be silently rewritten, or even deleted by the stale-baseline + // self-heal). Computed once; every read/write/remove site downstream uses it. + const std::string baselineFile = quality::baselinePath( d.root ); + const std::string acksFile = quality::acksPath( d.root ); + if( cfg.qualityBaseline ) + { + return runQualityBaselinePin( d, baselineFile, acksFile ); + } + + // Precedence for the baseline: (1) an explicit `.ripwire_quality_baseline` sidecar (from + // --quality-baseline) wins whenever it is pinned at the CURRENT HEAD — the mid-task convergence loop + // (baseline once, edit, re-check) is unchanged; (2) else — no sidecar, or a STALE one (see R3 below) — + // if the root is a git repo with a HEAD tree, auto-baseline against HEAD so the "before I push" loop + // works with no start-of-task ritual (T0.1); (3) else degrade to the exit-1 "run --quality-baseline + // first" guidance (non-git / unborn / detached-no-tree — unchanged). + // + // STALENESS + the self-heal now live in ONE place, quality::selectBaseline — R3 owner ruling + // (2026-07-29): a sidecar whose pinned sha != the CURRENT HEAD sha is STALE, full stop. The B10.1b + // "reachable ancestor is a deliberately-pinned floor" carve-out this arm used to apply (gitIsAncestor) + // is REVOKED: a parallel session's sidecar pinned at a commit that merely happened to be an ancestor of + // this session's HEAD made THIS arm report 31 phantom regressions while the MCP quality_delta verb — + // same binary, same repo, same second — correctly reported zero. That divergence was only possible + // because each arm carried its own copy of the test; there is now exactly one, in quality.h. + // + // What remains this arm's own POLICY is the `removeStaleFile=true` argument: the stale sidecar is + // silently UNLINKED (best-effort) so the NEXT run sees no file at all rather than rediscovering the + // same dead pin, and the ONLY record is the `baseline=` XML attribute ("git-HEAD (stale sidecar + // removed)") — no stderr spam, which is the B10.1b noise fix that survives the ruling intact. The + // read-only MCP arm passes false and reports "…ignored" instead. When the unlink FAILS (read-only + // parent dir) this arm degrades to the read-only story — marker "…ignored", one DISCLOSE + // from the seam — because the pin is still on disk; `baseSel.isStaleFileOnDisk()` is the fact, and the + // fatal message words itself from it rather than from the intent. + // + // F-04 (round-4 audit) — SERIALIZE THE ACK LEDGER'S READ-MODIFY-WRITE, cross-process. + // + // --quality-ack reads the whole ledger (inside resolveDeltaBasis just below — the heal has to happen + // before computeDelta), folds this run's accepted findings into that map, then rewrites the file from + // it. Nothing serialized that. Three sessions acking DISJOINT rows in one shared checkout — the exact + // scenario --scope exists for — lost two of the three acks on 8 of 8 measured runs, because whichever + // process rewrote last overwrote a map the other two had already published into. + // + // The lock therefore has to span the READ as well as the write, which is why it is taken HERE and not + // inside writeAckRecords: a lock held only around the final rewrite still lets two processes read the + // same stale map first and then take turns clobbering. Engaged ONLY under --quality-ack — a read-only + // --quality-delta never waits, never creates the lockfile, and is byte-for-byte the run it always was. + // RAII: released when this function returns, on every path including the refusals below. quality.h's + // SidecarWriteLock has the lockfile's location (per-user cache dir, never a repo-tree sidecar), the + // wait budget, and the honest limits. + std::optional ackLock; + if( cfg.qualityAck ) + { + ackLock.emplace( acksFile ); + } + + // `refs` is declared HERE because it owns both materialized trees' teardown and they must outlive every read of the + // delta (QdComparison's header). + RefPairDelta refs; + DeltaBasis basis; + if( const std::optional refused = applyKindSelector( cfg, refs ) ) + { + return refused; + } + if( const std::optional refused = resolveDeltaBasis( d, baselineFile, refs, basis ) ) + { + return refused; + } + const bool refPair = !cfg.qualityDeltaRange.empty(); + const IngestResult& judgedIndex = refPair ? refs.target().ing : d.ing; // the JUDGED tree's index: tree B in the range form + + // ── P1 SCOPE — the OWNERSHIP partition for a working tree with several writers in it ───────────── + quality::Scope scope = quality::parseScope( cfg.qualityScope ); + std::size_t diffFileCount = 0; // P1.2: 0 = the reserved diff token was not used + if( const std::optional refused = expandScopeDiff( scope, refPair, judgedIndex, d.root, basis.deltaRoot, diffFileCount ) ) + { + return refused; + } + if( const std::optional refused = refuseUnusableScope( cfg, scope, judgedIndex, basis.deltaRoot, refs.scopeFiles() ) ) + { + return refused; + } + const QdPartition part = applyScopeAndAcks( scope, basis ); + if( cfg.qualityAck ) + { + return runQualityAckWrite( cfg, scope, part, basis, acksFile ); + } + + // L2 — stale-ack disclosure (rationale: quality.h's computeStaleAcks). Checked against the CURRENT tree, not the baseline, + // so it costs one more computeSnapshot; skipped when the ledger is empty. Reported, never gated — the exit code reads the + // rows alone. R-I: "the CURRENT tree" is the JUDGED tree, which in the range form is tree B — checking the ledger against + // the working tree there would report acks as stale because of edits that have nothing to do with the comparison. + // qd-memory-degrade: refPairStaleAcks owns the two range-form departures (a changed-files answer judges none; a kind + // selection judges its own kinds' acks only). The bare form's snapshot is the working tree's own (d.ing, d.g) and reuses + // the clone and construct passes the delta already ran (QD-IDENTITY-ONCE), so it writes basis.passes — here, in view. + std::vector staleAcks = basis.acks.empty() ? std::vector{} + : refPair ? refPairStaleAcks( basis.acks, refs ) + : quality::computeStaleAcks( basis.acks, quality::computeSnapshot( d.ing, d.g, cfg.rootPath, nullptr, {}, &basis.passes ) ); + const QdComparison comparison{ .cfg = cfg, .root = d.root, .refs = refs, .basis = basis, .scope = scope, .part = part, + .judgedIndex = judgedIndex, .refPair = refPair, .diffFileCount = diffFileCount }; + const QdReport report = computeQdReport( comparison, std::move( staleAcks ), baselineFile ); + emitQdStderrLines( report ); + if( cfg.json ) + { + emitQualityDeltaJson( report ); + } + else + { + emitQualityDeltaXml( report ); + } + return report.exitCode(); } // #387: the range form compares two COMMITTED trees, each materialized and indexed by loadRefPairDelta, and reads the diff --git a/test/ackonlycheck.sh b/test/ackonlycheck.sh index 7ed8fe796..2faa7b289 100755 --- a/test/ackonlycheck.sh +++ b/test/ackonlycheck.sh @@ -115,5 +115,23 @@ rc=$? if [ $rc -eq 0 ]; then ok "--ack-only=gating clears the gate (exit 0)"; else no "--ack-only=gating left exit $rc"; fi if grep -q 'gating="0"' "$TMP/all.xml"; then ok "…and the header agrees (gating=\"0\")"; else no "…but the header still counts gating findings"; fi +# 5) CR721: "gating" is a RESERVED token, not a substring. A new symbol named gatingHelper carries never-gating +# new-symbol rows (params, dead-code); --ack-only=gating must ack only the one gating contract-change, never those +# rows because "gating" occurs in their sym=. RED before CR721 (train GE3 cbed31d4c): "acknowledged 3 of 3". +R5="$TMP/repo5"; mkdir -p "$R5"; cd "$R5"; git init -q .; git config user.email t@t; git config user.name t +printf '#pragma once\ninline int alpha( int a ) { return a; }\n' > lib.h +git add lib.h; git commit -qm base; "$BIN" . --quality-baseline >/dev/null 2>&1; b5=$? +printf '#pragma once\ninline int alpha( int a, int b ) { return a + b; }\ninline int gatingHelper( int a, int b, int c ) { return a + b + c; }\n' > lib.h +"$BIN" . --quality-delta >"$TMP/g5.xml" 2>/dev/null; d5=$? +n5="$( grep -oE ']*sym="gatingHelper"[^>]*' "$TMP/g5.xml" | wc -l | tr -d ' ' )" +if [ "$b5" = 0 ] && [ "$d5" = 2 ] && [ "${n5:-0}" -ge 1 ] && ! grep -oE ']*sym="gatingHelper"[^>]*' "$TMP/g5.xml" | grep -q 'gating="1"'; then + ok "(5) premise: $n5 never-gating row(s) on gatingHelper" +else no "(5) premise: want baseline rc 0 (got $b5), delta rc 2 (got $d5) and >=1 non-gating gatingHelper row, got $n5: $( grep -oE ']*' "$TMP/g5.xml" | tr '\n' ' ' )"; fi +"$BIN" . --quality-delta --ack-only=gating --quality-ack="the gating one" >/dev/null 2>"$TMP/g5.err"; k5=$? +a5="$( grep -c '^ack ' .ripwire_quality_acks 2>/dev/null )" +if [ "$k5" = 0 ] && grep -q 'acknowledged 1 of ' "$TMP/g5.err" && [ "${a5:-0}" = 1 ] && grep -q '^ack api-surface .*facet=contract-change' .ripwire_quality_acks; then + ok "(5) --ack-only=gating acks only the gating row, not gatingHelper's: $( head -1 "$TMP/g5.err" )" +else no "(5) --ack-only=gating swept in gatingHelper by substring: $( head -1 "$TMP/g5.err" ) (rc=$k5); ack lines: ${a5:-0}"; fi + [ "$fail" = 0 ] && echo "ALL PASS" || echo "FAILURES ABOVE" exit $fail diff --git a/test/capdisclose.map b/test/capdisclose.map index 387968960..6c5b7c6ec 100644 --- a/test/capdisclose.map +++ b/test/capdisclose.map @@ -182,6 +182,7 @@ kMaxQualifierHops pending:B43 ingest extraction bound (LARGE-PARTIAL-1 widened t kMaxRefs pending:B43 disclosed elsewhere: refs_omitted= (refsOmittedAttr, which the lint cannot tie to the cap) and a stderr warning (LARGE-PARTIAL-1) kMaxRenameProbeFiles none:a rename hint is never a claim (Stage 0 class d) kMaxRestDepth sink:noteCapped +kMaxShellNest sink:cut kMaxRestName pending:B43 ingest extraction bound (LARGE-PARTIAL-1 widened the lint to ingest*.h); the sibling lane NO-SKIP-INGEST owns the ingest limits and audits it kMaxRestUnits sink:noteCapped kMaxRoleBytes pending:B43 ingest extraction bound (LARGE-PARTIAL-1 widened the lint to ingest*.h); the sibling lane NO-SKIP-INGEST owns the ingest limits and audits it diff --git a/test/defectackschemecheck.sh b/test/defectackschemecheck.sh new file mode 100755 index 000000000..756720807 --- /dev/null +++ b/test/defectackschemecheck.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# defectackschemecheck.sh — CR712-ACK-KEY-MASK: a defect-shape ack written under the TWO-BIT site-value scheme (v0.6.9/v0.6.10: +# defectSiteValue masked `& ~3`) still suppresses its row after QD-UNCHECKED-STATUS widened the facet bits to three (`& ~7`). +# The widening moved every site value whose hash had bit 2 set, and with it the defectRowKey of the row holding it; about half +# of the released format-arity acks stopped matching, so the acked row gated again (exit 2) and the ack was listed stale. +# addDefectFacetSchemeAliases (src/quality.h) re-files such an ack through the SCHEME alias path (acks_rekeyed_by_scheme=). +# +# The fixture is GENERATED here: a one-commit repo whose working tree adds label1(), a format-arity defect (two arguments to a +# one-placeholder std::format). Its two-bit key was recorded from the released v0.6.9 binary (built_from b8c317899); set +# RIPWIRE_LEGACY_BIN to a pre-74dee2e9b binary and arm (r) re-derives it instead of trusting the constant. +# (p) PREMISE: an ack the binary under test writes for the same row has a DIFFERENT key (the site moved between schemes; +# a fixture whose site did not move would pass every arm below vacuously). +# (l) LEGACY: the two-bit ack suppresses the row: exit 0, acked="1", stale="0", gating="0", acks_rekeyed_by_scheme="1". +# Red before the lane (main 8861b0d4d): exit 2, acked="0", stale="1", the format-arity row gates. +# (c) CURRENT: the binary's own ack matches directly: exit 0, acked="1", no acks_rekeyed_by_scheme= (no alias needed). +# (h) HEAL: --quality-ack over the legacy ledger re-files the row at the current key (the (p) key, reason kept), and the +# next run needs no alias. +# (r) optional, RIPWIRE_LEGACY_BIN: the legacy binary writes the recorded key. +# Usage: test/defectackschemecheck.sh [BIN] +set -u +ROOT="$( cd "$( dirname "$0" )/.." && pwd )" +. "$ROOT/test/lib/clean-env.sh" +BIN="${1:-${RIPWIRE_BIN:-$ROOT/build/ripwire}}" +[ "${BIN#/}" = "$BIN" ] && BIN="$ROOT/$BIN" +[ -x "$BIN" ] || { echo "no ripwire binary at $BIN — build first"; exit 2; } +TMP="$( mktemp -d )"; trap 'rm -rf "$TMP"' EXIT +export TMPDIR="$TMP/cache"; mkdir -p "$TMPDIR" +export HOME="$TMP/home"; mkdir -p "$HOME" +fail=0 +ok(){ printf ' PASS %s\n' "$*" || { fail=1; printf ' FAIL could not write the PASS line for: %s\n' "$*"; }; return 0; } +no(){ printf ' FAIL %s\n' "$*"; fail=1; } +echo "defectackschemecheck: BIN=$BIN" +G=( git -c user.name=t -c user.email=t@t -c commit.gpgsign=false ) +LEGACY_KEY=69365bba7ebf69de +LEDGER=.ripwire_quality_acks + +# fixture DIR — the one-commit repo plus the working-tree defect +fixture(){ mkdir -p "$1/src"; "${G[@]}" -C "$1" init -q + printf '#include \n#include \nint drive() { return 1; }\n' >"$1/src/a.cpp" + "${G[@]}" -C "$1" add -A && "${G[@]}" -C "$1" commit -qm a + printf '#include \n#include \nstd::string label1( int a )\n{\n return std::format( "{} 1", a, a );\n}\nint drive() { return 1; }\n' >"$1/src/a.cpp"; } +ackkey(){ grep -E '^ack defect-shape ' "$1/$LEDGER" | awk '{ print $3 }' | tr '\n' ' ' | sed 's/ $//'; } +root(){ grep -oE ']*' "$1"; } +attr(){ root "$2" | grep -oE " $1=\"[0-9]+\"" | grep -oE '[0-9]+'; } +ack(){ ( cd "$1" && "$BIN" . --quality-delta --no-cache --ack-only=format-arity --quality-ack="$2" >/dev/null 2>&1 ); } +run(){ ( cd "$1" && "$BIN" . --quality-delta --no-cache >"$2" 2>/dev/null ); } + +# (p) the binary's own key for this row +fixture "$TMP/cur"; ack "$TMP/cur" "current ack"; arc=$? +[ "$arc" = 0 ] || no "(p) --quality-ack on the fresh row exited $arc, want 0" +CUR="$( ackkey "$TMP/cur" )" +if [ -n "$CUR" ] && [ "$CUR" != "$LEGACY_KEY" ]; then ok "(p) the row's current key $CUR differs from its two-bit key $LEGACY_KEY" +else no "(p) want one current key different from $LEGACY_KEY; got '${CUR:-none}' — the fixture no longer exercises a moved site"; fi + +# (l) the legacy ledger row, verbatim as v0.6.9 wrote it +fixture "$TMP/leg" +printf 'ack defect-shape %s 1 now=1 was=0 facet=format-arity p=src/a.cpp:3 legacy ack\n' "$LEGACY_KEY" >"$TMP/leg/$LEDGER" +run "$TMP/leg" "$TMP/leg.xml"; rc=$? +a="$( attr acked "$TMP/leg.xml" )"; s="$( attr stale "$TMP/leg.xml" )"; g="$( attr gating "$TMP/leg.xml" )"; k="$( attr acks_rekeyed_by_scheme "$TMP/leg.xml" )" +if [ "$rc" = 0 ] && [ "$a" = 1 ] && [ "$s" = 0 ] && [ "$g" = 0 ] && [ "$k" = 1 ]; then ok "(l) the two-bit ack suppresses its row: rc=0 acked=1 stale=0 gating=0 acks_rekeyed_by_scheme=1" +else no "(l) want rc=0 acked=1 stale=0 gating=0 acks_rekeyed_by_scheme=1; got rc=$rc acked=${a:-?} stale=${s:-?} gating=${g:-?} acks_rekeyed_by_scheme=${k:-absent}"; fi + +# (c) the binary's own ack +run "$TMP/cur" "$TMP/cur.xml"; rc=$? +a="$( attr acked "$TMP/cur.xml" )"; k="$( attr acks_rekeyed_by_scheme "$TMP/cur.xml" )" +if [ "$rc" = 0 ] && [ "$a" = 1 ] && [ -z "$k" ]; then ok "(c) the current-key ack matches directly: rc=0 acked=1, no acks_rekeyed_by_scheme=" +else no "(c) want rc=0 acked=1 and no acks_rekeyed_by_scheme=; got rc=$rc acked=${a:-?} acks_rekeyed_by_scheme=${k:-absent}"; fi + +# (h) re-ack heals the legacy row forward +ack "$TMP/leg" "re-ack" # status: exits 1 by design (the row is already acked through the alias: nothing new to accept); (h) judges the ledger it re-serialised +HK="$( ackkey "$TMP/leg" )"; reason="$( grep -cE '^ack defect-shape .* legacy ack$' "$TMP/leg/$LEDGER" )" +run "$TMP/leg" "$TMP/heal.xml"; rc=$?; k="$( attr acks_rekeyed_by_scheme "$TMP/heal.xml" )" +if [ "$HK" = "$CUR" ] && [ "$reason" = 1 ] && [ "$rc" = 0 ] && [ -z "$k" ]; then ok "(h) --quality-ack re-filed the row at $HK with its reason; the next run needs no alias" +else no "(h) want the ledger at $CUR with the legacy reason and a later run without acks_rekeyed_by_scheme=; got key='${HK:-none}' reason-rows=$reason rc=$rc acks_rekeyed_by_scheme=${k:-absent}"; fi + +# (r) optional: re-derive the recorded key with a two-bit binary +if [ -n "${RIPWIRE_LEGACY_BIN:-}" ]; then + fixture "$TMP/rec"; ( cd "$TMP/rec" && "$RIPWIRE_LEGACY_BIN" . --quality-delta --no-cache --ack-only=format-arity --quality-ack="legacy ack" >/dev/null 2>&1 ) # status: (r) judges the key the legacy binary wrote, not its exit + RK="$( ackkey "$TMP/rec" )" + if [ "$RK" = "$LEGACY_KEY" ]; then ok "(r) $RIPWIRE_LEGACY_BIN writes the recorded two-bit key $RK"; else no "(r) $RIPWIRE_LEGACY_BIN wrote '${RK:-none}', the recorded key is $LEGACY_KEY"; fi +fi + +[ "$fail" = 0 ] && echo "defectackschemecheck: PASS" || echo "defectackschemecheck: FAIL" +exit "$fail" diff --git a/test/defectshapecheck.sh b/test/defectshapecheck.sh index 94d76475b..377574162 100644 --- a/test/defectshapecheck.sh +++ b/test/defectshapecheck.sh @@ -2149,9 +2149,10 @@ fi # rule states the exception in ONE fixed phrase (PHRASE below), so no surface still reads unqualified. L="surfaces" PHRASE='new-symbol rows never gate, except defect-shape format-arity' -# QD-ENTRY-CEILING (2026-11-13) adds the second exception, a NEW function at 4x the bar: every statement of the -# rule names it too, in the long form (legend, help, MCP, docs) or the compact legend's ceiling= row. -CEILX='( and a new function at the ceiling| or a ceiling= row)' +# QD-ENTRY-CEILING (2026-11-13) adds the second exception, a NEW function at 4x the bar, and TANGLE-GATE-B (2026-11-21) +# the third, a new function at tangle 6 or more: every statement of the rule names both, in the long form (legend, +# help, MCP, docs) or the compact legend's ceiling= row and tangle row. +CEILX='(, a new function at the ceiling[^.;]* (and a tangled (new )?(function|one)|and a new one at tangle 6 or more)|, ceiling=, tangle)' phrase_ok(){ # LABEL TEXT — the text states the exception, and every "new-symbol rows never gate" in it carries it local all qual flat # whitespace-normalized first: a sentence may wrap anywhere in a document flat="$( printf '%s' "$2" | tr '\n' ' ' | tr -s ' ' )" diff --git a/test/fixedbufsweep.sh b/test/fixedbufsweep.sh index 16549d4e9..d11680d6d 100755 --- a/test/fixedbufsweep.sh +++ b/test/fixedbufsweep.sh @@ -188,8 +188,7 @@ TABLE = { ( "src/packtask.h", "bodylessAttr" ): ( 2, "safe", "bodylessAttr[40], TWO call sites, same shape: line 1253 in restatePackTaskBodiesWrapper (issue #60, integration/train-12); line 1758 in the bare-wrapper placeholder branch (t14-cleanup #6) — the section-dropped tag that never calls packBodies, so it could not reuse serialize.h's emitter and needed its own copy of the same attribute. Both format ' bodyless=\"{}\"' — 12 B of literal (' bodyless=\"' 11 + '\"' 1) and ONE interpoland, a std::size_t: 20 digits at absolute most, so 32 B against 39 usable + NUL, 7 B of margin. No string interpolation at all — the count is a count, never caller text — so no escaper can sit on either side of the buffer. It is a TABLE row and not NUMERIC_ONLY for arch.h hex[17]'s reason: a buffer that never existed before the std::print conversion has no pre-conversion format to derive a class from. THE ORIGINAL BUFFER WAS DECLARED [32] WHEN IT ARRIVED, which is 1 B short of its own worst case (32 B of text needs 33 with the NUL); formatTo truncates rather than overruns, so the failure mode was a dropped closing quote and a document that stops being well-formed, not a memory breach. Widened to 40 in the same commit as that row; the second site was declared [160]/[40] correctly from the start." ), # ── src/serialize.h ────────────────────────────────────────────────────────────────────────────────── ( "src/serialize.h", "bodylessAttr" ): ( 1, "safe", "bodylessAttr[40] in packBodies (issue #60, integration/train-12): the exact twin of the packtask.h row above — same format, same 12 B of literal, one std::size_t (bodylessCount), 32 B against 39 usable + NUL, 7 B of margin, no string interpoland. Same [32]-on-arrival correction, widened in the same commit." ), - ( "src/serialize.h", "fitAttr" ): ( 1, "safe", "fitAttr[96]: two %zu plus the literal ' over_ceiling=1'." ), - ( "src/serialize.h", "attr" ): ( 2, "safe", "attr[352] x2: the per-symbol metric attrs. Widest 26 lit + 4x10 digits + 11 role + qbuf(<=95) + ambs(<=35: amb= + lpin=) + kbuf(<=23) = 230 B." ), + ( "src/serialize.h", "attr" ): ( 1, "safe", "attr[352]: the per-symbol --metrics run (rowMetricsAttrs). Widest 26 lit + 4x10 digits + 11 role + the BoundedAttrRun (<=191) = 268 B. GE-SERIALIZE round 2 (2026-11-22): was x2 with ambs(<=35) + kbuf(<=23) folded into the same buffer (326 B worst case, never truncated), now written as their own attributes beside it." ), ( "src/serialize.h", "tail" ): ( 3, "safe", "tail[192] x3: the row tail. Widest 34 lit+digits + inAttr(<=23) + lens(qbuf, <=79) + pure(9) = 145 B. The third (lane/lean-answers-068, sigRowTail's zero-elision branch) prints cxAttr/ccxAttr/inAttr pre-formatted, each omitted at 0 — never wider than the second." ), ( "src/serialize.h", "hdr" ): ( 14, "safe", "hdr[64] x2 (packBodies/packOutline) (14: arch-honest — packDeps' row for a no-edge file writes includes= and a language tag, hdr[144], one integer + a label of at most 8 B: far under the buffer; 13: train 26b — count-floor-068 replaced the implementors= header writes, two hdr sites, with string appends): ' plus pageDisclosure's own capped buffer, sized against that cap by construction." ), @@ -219,7 +218,7 @@ TABLE = { # A NEW row here still fails the gate until someone adds it, which is the point. When you add one, say which # set it belongs in and why: a string argument makes it a TABLE row, with real prose. NUMERIC_ONLY = { - ( "src/serialize.h", "p" ): 2, + ( "src/serialize.h", "p" ): 1, # GE-SERIALIZE (2026-11-21): the map row's copy of the snprintf( p, S, ... ) comment became BoundedAttrRun's; one comment mention left (the --for lens qbuf) ( "src/degradedscan.h", "hit.errRatio" ): 1, ( "src/dmm.h", "value" ): 1, ( "src/editcheck.h", "callersOpen" ): 1, @@ -262,7 +261,6 @@ NUMERIC_ONLY = { ( "src/serialize.h", "callsHdr" ): 2, ( "src/serialize.h", "cb" ): 1, ( "src/serialize.h", "ccxAttr" ): 1, # lane/lean-answers-068: sigRowTail's zero elision, " ccx=\"{}\"" of one count (<= 17 B of 23) - ( "src/serialize.h", "changedAttr" ): 1, ( "src/serialize.h", "eAttr" ): 1, # lane/for-spine-span-068 (2026-10-04): writeSigHeadWithEnd's ' e="{}"' — 5 B literal + one # std::uint32_t (10 digits) = 15 B against 23 usable + NUL. A count, no %s, nothing escaped. ( "src/serialize.h", "cxAttr" ): 1, # lane/lean-answers-068: the same, " cx=\"{}\"" (<= 16 B of 23) @@ -293,12 +291,9 @@ NUMERIC_ONLY = { # digits = 35 B). A count, no %s, nothing escaped. # lane/hrr (2026-10-18): +1 in the same nb[96] — ' files_first="{}"' (15 B + 20 # digits = 35 B), the head round-robin's moved count. A count, no %s, nothing escaped. - ( "src/serialize.h", "precAttr" ): 1, ( "src/serialize.h", "rankAttr" ): 1, ( "src/serialize.h", "rc" ): 1, - ( "src/serialize.h", "rootsAttr" ): 1, ( "src/serialize.h", "sh" ): 1, - ( "src/serialize.h", "skippedAttr" ): 1, ( "src/serialize.h", "vb" ): 1, ( "src/testmap.h", "buf" ): 6, ( "src/verbs_report.h", "buf" ): 2, @@ -628,6 +623,8 @@ if not bad: # 2026-10-18 (lane/hrr): +1 call/+1 mention/+1 site, rows unchanged (363/248/248/109 -> 364/249/249/109): sigsOpenTag's # nb[96] ' files_first="{}"' (35 B worst case, one size_t, nothing escaped) — re-read and sized before this pin. EXPECTED = { "mentions": 366, "calls": 251, "sites": 251, "rows": 109, "widthforms": 0 } # lane/hrr: +1 nb site (files_first=); arch-honest: +2 (packDeps hb, hdr) +# 2026-11-21 (GE-SERIALIZE): -5 calls/-5 sites/-5 rows (precAttr, rootsAttr, changedAttr, skippedAttr, fitAttr): the map +# header's coverage attributes are composed on std::string in renderMapCoverageAttrs / mapFitAttrs (serialize.h), no fixed buffer left. # 2026-11-12 (B43 PINNED-SELF-COUNTS): EXPECTED above is now HISTORY, not a pin -- it drifted on #619 (and on every # lane that added one site) while (S1)/(S2) already held the member set both ways: every derived site is a TABLE # row with its multiplicity, and no row is stale. An exact count on top of that only re-pins arithmetic. What (S1)/(S2) diff --git a/test/langidentity/ratchet.tsv b/test/langidentity/ratchet.tsv index 6452c2e66..bb33ef201 100644 --- a/test/langidentity/ratchet.tsv +++ b/test/langidentity/ratchet.tsv @@ -23,7 +23,12 @@ # 324 -> 321 (train ge2, the composed tree): qd-unchecked-status + qd-unhandled-arm added two C-family predicates (the enum table's # Cpp/C filter, the C scanner branch) and the composed tree counted 326; quality.h defectSitesOf and cFamilyEnumTable now read # langfacts.h's DefectScan column, so all six defect-shape language tests (four of them main's) left the count. -ceiling 321 +# 321 -> 317 (GE-CAPTURETAGS): captureTagsFacts' three Elixir capture filters and its three Elixir definition-name arms each ask +# the language once, in a named step (ingest_sidecap.h languageFilterFate, indexedNameOf). +# 317 -> 316 (GE-CAPTURETAGS round 2): a definition's language rules are decided once (definitionIdentityOf), the language filters +# and the per-language binds dispatch by one switch each (languageFilterFate, emitLanguageDefinitionFacts), the Elixir def-head +# steps read @_keyword (queries/elixir/tags.scm's only) as their gate, and C++'s std-rooted scope comes with its scope (DefScope). +ceiling 316 perlang ingest_elixir.h perlang elixir_resolve.h perlang ingest_clojure.h diff --git a/test/lib/capdisclose.py b/test/lib/capdisclose.py index de7204ce5..92bc47c06 100755 --- a/test/lib/capdisclose.py +++ b/test/lib/capdisclose.py @@ -6,7 +6,7 @@ Scope: a constant `constexpr kName = ` defined in an answer-path file (src/for*.h, src/verbs_*.h, src/pathroute.h, src/clones.h; LARGE-PARTIAL-1 added the size and git-sweep caps' files src/crossref.h, -src/ingest*.h, src/search.h, src/binstale.h) that some line of src/ compares as a bound (a CAP SITE, below), or whose +src/ingest*.h, src/search.h, src/binstale.h; CR712-SHSTATUS-DEPTH the shell parser's nesting budget, src/shstatus.h) that some line of src/ compares as a bound (a CAP SITE, below), or whose name says it bounds something (Max, Limit, Cap, Ceiling, Depth, Pairs), or that a `static_assert( kName == N, ... )` ties to legend text. The name alone is not the scope: #613's reader cap was kReaderCallerReaders. A name with `Min` is a threshold (a row needs at least N), not a cut, and is out of scope. A CAP SITE is a line that compares the @@ -47,7 +47,7 @@ def uncommented( text ): def answer_path( root ): out = [] for f in sorted( os.listdir( os.path.join( root, "src" ) ) ): - if ( f.startswith( ( "for", "verbs_", "ingest" ) ) and f.endswith( ".h" ) ) or f in ( "pathroute.h", "clones.h", "crossref.h", "search.h", "binstale.h" ): + if ( f.startswith( ( "for", "verbs_", "ingest" ) ) and f.endswith( ".h" ) ) or f in ( "pathroute.h", "clones.h", "crossref.h", "search.h", "binstale.h", "shstatus.h" ): out.append( "src/" + f ) return out diff --git a/test/lib/tanglefixtures.py b/test/lib/tanglefixtures.py index b97aa4cdd..e6f9b6fba 100644 --- a/test/lib/tanglefixtures.py +++ b/test/lib/tanglefixtures.py @@ -21,6 +21,13 @@ shrink — tangled at v1/c2; wt removes its deep region: credited in (tangle), no row. simplify — ccx 21 at v1/c2, ccx 11 in wt: credited in (complexity). nudge — tangled at v1/c2 (40 deep lines); wt drops 2 of them: under the rise step, so no entry (and no row). + crossing — 100 flat lines at v1/c2 (score 0); wt gives it tangled's body: it crossed the bar, a GATING row (rule (b), 11-21). + harnessmain — new in wt under test/: tangled's body, a row that stays sev="minor" (test code never gates by tangle). + The RATCHET against the range base (QD-RATCHET-BASE, replay 11-21), three over-bar functions (v1 40 deep lines): + grow1 — 40 at c2, 42 in wt: the score grew a little, under the rise step and under its best since v1's rise: a ratchet row. + reflow — 46 at c2 (+6 over v1), wt adds one flat line: its inputs moved but the score is the same tenth: no row (the replay's + buildGraph in #706, +28 lines at 56.9 -> 56.9, that the tag-best compare flagged). + settle — 48 at c2 (+8 over v1), 47 in wt: the score fell: no row (the replay's captureTagsFacts 29.2 -> 29.1 in #714). The wip stage cuts creep to 5 deep lines on the side branch, whose next commit (c2) grows it back: a version the first-parent line never stood at, so it must not become creep's best (r1 would read deep 8->49). """ @@ -40,15 +47,7 @@ def deep_block(n, depth_indent): def creep(extra): # depth: for(1) if(2) for(3) if(4) -> the deep region is the body of the 4th level - body = deep_block(40 + extra, 20) - tail = "".join(f" total = total * 3 + {k};\n" for k in range(70)) - return ("int creep( const std::vector& xs )\n{\n int total = 0;\n" - " for( int x : xs )\n {\n if( x > 0 )\n {\n" - " for( int y = 0; y < x; ++y )\n {\n" - " if( y % 2 )\n {\n" - + body + - " }\n }\n }\n }\n" - + tail + " return total;\n}\n") + return overbar("creep", 40 + extra, mult=3, gt=0, mod=2) def shrink(deep): @@ -72,19 +71,24 @@ def simplify(branches): def nudge(deep): + return overbar("nudge", deep, mult=11) + + +def overbar(name, deep, extra=0, mult=13, gt=2, mod=5): + # nudge's shape under another name: for(1) if(2) for(3) if(4), `deep` lines at depth 4, a flat tail of 70 + extra lines inner = deep_block(deep, 20) - tail = "".join(f" total = total * 11 + {k};\n" for k in range(70)) - return ("int nudge( const std::vector& xs )\n{\n int total = 0;\n" - " for( int x : xs )\n {\n if( x > 2 )\n {\n" + tail = "".join(f" total = total * {mult} + {k};\n" for k in range(70 + extra)) + return (f"int {name}( const std::vector& xs )\n{{\n int total = 0;\n" + f" for( int x : xs )\n {{\n if( x > {gt} )\n {{\n" " for( int y = 0; y < x; ++y )\n {\n" - " if( y % 5 )\n {\n" + inner + + f" if( y % {mod} )\n {{\n" + inner + " }\n }\n }\n }\n" + tail + " return total;\n}\n") -def tangled(): +def tangled(name="tangled"): deep = deep_block(25, 28) seq = "".join(f" total = total + {k};\n" for k in range(60)) - return ("int tangled( const std::vector& xs )\n{\n int total = 0;\n bool found = false;\n" + return (f"int {name}( const std::vector& xs )\n{{\n int total = 0;\n bool found = false;\n" " for( int x : xs )\n {\n if( x > 0 )\n {\n" " for( int y = 0; y < x; ++y )\n {\n" " if( y % 2 )\n {\n" @@ -96,9 +100,9 @@ def tangled(): + seq + " if( found )\n {\n total *= 2;\n }\n return total;\n}\n") -def sequential(): - return ("int sequential( int x )\n{\n int total = x;\n" - + "".join(f" total = total * 7 + {k};\n" for k in range(150)) + " return total;\n}\n") +def sequential(name="sequential", n=150): + return (f"int {name}( int x )\n{{\n int total = x;\n" + + "".join(f" total = total * 7 + {k};\n" for k in range(n)) + " return total;\n}\n") def orchestrator(): @@ -189,7 +193,16 @@ def main(): write(d, "shrink.cpp", hdr + shrink(stage != "wt")) write(d, "simplify.cpp", simplify(20 if stage != "wt" else 10)) write(d, "nudge.cpp", hdr + nudge(40 if stage != "wt" else 38)) + if stage != "wt": + write(d, "crossing.cpp", sequential("crossing", 100)) + write(d, "grow1.cpp", hdr + overbar("grow1", 42 if stage == "wt" else 40, mult=17)) + write(d, "reflow.cpp", hdr + overbar("reflow", 40 if stage == "v1" else 46, extra=1 if stage == "wt" else 0, mult=19)) + write(d, "settle.cpp", hdr + overbar("settle", {"v1": 40, "wt": 47}.get(stage, 48), mult=23)) if stage == "wt": + write(d, "crossing.cpp", hdr + tangled("crossing")) + os.makedirs(os.path.join(d, "test"), exist_ok=True) + with open(os.path.join(d, "test", "harness.cpp"), "w") as f: + f.write(hdr + tangled("harnessmain")) write(d, "tangled.cpp", hdr + tangled()) write(d, "sequential.cpp", sequential()) write(d, "orchestrator.cpp", orchestrator()) diff --git a/test/printf_parity.manifest b/test/printf_parity.manifest index 54048d283..5251b1176 100644 --- a/test/printf_parity.manifest +++ b/test/printf_parity.manifest @@ -38,5 +38,5 @@ safe_delete 0 7b17c59f7606ebe5c5119ffc2a712e8249feea645887d791368324bb3f60b6c1 e verify_layer 1 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 5288c345d7d6e335f88b9c1daa8935db22e1dcf89c0c8bc1f6140d4cb5af0b48 graph_query 1 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 bfa4319feb9dee09cfbd3991cf6fbd752297e99d14de9e75768820d2a9c8832f callers_limit 0 04256d098a1e739789770682d305d4cae6102ecd99f702cbef7d1f34a8173160 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 -help_all 0 9c870f038f1ba0d5d9d97ddeb1f219e740bb693a03c9cf1319d17b15dddaf1ea e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 +help_all 0 7a8cc9daf0d713650f0cfe68cfe11aa34a98e5fb1783c20fb650123edb60de67 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 help_one 0 938ff4f8802a8f5d9cb10f9a1f3804ac755be44c8ab00e24e45bfe8255224a21 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 diff --git a/test/qdentryceilingcheck.sh b/test/qdentryceilingcheck.sh index 249c69e67..4f8b0de4f 100755 --- a/test/qdentryceilingcheck.sh +++ b/test/qdentryceilingcheck.sh @@ -287,9 +287,9 @@ JM="$( cd "$WORK/n4" && "$BIN" . --quality-delta --json --no-cache 2>/dev/null ) if printf '%s' "$JM" | grep -q '"origin":"moved"'; then ok "J: --json carries \"origin\":\"moved\""; else no "J: --json lacks origin moved"; fi # ═══ L) LEGEND — the exception is stated wherever the rule is ═════════════════════════════════════════ -PHRASE='new-symbol rows never gate, except defect-shape format-arity and a new function at the ceiling' +PHRASE='new-symbol rows never gate, except defect-shape format-arity, a new function at the ceiling' # TANGLE-GATE-B added a third exception after it # compact spends fewer bytes (its prose has a stair-step target): the exception names the ceiling= row it defines -CPHRASE='new-symbol rows never gate, except defect-shape format-arity or a ceiling= row' +CPHRASE='new-symbol rows never gate, except defect-shape format-arity, ceiling=' for leg in full compact; do T="$( cd "$WORK/p1" && "$BIN" . --quality-delta --no-cache --legend=$leg 2>/dev/null | tr '\n' ' ' | tr -s ' ' )" # status: output only — the L arm FAILs when the phrase count is 0 a="$( printf '%s' "$T" | grep -o 'never gate, except defect-shape' | wc -l | tr -d ' ' )" diff --git a/test/qdrefpaircheck.sh b/test/qdrefpaircheck.sh index 36ad1baf8..308a210da 100755 --- a/test/qdrefpaircheck.sh +++ b/test/qdrefpaircheck.sh @@ -277,6 +277,12 @@ printf 'register_macros = NOPE_NEVER_USED\n' >"$RC/.ripwire_config" # ── (E) DECISIVE: ripwire's own recorded harvest wave, against the live-recomputed overlay oracle ───────── # RE-PIN LOG for the recorded literal below (it is a bare number, so its justification has to live here). +# 2026-11-21, lane QD-LESSONS-2a (TANGLE-GATE-B / QD-RATCHET-BASE): 8 → 10 gating rows on this wave. Both new rows are +# tangle rows the kind now gates by design (it was report-only): +# (over the bar and grew: deep 45->49, 257->277 lines) +# (crossed the bar: deep 14->22, 182->213 lines) +# The eight rows before are unchanged, and (E)'s row-for-row oracle comparison stays green (7 rows = the 5 before + these 2), +# so 7 + 3 churn = 10. # 2026-09-20, integration/train-13 (lane/t13-honesty-fixes fix 2): 9 → 8 gating rows on this wave, and the # row that left is EXACTLY the row train 12 added below. Fix 2 gives `reuse-decline` # (new-clone-of-reused-helper) the two demotions its sibling `duplication` already had, one of which is @@ -342,9 +348,9 @@ else # the two RECORDED literals from the round record — a cross-check that these shas still name that wave overlayTotal=$(( oracleN + overlayChurn )) - [ "$overlayTotal" = 8 ] \ - && ok "(E) the overlay reproduces the pinned 8 gating rows (= $oracleN + $overlayChurn churn; 9 between #60 and reuse-decline's test-script skip, 8 before #60, 18 pre-dial)" \ - || no "(E) the overlay gave $overlayTotal gating rows; this binary is pinned at 8 (9 between #60's file-scope callers and reuse-decline's all-test-script skip, 8 before #60, 18 before the 2026-09-10 dial round) — the shas, the corpus, a kind's tier or a kind's EVIDENCE moved; the RE-PIN LOG above arm (E) records how the last move was justified" + [ "$overlayTotal" = 10 ] \ + && ok "(E) the overlay reproduces the pinned 10 gating rows (= $oracleN + $overlayChurn churn; 8 before tangle gated, 9 between #60 and reuse-decline's test-script skip, 8 before #60, 18 pre-dial)" \ + || no "(E) the overlay gave $overlayTotal gating rows; this binary is pinned at 10 (8 before tangle gated (QD-LESSONS-2a), 9 between #60's file-scope callers and reuse-decline's all-test-script skip, 8 before #60, 18 before the 2026-09-10 dial round) — the shas, the corpus, a kind's tier or a kind's EVIDENCE moved; the RE-PIN LOG above arm (E) records how the last move was justified" dmmVal="$( "$BIN" "$ROOT" "--dmm=$WAVE_A..$WAVE_B" 2>/dev/null | grep -o ' dmm="[0-9.]*"' | head -1 | sed -E 's/.*"([0-9.]*)".*/\1/' )" # tolerance band, not equality: dmm is a float printed to 3 places (house float rule). if [ -n "$dmmVal" ] && awk -v v="$dmmVal" 'BEGIN{ exit !(v > 0.525 && v < 0.535) }'; then diff --git a/test/qoriginoraclecheck.sh b/test/qoriginoraclecheck.sh index e271f479d..802866035 100755 --- a/test/qoriginoraclecheck.sh +++ b/test/qoriginoraclecheck.sh @@ -202,5 +202,14 @@ PE="$( cd "$P" && "$BIN" . --quality-delta --no-cache 2>/dev/null )" printf '%s' "$PE" | grep -q 'kind="new-clone-of-reused-helper"' \ && ok "a new clone of a PREEXISTING reused helper is still reported (the kind is narrowed, not emptied)" \ || { no "the reuse-decline kind no longer fires on its own headline case"; printf '%s' "$PE" | tr '<' '\n' | grep '^r kind='; } +# (e2) CR721: that row's sym= is a member LIST and p= is the first member's, so it hands no --expand next= (a single-body +# selector would be "FILE:a | b", which resolves nothing). Premise: the row is there and gates. RED before CR721 +# (main b576a95e3 and train GE3 cbed31d4c): next="--expand='copy.cpp:… | …'". +crow="$( printf '%s' "$PE" | grep -oE ']*' | head -1 )" +case "$crow" in + *'gating="1"'*next=*) no "(e2) the gating clone-group row offers a single-body next=: $crow" ;; + *'gating="1"'*) ok "(e2) the gating clone-group row carries no next=: $crow" ;; + *) no "(e2) PREMISE: want a gating new-clone-of-reused-helper row, got '${crow:-none}'" ;; +esac [ "$fail" -eq 0 ] && echo "qoriginoraclecheck: ALL PASS" || { echo "qoriginoraclecheck: SOME CHECKS FAILED"; exit 1; } diff --git a/test/qschemetrip.hash b/test/qschemetrip.hash index 3eae000f4..af7340c97 100644 --- a/test/qschemetrip.hash +++ b/test/qschemetrip.hash @@ -1 +1 @@ -a57b75c512a18d0769a1034b24104c85ae9102a6c43c9e89a7cdee5350ee08a9 +8b4885839dab9cd966142580a2f442d5b3e53cc06ea3d856ce37236dab3727cf diff --git a/test/qschemetripcheck.sh b/test/qschemetripcheck.sh index b0931e0f1..34e13de00 100755 --- a/test/qschemetripcheck.sh +++ b/test/qschemetripcheck.sh @@ -34,6 +34,10 @@ SRC="$ROOT/src/quality.h" ING="$ROOT/src/ingest_cache.h" # extraction-identity constants moved here (2026-08-29 ingest.cpp section split); the hashed CONCAT label keeps its historical spelling so the pin holds PIN="$ROOT/test/qschemetrip.hash" # RE-PIN LOG (the pin is a bare hash, so its justification has to live here). +# 2026-11-22, train ge3 (ge-runqd, qd-lessons-2-r, ge-capturetags, ge-serialize, ge-lextiers; composed on main b576a95e3): +# RE-PINNED ONCE with UPDATE_GOLDEN=1 from the composed build (hash 8b4885839d…ab3727cf). Watched text moved only by the +# qd-lessons-2 members (defectSitesOf's shell-cut counter + legacySite, logged below) on top of #715's kParserVer 337/338. +# No member bumps kParserVer, kCacheVersion (54) or kQSnapCacheScheme (38). # 2026-11-21, lane land-715 (#715 by @himanchalkaushale, #548 arm 1: Clojure calls whose list head carries metadata; stacked on # train 1118a 4b1f4516e): RE-PINNED with UPDATE_GOLDEN=1 (hash a57b75c512…5350ee08a9). Watched text: kParserVer 335 -> 337 # (rich file tag 338; the PR's 311/312 renumbered above the train's 335/336): queries/clojure/tags.scm accepts a meta_lit before a @@ -46,6 +50,12 @@ PIN="$ROOT/test/qschemetrip.hash" # 2026-11-19, lane qual-ns-call-bind (stacked on lane/import-proved-splits 4787d1ed0): RE-PINNED with UPDATE_GOLDEN=1. kParserVer # 335 PLACEHOLDER (C++ using-declarations + namespace aliases recorded, ingest_binds.h kCppCallScopeFacts; mirrored in quality.h); # the train renumbers and re-pins. kCacheVersion and kQSnapCacheScheme unchanged. +# 2026-11-21, lane QD-LESSONS-2a (on main 8861b0d4d): RE-PINNED with UPDATE_GOLDEN=1 (hash 269831ba67…15a52a). defectSitesOf moved: +# it takes an optional shell-cut counter (CR712-SHSTATUS-DEPTH) and each site record also carries its two-bit value +# (legacySite, CR712-ACK-KEY-MASK), which computeSnapshot does not store. The blob shape is unchanged; the Bash scanners +# now stop at the one nesting budget (64) instead of crashing (subshell/group/if) or cutting $( ) at 40, which changes +# the site set only for a script nested that deep, and the producer identity keeps this build's blobs apart, so +# kQSnapCacheScheme stays 38 (the cr-qd-kinds-068 fix-round-1 precedent below). # 2026-11-20, train 1117d2-s (std-namesake, rust-reexport, rust-modalias-glob, rust-self-chain, rust-macro-args, # rust-path-unhedged, redact-touch, qd-swap, qd-similar-default, py-class-spray; rebased onto main ee8d1a50e, #705 = train 1117d1): # RE-PINNED ONCE with UPDATE_GOLDEN=1 from the rebased build (hash 14b63d9888…d246329). kParserVer 333 (rich 334) replaces the diff --git a/test/regression.sh b/test/regression.sh index 605fbe807..a84e850ea 100755 --- a/test/regression.sh +++ b/test/regression.sh @@ -451,6 +451,7 @@ for _g in \ decltodefcheck \ deeptailcheck \ defaultceilingcheck \ + defectackschemecheck \ defectshapecheck \ defoverdeclcheck \ defslookupcheck \ @@ -1043,6 +1044,7 @@ for _g in \ shallowhistorycheck \ shapingflagcheck \ shellgateindexcheck \ + shellnestcheck \ showcasecapturecheck \ shrinkpaircheck \ sibliftcheck \ diff --git a/test/shellnestcheck.sh b/test/shellnestcheck.sh new file mode 100755 index 000000000..73e09211d --- /dev/null +++ b/test/shellnestcheck.sh @@ -0,0 +1,124 @@ +#!/usr/bin/env bash +# shellnestcheck.sh — CR712-SHSTATUS-DEPTH: the shell parser's ONE nesting budget (src/shstatus.h kMaxShellNest), shared by the +# lexer's quote / $( ) / ${ } skips and the parser's compound commands and substitutions, cuts a deeply nested script instead +# of exhausting the stack, and --quality-delta says so (shell_cut= on the root, XML and --json). +# +# The scripts are GENERATED here, never committed (PRODUCER_COMMON 12: a committed fixture that trips a cap would put a +# disclosure into every whole-repo run). Each is a new test script under test/ in a one-commit repo, so the defect-shape +# scan (vacuous-assert and unhandled-arm, both through shstatus::parse) reads it. +# (p1)-(p5) DEEP: 5,000 levels of one shape each — nested subshells, brace groups, if-then, "$( … "$( … )" … )" quotes and +# bare $( ) substitutions: the run exits 0 or 2 (no signal), within 60 s, and the root carries shell_cut="1". +# Red before the lane (main 8861b0d4d): subshell, group and if die on SIGSEGV (rc 139); quote and subst exit 0 with no +# disclosure (the old 40-level substitution cap cut them silently). At 20,000 levels ingest itself takes 60-70 s +# (tree-sitter on the file, outside this card), so the gate stays at 5,000. +# (j) --json on the subshell script: "shell_cut":1. +# (n1) UNDER THE BUDGET: a function ending in a case with no *) arm (unhandled-arm), 40 subshells deep: the unhandled-arm row is still found +# and there is no shell_cut= (the budget cut nothing real). Red on a build with a budget under 40. +# (n2) SHALLOW: the same file at depth 1: no shell_cut= (premise for n1: the row exists without nesting too). +# (v) CUT TREE: an absence assertion whose guard lies past the cut is not judged vacuous (premise v0: the facet is live). +# (f) FOLD: the subshell script committed with one stale ack: the identity-tree verdict fold keeps shell_cut="1". +# Usage: test/shellnestcheck.sh [BIN] +set -u +ROOT="$( cd "$( dirname "$0" )/.." && pwd )" +. "$ROOT/test/lib/clean-env.sh" +BIN="${1:-${RIPWIRE_BIN:-$ROOT/build/ripwire}}" +[ "${BIN#/}" = "$BIN" ] && BIN="$ROOT/$BIN" +[ -x "$BIN" ] || { echo "no ripwire binary at $BIN — build first"; exit 2; } +TMP="$( mktemp -d )"; trap 'rm -rf "$TMP"' EXIT +export TMPDIR="$TMP/cache"; mkdir -p "$TMPDIR" +export HOME="$TMP/home"; mkdir -p "$HOME" +fail=0 +ok(){ printf ' PASS %s\n' "$*" || { fail=1; printf ' FAIL could not write the PASS line for: %s\n' "$*"; }; return 0; } +no(){ printf ' FAIL %s\n' "$*"; fail=1; } +echo "shellnestcheck: BIN=$BIN" +G=( git -c user.name=t -c user.email=t@t -c commit.gpgsign=false ) +# cap60 CMD...: the 60 s deadline is ENFORCED, not just measured after the fact (CR721): SIGALRM kills a hung scan (rc 142), which +# every arm below reads as a failure, so regression.sh never stalls on this gate. +cap60(){ perl -e 'alarm 60; exec @ARGV or exit 127' "$@"; } + +# gen KIND N OUT — one script nested N levels in one shape (python: no shell recursion of our own) +gen(){ python3 - "$1" "$2" "$3" <<'PY' +import sys +kind, n, out = sys.argv[1], int(sys.argv[2]), sys.argv[3] +case = 'kindof() { case "$1" in a) echo x ;; b) echo y ;; esac; }; kindof a' +body = { + "subshell": "( " * n + "false" + " )" * n, + "group": "{ " * n + "false; " + "}; " * n, + "if": "if true; then " * n + "false" + "; fi" * n, + "quote": 'x="' + '$( echo "' * n + "y" + '" )' * n + '"', + "subst": "x=" + "$( echo " * n + "y" + " )" * n, + "case": "( " * n + case + " )" * n, +}[kind] +with open(out, "w") as f: + f.write("#!/usr/bin/env bash\nset -u\n" + body + "\n") +PY +} +# repo KIND N — a one-commit repo whose working tree adds test/deep_check.sh; prints its path +repo(){ local R="$TMP/r-$1-$2"; mkdir -p "$R/test"; "${G[@]}" -C "$R" init -q; echo 'echo hi' >"$R/test/a.sh" + "${G[@]}" -C "$R" add -A && "${G[@]}" -C "$R" commit -qm a; gen "$1" "$2" "$R/test/deep_check.sh"; printf '%s' "$R"; } +cutof(){ grep -oE ']*' "$1" | grep -oE ' shell_cut="[0-9]+"' | grep -oE '[0-9]+'; } + +for k in subshell group if quote subst; do + R="$( repo "$k" 5000 )"; s=$( date +%s ) + cap60 "$BIN" "$R" --quality-delta --no-cache >"$TMP/$k.xml" 2>"$TMP/$k.err"; rc=$?; t=$(( $( date +%s ) - s )) + c="$( cutof "$TMP/$k.xml" )" + if { [ "$rc" = 0 ] || [ "$rc" = 2 ]; } && [ "$t" -le 60 ] && [ "${c:-0}" = 1 ]; then ok "($k) 5000 deep: rc=$rc in ${t}s, shell_cut=\"$c\"" + else no "($k) 5000 deep: want rc 0/2 within 60 s and shell_cut=\"1\"; got rc=$rc in ${t}s, shell_cut='${c:-none}' ($( tail -c 160 "$TMP/$k.err" | tr '\n' ' ' ))"; fi +done +R="$TMP/r-subshell-5000" +cap60 "$BIN" "$R" --quality-delta --json --no-cache >"$TMP/j.json" 2>/dev/null; jrc=$? +j="$( python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("shell_cut","absent"))' "$TMP/j.json" 2>/dev/null || echo unparseable )" +if { [ "$jrc" = 0 ] || [ "$jrc" = 2 ]; } && [ "$j" = 1 ]; then ok "(j) --json: \"shell_cut\":1"; else no "(j) --json: want rc 0/2 and \"shell_cut\":1, got rc=$jrc '$j'"; fi + +for n in 40 1; do + R="$( repo case "$n" )" + cap60 "$BIN" "$R" --quality-delta --no-cache >"$TMP/case$n.xml" 2>/dev/null; crc=$? + case "$crc" in 0|2) ;; *) no "(case $n) --quality-delta exited $crc";; esac + row="$( grep -oE ']*defect="unhandled-arm"[^>]*>' "$TMP/case$n.xml" | grep 'deep_check.sh' | head -1 )" + c="$( cutof "$TMP/case$n.xml" )" + label=n1; [ "$n" = 1 ] && label=n2 + if [ -n "$row" ] && [ -z "$c" ]; then ok "($label) case $n deep: the unhandled-arm row is found, no shell_cut=: $row" + else no "($label) case $n deep: want an unhandled-arm row in deep_check.sh and no shell_cut=; got row='${row:-none}' shell_cut='${c:-none}'"; fi +done + +# (f) CR721 FOLD: the deep script COMMITTED (tree = HEAD, head_basis="identity") plus one stale ack: the verdict-only fold +# (the root line alone) must still carry shell_cut="1" — it is a disclosure, so the fold must not win. --show-stale is the +# premise (the unfolded root has it). RED before CR721 (train GE3 cbed31d4c): the folded root had no shell_cut=. +R="$TMP/r-fold"; mkdir -p "$R/test"; "${G[@]}" -C "$R" init -q; echo 'echo hi' >"$R/test/a.sh"; gen subshell 5000 "$R/test/deep_check.sh" +printf '# ripwire quality acks v1\nack complexity 0123456789abcdef 5 a target long gone\n' >"$R/.ripwire_quality_acks" +"${G[@]}" -C "$R" add -A && "${G[@]}" -C "$R" commit -qm a +cap60 "$BIN" "$R" --quality-delta --no-cache --show-stale >"$TMP/fold-full.xml" 2>/dev/null +cap60 "$BIN" "$R" --quality-delta --no-cache >"$TMP/fold.xml" 2>/dev/null; frc=$? +full="$( grep -oE ']*' "$TMP/fold-full.xml" )"; root="$( grep -oE ']*' "$TMP/fold.xml" )" +if printf '%s' "$full" | grep -q 'head_basis="identity"' && printf '%s' "$full" | grep -q 'stale="1"' && [ "$( cutof "$TMP/fold-full.xml" )" = 1 ]; then + ok "(f) premise: identity tree, one stale ack, --show-stale root has shell_cut=\"1\"" +else no "(f) premise: want head_basis=identity, stale=1 and shell_cut=1 under --show-stale; got: $full"; fi +if [ "$frc" = 0 ] && [ "$( cutof "$TMP/fold.xml" )" = 1 ]; then ok "(f) the default (folded) answer keeps shell_cut=\"1\"" +else no "(f) the default answer dropped shell_cut= (rc=$frc): $root"; fi + +# (v) CR721 CUT TREE NOT JUDGED: an absence assertion, a 5,000-deep group, then the presence guard that protects it. The parse +# stops inside the group, so the guard is invisible; the vacuous-assert facet must not judge the prefix (shell_cut="1" says +# the file was cut). Premise (v0): the same assertion with NO guard and no nesting rows vacuous-assert (the facet is live). +# RED before CR721 (train GE3 cbed31d4c): a vacuous-assert row at test/deep_check.sh:4. +vgen(){ python3 - "$1" "$2" "$3" <<'PY' +import sys +n, guard, out = int(sys.argv[1]), sys.argv[2] == "guard", sys.argv[3] +s = '#!/usr/bin/env bash\nset -u\nOUT="$( ./tool --run )"\n' +s += "printf '%s' \"$OUT\" | grep -q 'bad' && echo \"FAIL bad\" || echo \"PASS no bad\"\n" +if n: s += "( " * n + "false" + " )" * n + "\n" +if guard: s += "printf '%s' \"$OUT\" | grep -q 'good' && echo \"PASS good\" || echo \"FAIL no good\"\n" +open(out, "w").write(s) +PY +} +vrepo(){ local R="$TMP/v-$1"; mkdir -p "$R/test"; "${G[@]}" -C "$R" init -q; echo 'echo hi' >"$R/test/a.sh" + "${G[@]}" -C "$R" add -A && "${G[@]}" -C "$R" commit -qm a; vgen "$2" "$3" "$R/test/deep_check.sh"; printf '%s' "$R"; } +vac(){ grep -oE ']*defect="vacuous-assert"[^>]*' "$1" | grep 'deep_check.sh'; } +R="$( vrepo v0 0 noguard )"; cap60 "$BIN" "$R" --quality-delta --no-cache >"$TMP/v0.xml" 2>/dev/null +if [ -n "$( vac "$TMP/v0.xml" )" ]; then ok "(v0) premise: the unguarded absence assertion rows vacuous-assert"; else no "(v0) premise: no vacuous-assert row on the unguarded script"; fi +R="$( vrepo v 5000 guard )"; cap60 "$BIN" "$R" --quality-delta --no-cache >"$TMP/v.xml" 2>/dev/null; vrc=$? +vr="$( vac "$TMP/v.xml" )"; c="$( cutof "$TMP/v.xml" )" +if { [ "$vrc" = 0 ] || [ "$vrc" = 2 ]; } && [ -z "$vr" ] && [ "${c:-0}" = 1 ]; then ok "(v) cut tree: no vacuous-assert row, shell_cut=\"1\"" +else no "(v) cut tree: want no vacuous-assert row and shell_cut=\"1\"; got rc=$vrc row='${vr:-none}' shell_cut='${c:-none}'"; fi + +[ "$fail" = 0 ] && echo "shellnestcheck: PASS" || echo "shellnestcheck: FAIL" +exit "$fail" diff --git a/test/showcase_capture.py b/test/showcase_capture.py index c4b97c939..054c5c878 100644 --- a/test/showcase_capture.py +++ b/test/showcase_capture.py @@ -415,7 +415,7 @@ def add(section, cmd, what, **opts): add(S3, f"{BIN} . --outline=rankGraphTeleport:1-10 --top-k=0", "CHANGED: a line range on --outline is now STRIPPED with a stderr note (it used to refuse).") add(S3, f"{BIN} . --expand=rankGraphTeleport --top-k=0", "Full body + inline callee signatures.") add(S3, f"{BIN} . --expand=rankGraphTeleport:1-12 --top-k=0", "Body SLICE: lines 1..12 of the symbol's own body, with lines=\"lo-hi/total\" marking it partial.") -add(S3, f"{BIN} . --expand=compressBody --top-k=0 --compress", "Comments stripped + blank runs collapsed — compressBody is the function that implements --compress itself, chosen because it is comment-heavy enough to show a real reduction (the previously captioned symbol had no comments or blank runs, so before/after were byte-identical under a caption promising a difference).") +add(S3, f"{BIN} . --expand=collapseBlankLineRuns --top-k=0 --compress", "Comments stripped + blank runs collapsed — collapseBlankLineRuns is --compress's own second step (compressBody is now the one-line stripCommentsKeepLiterals-then-collapse pipeline, with nothing left to strip), chosen because it is comment-heavy enough to show a real reduction (a symbol with no comments or blank runs reads byte-identical, or a few bytes larger for the compress attribute, under a caption promising a difference).") add(S3, f"{BIN} . --expand=readAckRecords --top-k=0 --no-redact", "--no-redact: emit bodies verbatim (credential redaction is on by default).") add(S3, f"{BIN} . --pack-top-n=3 --top-k=0", "Pack the top-3 ranked symbols' full bodies (deprecated verb; see stderr).") diff --git a/test/tanglecheck.sh b/test/tanglecheck.sh index 6b66c92b3..948b3c414 100755 --- a/test/tanglecheck.sh +++ b/test/tanglecheck.sh @@ -1,11 +1,15 @@ #!/usr/bin/env bash -# tanglecheck.sh — QD-TANGLE gate: the tangle kind (report-only), its steering-local fact, the D4 best-since ratchet and the +# tanglecheck.sh — QD-TANGLE gate: the tangle kind (rule (b) gates, owner 11-21), its steering-local fact, the D4 best-since ratchet and the # QD-CREDIT-ROW section (STAGE0 2.1-2.8; quality.h appendTangleRows / appendTangleRatchet, qdbestsince.h). # # One seeded C++ repo, four stages (test/lib/tanglefixtures.py): v1 (tagged); a side branch with wip (cuts creep) then c2, # merged --no-ff; the working tree (judged). -# (t1) TANGLED NEW: a depth-6 function with a steering flag rows: kind="tangle" sev="minor" origin="new-symbol", why= names the -# nesting, fix= an extraction with its lines, locals= the flag. +# (t1) TANGLED NEW: a depth-6 function with a steering flag rows: kind="tangle" origin="new-symbol" gating="1" (rule (b)), why= +# names the nesting, fix= an extraction with its lines, locals= the flag. +# (b1) CROSSING: crossing was 100 flat lines (score 0) and now has tangled's body: a preexisting row (no origin=) with gating="1". +# (b2) TEST CODE: harnessmain, new under test/ with tangled's body: a row with sev="minor" and no gating= (premise: the row exists). +# (p1) PIN UNITS: the dirty-tree --quality-baseline refusal names a tangle row as "was=10.5 now=10.9", like the delta row. +# (b3) EXIT: the answer exits 2 and the root's gating= counts at least t1 + b1; the stderr line names a tangled new function. # (n1) LONG SEQUENTIAL, (n2) LONG ORCHESTRATOR, (n3) FLAT DISPATCHER, (n4) SHORT NESTED HELPER: no tangle row. Each counts its # premise in --metrics first (the function is there, and n3/n4 really reach depth 4+) and FAILS on a zero premise. # (n5) ARM NESTING: a 6-arm else-if chain whose short arms nest to depth 7, beside one depth-4 region outside it: no tangle row @@ -15,17 +19,26 @@ # an index (`xs[ pos ]`): no steer= (premise: steercursor in --metrics). Census 11-19: lexCpp's `j`, buildGraph's indices. # (s4) SCOPE: a counter rewritten in a block that closes, then a for-head local of the same name tested 12 statements # later: no steer= (premise: steerscope in --metrics). Census 11-19: genPathOf's `a`. -# (r1) RATCHET: creep gained 3 deep lines at c2 and 3 more in the working tree — each step under the rise rule (+5), so no -# baseline row reason exists, but against its best since v1 it rose 6: a tangle row with ratchet="v1"; root ratchet_ref="v1". +# (r1) RATCHET: creep gained 3 deep lines at c2 and 3 more in the working tree — each step under the rise rule (+5); its score +# grew against HEAD (a ratchet row, k1's rule), and against its best since v1 it rose 6: the row carries ratchet="v1" and why= +# "best since v1: ..."; root ratchet_ref="v1". # The wip side branch's 5-deep-line creep is not its best: the ratchet reads the first-parent line (replay 11-19). +# (k1) RATCHET VS THE BASE: grow1 (over the bar) gained 2 deep lines: under the rise step and under its best-since-v1 rise, yet +# its score grew against HEAD: a GATING tangle row was= HEAD's score, now= higher, no ratchet= facet (QD-RATCHET-BASE gate). +# (k2) MOVED, NOT GROWN: reflow's inputs moved (one flat line) but its score is HEAD's tenth: no row. Against its best since v1 +# it is 6 deep lines up, which made the tag-best compare row it (replay 11-21: buildGraph in #706). +# (k3) FELL: settle's score fell against HEAD (48 -> 47 deep lines), still 7 over v1: no row and no entry (under the +# rise step). Replay 11-21: captureTagsFacts 29.2 -> 29.1 in #714. k1-k3 read their premise from --metrics of HEAD and wt. # (r2) CREDIT: shrink lost its deep region: listed in as kind="tangle", and no tangle row. # (r4) NO CREDIT FOR A NUDGE: nudge (over the bar) lost 2 of its 40 deep lines, under the rise step: no entry # (premise: nudge over the bar in --metrics). Replay 11-19: buildGraph 56.9 -> 56.8 was credited for one deep line. # (r3) NEW FN: the tangled new function's row carries no ratchet= (a symbol created after the tag has no history here). # (c1) CREDIT: simplify ccx 21 -> 11: listed in as kind="complexity". -# (g) report-only: gating="0" on the root although tangle rows are present (premise: >= 1 tangle row). +# (g) only rule (b) and the ratchet gate: the gating tangle rows are exactly creep crossing grow1 tangled; the rest are sev="minor". # (j) --json carries the same tangle rows (count) and "improved". # (d) determinism: the working-tree run twice is byte-identical. +# Red before QD-LESSONS-2 (main 8861b0d4d): t1 b1 b3 (every tangle row minor), k1 (no row: no rise), k2 k3 (the tag-best rows); b2 +# is red only on a guard-off build (no test-path exemption). # Red before the lane (main's bin): t1 r1 r2 r3 c1 s1 (no tangle kind, no steer=, no improved); red before the census fixes (11-19): n5 s3 s4; before the replay fixes (11-19): r1 (wip best) r4. # Usage: test/tanglecheck.sh [BIN] set -u @@ -60,24 +73,41 @@ Q="$TMP/qd.xml" "$BIN" "$R" --quality-delta --no-cache >"$Q.2" 2>/dev/null; rc2=$? "$BIN" "$R" --quality-delta --json --no-cache >"$TMP/qd.json" 2>/dev/null; rcj=$? M="$( "$BIN" "$R" --metrics --no-cache 2>/dev/null )"; rcm=$? +mkdir -p "$TMP/head" && "${G[@]}" -C "$R" archive HEAD | tar -x -C "$TMP/head" +MH="$( "$BIN" "$TMP/head" --metrics --no-cache 2>/dev/null )"; rcmh=$? rc="$( cat "$Q.rc" )" case "$rc" in 0|2) ;; *) no "quality-delta exit status $rc (stderr: $( head -c 300 "$Q.err" ))";; esac if [ "$rc2" != "$rc" ] || [ "$rcj" != "$rc" ]; then no "quality-delta exit status differs between runs: $rc, again $rc2, --json $rcj"; fi -if [ "$rcm" != 0 ]; then no "--metrics exit status $rcm"; fi +if [ "$rcm" != 0 ] || [ "$rcmh" != 0 ]; then no "--metrics exit status $rcm (working tree), $rcmh (HEAD)"; fi # tangle row for a symbol (sym= ends in ::NAME or is NAME), or empty trow(){ grep -oE "]*>" "$Q" | head -1; } attr(){ printf '%s' "$1" | grep -oE " $2=\"[^\"]*\"" | head -1 | sed -E "s/.*=\"([^\"]*)\"/\1/"; } mrow(){ printf '%s' "$M" | tr '>' '\n' | grep "n=\"$1\"" | head -1; } +hrow(){ printf '%s' "$MH" | tr '>' '\n' | grep "n=\"$1\"" | head -1; } +kpre(){ local h w; h="$( hrow "$1" )"; w="$( mrow "$1" )"; printf '%s %s %s %s' "$( attr "$h" tangle )" "$( attr "$w" tangle )" "$( attr "$h" loc )" "$( attr "$w" loc )"; } tangles="$( grep -oE '= 2 and the tangled-new stderr line; got rc=$rc gating=${rg:-none} stderr='$( grep -F 'gating:' "$Q.err" | head -c 300 )'"; fi # (n1)-(n4): premise from --metrics, then no row neg(){ local label="$1" sym="$2" need="$3" m; m="$( mrow "$sym" )" @@ -113,10 +143,25 @@ else if [ -z "$( attr "$ms" steer )" ]; then ok "(s4) steerscope: no steer= (clo # (r1) r="$( trow creep )" dw="$( attr "$r" why | sed -nE 's/.*best since v1: deep ([0-9]+)->([0-9]+) lines.*/\1 \2/p' )" -if [ -n "$r" ] && [ "$( attr "$r" ratchet )" = v1 ] && [ -n "$dw" ] && [ $(( ${dw#* } - ${dw% *} )) = 6 ]; then +read -r ht wt hl wl <<<"$( kpre creep )" +if [ -n "$r" ] && [ "$( attr "$r" ratchet )" = v1 ] && [ -n "$dw" ] && [ $(( ${dw#* } - ${dw% *} )) = 6 ] && [ "$( attr "$r" was )" = "$ht" ]; then ok "(r1) creep: ratchet=\"v1\" row: $r" -else no "(r1) creep: want a tangle row with ratchet=\"v1\" and why=best since v1: deep N->N+6 lines, got '${r:-none}'"; fi +else no "(r1) creep: want a tangle row was=\"$ht\" (HEAD) with ratchet=\"v1\" and why=best since v1: deep N->N+6 lines, got '${r:-none}'"; fi if grep -q 'ratchet_ref="v1"' "$Q"; then ok "(r1) root ratchet_ref=\"v1\""; else no "(r1) root: no ratchet_ref=\"v1\""; fi +# (k1)-(k3): the ratchet against the range base; premise from HEAD's and the working tree's --metrics +read -r ht wt hl wl <<<"$( kpre grow1 )"; r="$( trow grow1 )" +if [ -z "$ht" ] || [ -z "$wt" ] || [ "${ht%.*}" -lt 6 ] || [ "${ht/./}" -ge "${wt/./}" ]; then no "(k1) PREMISE: grow1 over the bar and higher in wt, got HEAD=$ht wt=$wt" +elif [ -n "$r" ] && [ "$( attr "$r" was )" = "$ht" ] && [ "$( attr "$r" now )" = "$wt" ] && [ "$( attr "$r" gating )" = 1 ] && [ -z "$( attr "$r" ratchet )" ]; then + ok "(k1) grow1 $ht -> $wt: a gating ratchet row, no ratchet= facet: $r" +else no "(k1) grow1 $ht -> $wt: want a gating tangle row was=\"$ht\" now=\"$wt\" without ratchet=, got '${r:-none}'"; fi +read -r ht wt hl wl <<<"$( kpre reflow )" +if [ -z "$ht" ] || [ "$ht" != "$wt" ] || [ "$hl" = "$wl" ] || [ "${ht%.*}" -lt 6 ]; then no "(k2) PREMISE: reflow over the bar, same score, lines moved; got $ht/$wt, $hl/$wl lines" +elif [ -z "$( trow reflow )" ]; then ok "(k2) reflow (S $ht, $hl -> $wl lines): no tangle row" +else no "(k2) reflow: want no tangle row (score unchanged), got $( trow reflow )"; fi +read -r ht wt hl wl <<<"$( kpre settle )" +if [ -z "$ht" ] || [ -z "$wt" ] || [ "${wt%.*}" -lt 6 ] || [ "${wt/./}" -ge "${ht/./}" ]; then no "(k3) PREMISE: settle over the bar and lower in wt, got HEAD=$ht wt=$wt" +elif [ -z "$( trow settle )" ] && ! grep -qE ' $wt: no tangle row, no entry" +else no "(k3) settle $ht -> $wt: want no row and no credit, got row '$( trow settle )' / $( grep -oE ']*>' "$Q" )"; fi # (r2) / (c1) if grep -qE '"; else no "(r2) shrink: no entry"; fi if [ -z "$( trow shrink )" ]; then ok "(r2) shrink: no tangle row"; else no "(r2) shrink: unexpected tangle row $( trow shrink )"; fi @@ -130,10 +175,11 @@ elif grep -qE ' entry"; fi # (r3) if r="$( trow tangled )"; [ -n "$r" ] && [ -z "$( attr "$r" ratchet )" ]; then ok "(r3) tangled (new): no ratchet="; else no "(r3) tangled: want a row without ratchet=, got '${r:-none}'"; fi -# (g) report-only: no tangle row gates (other kinds' rows on these fixtures may) +# (g) only rule (b) gates: the gating tangle rows are exactly the new and crossing ones; every other tangle row is minor +gsyms="$( grep -oE ']*gating="1"[^>]*>' "$Q" | grep -oE ' sym="[^"]*"' | sed -E 's/.*(::|")([A-Za-z0-9_]+)"$/\2/' | sort | tr '\n' ' ' )" tg="$( grep -oE ']*>' "$Q" | grep -c 'gating="1"' )"; tm="$( grep -oE ']*>' "$Q" | grep -c 'sev="minor"' )" -if [ "$tangles" -ge 1 ] && [ "$tg" = 0 ] && [ "$tm" = "$tangles" ]; then ok "(g) report-only: $tangles tangle row(s), all sev=\"minor\", none gating" -else no "(g) tangle rows $tangles: gating $tg, minor $tm"; fi +if [ "$tangles" -ge 3 ] && [ "$gsyms" = "creep crossing grow1 tangled " ] && [ $(( tg + tm )) = "$tangles" ]; then ok "(g) $tangles tangle row(s): gating $gsyms, the other $tm sev=\"minor\"" +else no "(g) tangle rows $tangles: want gating exactly 'creep crossing grow1 tangled ', got '$gsyms' (gating $tg, minor $tm)"; fi # (j) the JSON twin: the same tangle rows in "r" and an "improved" list jt="$( python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(sum(1 for r in d["r"] if r.get("kind")=="tangle"), len(d.get("improved",[])))' "$TMP/qd.json" 2>/dev/null )" if [ "${jt% *}" = "$tangles" ] && [ "${jt#* }" -ge 2 ]; then ok "(j) --json: ${jt% *} tangle row(s) and ${jt#* } improved entries" @@ -141,5 +187,19 @@ else no "(j) --json: '$jt' (tangle rows, improved) vs XML $tangles rows"; fi # (d) if cmp -s "$Q" "$Q.2"; then ok "(d) two runs byte-identical"; else no "(d) two runs differ"; fi +# (p1) CR721 PIN UNITS: --quality-baseline on a dirty tree whose one gating row is a tangle (grow1 over the bar, growing) refuses +# and names that row in the SAME display units as the --quality-delta row (was="10.5" now="10.9"), not raw tenths. +# RED before CR721 (train GE3 cbed31d4c): "First: tangle grow1 (was=105 now=109)". +P="$TMP/pin"; mkdir -p "$P/src"; "${G[@]}" -C "$P" init -q +g1(){ python3 -c 'import sys; sys.path.insert(0, sys.argv[1]); import tanglefixtures as t; open(sys.argv[2], "w").write("#include \n" + t.overbar("grow1", int(sys.argv[3]), mult=17))' "$ROOT/test/lib" "$P/src/grow1.cpp" "$1"; } +g1 40; "${G[@]}" -C "$P" add -A && "${G[@]}" -C "$P" commit -qm v1; g1 42 +pr="$( "$BIN" "$P" --quality-delta --no-cache 2>/dev/null | grep -oE ']*sym="grow1"[^>]*gating="1"[^>]*' )" # status: the delta exits 2 on this gating row; an empty $pr FAILs the (p1) premise below +pw="$( attr "$pr" was )"; pn="$( attr "$pr" now )" +"$BIN" "$P" --quality-baseline --no-cache >/dev/null 2>"$TMP/pin.err"; prc=$? +first="$( tr '\n' ' ' <"$TMP/pin.err" | grep -oE 'First: [^)]*\)' )" +if [ -z "$pr" ] || [ "${pw#*.}" = "$pw" ]; then no "(p1) PREMISE: want a gating tangle row on grow1 with a decimal was=, got '${pr:-none}'" +elif [ "$prc" = 1 ] && [ "$first" = "First: tangle grow1 (was=$pw now=$pn)" ]; then ok "(p1) the pin refusal names the tangle row in display units: $first" +else no "(p1) want rc 1 and 'First: tangle grow1 (was=$pw now=$pn)', got rc=$prc '$first'"; fi + [ "$fail" = 0 ] && echo "tanglecheck: PASS" || echo "tanglecheck: FAIL" exit "$fail"