Skip to content

Gate the shipped agent kit against modifier drift - #1122

Merged
Alexandre Zollinger Chohfi (azchohfi) merged 41 commits into
microsoft:mainfrom
azchohfi:azchohfi-gate-agent-kit-skill-drift
Aug 26, 2026
Merged

Alexandre Zollinger Chohfi (azchohfi) merged 41 commits into
microsoft:mainfrom
azchohfi:azchohfi-gate-agent-kit-skill-drift

Conversation

@azchohfi

Copy link
Copy Markdown
Collaborator

Summary

src/Reactor/Reactor.csproj packs ~63 agent-kit documents into Microsoft.UI.Reactor.nupkg under agentkit/, and nothing checked that the C# they show a consuming agent is code the framework's own analyzers would accept. That is how #1119 was able to ship a rule in reactor-design/SKILL.md ("Flex containers take FlexPadding, NOT Padding [...] do not reach for a Border wrapper") inside the same NuGet as two documents saying the opposite. #1119 fixed the documents by hand and left no gate, so the next divergence would land the same way. This adds two Reactor.Tests facts that check the claims in those documents against ModifierTable and NoOpModifierAnalyzer.

One finding changed the shape of the fix. The issue proposes running REACTOR_MOD_003 over the snippets and states it would have caught the design.md sample. It would not. The pre-#1119 sample was Border(FlexColumn(...)).Padding(24), and ModifierTable.cs:406 gates Padding to Control/Border/Grid/StackPanel/RelativePanel/TextBlock -- Border is a legal receiver, so the analyzer was correctly silent. What was wrong was that the sample demonstrated the Border-wrapper workaround the new rule forbids. So the gate ships two rules:

Fact Catches Findings on main
Shipped_Snippets_Never_Apply_A_Modifier_Its_Receiver_Drops a future doc writing FlexColumn(x).Padding(16) as a positive sample 2, both the deliberate // Wrong: counterexamples #1119 added
Shipped_Snippets_Never_Reach_For_A_Wrapper_Instead_Of_The_Replacement the actual #1119 regression 0

Counterexamples are exempt from the first rule only when the document also names the replacement. A shipped "do not write this" with no "write this instead" is precisely the half of #1119 that caused the contradiction.

Approach

Syntax-only Roslyn (CSharpSyntaxTree.ParseText) plus metadata reflection over the already-referenced assemblies. No compilation and no semantic model: the snippets are fragments with undeclared identifiers and no class context, so a semantic pass would bind every receiver to an error type, every check would skip, and the fact would report "no findings" while measuring nothing. Instead the chain head resolves by name through the Factories return type and the element's Set(this TElement, Action<TControl>) overload -- the same signal NoOpModifierAnalyzer reads -- and anything unresolvable is skipped. Uncertainty never produces a finding, because this gate runs in CI over prose-adjacent artifacts and one false positive gets it deleted.

The corpus is derived from the csproj's agentkit/ <None> globs rather than listed in the test. The complaint in #1121 is that the next divergence lands unnoticed; a hand-maintained path list would reproduce that defect one level up, inside the gate itself. A glob that stops matching any file is itself reported, since a renamed folder silently drops a skill from the package.

ModifierTableIntegrityTests now resolves an element's mounted control through the same shared ReactorSurface, so that pairing has one implementation instead of two.

Worth a careful look

  • The wrapper rule is intentionally narrow. It only fires on single-child wrappers whose chain applies none of Background / Border* / CornerRadius / Shadow / Clip / Set. Set is on that list because its lambda can write anything and the walker cannot see inside it. Multi-child containers such as VStack(8, flex, button).Padding(16) are real layouts, not workarounds, and are not flagged. All of this was measured against the current corpus before being written, not guessed.
  • Not included, deliberately: compiling the snippets (the issue's follow-on -- fragments will not bind, so it would be vacuous), single-sourcing the two design docs (the issue's own "much larger change" alternative), and the REACTOR_MOD_003-never-runs-on-src/ analyzer coverage gap, which the issue itself scopes out as a separate concern.

Linked issue / spec

Fixes: #1121

Prior art this follows: ModifierGateProseParityTests (#1062), which pins the REACTOR_MOD_003 Gates: prose to the same table.

Test plan

  • Added tests/Reactor.Tests/AnalyzerTests/AgentKitDocGateTests.cs (the two gates) and AgentKitDocGateInstrumentTests.cs (positive controls + floors)
  • Ran dotnet test tests/Reactor.Tests -- 13,384 tests pass
  • Release build of Reactor.Tests and its project references: 0 warnings, 0 errors

Mutation-checked, each mutation restored afterwards. A gate that reports nothing reads identically to a broken one, so every oracle was made to fail on purpose:

Mutation Expected result Observed
Revert the design.md app shell to its pre-#1119 form wrapper fact reddens fails at skills/design.md:33; the dropped-modifier fact stays silent, confirming one rule alone was insufficient
Strip the // Wrong: marker above FlexColumn(children).Padding(16) dropped-modifier fact reddens fails
Rename FlexPadding out of design.md names-its-remedy clause reddens fails
Typo a packed skill folder in the csproj pack-glob fact reddens fails, naming the unmatched glob
Empty NoOpModifierAnalyzer.ElementReplacements rules derived from it collapse 3 facts fail

Floors (50 documents, 150 snippets, 100 resolved chains, 100 factories) sit under the values measured by temporarily raising each to an impossible threshold and reading the actual: 63 / 374 / 345 / 115. The pre-filter that skips parsing snippets naming no gated modifier is count-preserving -- 345 resolved chains before and after.

Risk / breaking changes

No public API change, no product code, no analyzer change, and no shipped document modified. Test-only.

Two things a reviewer should know:

  • CI impact is a new failure mode, not a new API. These facts fail the build when a shipped doc contradicts the framework. That is the point, but it means the fix for a red build is to correct the document, not to widen the gate.
  • CompilationLoaderTests.Cold_load_under_500ms_warm_under_50ms_for_minimal_project is a pre-existing wall-clock flake and may show up red alongside this branch. I measured it: a stashed clean baseline failed 4 of 6 full-suite runs under machine load (and 0 of 2 when idle), versus 5 of 6 with this branch -- within noise for a Stopwatch budget under parallel test load, and it passes in isolation either way. I still reduced this branch's contribution to that load: the three facts share one lazy corpus scan instead of running three, and snippets naming no gated modifier skip their Roslyn parse. Both changes were verified equivalence-preserving rather than assumed.

Reactor packs ~63 agent-kit documents into Microsoft.UI.Reactor.nupkg under
agentkit/, and nothing checked that the C# they show agrees with the analyzers
shipped in the same package. microsoft#1119 was able to land a rule in reactor-design
("Flex containers take FlexPadding, NOT Padding [...] do not reach for a Border
wrapper") alongside two documents saying the opposite, and fixed them by hand
without leaving a gate.

Two facts, because the proposed one is not enough. microsoft#1121 asks for
REACTOR_MOD_003 run over the snippets, and states it would have caught the
design.md sample. It would not: that sample was Border(FlexColumn(...)).Padding(24),
and ModifierTable gates Padding to Control/Border/Grid/StackPanel/RelativePanel/
TextBlock -- Border is a legal receiver, so the analyzer was correctly silent.
What was wrong was the Border-wrapper workaround the new rule forbids.

- Shipped_Snippets_Never_Apply_A_Modifier_Its_Receiver_Drops: the documentation
  form of REACTOR_MOD_003. Deliberate counterexamples are exempt -- the corpus
  has two, both added by microsoft#1119 -- but only when the document also names the
  replacement, so "do not write this" can never ship without "write this instead".
- Shipped_Snippets_Never_Reach_For_A_Wrapper_Instead_Of_The_Replacement: the
  microsoft#1119 shape, parameterised off NoOpModifierAnalyzer.ElementReplacements so a
  second entry there extends the rule with no edit.

Syntax-only Roslyn plus metadata reflection; the snippets are fragments and do
not bind, so a semantic pass would resolve every receiver to an error type and
measure nothing. Every ambiguity resolves to no finding, mirroring the analyzer.
The corpus is derived from the csproj's agentkit/ <None> globs rather than a
list in the test, because a hand-maintained list would reproduce microsoft#1121's own
defect one level up.

ModifierTableIntegrityTests now resolves an element's mounted control through
the same shared ReactorSurface, so that pairing has one implementation.

Verified by mutation, each restored afterwards: reverting the design.md app
shell to its pre-microsoft#1119 form reddens the wrapper fact at skills/design.md:33
while the dropped-modifier fact stays silent; stripping the "// Wrong:" marker
reddens the dropped-modifier fact; renaming FlexPadding out of design.md reddens
the names-its-remedy clause; typoing a packed skill folder reddens the pack-glob
fact; emptying ElementReplacements reddens three. Floors (50 documents, 150
snippets, 100 chains, 100 factories) sit under measured 63/374/345/115. The
pre-filter that skips parsing snippets naming no gated modifier is
count-preserving: 345 resolved chains before and after.

13,384 unit tests pass. Release build of Reactor.Tests and its project
references: 0 warnings, 0 errors. CompilationLoaderTests' wall-clock budget test
fails intermittently on a loaded machine (4/6 on a clean baseline, 5/6 here) --
pre-existing and unrelated.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a test-only CI gate for #1121, preventing the shipped agent kit from repeating the modifier-guidance drift fixed in #1119.

Changes:

  • Derives the documentation corpus from NuGet pack entries.
  • Detects dropped modifiers and unnecessary wrapper workarounds.
  • Adds positive controls and shared reflection metadata.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
ModifierTableIntegrityTests.cs Reuses shared control-resolution metadata.
AgentKitSnippetWalker.cs Analyzes snippet modifier chains.
AgentKitDocGateTests.cs Enforces agent-kit consistency.
AgentKitDocGateInstrumentTests.cs Adds positive controls and coverage floors.
AgentKitDocCorpus.cs Discovers packed files and extracts C# snippets.

💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Copilot review on microsoft#1122 found the opening-fence regex capped indentation at
0-3 spaces, so fenced blocks nested under a list item were never extracted.
CommonMark measures a fence's indent relative to its container, so a block
inside a numbered list item legitimately sits at four or more absolute spaces.
skills/design-docs/typography-and-colors.md has two such blocks, under list
items 10 and 11, and the gate was not inspecting either.

The aggregate snippet floor could not have caught this, exactly as the review
said: 374 blocks clear a floor of 150 as comfortably as 376 do. A floor bounds
the corpus from below and says nothing about completeness. So this adds
Every_CSharp_Fence_In_The_Corpus_Is_Extracted, a differential oracle that scans
every packed document with a separate, indentation-blind probe and requires each
fence it sees to have produced a snippet. The probe is a distinct regex rather
than a second call to the extractor, because two derivations of one number only
corroborate each other when they can fail independently. It carries its own
positive-control floor, since zero probe hits would read identically to perfect
coverage.

Also strips the opening fence's indentation from the body, per CommonMark. C#
is whitespace-insensitive so no verdict changes; it keeps a reported snippet
reading the way its author wrote it.

The extraction unit test now covers the list-nested shape, again as the review
asked, pinning that the block is found, reported at its real line, and un-nested.

Verified: reverting the cap to [ ]{0,3} reddens both new checks, and the
differential one names skills/design-docs/typography-and-colors.md:128 and :134
precisely. Corpus grows 374 -> 376 snippets and 345 -> 348 resolved chains --
the two recovered blocks and nothing else. Neither introduces a finding, so both
gates stay green. 13,385 unit tests pass; Reactor.Tests builds Release with 0
warnings.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated no new comments.

Suppressed comments (2)

Previously missed (2) — in code that hasn't changed since the last review.

tests/Reactor.Tests/AnalyzerTests/AgentKitSnippetWalker.cs:309

  • This reports valid constant-null calls that REACTOR_MOD_003 deliberately ignores. For example, Rectangle().Background((Brush)null) reaches this branch and is classified as dropped, while NoOpModifierAnalyzer.HasConstantNullArgument skips it because the modifier is inert and rewriting it would change behavior (also pinned by NoOpModifierAnalyzerTests.Does_Not_Fire_For_A_Constant_Null_Argument). Mirror that hard gate before creating a finding; otherwise the documentation gate can reject code the packaged analyzer accepts.
                if (DroppedModifier(element, modifier, info) is { } dropped)
                {
                    findings.Add(dropped with { Path = snippet.Path, Line = line, ChainStartLine = chainStart });
                    continue;

tests/Reactor.Tests/AnalyzerTests/AgentKitDocGateTests.cs:175

  • IndexOf("//") does not distinguish a comment from // inside a string. For example, FlexColumn(TextBlock("https://example/avoid")).Padding(16) is silently exempted because the URL suffix matches avoid, despite being a real violation. This contradicts the comment-only guarantee above; inspect C# single-line-comment trivia instead.
        var trailing = lines[index].IndexOf("//", StringComparison.Ordinal);
        if (trailing >= 0 && CounterexampleMarker.IsMatch(lines[index][trailing..]))
            return true;

Two defects Copilot surfaced as suppressed findings on microsoft#1122. Both are in the
direction that matters most for this gate -- one makes it stricter than the rule
it enforces, the other quietly widens the one exemption it grants.

NoOpModifierAnalyzer returns early on a syntactically constant null argument
(its line 232): the modifier is inert whatever the receiver is, so the control
gate is not what stops it doing anything, and the replacement would not be
equivalent because Optional<T> turns `with { X = null }` into an explicit clear
rather than Unset. The walker did not mirror that, so a documented
`Rectangle().Background((Brush)null)` would be reported as dropped while the
packaged analyzer accepts it. A gate stricter than its own rule produces
findings a reader cannot act on, and the only remedy on offer is to delete the
gate. Now mirrored, unwrapping casts and parentheses, covering `null`,
`default`, and `default(T)`.

Counterexample detection used IndexOf("//"), which cannot tell a comment from a
string. `FlexColumn(TextBlock("https://example/avoid")).Padding(16)` exempted
itself -- a real violation silently passing -- and the doc comment above it
claimed comment-only inspection, so the code contradicted its own stated
guarantee. Markers now come from Roslyn SingleLineComment/MultiLineComment
trivia. As a side effect `/* Wrong */` works, which the old scan missed. Prose
lines above a fence have URLs stripped for the same reason in the markdown
direction: a link ending in /avoid is a citation, not an instruction.

Both are pinned by tests that fail when the fix is reverted: nine failures
across Walker_Mirrors_The_Analyzers_Constant_Null_Gate and
Counterexample_Markers_Come_Only_From_Comments, covering every shape named in
the review plus the multi-line-comment case. The null-gate theory also asserts
the chain resolved, so it cannot pass merely because the walker failed to read
the line. IsMarkedAt and CommentText widened to internal so the exemption is
tested directly rather than only through the aggregate fact.

13,400 unit tests; the only failure is the pre-existing CompilationLoaderTests
wall-clock flake. Reactor.Tests builds with 0 warnings.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098
@azchohfi

Copy link
Copy Markdown
Collaborator Author

Both suppressed findings from the last review were real and are fixed in a7b49ba. They sit on opposite sides of the same risk, which is why I took both rather than treating "no new comments" as clean.

Constant-null gate. Correct: NoOpModifierAnalyzer returns at its line 232 on a syntactically constant null, and the walker did not mirror it, so Rectangle().Background((Brush)null) would have been reported as dropped while the packaged analyzer accepts it. A gate stricter than the rule it enforces produces findings a reader cannot act on, and the only remedy on offer is to delete the gate. Now mirrored, unwrapping casts and parentheses, covering null, default, and default(T).

Comment trivia. Also correct, and worse than it first looks: the doc comment directly above that line claimed comment-only inspection, so the code contradicted its own stated guarantee. Markers now come from Roslyn SingleLineCommentTrivia/MultiLineCommentTrivia, which additionally makes /* Wrong */ work -- the old scan matched it by luck of position, not by kind. Prose lines above a fence have URLs stripped for the same reason in the markdown direction: a link ending in /avoid is a citation, not an instruction.

Both are pinned by tests that fail when the fix is reverted -- nine failures across Walker_Mirrors_The_Analyzers_Constant_Null_Gate and Counterexample_Markers_Come_Only_From_Comments, covering every shape named in the review. The null-gate theory also asserts the chain resolved, so it cannot pass merely because the walker failed to read the line at all. IsMarkedAt and CommentText are now internal so the exemption is tested directly rather than only through the aggregate fact.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Suppressed comments (1)

tests/Reactor.Tests/AnalyzerTests/AgentKitSnippetWalker.cs:479

  • A single child does not establish that the wrapper exists only to carry this modifier. For example, ScrollViewer(FlexColumn(children)).Padding(16) reaches this branch and is reported as a workaround, even though removing ScrollViewer removes scrolling. Please restrict this rule to wrapper types known to be semantically passive (at minimum the exact Border shape from #1119), and add a sound-code case for a semantic single-child control.
            // Single-child wrappers only. `Border(inner)` is unambiguously "this element exists to
            // hold that one", which is the shape the rule is about; a multi-argument container such
            // as `VStack(8, flex, button)` is a real layout whose padding is its own business, and
            // flagging it would be a false positive on correct documentation.
            if (wrapperArguments.Count != 1)
                continue;

Two more from Copilot review on microsoft#1122. Both are cases where a check claimed more
than it could prove -- and one of them was introduced by the previous round's
fix, which is exactly the kind of regression a review loop is for.

`default` is not necessarily null. The constant-null exemption added in a7b49ba
treated every `default` and `default(T)` as null, but `default(double)` is 0 --
a real write the analyzer reports and ApplyModifiers really does drop on a Flex
receiver. Exempting it hid a true finding: a silent miss, which is the failure
this gate is least able to detect in itself, since the result is
indistinguishable from clean documentation. The question is now answered from
the written type where there is one, and from the modifier's real single-argument
overload types otherwise; unprovable never exempts.

Two of the tests written last round were themselves wrong, which the new check
surfaced:
- `.Background(default)` is ambiguous across string/Brush/ThemeRef and does not
  compile, because ThemeRef is a readonly record struct. Refusing to exempt it
  costs nothing, so that case is dropped rather than accommodated.
- `Viewbox(...)` would not do as a "sound code" example: a Viewbox is outside
  Padding's gate, so the dropped-modifier rule fires on it correctly.

A single child does not make a wrapper passive.
`ScrollViewer(FlexColumn(children)).Padding(16)` is one-child and gate-legal,
but deleting the ScrollViewer deletes scrolling -- the wrapper is load-bearing
and the sample is correct. Reporting there would be a false positive whose only
remedy is to break the sample. The rule is now restricted to element types whose
sole contribution is decoration, which today is BorderElement alone: the microsoft#1119
shape, and the one reactor-design/SKILL.md names in prose. The list is
documented as hard to extend, with the criterion stated.

Verified by mutation: restoring the blanket `default` exemption reddens all three
value-typed-default cases, and dropping the passive-wrapper test reddens the
ScrollViewer case. The parity test also pins that ThemeRef is still a value type,
so the Background assertions cannot start passing for an unrelated reason.

13,404 unit tests; the only failure is the pre-existing CompilationLoaderTests
wall-clock flake. Reactor.Tests builds with 0 warnings.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098
@azchohfi

Copy link
Copy Markdown
Collaborator Author

Both fixed in 4779e64. The default one is especially fair, because I introduced it in the previous round's fix.

default is not necessarily null. Correct, and the direction matters: default(double) is 0, a real write the analyzer reports and ApplyModifiers really does drop on a Flex receiver. Exempting it hid a true finding, which is a silent miss -- the failure this gate is least able to detect in itself, since the result is indistinguishable from clean documentation. It is now answered from the written type where there is one, and from the modifier's real single-argument overload types otherwise. Unprovable never exempts.

Writing that check surfaced two of my own test cases from last round as wrong, so both are gone rather than accommodated: .Background(default) is ambiguous across string/Brush/ThemeRef and does not compile (ThemeRef is a readonly record struct), and Viewbox(...) was a bad "sound code" example because a Viewbox is outside Padding's gate, so the dropped-modifier rule fires on it for a different and entirely correct reason.

Single child does not make a wrapper passive. Also correct. ScrollViewer(FlexColumn(children)).Padding(16) is one-child and gate-legal, but deleting the ScrollViewer deletes scrolling -- a false positive whose only remedy would be to break the sample. Restricted to element types whose sole contribution is decoration, which today is BorderElement alone: the #1119 shape and the one reactor-design/SKILL.md names in prose. The list is documented as deliberately hard to extend, with the criterion stated, and ScrollViewer(...) is now a pinned sound-code case as you asked.

Mutation-verified both ways: restoring the blanket default exemption reddens all three value-typed-default cases, and dropping the passive-wrapper test reddens the ScrollViewer case. The parity test additionally pins that ThemeRef is still a value type, so the Background assertions cannot start passing for a reason unrelated to what they claim to test.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Suppressed comments (2)

Previously missed (2) — in code that hasn't changed since the last review.

tests/Reactor.Tests/AnalyzerTests/AgentKitSnippetWalker.cs:617

  • Set needs exact matching here. The current substring check also treats unrelated modifiers such as the generic .PositionInSet(...) as opaque .Set(...), so Border(FlexColumn(...)).Padding(16).PositionInSet(...) produces no wrapper finding even though the accessibility modifier can live on the inner element and the Border is still only a padding workaround.
            if (ChainModifiers(invocation).Any(name =>
                    WrapperJustifications.Any(j => name.Contains(j, StringComparison.Ordinal))))

tests/Reactor.Tests/AnalyzerTests/AgentKitDocGateTests.cs:59

  • These broad words do not establish that the sample itself is a counterexample. For example, FlexColumn(children).Padding(16) // avoid re-enumerating children matches avoid; in a document that mentions FlexPadding elsewhere, both exemption checks then pass and this positive broken sample ships unnoticed. Require an explicit counterexample label/directive rather than any incidental occurrence of these words.
    internal static readonly Regex CounterexampleMarker = new(
        @"\b(wrong|bad|don'?t|do not|avoid|never|incorrect|anti-?pattern)\b|❌",
        RegexOptions.IgnoreCase | RegexOptions.Compiled);

Three more from Copilot review on microsoft#1122, all cases of a check being looser than
its own stated contract.

A marker word is not a label. The regex matched any occurrence of "wrong",
"avoid", "never" and friends, so `// avoid re-enumerating children` -- an
ordinary explanatory comment -- exempted the sample beneath it, and a genuine
violation would ship unnoticed. What separates a label from an explanation is
length, not vocabulary: a label is the short run before the first delimiter
("Wrong", "Bad", "Avoid this"), while an explanation keeps going. Replaced the
regex with an explicit test: strip decoration, take the text up to the first
delimiter, require at most two words opening with a marker. An explicit cross
short-circuits, being unambiguous alone. This is also more readable than the
regex it replaces, which was already on its way to becoming unmaintainable.

Ordinary lead-in paragraphs were not recognised as prose. The walk inferred
"prose" from a line's shape, but a lead-in usually has no #, > or - to recognise
it by, so `Avoid this:` directly above a fence was read as code and the walk
abandoned -- turning a clearly labelled counterexample into a CI failure its
author could not satisfy without deleting the example. Now tracks whether the
opening fence has been crossed, and stops at a second fence so a previous
block's label cannot be borrowed.

`Set` needed exact matching. It justifies a wrapper because its lambda is opaque
to this walker, but as a substring it also swallowed `.PositionInSet(...)`, an
accessibility modifier that can live on the inner element -- so a Border that
was still only a padding workaround stopped being reported. Split into exact and
substring justification sets.

All three are mutation-verified: restoring the any-occurrence match reddens the
two incidental-word cases, restoring substring `Set` reddens the PositionInSet
case, and restoring shape-based prose detection reddens the lead-in case. The
lead-in test carries a negative control (an unlabelled sentence must not exempt)
and a same-shape check that the walk cannot borrow an earlier block's label, so
it cannot pass merely by reaching prose.

The two real counterexamples in the corpus still exempt correctly under the
tighter rule -- both are `// Wrong:` labels -- so this narrows the exemption
without touching any shipped document.

13,418 unit tests; the only failure is the pre-existing CompilationLoaderTests
wall-clock flake. Reactor.Tests builds with 0 warnings.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098
@azchohfi

Copy link
Copy Markdown
Collaborator Author

All three fixed in 9b46607. Common thread: each check was looser than its own stated contract.

A marker word is not a label. Right, and // avoid re-enumerating children is a realistic comment to find above a sample. What separates a label from an explanation turned out to be length rather than vocabulary: a label is the short run before the first delimiter (Wrong, Bad, Avoid this), an explanation keeps going. So the regex is gone, replaced by an explicit test -- strip decoration, take the text up to the first delimiter, require at most two words opening with a marker; an explicit ❌ short-circuits. That also reads better than the regex it replaces, which was heading somewhere unmaintainable.

Plain lead-in paragraphs. Also right, and it is the worse direction of the two: a false positive whose author cannot satisfy the gate without deleting their own correctly-labelled example. Now tracks whether the opening fence has been crossed instead of guessing from each line's shape, and stops at a second fence so a previous block's label cannot be borrowed.

Exact Set. Correct -- .Set(...) justifies a wrapper because its lambda is opaque to the walker, but as a substring it swallowed .PositionInSet(...), which can live on the inner element. Split into exact and substring justification sets.

Mutation-verified all three: restoring the any-occurrence match reddens both incidental-word cases, restoring substring Set reddens the PositionInSet case, and restoring shape-based prose detection reddens the lead-in case. The lead-in test carries a negative control (an unlabelled sentence must not exempt) plus a same-shape check that the walk cannot borrow an earlier block's label, so it cannot pass merely by managing to reach prose.

Worth noting the tightened rule changes nothing in the corpus: both real counterexamples are // Wrong: labels and still exempt, so the exemption narrowed without touching a shipped document.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

tests/Reactor.Tests/AnalyzerTests/AgentKitDocCorpus.cs:121

  • Normalize the package path before testing this prefix. MSBuild/NuGet accepts backslashes in PackagePath (this same project uses them at Reactor.csproj:210), so an item packed as agentkit\skills\... would still ship but would be omitted from this corpus—and because the entry is skipped entirely, the unmatched-glob guard cannot detect the gap.
                || !packagePath.StartsWith(AgentKitPrefix, StringComparison.Ordinal))

Two more from Copilot review on microsoft#1122.

A styled factory returning BorderElement is not a passive wrapper. Factories.Card
is Border(child).Background(...).WithBorder(...).CornerRadius(8).Padding(16), so
its decoration is baked in where no chain inspection can see it -- and its own
XML doc offers `Card(child).Padding(24)` as the sanctioned way to override the
preset. Judging passivity by element type reported that as a workaround: a false
positive on documented usage, whose only remedy would be to stop using the
factory as designed. The check now keys on factory identity, which is carried
through from the resolved chain head rather than re-derived. `Style` joins the
justification list for the same reason, since a style can supply background,
border and corner radius from a resource this walker cannot read.

PackagePath is separator-agnostic. NuGet accepts either, and Reactor.csproj
already uses backslashes for other items (`lib\$(TargetFramework)\Reactor\
Hosting\`). An agentkit item written that way would ship and never enter the
corpus, and because the entry was dropped whole the unmatched-glob guard could
not see the gap either -- the inspected set would just be quietly smaller than
the packed set. The predicate is extracted so it can be tested against project
XML directly instead of only through the working tree.

Mutation-verified: reverting to element-type passivity reddens both the Card and
ApplyStyle cases, and reverting the normalisation reddens the separator case. The
decorated-wrapper test carries a positive control on the same shape -- the plain
Border must still report -- so it cannot pass by the wrapper rule having stopped
working altogether.

13,421 unit tests, 0 failures.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098
@azchohfi

Copy link
Copy Markdown
Collaborator Author

Both fixed in the latest push.

Card is not a passive Border. Correct, and the XML doc you pointed at makes it worse than a theoretical false positive: Card(child).Padding(24) is the documented way to override the preset, so the gate would have been rejecting the sanctioned usage with no remedy short of abandoning the factory. The check now keys on factory identity, carried through from the resolved chain head rather than re-derived from the element type. Style joins the justification list for the same reason you raise about ApplyStyle -- a style can supply background, border and corner radius from a resource this walker cannot read.

PackagePath separators. Also correct, and the second-order point is the one that matters: because the entry was dropped whole, Every_AgentKit_Pack_Glob_Still_Matches_Files could not have caught it either, so the inspected set would have been quietly smaller than the packed set -- exactly the class of silent shortfall this PR exists to prevent. Normalised, and the predicate is extracted so it can be tested against project XML directly instead of only through the working tree.

Mutation-verified both: reverting to element-type passivity reddens the Card and ApplyStyle cases, reverting the normalisation reddens the separator case. The decorated-wrapper test carries a positive control on the same shape -- the plain Border must still report -- so it cannot pass by the wrapper rule having stopped working altogether.

Full suite is 13,421 tests, 0 failures on this run.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated no new comments.

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

tests/Reactor.Tests/AnalyzerTests/AgentKitDocCorpus.cs:169

  • This aggregates all semicolon-separated patterns into one Files list, so the promised per-glob failure is not enforced. The existing recipes entry contains both *.md and *.cs; if either pattern stops matching while the other still matches, entry.Files.Count == 0 remains false and CI silently misses that packaging drift. Emit one AgentKitPackEntry per pattern (or separately retain unmatched patterns) so Every_AgentKit_Pack_Glob_Still_Matches_Files can identify the failed glob.
            foreach (var pattern in include.Split(';', StringSplitOptions.RemoveEmptyEntries))
            {
                foreach (var file in Expand(projectDirectory, pattern.Trim()))
                    files.Add(file);
            }

From Copilot review on microsoft#1122. An <None> Include may carry several
semicolon-separated globs -- skills\recipes\*.md;skills\recipes\*.cs is packed
that way -- and pooling their matches let a dead glob hide behind a live
sibling. The item still matched files, so the emptiness check stayed false while
half the recipes had stopped shipping. PackEntries now emits one entry per
pattern, so the guard is per-glob as its name promised.

Confirmed in both directions rather than assumed. With only the *.md half of the
recipes item broken: the new code fails and names the dead glob, the old
aggregating code passes silently. That is the reviewer's claim reproduced
end-to-end.

Doing that also exposed the granularity control added alongside the fix as
vacuous. It compared entry count to distinct PackagePath count, which is already
unequal because several agentkit items legitimately share one PackagePath (two
pack straight into agentkit/), so it passed under aggregation too -- a control
that could not fail for the reason it existed. Replaced with an assertion that no
entry's pattern contains a ';', which detects aggregation on its own with no
csproj mutation needed, plus a check that some item really does carry multiple
globs so the assertion cannot go vacuous if the csproj changes shape.

13,421 unit tests; the only failure is the pre-existing CompilationLoaderTests
wall-clock flake. Reactor.Tests builds with 0 warnings.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated no new comments.

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

tests/Reactor.Tests/AnalyzerTests/AgentKitDocGateTests.cs:305

  • StripBlockquote removes every quote level here, so a marker in a nested quote can exempt a later sample in its parent quote. For example, > > Avoid this: followed by > ```csharp and > FlexColumn(...).Padding(16) is treated as marked even though the label belongs to the nested blockquote. Track the opening fence's quote depth and ignore prose from deeper/sibling quote containers, as the fence scanner already does, so unrelated nested guidance cannot silently suppress a real finding.
            var text = AgentKitDocCorpus.StripBlockquote(lines[i]).Content.Trim();

The label walk stripped every blockquote level before matching, so a line
in a nested quote read as an ordinary label for a sample in the container
around it: `> > Avoid this:` above `> ```csharp` exempted the parent
quote's snippet. That nested line belongs to its own container and
introduces its own example, so borrowing it silently suppressed a real
finding one level out.

Compare each candidate line's depth against the sample's and skip anything
deeper, mirroring the bookkeeping the fence scanner already does. A
shallower label still counts: it encloses the quote, so it does introduce
what sits inside it, and exempting is the safe direction for an ambiguous
container boundary.

Mutation-checked; the fixture carries a same-depth positive control so the
negative assertion fails on the depth test rather than on the walk being
unable to reach that line at all.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

tests/Reactor.Tests/AnalyzerTests/AgentKitDocGateTests.cs:252

  • This substring check can treat an unrelated identifier as the documented remedy. For example, a marked Rectangle().Background(...) counterexample passes the remedy condition if the document only mentions FillColor or an *FillColor*Brush resource, even though it never names .Fill(...). Since this is the exemption that permits otherwise-invalid snippets, match replacement at identifier boundaries so compound identifiers cannot silently satisfy it.
    internal static bool NamesRemedy(string documentText, string? replacement) =>
        replacement is null || documentText.Contains(replacement, StringComparison.Ordinal);

Three fixes, all in the direction of the extractor and the facts agreeing
about the same document.

The marker walk did not recognise a fence opened on a list marker's own
line, which the extractor now accepts. It read `- ```csharp` as C# code,
abandoned the search, and reported a deliberately labelled counterexample
as a finding — a false positive on correct documentation, introduced by
adding inline-marker support to only one of the two halves. Strip the
marker there too.

The scanner ended an unclosed region when a blockquote closed but had no
counterpart for list items, so an unclosed indented ```text under a bullet
absorbed the next top-level ```csharp block and that sample shipped
unscanned; the completeness fact reads the same scan, so it could not have
reported the gap. End the region when a non-blank line falls left of the
item's content column. The rule applies only when the fence itself sits at
or past that column: `ContainerIndent` reports the nearest list above a
line, which for a block that has already de-indented out of the list is a
container it is not in, and applying it there emptied the region.

`NamesRemedy` matched the replacement as a bare substring, so a document
mentioning only `FillColor` counted as having named `Fill`. This is the
clause that permits an otherwise-invalid snippet, so a loose match exempts
the sample it exists to hold to account. Match at identifier boundaries.

All three mutation-checked, each with a positive control alongside so the
negative assertions fail on the rule rather than on the walk being unable
to reach the line at all.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

tests/Reactor.Tests/AnalyzerTests/AgentKitDocGateInstrumentTests.cs:635

  • This negative control does not prove that ResolveHead stops at Semantics: if that branch is deleted, the walker resolves the head as Border and still reports nothing because Border is a legal Padding receiver. Use a head that would produce a finding when misattributed, such as Rectangle().Semantics(...).Background(brush), so removing the type-changing stop makes this test fail.
        var scan = AgentKitSnippetWalker.Scan(new[]
        {
            new AgentKitSnippet("fixture/semantics.md", 1, "Border(child).Semantics(role: \"button\").Padding(16)"),

The `Semantics` negative control could not fail. It scanned
`Border(child).Semantics(...).Padding(16)` and asserted no finding, but
Border is a legal `Padding` receiver, so deleting the type-changing stop
left the scan silent for the wrong reason and the test passed either way —
a vacuous assertion guarding the one rule whose whole value is
non-attribution. Scan a FlexColumn head instead, which mounts a FlexPanel
outside Padding's gate, so misattributing the chain produces a finding.
A positive control alongside it pins that the walker can see the shape at
all. Mutation-checked: removing the stop now reddens it.

Separately, an inline list marker took all of its padding as the content
column, so `-     ```csharp` scanned as a fence. Under CommonMark five or
more spaces put the item's content one space along and make the rest
indented code, so that line is literal text and the gate could fail on
prose. Use the same `ContentColumn` rule as ordinary items and measure the
three-column fence limit from where the fence characters actually start,
which also gives body de-indentation one definition instead of two. The
independent probe gets the same padding limit: it is deliberately a
different mechanism, but if it accepted what the scanner rejects the
completeness fact would report literal text as an unscanned sample.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated no new comments.

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

tests/Reactor.Tests/AnalyzerTests/AgentKitSnippetWalker.cs:854

  • ResolveHead walks through fluent modifiers on the wrapped child, but the removability check only inspects modifiers on the outer Border chain. This makes Border(FlexColumn(children).Flex(grow: 1)).Padding(16) report as safely replaceable even though deleting the Border changes the .Flex target: it was a child of Border, but becomes a direct FlexPanel child and starts affecting layout. Conservatively suppress the finding when the inner chain contains parent-relative modifiers (such as Flex, Grid, or Dock) and add this shape as a negative control.
            var innerHead = ResolveHead(wrapperArguments[0].Expression);
            if (innerHead is null)
                continue;

            var inner = ReactorSurface.Instance.Element(innerHead.Value.Factory, innerHead.Value.TypeArgumentCount);

The wrapper remedy deletes the Border, which reparents what it wrapped.
Modifiers on the *inner* chain that the parent interprets then resolve
against a different container than they were written for: in
`Border(FlexColumn(children).Flex(grow: 1)).Padding(16)` the `.Flex` is
inert inside the Border and starts driving layout once it is gone. The
removability check only inspected the outer chain, so it recommended a fix
that is not behaviour-preserving.

Suppress when the wrapped expression's own chain carries any of them,
reusing the relocation allowlist so there is one table for "modifiers whose
meaning depends on the parent". `ChainModifiers` climbs to the outermost
invocation first, which from an inner expression walks straight back out
into the wrapper's chain and would have re-read the wrapper's own
modifiers, so the walk is split and the inner check starts where it is
pointed.

The microsoft#1119 positive control is unaffected: its inner chain carries a `with`
initializer, not modifiers, so the shape this fact exists to catch is still
caught. Mutation-checked, with an inner modifier the parent does not
interpret as the control that keeps the suppression from swallowing
everything.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated no new comments.

Suppressed comments (2)

Previously missed (1) — in code that hasn't changed since the last review.

tests/Reactor.Tests/AnalyzerTests/AgentKitDocCorpus.cs:92

  • The optional list marker also accepts arbitrary leading indentation. At top level, - ```csharp is indented code rather than a list/fence, but this regex calculates a synthetic list content column and extracts it; the repository's CommonMark fixture at Md4cCommonMarkSpecTest.cs:2595-2601 establishes that a list marker indented four spaces is literal code. Because CSharpFenceProbe accepts the same shape, the completeness check remains green while the gate can fail on quoted examples. Validate the marker against its actual container before treating it as list syntax.

This issue also appears on line 107 of the same file.

    private static readonly Regex FenceOpen = new(
        @"^(?<indent>[ \t]*)((?<marker>[-*+]|\d+[.)])(?<pad>[ \t]+))?(?<fence>`{3,}|~{3,})[ ]*(?<info>[^`\r\n]*)$",
        RegexOptions.Compiled);

tests/Reactor.Tests/AnalyzerTests/AgentKitDocCorpus.cs:107

  • BlockquoteLevel treats any amount of leading whitespace as a blockquote prefix. Consequently, a four-space-indented literal such as > ```csharp is stripped and scanned as a real C# fence, even though the repository's CommonMark fixture confirms that four-space-indented > content is an indented code block (Md4cCommonMarkSpecTest.cs:2073-2079). If that literal contains a gated modifier, this gate reports a false violation. Parse the marker relative to its container with CommonMark's three-column limit, and update the independent probe similarly so it cannot corroborate the same misclassification.
    private static readonly Regex BlockquoteLevel = new(@"^[ \t]*>[ \t]?", RegexOptions.Compiled);

A `>` or list marker four columns past its container is an indented code
block, not container syntax. The repository's own conformance fixtures pin
this: `    > # Foo` renders as literal `> # Foo` text
(Md4cCommonMarkSpecTest.Example_0230) and `    1.  A paragraph` likewise
(Example_0288). The scanner accepted arbitrary indentation before both, so
it stripped the prefix off a quoted literal and scanned it as a real
sample; a gated modifier written inside one would have failed the gate on
text that is not a sample at all.

Bound the blockquote prefix to three columns and validate an inline list
marker against its own container rather than deriving the content column
from the line alone. The independent probe gets the same two limits: it is
deliberately a different mechanism, but one that accepted what the scanner
rejects would report literal text as an unscanned sample and redden the
completeness fact on a correct document.

Measured before and after: zero instances of either shape in the 58 packed
documents, with positive controls (96 quoted lines, 798 fence lines) to
show the probe could have found them. Defensive, not a live fix. Also drops
`BlockquotePrefix`, dead since `BlockquoteLevel` replaced it.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Review flagged that `- Avoid this:` above a separate `- ```csharp` item
lets the first item's label mark the second item's sample, and proposed
tracking list-container boundaries so it cannot.

Declining that, and recording why in the code instead. Two adjacent list
items are one list making one point, and it is how these documents are
actually written; treating the boundary as a barrier would report a
deliberately labelled counterexample and fail CI on correct documentation.
That is the one failure mode this gate cannot afford, and it is the same
direction every other ambiguity here resolves in — including the blockquote
depth rule, which accepts a shallower label for the same reason.

The reach was already bounded and now has a test saying so: the walk gives
up after eight lines or at the previous block's fence, whichever comes
first, so a label introducing an earlier block cannot be borrowed. An
exemption still requires the document to name the remedy, so the microsoft#1119
half-guidance shape is caught either way. Pinned with the sibling case, the
previous-block case and an unlabelled negative control, so the trade-off is
a decision rather than an accident.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated no new comments.

Suppressed comments (3)

Previously missed (3) — in code that hasn't changed since the last review.

tests/Reactor.Tests/AnalyzerTests/AgentKitDocGateTests.cs:114

  • Sentence-ending punctuation defeats the two-word safeguard below. // avoid allocations. is split at the period into the two-word head avoid allocations, so it is treated as a counterexample label even though the same comment without the period is explicitly meant not to qualify; if the document mentions the remedy elsewhere, a real violation is silently exempted. Restrict this branch to punctuation that actually introduces a label/body (or otherwise distinguish terminal sentence punctuation), and add punctuated negative controls.
        var cut = stripped.IndexOfAny(new[] { ':', '—', '–', ',', '!', '.', ';' });

tests/Reactor.Tests/AnalyzerTests/AgentKitDocCorpus.cs:469

  • Counting a tab as one column is incompatible with the CommonMark block rules this scanner implements: the repository's own spec fixture says tabs advance to 4-column tab stops (tests/Reactor.Tests/Md4cFixtures/spec.txt:343-348). Thus a top-level tab followed by `````csharp`` is an indented code block, but this scanner measures width 1 and extracts it as a real fence, allowing code-like quoted text to cause a false CI failure. Compute visual columns using tab stops consistently in opening/container/closing logic and add tab-indentation controls.
    /// Width of a line's leading whitespace, counting a tab as one column.
    /// </summary>
    /// <remarks>
    /// One column per character is what every other measurement here uses — the indent groups are
    /// <c>[ \t]*</c> matched by length — so widths stay comparable across the scanner.

tests/Reactor.Tests/AnalyzerTests/AgentKitSnippetWalker.cs:724

  • Named arguments can make a bare default provably null even when the complete overload set is not. For example, Rectangle().Background(brush: default) selects the Brush overload, so the analyzer's semantic constant-null check skips it; this walker passes no type here, checks string/Brush/ThemeRef together, and emits a false dropped-modifier finding. Preserve modifier parameter names and use argument.NameColon to narrow the candidate overloads before deciding whether default is null, with a named-argument control test.
                if (invocation.ArgumentList.Arguments.Count == 1
                    && ReactorSurface.Instance.DefaultIsProvablyNull(modifier, written))
                    return true;

Three fixes, each one the gate disagreeing with something it mirrors.

A trailing period defeated the label safeguard. `// avoid allocations` is
named in the code as exactly what the two-word rule must reject, but the
period counted as a delimiter, so the punctuated form split into a two-word
head and qualified as a counterexample label — identical text, opposite
verdicts. Trim terminal `.` and `;` before looking for an introducer. A
mid-comment period still delimits, so `// Bad. This allocates.` keeps its
label.

Indentation was measured one column per character. CommonMark advances a
tab to the next four-column tab stop (`Md4cFixtures/spec.txt`, "Tabs"), so
a tab-indented ```csharp at top level is an indented code block, not a
fence; measuring width 1 scanned the literal as a sample and the gate could
fail on quoted, code-like prose. Every indentation measurement now goes
through one tab-aware helper, and the probe stops accepting a tab-indented
top-level fence so it cannot corroborate what the scanner rejects.

A bare `default` was judged against the modifier's whole overload set even
when a named argument had already selected one. `.Background(brush: default)`
binds only to the Brush overload and is provably null, but the ambiguous
string/Brush/ThemeRef set says unprovable, so the gate would report a
sample REACTOR_MOD_003 accepts — being stricter than the analyzer it
mirrors is worse than the drift it exists to catch. Index the argument
types by parameter name and narrow before deciding; an unrecognised name
falls back to the full set.

All three mutation-checked, each with controls that fail if the narrowing,
the tab stops, or the trimming is removed.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated no new comments.

Suppressed comments (1)

tests/Reactor.Tests/AnalyzerTests/AgentKitDocCorpus.cs:622

  • Closing-fence indentation is measured in characters here, while opening/container indentation is measured in visual columns. A leading tab therefore counts as 1 and \t``` incorrectly closes a top-level fence even though CommonMark allows at most three spaces (a tab advances to column 4). Any gated modifier later in that code block is then omitted from the corpus. Use the existing visual-width helper for this check, and cover a tab-indented fence run inside a real fenced block.
        if (line.Length - text.Length - containerIndent > 3)
            return false;

The previous commit claimed every indentation measurement went through the
tab-aware helper. `IsClosingFence` did not, so opening and container
indentation were columns while the close was still characters. A leading
tab counted as 1 rather than 4, so a tab-indented ``` inside a sample read
as the close, ended the block three columns early, and everything after it
in that block went uninspected — and the differential probe trusts this
scanner for block structure, so it could not have reported the loss.

The first fixture for this was vacuous: it put the tab inside a string
literal rather than in leading whitespace, so the line was never a
closing-fence candidate and the mutation left it green. Replaced with a
genuinely tab-indented fence line, re-checked, and it now reddens when the
measurement goes back to characters.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated no new comments.

Suppressed comments (2)

Previously missed (2) — in code that hasn't changed since the last review.

tests/Reactor.Tests/AnalyzerTests/AgentKitDocCorpus.cs:521

  • Tab width is computed from column 0 here, but a tab after a list marker advances from the marker's current column. For example, in valid Markdown 10.\t```csharp, the tab advances from column 3 to 4; this code calculates a padding of 4 and a content column of 7. The four-space-indented first body line is then treated as having exited the list, so the C# snippet is omitted. Make VisualWidth accept an initial column and use it both here and when calculating fenceColumn, with a tab-padded numbered-list fixture.
        var beforePad = VisualWidth(marker.Groups["indent"].Value) + marker.Groups["marker"].Length;
        var padding = VisualWidth(marker.Groups["pad"].Value);

        return beforePad + (padding <= 4 ? padding : 1);

tests/Reactor.Tests/AnalyzerTests/AgentKitSnippetWalker.cs:628

  • ParseText uses the default preprocessor symbols, so code in an inactive #if branch is represented only as DisabledTextTrivia and never reaches DescendantNodes(). The packed corpus already contains conditional C# (skills/devtools.md:49); a future #if DEBUG block containing FlexColumn(...).Padding(...) would therefore pass this gate unchecked. Parse disabled branches as additional variants (or otherwise walk their text), and add a positive-control fixture for a gated modifier inside #if DEBUG.
            var tree = CSharpSyntaxTree.ParseText(snippet.Text);

`ParseText` uses the default preprocessor symbols, so an inactive branch
survives only as DisabledTextTrivia and never reaches DescendantNodes. A
violation written inside `#if DEBUG` shipped unscanned, and the corpus
already contains conditional C# (`skills/devtools.md`). Blank the directive
lines before parsing so every branch becomes ordinary text; blanking rather
than deleting keeps each remaining line at its original index, so a finding
still reports the line it is really on. Concatenated `#else` arms may not
parse, which costs nothing: an unresolvable chain is skipped, never
reported.

A tab's width depends on where it starts, and the marker padding was
measured from column 0. In `10.<TAB>```csharp` the tab advances column 3 to
4 and is worth one column, not four, so the content column is 4 rather than
7. The closing bound is measured against that column, so a ``` eight
columns in reads as literal text inside the block at 4 but as the close at
7 — truncating the sample.

The first fixture for the tab fix was vacuous: with the container guard in
place, the wrong content column changed nothing observable, and the
mutation left it green. Rebuilt around an inner fence at the column where
the two answers disagree, and re-checked.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Blanking the directives put every arm in one text, which does not make them
independently parseable. Two valid alternatives in an expression position
become adjacent expressions, and Roslyn may place the later one in skipped
trivia — so a dropped modifier in the `#else` arm was still never reached,
which is the hole the previous commit set out to close.

Enumerate arms instead: one variant keeps no arm and is the snippet's
unconditional code, and each further variant keeps exactly one arm with the
rest blanked, which is a configuration that arm really occurs in. Linear in
arm count rather than exponential in block count, so no snippet can make it
expensive, and blanking still preserves every line's index so findings
report the line they are really on.

Two consequences handled: the unconditional code appears in every variant,
so findings are de-duplicated by path, line, modifier and element, and the
resolved-chain count is taken only from the first variant — counting them
all would inflate the floors the corpus is measured against and make a
shortfall easier to pass rather than harder.

Mutation-checked with an `#if`/`#else` fixture whose violation is in the
`#else` arm; suppressing per-arm variants reddens it.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated no new comments.

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

tests/Reactor.Tests/AnalyzerTests/AgentKitSnippetWalker.cs:391

  • An explicit type name that is not identical to a reflected parameter type is treated as non-null, but it may be a reference-type alias or subclass. For example, using BrushAlias = Microsoft.UI.Xaml.Media.Brush; Rectangle().Background(default(BrushAlias)) is a compile-time null that NoOpModifierAnalyzer.GetConstantValue skips, while this path returns false and reports a dropped modifier. That creates the false-positive direction the gate says it avoids. Preserve an “unknown” result and suppress the finding when the written type cannot be resolved (or resolve aliases), and add this alias case to the constant-null controls.
        var matches = types.Where(t => string.Equals(t.Name, simpleName, StringComparison.Ordinal)).ToList();
        return matches.Count > 0 && matches.All(IsNullable);

Review proposed reading "matches no reflected parameter type" as "reference
type, therefore null", so an aliased `default(BrushAlias)` would be
exempted rather than reported.

Tried it, and the existing tests rejected it immediately: `Thickness` is
not among `Padding`'s reflected single-argument types either, so
`.Padding(default(Thickness))` takes exactly the same path. Exempting the
unknown case loses that finding — a value-typed default written to a Flex
receiver, which `ApplyModifiers` really does drop and which
`Walker_Still_Reports_A_Value_Typed_Default` already pins.

So the trade is a real, tested true positive against an alias shape that
documentation does not contain; declining it. Recorded at the call site and
as a test that asserts both halves together, including that `Thickness` is
absent from the reflected set, so the reasoning cannot quietly stop being
true.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

The chain walk stepped over every intermediate member call whose name was
not type-changing, which assumed an unrecognised method handed back what it
was given. `FlexColumn(children).AsBorder().Padding(16)` therefore resolved
to a FlexElement and was reported, though `AsBorder` returns a Border and
`Padding` is legal there — uncertainty creating a finding on valid shipped
guidance, against the rule the walker is built on.

Walk through a call only when its reflected signature proves it preserves
the element: `M<T>(this T el, ...) -> T`, or a non-generic
`M(this FooElement el, ...) -> FooElement`. An overload set that disagrees
with itself is not proof, so one non-conforming overload disqualifies the
name. Anything else leaves the head unresolvable, and an unresolvable head
is skipped rather than attributed to whatever sat underneath it.

Costs 17 of 348 resolved chains across the corpus, leaving 331 against a
floor of 100, and no finding changes. Mutation-checked, with a known
identity modifier as the control so the assertion proves the walk stops at
unknown names rather than at every member access.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

tests/Reactor.Tests/AnalyzerTests/AgentKitSnippetWalker.cs:684

  • Nested conditionals are not actually covered by these variants. Because entering an inner #if replaces the outer arm and #endif resets to arm 0, no variant retains an outer chain head together with an inner branch and the trailing call. For example, an outer Border(, an inner #if selecting FlexColumn(...), and a trailing ).Padding(16) is split across three variants, so the wrapper regression is silently missed. Preserve the active parent-arm stack when emitting each branch configuration, and add a nested-chain positive control.
    /// Linear in the number of arms rather than exponential in the number of blocks, so a snippet
    /// cannot make this expensive. Nesting is not modelled: an inner block's arms are treated as
    /// arms of the enclosing one, which over-produces variants but never drops a line from all of
    /// them, and unparseable text yields no resolvable chain rather than a finding.

Both are defects in the conditional-variant scan added two commits ago.

The de-duplication key was recorded before either rule ran, so a variant
that resolved a chain without reporting reserved the key and masked a real
finding at the same line in a later arm: `Border(child).Padding(16)` in the
`#if` is legal, and the `FlexColumn(children).Padding(16)` in the `#else`
was then skipped. Record the key only when a finding is emitted.

Arms were numbered flat, so entering an inner `#if` replaced the outer arm
and its `#endif` reset to the unconditional one. No variant then held an
outer arm's chain head together with an inner arm's body. Track the arm
stack and each arm's parent, and keep a variant's own arm plus every arm
enclosing it. Still linear in arm count.

The first nested fixture was vacuous — the chain resolved from the outer
arm alone, so the parent chain never mattered and the mutation left it
green. Rebuilt so the wrapper opens in the outer arm and its child is in
the inner one, which needs both. Added the missing de-duplication control
too: nothing previously failed if the same unconditional finding were
reported once per variant.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Suppressed comments (1)

tests/Reactor.Tests/AnalyzerTests/AgentKitDocCorpus.cs:95

  • This opener handles blockquote prefixes followed by one list marker, but not other valid recursive container orders. A fence opened as - > ```csharp (a list item containing a blockquote containing a fence) matches neither FenceOpen nor CSharpFenceProbe, so the extractor and its completeness oracle silently omit the same snippet. The repository’s CommonMark fixture defines containers recursively (tests/Reactor.Tests/Md4cFixtures/spec.txt:3650-3664) and includes list-contained blockquotes (:5714-5724). Parse repeated container prefixes and add this shape to the differential fixture.
    private static readonly Regex FenceOpen = new(
        @"^(?<indent>[ \t]*)((?<marker>[-*+]|\d+[.)])(?<pad>[ \t]+))?(?<fence>`{3,}|~{3,})[ ]*(?<info>[^`\r\n]*)$",
        RegexOptions.Compiled);

Review raised two more shapes the scan does not cover. Both are declined
and documented rather than built, because both would add machinery that
guards nothing in the shipped corpus and carries its own failure mode.

A chain split across two independent conditional blocks — factory in one
`#if`, modifier in another — exists only in a configuration selecting an
arm from each, and one-arm-at-a-time never holds both. Covering it means
combining arms across blocks, which is exponential and needs a cap. The
corpus contains a single conditional block, unnested and single-armed.

`- > ```csharp` is a legal opener that neither the scanner nor its probe
matches. That they agree is what makes it safe: the completeness fact still
means what it says, and the cost is an unscanned block, not a finding on
prose. Pinned with a test asserting both halves skip it and that each
container alone is still matched by both, so the boundary cannot drift into
the two disagreeing — which would fail CI on a correct document.

Measured, with positive controls: zero instances of either shape across the
58 packed documents.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098
`Assert.Empty` over a filtered sequence trips xUnit2029, which is an error
only in Release because TreatWarningsAsErrors is Release-only — so a green
Debug build and a green test run both missed it and CI's Build solution and
Pack jobs failed. Verified this time with `-c Release`.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 32acdb44-aca3-4bdb-ad41-f4dd687d9098

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 5 changed files in this pull request and generated no new comments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Gate shipped agent-kit skills against drift — the same rule can currently ship contradicting itself

2 participants