You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@shardingsphere.apache.org by zh...@apache.org on 2026/08/13 12:28:06 UTC

(shardingsphere) branch master updated: Refine gen-ut quality gates (#39442)

This is an automated email from the ASF dual-hosted git repository.

terrymanu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/shardingsphere.git


The following commit(s) were added to refs/heads/master by this push:
     new f8159e7fc4a Refine gen-ut quality gates (#39442)
f8159e7fc4a is described below

commit f8159e7fc4ab0e4104c543a93f6a4a307043aa05
Author: Liang Zhang <zh...@apache.org>
AuthorDate: Thu Aug 13 20:27:58 2026 +0800

    Refine gen-ut quality gates (#39442)
    
    * Refine gen-ut quality gates
    
    - keep semantic decisions out of mechanical rule scans
    - harden coverage and task-scope verification
    - remove unsafe gate-result reuse and add regression tests
    
    * Refine gen-ut quality gates
    
    - keep semantic decisions out of mechanical rule scans
    - harden coverage and task-scope verification
    - remove unsafe gate-result reuse and add regression tests
    
    * Refine gen-ut quality gates
    
    - keep semantic decisions out of mechanical rule scans
    - harden coverage and task-scope verification
    - remove unsafe gate-result reuse and add regression tests
    
    * Refine gen-ut quality gates
    
    - keep semantic decisions out of mechanical rule scans
    - harden coverage and task-scope verification
    - remove unsafe gate-result reuse and add regression tests
---
 .codex/skills/gen-ut/SKILL.md                      | 547 +++++++--------------
 .codex/skills/gen-ut/references/verification.md    | 110 +++++
 .../gen-ut/scripts/collect_quality_baseline.py     | 112 ++---
 .codex/skills/gen-ut/scripts/run_quality_gates.py  | 286 -----------
 .codex/skills/gen-ut/scripts/scan_quality_rules.py | 523 ++++++++++++++------
 .../gen-ut/scripts/verification_gate_state.py      | 232 ---------
 .../gen-ut/tests/test_collect_quality_baseline.py  | 105 ++++
 .../skills/gen-ut/tests/test_scan_quality_rules.py | 288 +++++++++++
 8 files changed, 1094 insertions(+), 1109 deletions(-)

diff --git a/.codex/skills/gen-ut/SKILL.md b/.codex/skills/gen-ut/SKILL.md
index 40364c14f40..4e7a01fca7a 100644
--- a/.codex/skills/gen-ut/SKILL.md
+++ b/.codex/skills/gen-ut/SKILL.md
@@ -8,382 +8,177 @@ description: >-
 
 # Generate Unit Tests
 
-## Input Conventions
-
-Required inputs:
-- Target class list (fully-qualified class names are recommended).
-
-Optional inputs:
-- Module name (limits Maven command scope).
-- Test class list (for targeted execution only; does not limit in-place updates for related test classes).
-
-Default completion level:
-- Unless the user explicitly waives or lowers the target, requests such as "add tests" remain bound to `R10-A` completion criteria (including default coverage and quality gates).
-
-Missing input handling:
-- Note: this section only describes entry handling; final decisions follow `R7`/`R10`.
-- Missing target classes: enter `R10-INPUT_BLOCKED`.
-- Missing test classes: auto-discover with the `TargetClassName + Test` convention.
-- No related test classes: create `<TargetClassName>Test` in the resolved module test source set.
-- Cannot resolve `<ResolvedTestModules>`: enter `R10-INPUT_BLOCKED` and request additional module scope.
-
-## Terms
-
-- `<ResolvedTestClass>`: one fully-qualified test class or a comma-separated list of test classes.
-- `<ResolvedTestFileSet>`: editable file set (space-separated in shell commands), containing only related test files and required test resources.
-- `<ResolvedTestModules>`: comma-separated Maven module list used by scoped verification commands.
-- `<ResolvedTargetClasses>`: one fully-qualified production class or a comma-separated list of target classes from user input.
-- `Target-class coverage scope`: for each target class, aggregate coverage for the target binary class and all binary classes whose names start with `<targetBinaryName>$` (including member/anonymous/local classes).
-- `Related test classes`: existing `TargetClassName + Test` classes resolvable within the same module's test scope.
-- `Assertion differences`: distinguishable assertions in externally observable results or side effects.
-- `Necessity reason tag`: fixed-format tag for retention reasons, using `KEEP:<id>:<reason>`, recorded in the "Implementation and Optimization" section of the delivery report.
-- `Baseline quality summary`: one pre-edit diagnostic run that combines rule scanning, candidate summary, and coverage evidence for the current scope.
-- `Verification snapshot digest`: content hash over `<ResolvedTestFileSet>` used to decide whether a previous green verification result is still reusable.
-- `Gate reuse state`: persisted mapping from logical gate names (for example `target-test`, `coverage`, `rule-scan`) to the latest green digest for that gate.
-- `Latest green target-test digest`: compatibility alias for the `target-test` entry in `Gate reuse state`.
-- `Consolidated hard-gate scan`: one script execution that enforces `R8`, `R14`, and all file-content-based `R15` rules while still reporting results per rule.
-- `SUT-owned behavior`: branches, state changes, call choices, returned values, or exception handling that the target class itself decides.
-- `Collaborator-owned behavior`: rules a dependency computes, classifies, parses, loads, matches, or defaults, such as SPI, registry, factory, parser, loader, metadata option, driver option, dialect default, exception classification, message parsing, or SQLState parsing.
-- `Testing through layers`: a unit test for the target class whose inputs, branch triggers, or assertions encode collaborator-owned behavior instead of mocking the collaborator result consumed by the target class.
-
-Module resolution order:
-1. If the user explicitly provides modules, use them first.
-2. Otherwise, resolve by searching upward for the nearest parent `pom.xml` from `<ResolvedTestFileSet>` paths.
-3. Otherwise, resolve by searching upward for the nearest parent `pom.xml` from target class source paths.
-
-## Mandatory Constraints
-
-- Norm levels: `MUST` (required), `SHOULD` (preferred), `MAY` (optional).
-- Definition source principle: mandatory constraints are defined only in this `R1-R15` section; other sections only provide term/workflow/command descriptions and must not add, override, or relax `R1-R15`.
-
-- `R1`: `MUST` comply with `AGENTS.md` and `CODE_OF_CONDUCT.md`; rule interpretation should prioritize corresponding clauses and line-number evidence in `CODE_OF_CONDUCT.md`.
-
-- `R2`: test types and naming
-  - Non-parameterized scenarios `MUST` use JUnit `@Test`.
-  - Data-driven scenarios `MUST` use JUnit `@ParameterizedTest(name = "{0}")` with `@MethodSource` + `Arguments`.
-  - Parameterized test method signatures `MUST` use `final String name` as the first parameter.
-  - Parameterized tests `MUST NOT` use `Consumer` (including `java.util.function.Consumer` and its generic forms) in method signatures or scenario-transport arguments.
-  - Each parameterized test `MUST` provide at least 3 `Arguments` rows; fewer than 3 is a violation and `MUST` be converted to non-parameterized `@Test`.
-  - Parameterized tests `MUST NOT` introduce new nested type declarations (member/local helper `class` / `interface` / `enum` / `record`) for scenario transport; use `Arguments` rows plus existing or JDK types instead.
-  - `MUST NOT` use `@RepeatedTest`.
-  - Test method naming `MUST` follow `CODE_OF_CONDUCT.md`: use the `assert` prefix; when a single test uniquely covers a production method, use `assert<MethodName>`.
-
-- `R3`: change and execution scope
-  - Edit scope `MUST` be limited to `<ResolvedTestFileSet>`.
-  - Path scope `MUST` be limited to `src/test/java` and `src/test/resources`.
-  - `MUST NOT` modify production code or generated directories (such as `target/`).
-  - `MUST NOT` modify other test files to fix failures outside scope; if scope expansion is needed, `MUST` be explicitly approved by the user in the current turn.
-  - `MUST NOT` use destructive git operations (for example, `git reset --hard`, `git checkout --`).
-
-- `R4`: branch list and mapping
-  - Before coding, `MUST` enumerate branches/paths of target public methods and build branch-to-test mappings.
-  - Branch mapping `MUST` classify each planned branch trigger and assertion as `SUT-owned behavior` or `Collaborator-owned behavior`.
-  - Branch mapping `MUST NOT` count collaborator-owned rules as target-class branches; when the target class only consumes a collaborator result, map the target branch from the consumed result, not from a real collaborator implementation that happens to produce it.
-  - Branch mapping scope `MUST` exclude Lombok-generated methods without custom logic.
-  - By default, one branch/path maps to one test method.
-  - Whether to keep additional tests on the same branch is determined by `R13`.
-
-- `R5`: test granularity
-  - Each test method `MUST` cover only one scenario.
-  - Each test method `MUST` call the target public method at most once; additional assertions are allowed in the same scenario.
-  - For parameterized tests, each `Arguments` row `MUST` represent one independent scenario and one branch/path mapping unit for `R4`.
-  - For parameterized tests, `Arguments` row count `MUST` be greater than or equal to 3.
-  - Tests `MUST` exercise behavior through public methods only.
-  - Coverage-relevant invocations of target public methods `MUST` appear in test method bodies together with assertions for the externally observable result of that invocation.
-  - Helper methods and `@MethodSource` providers `MUST NOT` invoke target public methods merely to warm caches, precompute coverage, or otherwise execute target behavior without assertions in the same test method body.
-  - Public production methods with business logic `MUST` be covered with dedicated test methods.
-  - For interface targets, only `default` public methods are required test targets by default, and non-`default` public methods `MUST NOT` be tested unless the user explicitly requests them in the current turn.
-  - Dedicated test targets `MUST` follow the `R4` branch-mapping exclusion scope.
-
-- `R6`: SPI, Mock, and reflection
-  - For interface `default` methods, this rule overrides SPI instantiation requirements in `R6`: tests `MUST` use Mockito `CALLS_REAL_METHODS` to invoke real default implementations, and this path does not require SPI-bypass justification.
-  - If the class under test can be obtained via SPI, `MUST` instantiate by default with `TypedSPILoader`/`OrderedSPILoader` (or database-specific loaders), and `MUST` keep the resolved instance as a test-class-level field (global variable) by default.
-  - SPI metadata accessor methods `TypedSPI#getType`, `OrderedSPI#getOrder`, and `getTypeClass` are default no-test-required targets.
-  - For these accessors, tests `MUST NOT` be added by default; they are allowed only when the user explicitly requests tests for them in the current turn.
-  - If such tests are added without explicit request, they `MUST` be removed before completion.
-  - If not instantiated via SPI, `MUST` record the reason before implementation.
-  - Test dependencies `SHOULD` use Mockito mocks by default.
-  - When a target-class branch depends on collaborator-owned behavior, tests `MUST` mock the nearest stable collaborator boundary to return the needed result and `MUST NOT` choose a real collaborator implementation only to trigger the branch.
-  - Simple value objects, pure data fixtures, and explicitly scoped integration, contract, or E2E tests are exceptions to the collaborator-boundary mocking rule.
-  - Reflection access `MUST` use `Plugins.getMemberAccessor()`, and field access only.
-
-- `R7`: related test class strategy
-  - If related test classes already exist, `MUST` update in place and fill missing coverage first.
-  - If no related test class exists, `MUST` create `<TargetClassName>Test`.
-  - If the user explicitly provides a test class list, it is only used as execution filtering input and `MUST NOT` replace the "in-place update of related test classes" strategy.
-  - Deletion/merge of coverage-equivalent tests is determined by `R13`.
-
-- `R8`: parameterized optimization (enabled by default)
-  - `MUST` run pre-implementation candidate analysis and output an `R8-CANDIDATES` record (target public method, candidate count, decision, and evidence).
-  - `MUST` report the mergeable method set and merge candidate count.
-  - Candidates meeting all conditions below are considered "high-fit for parameterization":
-    - A. target public method and branch skeleton are consistent;
-    - B. scenario differences mainly come from input data;
-    - C. assertion skeleton is consistent, or only declared assertion differences exist;
-    - D. parameter sample count is at least 3;
-    - E. parameterized test body does not require dispatch logic via `switch`.
-  - "Declared assertion differences" means differences explicitly recorded in the delivery report.
-  - Scenarios whose differences mainly encode collaborator-owned behavior are not high-fit target-class parameterization candidates, even when the method and assertion skeletons are otherwise consistent.
-  - If a candidate requires `switch` in a `@ParameterizedTest` body to distinguish argument rows, it is not high-fit and `MUST NOT` be refactored to parameterized form.
-  - High-fit candidates `MUST` be refactored directly to parameterized form.
-  - For high-fit candidates, a "do not recommend refactor" conclusion is allowed only when refactoring causes significant readability/diagnosability regression, and the exception `MUST` include a `Necessity reason tag` with concrete evidence.
-  - Parameter construction `MUST` use `Arguments + @MethodSource`.
-  - `MUST` provide either a "recommend refactor" or "do not recommend refactor" conclusion with reasons for each candidate; when no candidates exist, `MUST` output "no candidates + decision reason".
-  - If high-fit candidates exist but neither parameterized refactor nor valid `KEEP` evidence is present, status `MUST NOT` be concluded as `R10-A`.
-
-- `R9`: dead code and coverage blockers
-  - When dead code blocks progress, `MUST` report class name, file path, exact line number, and unreachable reason.
-  - Within this skill scope, `MUST NOT` bypass dead code by modifying production code.
-
-- `R10`: state machine and completion criteria
-  - `R10-INPUT_BLOCKED`: missing target classes, or unable to determine `<ResolvedTestModules>`.
-  - `R10-A` (done): all of the following must be satisfied:
-    - scope satisfies `R3`;
-    - target test command succeeds, and surefire report has `Tests run > 0` (recommended to also satisfy `Tests run - Skipped > 0`);
-    - coverage evidence satisfies the target (default class/line/branch 100%, unless explicitly lowered by the user);
-    - each class in `<ResolvedTargetClasses>` has explicit aggregated class-level coverage evidence (CLASS/LINE/BRANCH counters with covered/missed/ratio) over the `Target-class coverage scope`, and all ratios satisfy the declared target;
-    - Checkstyle, Spotless, two `R14` scans, and all required `R15` scans all pass;
-    - `R8` analysis and compliance evidence are complete, including `R8-CANDIDATES` and candidate-level decisions (refactor or valid `KEEP` evidence).
-  - `R10-B` (blocked): under the "production code cannot be changed" constraint, dead code blocks coverage targets, and evidence satisfies `R9`.
-  - `R10-C` (blocked): failure occurs outside `R3` scope, and evidence satisfies `R11`.
-  - `R10-D` (in-progress): none of `R10-INPUT_BLOCKED/R10-B/R10-C/R10-A` is satisfied yet.
-  - Decision priority: `R10-INPUT_BLOCKED` > `R10-B` > `R10-C` > `R10-A` > `R10-D`.
-  - `MUST NOT` conclude the task as completed while in `R10-D`; continue implementation and verification loops until reaching a terminal state.
-
-- `R11`: failure handling
-  - If failure is within `R3` scope: `MUST` fix within `<ResolvedTestFileSet>` and rerun minimal verification.
-  - If failure is outside `R3` scope: `MUST` record blocking evidence (failed command, exit code, key error lines, blocking file/line) and request user decision.
-  - Minimal verification is defined as "target test command + one `R14` hard-gate scan command".
-  - Minimal verification is only for in-scope repair and `MUST NOT` replace final gating of `R10-A`.
-  - Retryable errors (temporary plugin resolution failure, mirror timeout, transient network jitter) `MAY` retry up to 2 times.
-
-- `R12`: 100% coverage optimization mode
-  - If target class coverage evidence is already 100%, `MUST` skip coverage completion and execute only `R8` parameterized optimization.
-  - Coverage judgment `MUST` be reproducible (command + report path).
-  - In this mode, `MAY` omit `R4` branch mapping output, but `MUST` mark `R4=N/A (triggered by R12)` in rule mapping and attach coverage evidence.
-
-- `R13`: test necessity trimming
-  - Trimming order `MUST` be fixed as "objective trimming -> exception retention review".
-  - In objective trimming stage, `MUST` first remove coverage-equivalent tests and re-verify coverage uniformly, then remove redundant mock/stub/assertion and single-use local variables that do not affect branch selection/collaborator interaction behavior (call count, parameters)/observable assertions; if retention significantly improves readability, `MAY` keep and mark `Necessity reason tag`.
-  - Local variable declarations in test code `MUST NOT` use `final`; this rule applies only to local variables and does not change `R15-E` for parameterized-test method parameters.
-  - Each retained item `MUST` carry a `KEEP:<id>:<reason>` tag and be recorded in the delivery report; items without tags are treated as redundant.
-  - Each test method `MUST` provide unique value: cover a new branch/path, or add assertion differences.
-  - If deleting a test method does not change line/branch coverage and has no assertion differences, `MUST` delete it.
-  - If a test method, mock setup, data row, or assertion only verifies collaborator-owned behavior, it `MUST` be removed from the target-class unit test; if collaborator coverage is missing, report the need for a separate collaborator-focused test scope instead of editing outside `R3`.
-  - Unless scenario requires otherwise, `SHOULD` use Mockito default return values instead of extra stubs.
-
-- `R14`: boolean assertion hard gate
-  - Boolean literal/boolean constant assertions `MUST` use `assertTrue`/`assertFalse`.
-  - For boolean assertions where expected value is variable-driven (for example: parameter/local variable/field), `MUST` use `assertThat(actual, is(expected))`.
-  - `MUST NOT` dispatch boolean assertions through control flow (for example `if/else`, `switch`, or ternary) only to choose between `assertTrue` and `assertFalse`.
-  - `MUST NOT` use:
-    - `assertThat(<boolean expression>, is(true|false|Boolean.TRUE|Boolean.FALSE))`
-    - `assertEquals(true|false|Boolean.TRUE|Boolean.FALSE, ...)`
-    - `assertEquals(..., true|false|Boolean.TRUE|Boolean.FALSE)`
-  - `MUST` run one hard-gate scan after implementation and another before delivery; any hit means incomplete.
-
-- `R15`: pre-delivery hard gates
-  - `R15-A` (parameterization enforcement): if an `R8` high-fit candidate exists, the corresponding tests `MUST` be parameterized with `@ParameterizedTest(name = "{0}")`, unless a valid `KEEP` exception is recorded.
-  - `R15-B` (metadata accessor test ban): unless the user explicitly requests it in the current turn, tests targeting `getType` / `getOrder` / `getTypeClass` `MUST NOT` be added.
-  - `R15-C` (scope mutation guard): test-generation tasks `MUST NOT` introduce new diffs under any `src/main/` path.
-  - `R15-D` (parameterized argument floor): each `@ParameterizedTest` `MUST` bind to `@MethodSource` providers that together contain at least 3 `Arguments` rows; otherwise it is a violation.
-  - `R15-E` (parameterized name parameter): each `@ParameterizedTest` method `MUST` declare the first parameter exactly as `final String name`.
-  - `R15-F` (parameterized switch ban): `@ParameterizedTest` method bodies `MUST NOT` contain `switch` statements.
-  - `R15-G` (parameterized nested-type ban): when a file contains `@ParameterizedTest`, newly introduced diff lines `MUST NOT` add nested helper type declarations (`class` / `interface` / `enum` / `record`) inside the test class.
-  - `R15-H` (boolean variable assertion style): for variable-driven boolean expectations, tests `MUST` assert with `assertThat(actual, is(expected))`, and `MUST NOT` use control-flow dispatch only to choose `assertTrue`/`assertFalse`.
-  - `R15-I` (parameterized Consumer ban): files containing `@ParameterizedTest` `MUST NOT` introduce or retain `Consumer`-based scenario transport in parameterized method signatures or `@MethodSource` argument rows.
-  - `R15-J` (assertion-backed target invocation): non-test helper methods and `@MethodSource` providers `MUST NOT` invoke target public methods; target public method invocations that contribute to coverage `MUST` be asserted in the same test method body.
+## Inputs and Scope
+
+Require target production classes, preferably as fully-qualified names. Accept an optional module and optional test-class execution filter.
+Discover related tests by the exact `<TargetClassName>Test` convention and update them in place; create that class only when none exists.
+
+Resolve:
+
+- `<ResolvedTargetClasses>`: requested production classes.
+- `<ResolvedTestFileSet>`: only related test Java files and required test resources that may be edited.
+- `<ResolvedTestModules>`: explicit Maven modules owning those tests.
+- `<ResolvedTestClass>`: focused test-class filter for execution.
+
+Use an explicitly supplied module first. Otherwise resolve the nearest owning `pom.xml` from test files, then target sources.
+If target classes or modules cannot be resolved, return `R10-INPUT_BLOCKED`.
+
+## Ownership Terms
+
+- `SUT-owned behavior`: decisions, branches, state changes, calls, results, or error handling owned by the target class.
+- `Collaborator-owned behavior`: behavior computed by an SPI, registry, factory, parser, loader, driver, dialect, metadata option, or another dependency.
+- `Testing through layers`: driving or asserting collaborator-owned rules instead of mocking the result consumed by the target.
+- `KEEP:<id>:<reason>`: evidence for retaining an otherwise redundant candidate because removal materially harms readability or diagnosis.
+- `Task scope baseline`: structured pre-edit snapshot of the allowed test files and every dirty path outside them.
+
+## Mandatory Rules
+
+`MUST`, `SHOULD`, and `MAY` are normative. This section is the source of `R1-R15`; workflow and command examples do not override it.
+
+### R1: Repository authority
+
+Follow `AGENTS.md` and the applicable `CODE_OF_CONDUCT.md` sections. Their authority, safety, command-output, completion-loop, and unit-test rules remain in force.
+
+### R2: Test form and naming
+
+- Use JUnit 5 `@Test` for standalone scenarios.
+- Use `@ParameterizedTest(name = "{0}")`, `@MethodSource`, and `Arguments` for data-driven scenarios. Declare `final String name` first and provide at least three rows.
+- Do not use `@RepeatedTest`, `Consumer` as scenario transport, `switch` dispatch inside parameterized tests, or new nested transport types.
+- Follow repository test naming. A single test uniquely covering one public method is `assert<MethodName>`.
+
+### R3: Change boundary
+
+- Edit only `<ResolvedTestFileSet>` under `src/test/java` or `src/test/resources`.
+- Do not edit production, generated output, unrelated tests, or another file type.
+- Capture `Task scope baseline` after resolving the file set and before editing. Any candidate-relevant changed path outside that set is a failure,
+  including further mutation of a path already dirty at task start. Exclude only untracked or ignored reproducible verification outputs such as Maven `target/`
+  and Python `__pycache__/`; they are not editable scope and must not be modified intentionally.
+- Obtain explicit approval before expanding scope. Never use destructive Git operations.
+
+### R4: Branch map
+
+- Before coding, enumerate target public-method branches and map each planned scenario to one branch or path.
+- Classify every trigger and assertion as SUT-owned or collaborator-owned. Mock the nearest stable boundary for collaborator results.
+- Exclude Lombok-generated behavior without custom logic. Default to one test per branch or path; use `R13` for additional cases.
+
+### R5: Scenario granularity
+
+- Keep one scenario per test and invoke the target public method at most once per scenario.
+- Keep the coverage-relevant invocation and its externally observable assertions in the test body. Helpers and providers must not execute target behavior.
+- Give every behavior-owning public method focused coverage.
+- For interface targets, test only `default` methods unless the user explicitly requests abstract methods.
+
+### R6: SPI, mocks, and reflection
+
+- Exercise interface default methods with Mockito `CALLS_REAL_METHODS`.
+- Obtain SPI targets through the applicable project loader and keep the resolved instance as a test-class field by default. Record a concrete reason before bypassing the loader.
+- Do not add tests for `getType`, `getOrder`, or `getTypeClass` unless explicitly requested.
+- Mock heavy dependencies and collaborator-owned decisions. Allow real simple values and explicitly scoped integration, contract, or E2E behavior.
+- Use `Plugins.getMemberAccessor()` only for permitted field access; never invoke private methods reflectively.
+
+### R7: Related tests
+
+Update existing related tests in place and fill missing coverage first. An explicit test-class input filters execution only; it does not replace related-test discovery.
+Create a new exact-name test class only when none exists.
+
+### R8: Parameterization analysis
+
+For each target public method, record `R8-CANDIDATES` with the method, candidate count, decision, and evidence. A candidate is high-fit only when all are true:
+
+1. target method and branch skeleton are consistent;
+2. differences are mainly input data;
+3. assertion skeleton is consistent or differences are explicitly declared;
+4. at least three scenarios exist;
+5. no `switch` dispatch is required.
+
+Collaborator-owned differences are not high-fit. Refactor high-fit candidates; otherwise record the concrete reason.
+Use `KEEP` only when a genuinely high-fit refactor would materially reduce readability or diagnosis.
+
+The scanner discovers possible groups but never decides semantic high-fit. Treat its candidate count as evidence to review, not an instruction to refactor.
+
+### R9: Coverage blockers
+
+When unreachable production code blocks coverage, report the class, path, exact line, and reason. Do not change production code within this Skill.
+
+### R10: Completion state
+
+Use exactly one state:
+
+- `R10-INPUT_BLOCKED`: target classes or test modules cannot be resolved.
+- `R10-A`: scope is clean; focused tests execute at least one test; declared target coverage is met for every target and inner class;
+  repository formatting/checkstyle gates pass; both final rule scans pass; semantic reviews and `R8` decisions are complete.
+- `R10-B`: production dead code blocks the target and `R9` evidence is complete.
+- `R10-C`: an out-of-scope failure is evidenced under `R11`.
+- `R10-D`: work remains; continue instead of claiming completion.
+
+Priority is `INPUT_BLOCKED > B > C > A > D`. Default coverage is 100% CLASS, LINE, and BRANCH unless the user lowers it.
+
+### R11: Failures
+
+Fix in-scope failures and rerun the focused test plus mechanical rule scan. For out-of-scope failures, record command, exit code,
+decisive lines, and blocking file/line, then request direction. Retry transient dependency or network failures at most twice.
+Minimal repair checks never replace final gates.
+
+### R12: Existing full coverage
+
+If reproducible target-class evidence is already 100%, skip coverage completion and perform only required optimization and quality work.
+Mark `R4=N/A (triggered by R12)` and retain the coverage command and report path.
+
+### R13: Necessity trimming
+
+- Treat equal line/branch coverage only as a duplicate candidate, never as removal proof.
+- Remove a test only when it adds no unique branch, input class, boundary, calculation path, failure mode, contract, collaborator interaction, or externally observable regression protection.
+- Remove collaborator-only tests from the target unit test and report the separate owner when coverage is needed there.
+- Remove redundant stubs, assertions, and locals that affect neither behavior nor diagnosis. Prefer Mockito defaults when the scenario permits.
+- Apply `KEEP` only to an otherwise redundant item retained for a concrete readability or diagnostic reason; meaningful tests need no tag.
+- Do not declare local variables `final`.
+
+### R14: Boolean assertions
+
+Use `assertTrue`/`assertFalse` for literal or constant expectations and `assertThat(actual, is(expected))` for variable expectations.
+Do not use boolean `assertEquals`, boolean literals inside Hamcrest `is`, or control flow whose only purpose is selecting
+`assertTrue` versus `assertFalse`. Run the mechanical scan after implementation stabilizes and again immediately before delivery.
+
+### R15: Delivery gates
+
+- `R15-A`: complete the semantic `R8` decision; the scanner cannot infer high-fit.
+- `R15-B`: confirm any metadata-accessor candidate was explicitly requested; the scanner only reports likely candidates.
+- `R15-C`: compare the final worktree with `Task scope baseline`; any candidate-relevant out-of-scope mutation fails. Ignore only reproducible,
+  untracked or Git-ignored verification outputs.
+- `R15-D`: every parameterized test uses `@MethodSource` with at least three `Arguments` rows. Inspect external providers manually.
+- `R15-E`: the first parameter is exactly `final String name`.
+- `R15-F`: parameterized bodies contain no `switch`.
+- `R15-G`: parameterized test changes add no nested transport type.
+- `R15-H`: boolean assertions obey `R14` without assertion-dispatch control flow.
+- `R15-I`: parameterized signatures and provider rows contain no `Consumer`; inspect external providers manually.
+- `R15-J`: helpers and providers do not invoke target public methods. Treat scanner results as partial evidence and inspect unresolved ownership manually.
 
 ## Workflow
 
-1. Read `AGENTS.md` and `CODE_OF_CONDUCT.md`, and record hard constraints for this round (`R1`).
-   - Capture scope baseline once: `git status --porcelain > /tmp/gen-ut-status-before.txt`.
-2. Parse target classes, related test classes, and input-blocked state (`R10-INPUT_BLOCKED`).
-3. Resolve `<ResolvedTestClass>`, `<ResolvedTestFileSet>`, `<ResolvedTestModules>`, and record `pom.xml` evidence (`R3`).
-4. Run a `Baseline quality summary` using the bundled baseline script unless equivalent evidence was just produced in the same turn.
-    - Use the baseline summary to identify current branch-miss lines, existing `R15` risks, and likely `R8-CANDIDATES` before editing.
-    - `SHOULD` fix deterministic precheck warnings from the baseline summary before the first standalone target-test run; these warnings are advisory only and do not replace final `checkstyle` / `spotless` / hard-gate verification.
-5. Decide whether `R12` is triggered; if not, output `R4` branch mapping.
-   - Before outputting `R4`, record the target-class ownership boundary: `SUT owns`, `Collaborator owns`, and the mocked collaborator boundary used for each collaborator-owned result consumed by the target.
-   - For parser / utility classes that return context or value objects, `SHOULD` align planned assertions with the returned object's public API before the first target-test run, to avoid internal-branch coverage assertions that do not match externally observable behavior.
-6. Execute `R8` parameterized optimization analysis, output `R8-CANDIDATES`, and apply required refactoring.
-7. Execute `R9` dead-code checks and record evidence.
-8. Complete test implementation or extension according to `R2-R7`.
-9. Perform necessity trimming and coverage re-verification according to `R13`.
-10. After each edit batch, `SHOULD` run one lightweight precheck pass before expensive verification when signatures or parameterized-test structure changed.
-    - Recommended command: `python3 scripts/scan_quality_rules.py --precheck-only <ResolvedTestFileSet>`.
-    - This pass is advisory and deterministic; it may fail fast on early style issues such as missing `final` on test-method parameters, missing `@MethodSource`, too-few `Arguments` rows, or an invalid first parameter for parameterized tests, but it does not replace formal `R14` / `R15` / `checkstyle` verification.
-11. After each edit batch, recompute the `Verification snapshot digest`; during in-scope repair loops, prefer `target test + one consolidated hard-gate scan` as the minimal verification required by `R11`.
-    - After any standalone target-test command succeeds, `SHOULD` persist the digest through `scripts/verification_gate_state.py mark-gate-green --gate target-test`.
-12. Run final verification commands and handle failures by `R11`.
-    - Independent final gates (`coverage`, `checkstyle`, `spotless`, `consolidated hard-gate scan`) `SHOULD` run in parallel when the environment allows; otherwise serialize them.
-    - Prefer the bundled `scripts/run_quality_gates.py` runner so independent gates share one orchestration entry and can reuse gate-level green results from `Gate reuse state`.
-    - If `scripts/verification_gate_state.py match-gate-green --gate target-test` reports a match for the current `<ResolvedTestFileSet>`, and the final coverage command re-executes tests on that same digest, `MAY` skip an extra standalone target-test rerun before delivery.
-    - A previously green `coverage` gate `MAY` be reused for the same digest; `checkstyle` and `spotless` `SHOULD` still execute for the current module scope.
-    - The consolidated hard-gate scan `MUST` be executed twice to satisfy `R14`: once after implementation stabilizes and once immediately before delivery. Only the earlier scan may be reused for diagnostics; the delivery scan must execute again.
-13. Decide status by `R10` after verification; if status is `R10-D`, return to Step 5 and continue.
-14. Before final response, run a second `R10` status decision and output `R10=<state>` with rule-to-evidence mapping.
-
-## Verification and Commands
-
-Flag presets:
-- Module input provided:
-  - `<TestModuleFlags>` = `-pl <module>`
-  - `<GateModuleFlags>` = `-pl <module>`
-- Module input not provided:
-  - `<TestModuleFlags>` = `-pl <ResolvedTestModules>`
-  - `<GateModuleFlags>` = `-pl <ResolvedTestModules>`
-  - `<FallbackGateModuleFlags>` = `<GateModuleFlags> -am` (for troubleshooting missing cross-module dependencies only; does not change `R3` and `R10`).
-
-0. Baseline quality summary (recommended before editing):
-```bash
-python3 scripts/collect_quality_baseline.py --workdir <RepoRoot> \
-  --coverage-command "./mvnw <GateModuleFlags> -DskipITs -Dsurefire.useManifestOnlyJar=false -Dtest=<ResolvedTestClass> -DfailIfNoTests=true -Dsurefire.failIfNoSpecifiedTests=false -Djacoco.skip=false -Djacoco.append=false -Djacoco.destFile=/tmp/gen-ut-baseline.exec test jacoco:report -Djacoco.dataFile=/tmp/gen-ut-baseline.exec" \
-  --jacoco-xml-path <JacocoXmlPath> \
-  --target-classes <ResolvedTargetClasses> \
-  --baseline-before /tmp/gen-ut-status-before.txt \
-  <ResolvedTestFileSet>
-```
-The baseline script reuses `scan_quality_rules.py` diagnostics and prints current coverage plus branch-miss lines for each target class.
-It also prints deterministic non-blocking precheck warnings for high-frequency style failures such as missing `final` on test-method parameters or obvious parameterized-test structure issues; these warnings are for early repair only and do not replace formal gates.
-
-0.1 Lightweight precheck pass (recommended after structural edits and before the next standalone target-test):
-```bash
-python3 scripts/scan_quality_rules.py --precheck-only <ResolvedTestFileSet>
-```
-This mode is intentionally narrower than the consolidated hard-gate scan. It exists only to catch deterministic early-fix issues cheaply and `MUST NOT` be used as a replacement for final `R14`, `R15`, `checkstyle`, or `spotless` verification.
-
-1. Target tests:
-```bash
-./mvnw <TestModuleFlags> -DskipITs -Dspotless.skip=true -Dtest=<ResolvedTestClass> -DfailIfNoTests=true -Dsurefire.failIfNoSpecifiedTests=false test
-```
-After a green standalone target-test command, record the digest:
-```bash
-python3 scripts/verification_gate_state.py mark-gate-green --state-file /tmp/gen-ut-gate-state.json --gate target-test <ResolvedTestFileSet>
-```
-
-1.1 Verification snapshot digest:
-```bash
-python3 scripts/verification_gate_state.py digest <ResolvedTestFileSet>
-```
-
-1.2 Latest green target-test digest reuse check:
-```bash
-python3 scripts/verification_gate_state.py match-gate-green --state-file /tmp/gen-ut-gate-state.json --gate target-test <ResolvedTestFileSet>
-```
-
-2. Coverage:
-```bash
-./mvnw <GateModuleFlags> -DskipITs -Djacoco.skip=false test jacoco:report jacoco:check@jacoco-check -Pcoverage-check
-```
-If the module does not define `jacoco-check@jacoco-check`:
-```bash
-./mvnw <GateModuleFlags> -DskipITs -Djacoco.skip=false test jacoco:report
-```
-After a green standalone coverage command, the digest may be recorded for reuse:
-```bash
-python3 scripts/verification_gate_state.py mark-gate-green --state-file /tmp/gen-ut-gate-state.json --gate coverage <ResolvedTestFileSet>
-```
-
-2.1 Target-class coverage hard gate (default target 100 unless explicitly lowered, aggregated over `Target-class coverage scope`):
-```bash
-bash -lc '
-python3 - <JacocoXmlPath> <TargetRatioPercent> <ResolvedTargetClasses> <<'"'"'PY'"'"'
-import sys
-import xml.etree.ElementTree as ET
-xml_path, target = sys.argv[1], float(sys.argv[2])
-target_classes = [each.strip() for each in sys.argv[3].split(",") if each.strip()]
-if not target_classes:
-    print("[R10] empty target class list")
-    sys.exit(1)
-all_classes = list(ET.parse(xml_path).getroot().iter("class"))
-all_ok = True
-for fqcn in target_classes:
-    class_name = fqcn.replace(".", "/")
-    matched_nodes = [each for each in all_classes if each.get("name") == class_name or each.get("name", "").startswith(class_name + "$")]
-    if not matched_nodes:
-        print(f"[R10] class not found in jacoco.xml: {fqcn}")
-        all_ok = False
-        continue
-    for counter_type in ("CLASS", "LINE", "BRANCH"):
-        covered = 0
-        missed = 0
-        found_counter = False
-        for each in matched_nodes:
-            counter = next((c for c in each.findall("counter") if c.get("type") == counter_type), None)
-            if counter is None:
-                continue
-            found_counter = True
-            covered += int(counter.get("covered"))
-            missed += int(counter.get("missed"))
-        if not found_counter:
-            print(f"[R10] missing {counter_type} counter for {fqcn}")
-            all_ok = False
-            continue
-        total = covered + missed
-        ratio = 100.0 if total == 0 else covered * 100.0 / total
-        print(f"[R10] {fqcn} (+inner) {counter_type} covered={covered} missed={missed} ratio={ratio:.2f}%")
-        if ratio + 1e-9 < target:
-            print(f"[R10] {fqcn} (+inner) {counter_type} ratio {ratio:.2f}% < target {target:.2f}%")
-            all_ok = False
-if not all_ok:
-    sys.exit(1)
-PY
-'
-```
-
-3. Checkstyle:
-```bash
-./mvnw <GateModuleFlags> -Pcheck checkstyle:check -DskipTests
-```
-
-4. Spotless:
-```bash
-./mvnw <GateModuleFlags> -Pcheck spotless:check -DskipTests
-```
-If missing cross-module dependencies occur, rerun the gate command above once with `<FallbackGateModuleFlags>` and record the trigger reason and result.
-
-4.1 Unified final-gate runner (recommended):
-```bash
-python3 scripts/run_quality_gates.py --workdir <RepoRoot> \
-  --state-file /tmp/gen-ut-gate-state.json \
-  --tracked-path <ResolvedTestFileSet> \
-  --reuse-gate coverage \
-  --record-gate coverage \
-  --record-gate hard-gate=rule-scan \
-  --gate coverage="./mvnw <GateModuleFlags> -DskipITs -Djacoco.skip=false test jacoco:report" \
-  --gate checkstyle="./mvnw <GateModuleFlags> -Pcheck checkstyle:check -DskipTests" \
-  --gate spotless="./mvnw <GateModuleFlags> -Pcheck spotless:check -DskipTests" \
-  --gate hard-gate="python3 scripts/scan_quality_rules.py --baseline-before /tmp/gen-ut-status-before.txt <ResolvedTestFileSet>"
-```
-If the environment cannot or should not parallelize, rerun the same command with `--serial`.
-Coverage still remains the authoritative source for target-class counters, and the runner does not relax any gate.
-
-5. Consolidated hard-gate scan (`R8`, `R14`, `R15-A/B/C/D/E/F/G/H/I/J`):
-```bash
-python3 scripts/scan_quality_rules.py --baseline-before /tmp/gen-ut-status-before.txt <ResolvedTestFileSet>
-```
-If the user explicitly requested metadata accessor tests in the current turn:
-```bash
-python3 scripts/scan_quality_rules.py --allow-metadata-accessor-tests --baseline-before /tmp/gen-ut-status-before.txt <ResolvedTestFileSet>
-```
-The script consolidates repeated file parsing and git-diff inspection without changing rule accuracy. It also evaluates `R15-C` by comparing the current git status against `/tmp/gen-ut-status-before.txt`.
-For machine-readable automation or quick summaries, the script also supports:
-```bash
-python3 scripts/scan_quality_rules.py --json --baseline-before /tmp/gen-ut-status-before.txt <ResolvedTestFileSet>
-python3 scripts/scan_quality_rules.py --summary-only --baseline-before /tmp/gen-ut-status-before.txt <ResolvedTestFileSet>
-```
-
-6. Scope validation:
-```bash
-git diff --name-only
-```
-
-## Final Output Requirements
-
-- `MUST` include a status line `R10=<state>`.
-- `MUST` include aggregated class-level coverage evidence for each class in `<ResolvedTargetClasses>` over the `Target-class coverage scope` (CLASS/LINE/BRANCH counters and ratios).
-- `MUST` include `R8-CANDIDATES` output (candidate set, counts, and per-candidate decision evidence).
-- `MUST` include executed commands and exit codes.
-- If `R10` is not `R10-A`, `MUST` explicitly mark the task as not completed and provide blocking reason plus next action.
-- `MUST NOT` use completion wording when `R10` is `R10-D`.
+1. Read `AGENTS.md`, `CODE_OF_CONDUCT.md`, and [references/verification.md](references/verification.md).
+2. Resolve targets, related tests, editable files, modules, and input-blocked state.
+3. Create a task-specific temporary directory and capture `Task scope baseline` for the resolved file set.
+4. Run focused baseline coverage through the repository command wrapper, then use `collect_quality_baseline.py` to report coverage and mechanical risks.
+5. Decide `R12`; otherwise record the SUT/collaborator ownership boundary and `R4` branch map.
+6. Review scanner candidates against every `R8` condition and record candidate-level decisions.
+7. Check `R9`, then implement the smallest tests allowed by `R2-R7`.
+8. After each coherent edit, run the lightweight precheck, focused test, and mechanical scan.
+9. Apply `R13`, re-run coverage, and inspect semantic `R15-A/B/D/I/J` obligations.
+10. Run final coverage, repository formatting/checkstyle gates, and the two required mechanical scans.
+11. Recheck scope against the baseline and decide `R10` twice before delivery.
+
+Do not reuse a prior task's test or coverage result. Final coverage must execute tests for the effective candidate.
+
+## Output
+
+Include:
+
+- `R10=<state>`;
+- aggregated CLASS/LINE/BRANCH counters and ratios for every target plus inner classes;
+- `R8-CANDIDATES` with candidate decisions and evidence;
+- branch/ownership mapping, or the `R12` exemption;
+- executed commands, exit codes, and bounded log paths/summaries;
+- rule-to-evidence mapping for `R1-R15`;
+- blocker and next action when state is not `R10-A`.
+
+Never use completion wording for `R10-D`.
diff --git a/.codex/skills/gen-ut/references/verification.md b/.codex/skills/gen-ut/references/verification.md
new file mode 100644
index 00000000000..09021bc0e8e
--- /dev/null
+++ b/.codex/skills/gen-ut/references/verification.md
@@ -0,0 +1,110 @@
+<!--
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+
+# Verification Commands
+
+Run commands from the repository root. Before every Maven command, apply the Mandatory Execution Contract in
+`.codex/context/token-efficiency.md`; place the Maven command inside its canonical wrapper and report only the bounded summary,
+log path, and exit code.
+
+## Task setup
+
+Create one private temporary directory per task and use it for all transient reports:
+
+```bash
+task_dir="$(mktemp -d -t shardingsphere-gen-ut.XXXXXX)"
+python3 .codex/skills/gen-ut/scripts/scan_quality_rules.py \
+  --capture-scope-baseline "$task_dir/scope-baseline.json" \
+  <ResolvedTestFileSet>
+```
+
+Do not use shared fixed files under `/tmp`. Keep the temporary directory through delivery so logs and evidence remain inspectable.
+The scope guard excludes untracked or ignored Maven `target/` files and Python `__pycache__/` files because the required verification commands create them.
+It still rejects tracked files in those directories and other ignored files outside the resolved test file set.
+
+## Baseline
+
+Run focused tests with a task-specific JaCoCo data file:
+
+```bash
+./mvnw -pl <ResolvedTestModules> -DskipITs -Dspotless.skip=true \
+  -Dtest=<ResolvedTestClass> -Dsurefire.failIfNoSpecifiedTests=false \
+  -Djacoco.skip=false -Djacoco.append=false \
+  -Djacoco.destFile="$task_dir/baseline.exec" test jacoco:report \
+  -Djacoco.dataFile="$task_dir/baseline.exec"
+```
+
+Then print the baseline without executing another shell command:
+
+```bash
+python3 .codex/skills/gen-ut/scripts/collect_quality_baseline.py \
+  --jacoco-xml-path <JacocoXmlPath> \
+  --target-classes <ResolvedTargetClasses> \
+  --scope-baseline "$task_dir/scope-baseline.json" \
+  <ResolvedTestFileSet>
+```
+
+`coverageStatus=missing` means required target, CLASS, or LINE evidence does not exist; it never means 100%.
+For a present target with no BRANCH counter, report `covered=0 missed=0 ratio=100%` because JaCoCo omits zero-total branch counters.
+
+## Edit-loop checks
+
+Run the structural precheck before an expensive build when signatures or parameterized-test structure changed:
+
+```bash
+python3 .codex/skills/gen-ut/scripts/scan_quality_rules.py \
+  --precheck-only <ResolvedTestFileSet>
+```
+
+Run focused tests after each coherent edit:
+
+```bash
+./mvnw -pl <ResolvedTestModules> -DskipITs -Dspotless.skip=true \
+  -Dtest=<ResolvedTestClass> -Dsurefire.failIfNoSpecifiedTests=false test
+```
+
+Then run the mechanical rules and scope guard:
+
+```bash
+python3 .codex/skills/gen-ut/scripts/scan_quality_rules.py \
+  --scope-baseline "$task_dir/scope-baseline.json" \
+  <ResolvedTestFileSet>
+```
+
+The scanner labels semantic or partly semantic rules as `semanticReviewRequired=true`. Resolve them through source inspection and record evidence; zero mechanical violations alone is not `R10-A`.
+
+## Final coverage
+
+Run focused coverage again for the effective candidate. Use the module's configured JaCoCo check when present; otherwise run `test jacoco:report` and enforce target ratios with the bundled reporter:
+
+```bash
+python3 .codex/skills/gen-ut/scripts/collect_quality_baseline.py \
+  --jacoco-xml-path <JacocoXmlPath> \
+  --target-classes <ResolvedTargetClasses> \
+  --minimum-ratio <TargetRatioPercent> \
+  --scope-baseline "$task_dir/scope-baseline.json" \
+  <ResolvedTestFileSet>
+```
+
+Missing target classes, CLASS counters, or LINE counters fail when `--minimum-ratio` is present. A branchless target satisfies BRANCH coverage with zero missed branches.
+
+## Repository completion gates
+
+After the last edit, run the exact Spotless and Checkstyle commands required by `AGENTS.md`, through the canonical output wrapper.
+Do not replace `spotless:apply` with `spotless:check`. Re-run invalidated checks after any later edit.
+
+Run the mechanical scan once after implementation stabilizes and once immediately before delivery. The second scan must execute; do not reuse its earlier result.
diff --git a/.codex/skills/gen-ut/scripts/collect_quality_baseline.py b/.codex/skills/gen-ut/scripts/collect_quality_baseline.py
index 02643c98176..ffa1ba3a2e4 100644
--- a/.codex/skills/gen-ut/scripts/collect_quality_baseline.py
+++ b/.codex/skills/gen-ut/scripts/collect_quality_baseline.py
@@ -21,11 +21,8 @@ Collect a baseline quality summary for gen-ut before editing begins.
 """
 
 import argparse
-import subprocess
 import sys
-import time
 import xml.etree.ElementTree as ET
-from dataclasses import dataclass
 from pathlib import Path
 
 
@@ -36,27 +33,6 @@ if str(SCRIPT_DIR) not in sys.path:
 import scan_quality_rules as quality_rules
 
 
-@dataclass(frozen=True)
-class CommandResult:
-    command: str
-    returncode: int
-    stdout: str
-    stderr: str
-    duration_seconds: float
-
-
-def run_command(command: str, workdir: Path) -> CommandResult:
-    started = time.monotonic()
-    completed = subprocess.run(command, shell=True, cwd=workdir, capture_output=True, text=True)
-    return CommandResult(
-        command=command,
-        returncode=completed.returncode,
-        stdout=completed.stdout,
-        stderr=completed.stderr,
-        duration_seconds=time.monotonic() - started,
-    )
-
-
 def parse_target_classes(raw: str) -> list[str]:
     result = [each.strip() for each in raw.split(",") if each.strip()]
     if result:
@@ -64,17 +40,8 @@ def parse_target_classes(raw: str) -> list[str]:
     raise ValueError("target-classes must not be empty")
 
 
-def validate_workdir(path: Path) -> Path:
-    workdir = path.resolve()
-    if not workdir.exists():
-        raise ValueError(f"working directory does not exist: {workdir}")
-    if not workdir.is_dir():
-        raise ValueError(f"working directory is not a directory: {workdir}")
-    return workdir
-
-
 def find_sourcefile_node(root: ET.Element, fqcn: str) -> ET.Element | None:
-    package_name, simple_name = fqcn.rsplit(".", 1)
+    package_name, _, simple_name = fqcn.rpartition(".")
     package_path = package_name.replace(".", "/")
     source_name = f"{simple_name}.java"
     for package in root.findall("package"):
@@ -86,26 +53,35 @@ def find_sourcefile_node(root: ET.Element, fqcn: str) -> ET.Element | None:
     return None
 
 
-def summarize_target_coverage(root: ET.Element, fqcn: str) -> tuple[dict[str, tuple[int, int, float]], list[int]]:
+def summarize_target_coverage(root: ET.Element, fqcn: str) -> tuple[bool, dict[str, tuple[int, int, float] | None], list[int]]:
     class_name = fqcn.replace(".", "/")
     matched_nodes = [each for each in root.iter("class") if each.get("name") == class_name or each.get("name", "").startswith(class_name + "$")]
-    counters = {}
+    counters: dict[str, tuple[int, int, float] | None] = {}
     for counter_type in ("CLASS", "LINE", "BRANCH"):
         covered = 0
         missed = 0
+        found_counter = False
         for each in matched_nodes:
             counter = next((item for item in each.findall("counter") if item.get("type") == counter_type), None)
             if counter is None:
                 continue
+            found_counter = True
             covered += int(counter.get("covered"))
             missed += int(counter.get("missed"))
         total = covered + missed
-        counters[counter_type] = (covered, missed, 100.0 if 0 == total else covered * 100.0 / total)
+        if found_counter:
+            counters[counter_type] = (covered, missed, 100.0 if 0 == total else covered * 100.0 / total)
+        else:
+            counters[counter_type] = (0, 0, 100.0) if matched_nodes and "BRANCH" == counter_type else None
     sourcefile = find_sourcefile_node(root, fqcn)
     missed_branch_lines = []
     if sourcefile is not None:
         missed_branch_lines = [int(each.get("nr")) for each in sourcefile.findall("line") if int(each.get("mb", "0")) > 0]
-    return counters, missed_branch_lines
+    return bool(matched_nodes), counters, missed_branch_lines
+
+
+def meets_target(found: bool, counters: dict[str, tuple[int, int, float] | None], minimum_ratio: float) -> bool:
+    return found and all(counters[each] is not None and counters[each][2] + 1e-9 >= minimum_ratio for each in ("CLASS", "LINE", "BRANCH"))
 
 
 def print_rule_baseline(scan_result: dict) -> None:
@@ -123,7 +99,15 @@ def print_rule_baseline(scan_result: dict) -> None:
             for each in violations:
                 print(each)
         else:
-            print(f"[{rule}] ok")
+            mode = scan_result["rules"][rule]["mode"]
+            if "automated" == mode:
+                print(f"[{rule}] ok")
+            elif "manual" == mode:
+                print(f"[{rule}] semanticReviewRequired=true")
+            else:
+                print(f"[{rule}] mechanical=ok semanticReviewRequired=true")
+            for each in scan_result.get("reviews", {}).get(rule, []):
+                print(f"review: {each}")
     prechecks = scan_result.get("prechecks", {})
     for name in sorted(prechecks):
         violations = prechecks[name]["violations"]
@@ -135,61 +119,63 @@ def print_rule_baseline(scan_result: dict) -> None:
             print(each)
 
 
-def print_coverage_baseline(jacoco_xml_path: Path, target_classes: list[str]) -> None:
+def print_coverage_baseline(jacoco_xml_path: Path, target_classes: list[str], minimum_ratio: float | None) -> bool:
     root = ET.parse(jacoco_xml_path).getroot()
+    result = True
     for fqcn in target_classes:
-        counters, missed_branch_lines = summarize_target_coverage(root, fqcn)
+        found, counters, missed_branch_lines = summarize_target_coverage(root, fqcn)
+        if not found:
+            print(f"[baseline] {fqcn} coverageStatus=missing")
+            result = False
+            continue
         for counter_type in ("CLASS", "LINE", "BRANCH"):
-            covered, missed, ratio = counters[counter_type]
+            counter = counters[counter_type]
+            if counter is None:
+                print(f"[baseline] {fqcn} (+inner) {counter_type} coverageStatus=missing")
+                result = False
+                continue
+            covered, missed, ratio = counter
             print(f"[baseline] {fqcn} (+inner) {counter_type} covered={covered} missed={missed} ratio={ratio:.2f}%")
         if missed_branch_lines:
             line_text = ",".join(str(each) for each in missed_branch_lines)
             print(f"[baseline] {fqcn} branchMissLines={line_text}")
         else:
             print(f"[baseline] {fqcn} branchMissLines=none")
+        if minimum_ratio is not None and not meets_target(found, counters, minimum_ratio):
+            result = False
+    return result
 
 
 def main() -> int:
     parser = argparse.ArgumentParser(description="Collect baseline coverage and quality-rule diagnostics for gen-ut.")
-    parser.add_argument("--workdir", default=".", help="Working directory for the coverage command.")
-    parser.add_argument("--coverage-command", required=True, help="Shell command that generates the jacoco report for the target test scope.")
     parser.add_argument("--jacoco-xml-path", required=True, help="Path to the jacoco.xml generated by the coverage command.")
     parser.add_argument("--target-classes", required=True, help="Comma-separated target production classes.")
-    parser.add_argument("--baseline-before", help="Path to the baseline git status captured at task start.")
-    parser.add_argument("--allow-metadata-accessor-tests", action="store_true", help="Allow R15-B when the user explicitly requested metadata accessor tests.")
+    parser.add_argument("--scope-baseline", help="Structured task scope baseline created by scan_quality_rules.py.")
+    parser.add_argument("--minimum-ratio", type=float, help="Fail unless every target CLASS, LINE, and BRANCH ratio meets this percentage.")
     parser.add_argument("paths", nargs="+", help="Resolved test file set.")
     args = parser.parse_args()
 
     try:
-        workdir = validate_workdir(Path(args.workdir))
         target_classes = parse_target_classes(args.target_classes)
+        if args.minimum_ratio is not None and not 0.0 <= args.minimum_ratio <= 100.0:
+            raise ValueError("minimum-ratio must be between 0 and 100")
     except ValueError as ex:
         parser.error(str(ex))
-    java_paths = [Path(each) for each in args.paths if each.endswith(".java")]
-    baseline_path = Path(args.baseline_before) if args.baseline_before else None
-    scan_result = quality_rules.collect_scan_result(java_paths, baseline_path, args.allow_metadata_accessor_tests)
+    paths = [Path(each) for each in args.paths]
+    baseline_path = Path(args.scope_baseline) if args.scope_baseline else None
+    scan_result = quality_rules.collect_scan_result(paths, baseline_path)
+    rules_ok = not quality_rules.failed_rule_names(scan_result)
     print_rule_baseline(scan_result)
-    coverage_result = run_command(args.coverage_command, workdir)
-    print(f"[baseline] coverageCommandExit={coverage_result.returncode} duration={coverage_result.duration_seconds:.2f}s")
-    print(f"[baseline] coverageCommand={coverage_result.command}")
-    if 0 != coverage_result.returncode:
-        if coverage_result.stdout.strip():
-            print("[baseline] coverageStdout:")
-            print(coverage_result.stdout.rstrip())
-        if coverage_result.stderr.strip():
-            print("[baseline] coverageStderr:")
-            print(coverage_result.stderr.rstrip())
-        return coverage_result.returncode
     jacoco_xml_path = Path(args.jacoco_xml_path)
     if not jacoco_xml_path.exists():
         print(f"[baseline] missingJacocoXml={jacoco_xml_path}", file=sys.stderr)
         return 2
     try:
-        print_coverage_baseline(jacoco_xml_path, target_classes)
+        coverage_ok = print_coverage_baseline(jacoco_xml_path, target_classes, args.minimum_ratio)
     except (OSError, ET.ParseError) as ex:
         print(f"[baseline] invalidJacocoXml={jacoco_xml_path}: {ex}", file=sys.stderr)
         return 2
-    return 0
+    return 0 if args.minimum_ratio is None or coverage_ok and rules_ok else 1
 
 
 if __name__ == "__main__":
diff --git a/.codex/skills/gen-ut/scripts/run_quality_gates.py b/.codex/skills/gen-ut/scripts/run_quality_gates.py
deleted file mode 100644
index e41b4ba5559..00000000000
--- a/.codex/skills/gen-ut/scripts/run_quality_gates.py
+++ /dev/null
@@ -1,286 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements.  See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License.  You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-#!/usr/bin/env python3
-"""
-Run independent quality gates in parallel with optional gate-level reuse.
-"""
-
-import argparse
-import json
-import sys
-import subprocess
-import time
-from concurrent.futures import ThreadPoolExecutor, as_completed
-from dataclasses import dataclass
-from pathlib import Path
-
-
-SCRIPT_DIR = Path(__file__).resolve().parent
-if str(SCRIPT_DIR) not in sys.path:
-    sys.path.insert(0, str(SCRIPT_DIR))
-
-import verification_gate_state as snapshot_state
-
-
-@dataclass(frozen=True)
-class GateSpec:
-    name: str
-    command: str
-
-
-@dataclass(frozen=True)
-class GateResult:
-    spec: GateSpec
-    status: str
-    returncode: int
-    stdout: str
-    stderr: str
-    duration_seconds: float
-    state_gate: str | None = None
-    digest: str | None = None
-
-
-def parse_gate(raw: str) -> GateSpec:
-    if "=" not in raw:
-        raise ValueError(f"invalid gate definition: {raw!r}")
-    name, command = raw.split("=", 1)
-    name = name.strip()
-    command = command.strip()
-    if not name or not command:
-        raise ValueError(f"invalid gate definition: {raw!r}")
-    return GateSpec(name=name, command=command)
-
-
-def parse_gates(raw_gates: list[str]) -> list[GateSpec]:
-    result = []
-    seen_names = set()
-    for each in raw_gates:
-        spec = parse_gate(each)
-        if spec.name in seen_names:
-            raise ValueError(f"duplicate gate name: {spec.name}")
-        seen_names.add(spec.name)
-        result.append(spec)
-    return result
-
-
-def parse_gate_mapping(raw: str) -> tuple[str, str]:
-    if "=" not in raw:
-        normalized = raw.strip()
-        if not normalized:
-            raise ValueError(f"invalid gate mapping: {raw!r}")
-        return normalized, normalized
-    gate_name, gate_key = raw.split("=", 1)
-    gate_name = gate_name.strip()
-    gate_key = gate_key.strip()
-    if not gate_name or not gate_key:
-        raise ValueError(f"invalid gate mapping: {raw!r}")
-    return gate_name, gate_key
-
-
-def parse_gate_mappings(raw_values: list[str]) -> dict[str, str]:
-    result = {}
-    for each in raw_values:
-        gate_name, gate_key = parse_gate_mapping(each)
-        if gate_name in result and result[gate_name] != gate_key:
-            raise ValueError(f"duplicate gate mapping for {gate_name}: {result[gate_name]} vs {gate_key}")
-        result[gate_name] = gate_key
-    return result
-
-
-def validate_gate_mappings(specs: list[GateSpec], mappings: dict[str, str], option_name: str) -> None:
-    valid_names = {each.name for each in specs}
-    unknown = sorted(each for each in mappings if each not in valid_names)
-    if unknown:
-        raise ValueError(f"{option_name} references unknown gate(s): {', '.join(unknown)}")
-
-
-def flatten_tracked_paths(values: list[list[str]]) -> list[str]:
-    result = []
-    for group in values:
-        result.extend(group)
-    return result
-
-
-def validate_workdir(path: Path) -> Path:
-    workdir = path.resolve()
-    if not workdir.exists():
-        raise ValueError(f"working directory does not exist: {workdir}")
-    if not workdir.is_dir():
-        raise ValueError(f"working directory is not a directory: {workdir}")
-    return workdir
-
-
-def validate_state_inputs(tracked_paths: list[str], reuse_mapping: dict[str, str], record_mapping: dict[str, str], state_file: str | None) -> None:
-    if not state_file and (reuse_mapping or record_mapping):
-        raise ValueError("state-file is required when reuse-gate or record-gate is configured")
-    if state_file and not tracked_paths:
-        raise ValueError("tracked-path is required when state-file is configured")
-
-
-def current_digest(tracked_paths: list[str]) -> tuple[str, int]:
-    normalized_paths = snapshot_state.tracked_paths(tracked_paths)
-    return snapshot_state.calculate_digest(normalized_paths), len(normalized_paths)
-
-
-def gate_digest(base_digest: str, spec: GateSpec, workdir: Path) -> str:
-    return snapshot_state.extend_digest(base_digest, [str(workdir), spec.name, spec.command])
-
-
-def run_gate(spec: GateSpec, workdir: Path) -> GateResult:
-    started = time.monotonic()
-    completed = subprocess.run(spec.command, shell=True, cwd=workdir, capture_output=True, text=True)
-    return GateResult(
-        spec=spec,
-        status="executed",
-        returncode=completed.returncode,
-        stdout=completed.stdout,
-        stderr=completed.stderr,
-        duration_seconds=time.monotonic() - started,
-    )
-
-
-def run_serial(specs: list[GateSpec], workdir: Path) -> list[GateResult]:
-    return [run_gate(spec, workdir) for spec in specs]
-
-
-def run_parallel(specs: list[GateSpec], workdir: Path, max_parallel: int) -> list[GateResult]:
-    ordered_results: list[GateResult | None] = [None] * len(specs)
-    with ThreadPoolExecutor(max_workers=max_parallel) as executor:
-        future_to_index = {executor.submit(run_gate, spec, workdir): index for index, spec in enumerate(specs)}
-        for future in as_completed(future_to_index):
-            ordered_results[future_to_index[future]] = future.result()
-    return [each for each in ordered_results if each is not None]
-
-
-def reusable_result(spec: GateSpec, gate_key: str, digest: str) -> GateResult:
-    return GateResult(spec=spec, status="reused", returncode=0, stdout="", stderr="", duration_seconds=0.0, state_gate=gate_key, digest=digest)
-
-
-def print_result(result: GateResult) -> None:
-    if "reused" == result.status:
-        print(f"[gate:{result.spec.name}] reused gate={result.state_gate} digest={result.digest}")
-        return
-    print(f"[gate:{result.spec.name}] exit={result.returncode} duration={result.duration_seconds:.2f}s")
-    print(f"[gate:{result.spec.name}] cmd={result.spec.command}")
-    if 0 != result.returncode:
-        if result.stdout.strip():
-            print(f"[gate:{result.spec.name}] stdout:")
-            print(result.stdout.rstrip())
-        if result.stderr.strip():
-            print(f"[gate:{result.spec.name}] stderr:")
-            print(result.stderr.rstrip())
-
-
-def load_state(state_file: str | None) -> dict:
-    return snapshot_state.read_state(Path(state_file)) if state_file else {}
-
-
-def gate_digests(specs: list[GateSpec], base_digest: str | None, workdir: Path) -> dict[str, str]:
-    if base_digest is None:
-        return {}
-    return {each.name: gate_digest(base_digest, each, workdir) for each in specs}
-
-
-def partition_specs_for_execution(
-        specs: list[GateSpec], reuse_mapping: dict[str, str], digests: dict[str, str], state: dict,
-) -> tuple[list[GateResult | None], list[GateSpec], list[int]]:
-    indexed_results: list[GateResult | None] = [None] * len(specs)
-    executable_specs = []
-    executable_indices = []
-    for index, spec in enumerate(specs):
-        gate_key = reuse_mapping.get(spec.name)
-        gate_result_digest = digests.get(spec.name)
-        if gate_key and gate_result_digest and snapshot_state.matches_gate_digest(state, gate_key, gate_result_digest):
-            indexed_results[index] = reusable_result(spec, gate_key, gate_result_digest)
-            continue
-        executable_specs.append(spec)
-        executable_indices.append(index)
-    return indexed_results, executable_specs, executable_indices
-
-
-def execute_specs(specs: list[GateSpec], workdir: Path, max_parallel: int) -> list[GateResult]:
-    if 1 == max_parallel:
-        return run_serial(specs, workdir)
-    return run_parallel(specs, workdir, max_parallel)
-
-
-def mark_green_gates(
-        state: dict, record_mapping: dict[str, str], results: list[GateResult], gate_digests: dict[str, str], tracked_file_count: int | None,
-) -> bool:
-    if not gate_digests or tracked_file_count is None:
-        return False
-    updated = False
-    for each in results:
-        if "executed" != each.status or 0 != each.returncode or each.spec.name not in record_mapping:
-            continue
-        snapshot_state.set_gate_digest(state, record_mapping[each.spec.name], gate_digests[each.spec.name], tracked_file_count)
-        updated = True
-    return updated
-
-
-def main() -> int:
-    parser = argparse.ArgumentParser(description="Run independent quality gates in parallel.")
-    parser.add_argument("--workdir", default=".", help="Working directory for every gate command.")
-    parser.add_argument("--serial", action="store_true", help="Run gates serially instead of in parallel.")
-    parser.add_argument("--max-parallel", type=int, default=4, help="Maximum parallel gate count.")
-    parser.add_argument("--state-file", help="Optional state file used for gate-level reuse.")
-    parser.add_argument("--tracked-path", nargs="+", action="append", default=[], help="Tracked file paths used to compute the verification digest.")
-    parser.add_argument("--reuse-gate", action="append", default=[], help="Reuse mapping in the form gate-name[=state-gate].")
-    parser.add_argument("--record-gate", action="append", default=[], help="Record mapping in the form gate-name[=state-gate].")
-    parser.add_argument("--gate", action="append", required=True, help="Gate definition in the form name=command.")
-    args = parser.parse_args()
-
-    try:
-        workdir = validate_workdir(Path(args.workdir))
-        specs = parse_gates(args.gate)
-        reuse_mapping = parse_gate_mappings(args.reuse_gate)
-        record_mapping = parse_gate_mappings(args.record_gate)
-        validate_gate_mappings(specs, reuse_mapping, "--reuse-gate")
-        validate_gate_mappings(specs, record_mapping, "--record-gate")
-        tracked_paths = flatten_tracked_paths(args.tracked_path)
-        validate_state_inputs(tracked_paths, reuse_mapping, record_mapping, args.state_file)
-    except ValueError as ex:
-        parser.error(str(ex))
-    try:
-        base_digest = None
-        tracked_file_count = None
-        state = load_state(args.state_file)
-        if tracked_paths:
-            base_digest, tracked_file_count = current_digest(tracked_paths)
-        gate_digest_map = gate_digests(specs, base_digest, workdir)
-        max_parallel = 1 if args.serial else max(1, min(args.max_parallel, len(specs)))
-        print(f"[quality-gates] mode={'serial' if 1 == max_parallel else 'parallel'} gateCount={len(specs)} workdir={workdir}")
-        indexed_results, executable_specs, executable_indices = partition_specs_for_execution(specs, reuse_mapping, gate_digest_map, state)
-        executed_results = execute_specs(executable_specs, workdir, max_parallel)
-        for index, result in zip(executable_indices, executed_results):
-            indexed_results[index] = result
-        results = [each for each in indexed_results if each is not None]
-        failed = False
-        for each in results:
-            print_result(each)
-            failed = failed or 0 != each.returncode
-        if args.state_file and mark_green_gates(state, record_mapping, results, gate_digest_map, tracked_file_count):
-            snapshot_state.write_state(Path(args.state_file), state)
-        return 1 if failed else 0
-    except (ValueError, OSError, json.JSONDecodeError) as ex:
-        print(ex, file=sys.stderr)
-        return 2
-
-
-if __name__ == "__main__":
-    sys.exit(main())
diff --git a/.codex/skills/gen-ut/scripts/scan_quality_rules.py b/.codex/skills/gen-ut/scripts/scan_quality_rules.py
index 74bdeaab467..bd4a1b7ce59 100644
--- a/.codex/skills/gen-ut/scripts/scan_quality_rules.py
+++ b/.codex/skills/gen-ut/scripts/scan_quality_rules.py
@@ -16,13 +16,15 @@
 #
 
 #!/usr/bin/env python3
-"""
-Consolidated quality-rule scan for gen-ut.
-"""
+"""Mechanical quality-rule scan and task-scope guard for gen-ut."""
 
 import argparse
+import difflib
+import hashlib
 import json
+import os
 import re
+import stat
 import subprocess
 import sys
 from collections import defaultdict
@@ -37,13 +39,13 @@ class CandidateSummary:
     method: str
     plain_test_count: int
     parameterized_present: bool
-    high_fit: bool
 
 
 @dataclass(frozen=True)
 class RuleSpec:
     name: str
     message: str
+    mode: str
 
 
 @dataclass(frozen=True)
@@ -55,6 +57,7 @@ class FileScanContext:
     candidates: list[CandidateSummary]
     target_type_name: str | None
     target_public_methods: set[str]
+    added_lines: list[str]
 
 
 RULE_ORDER = ("R8", "R14", "R15-A", "R15-B", "R15-C", "R15-D", "R15-E", "R15-F", "R15-G", "R15-H", "R15-I", "R15-J")
@@ -71,22 +74,29 @@ PRECHECK_MESSAGES = {
 RULE_MESSAGES = {
     "R8": "@ParameterizedTest must use name = \"{0}\"",
     "R14": "forbidden boolean assertion found",
-    "R15-A": "high-fit candidate likely exists but no parameterized test found",
-    "R15-B": "metadata accessor test detected without explicit user request",
-    "R15-C": "out-of-scope production path modified",
+    "R15-A": "parameterization suitability requires semantic evidence",
+    "R15-B": "metadata accessor candidates require request-scope review",
+    "R15-C": "out-of-scope worktree mutation detected",
     "R15-D": "each @ParameterizedTest must have >= 3 Arguments rows from @MethodSource",
     "R15-E": "each @ParameterizedTest method must declare first parameter as `final String name`",
     "R15-F": "@ParameterizedTest method body must not contain switch",
     "R15-G": "parameterized tests must not introduce nested helper type declarations",
     "R15-H": "do not dispatch boolean assertions by control flow to choose assertTrue/assertFalse",
     "R15-I": "parameterized tests must not use Consumer in signatures or @MethodSource argument rows",
-    "R15-J": "non-test helpers and @MethodSource providers must not invoke target public methods without assertions in test bodies",
+    "R15-J": "helper and provider target invocations require semantic ownership review",
 }
-RULE_SPECS = tuple(RuleSpec(each, RULE_MESSAGES[each]) for each in RULE_ORDER)
+RULE_MODES = {
+    "R15-A": "manual",
+    "R15-B": "manual",
+    "R15-D": "hybrid",
+    "R15-I": "hybrid",
+    "R15-J": "hybrid",
+}
+RULE_SPECS = tuple(RuleSpec(each, RULE_MESSAGES[each], RULE_MODES.get(each, "automated")) for each in RULE_ORDER)
 BOOLEAN_ASSERTION_BAN_PATTERN = re.compile(
-    r"assertThat\s*\((?s:.*?)is\s*\(\s*(?:true|false|Boolean\.TRUE|Boolean\.FALSE)\s*\)\s*\)"
+    r"assertThat\s*\((?s:[^;]*?)is\s*\(\s*(?:true|false|Boolean\.TRUE|Boolean\.FALSE)\s*\)\s*\)"
     r"|assertEquals\s*\(\s*(?:true|false|Boolean\.TRUE|Boolean\.FALSE)\s*,"
-    r"|assertEquals\s*\((?s:.*?),\s*(?:true|false|Boolean\.TRUE|Boolean\.FALSE)\s*\)",
+    r"|assertEquals\s*\((?s:[^;]*?),\s*(?:true|false|Boolean\.TRUE|Boolean\.FALSE)\s*\)",
     re.S,
 )
 CONSUMER_TOKEN_PATTERN = re.compile(r"\bConsumer\s*(?:<|\b)")
@@ -128,13 +138,6 @@ R15_H_IF_RETURN_PATTERN = re.compile(
 )
 R15_NAME_PATTERN = re.compile(r'name\s*=\s*"\{0\}"')
 R15_SWITCH_PATTERN = re.compile(r"\bswitch\s*\(")
-R15_B_PATTERN = re.compile(
-    r"@Test(?s:.*?)void\s+assert\w*(GetType|GetOrder|GetTypeClass)\b"
-    r"|assertThat\((?s:.*?)\.getType\(\)"
-    r"|assertThat\((?s:.*?)\.getOrder\(\)"
-    r"|assertThat\((?s:.*?)\.getTypeClass\(\)",
-    re.S,
-)
 TYPE_DECL_LINE_PATTERN = re.compile(
     r"^\s*(?:(?:public|protected|private|static|final|abstract|sealed|non-sealed)\s+)*(class|interface|enum|record)\s+(\w+)\b"
 )
@@ -142,14 +145,89 @@ PUBLIC_METHOD_DECL_PATTERN = re.compile(
     r"^\s*public\s+(?:default\s+)?(?:static\s+)?(?:final\s+)?[\w$<>\[\], ?]+\s+(\w+)\s*\(",
     re.M,
 )
-UNTRACKED_STATUS_PREFIX = "?? "
 CONSTRUCTOR_TEST_PREFIXES = ("New", "Construct", "Constructor")
+TEST_SCOPE_MARKERS = ("src/test/java/", "src/test/resources/")
+MAVEN_OUTPUT_DIRECTORY = "target"
+PYTHON_CACHE_DIRECTORY = "__pycache__"
+PYTHON_CACHE_SUFFIXES = frozenset((".pyc", ".pyo"))
 
 
 def line_number(source: str, index: int) -> int:
     return source.count("\n", 0, index) + 1
 
 
+def mask_java_non_code(source: str, mask_literals: bool) -> str:
+    result = list(source)
+    index = 0
+    state = "code"
+    while index < len(source):
+        if "line-comment" == state:
+            if "\n" == source[index]:
+                state = "code"
+            else:
+                result[index] = " "
+            index += 1
+            continue
+        if "block-comment" == state:
+            if source.startswith("*/", index):
+                result[index:index + 2] = [" ", " "]
+                index += 2
+                state = "code"
+            else:
+                if "\n" != source[index]:
+                    result[index] = " "
+                index += 1
+            continue
+        if state in ("string", "character"):
+            delimiter = '"' if "string" == state else "'"
+            if "\\" == source[index] and index + 1 < len(source):
+                if mask_literals:
+                    result[index:index + 2] = [" ", " "]
+                index += 2
+                continue
+            if mask_literals and "\n" != source[index]:
+                result[index] = " "
+            if delimiter == source[index]:
+                state = "code"
+            index += 1
+            continue
+        if "text-block" == state:
+            if source.startswith('"""', index):
+                if mask_literals:
+                    result[index:index + 3] = [" ", " ", " "]
+                index += 3
+                state = "code"
+            else:
+                escaped = "\\" == source[index] and index + 1 < len(source)
+                if mask_literals:
+                    result[index] = " " if "\n" != source[index] else "\n"
+                    if escaped and "\n" != source[index + 1]:
+                        result[index + 1] = " "
+                index += 2 if escaped else 1
+            continue
+        if source.startswith("//", index):
+            result[index:index + 2] = [" ", " "]
+            index += 2
+            state = "line-comment"
+        elif source.startswith("/*", index):
+            result[index:index + 2] = [" ", " "]
+            index += 2
+            state = "block-comment"
+        elif source.startswith('"""', index):
+            if mask_literals:
+                result[index:index + 3] = [" ", " ", " "]
+            index += 3
+            state = "text-block"
+        elif source[index] in ('"', "'"):
+            if mask_literals:
+                result[index] = " "
+            state = "string" if '"' == source[index] else "character"
+            index += 1
+        else:
+            index += 1
+    return "".join(result)
+
+
 def opening_brace_index(match: re.Match[str]) -> int:
     return match.end() - 1
 
@@ -216,10 +294,6 @@ def parse_method_sources(method_name: str, annotation_block: str) -> list[str]:
     return result
 
 
-def parse_method_bodies(source: str) -> dict[str, str]:
-    return {name: body for name, (_, body) in parse_method_blocks(source).items()}
-
-
 def parse_method_blocks(source: str) -> dict[str, tuple[int, str]]:
     result = {}
     for match in METHOD_DECL_PATTERN.finditer(source):
@@ -231,41 +305,192 @@ def parse_method_blocks(source: str) -> dict[str, tuple[int, str]]:
     return result
 
 
-def run_git_command(args: list[str], *, allow_failure: bool = False) -> str:
+def run_git_command(args: list[str], *, cwd: Path | None = None, allow_failure: bool = False) -> str:
     try:
-        return subprocess.run(args, check=True, capture_output=True, text=True).stdout
+        return subprocess.run(args, cwd=cwd, check=True, capture_output=True, text=True).stdout
     except subprocess.CalledProcessError:
         if allow_failure:
             return ""
         raise
 
 
-def get_git_diff_lines(path: Path, *, cached: bool = False) -> list[str]:
-    command = ["git", "diff"]
-    if cached:
-        command.append("--cached")
-    command.extend(["-U0", "--", str(path)])
-    return run_git_command(command, allow_failure=True).splitlines()
+def get_repo_root(path: Path | None = None) -> Path:
+    output = run_git_command(["git", "rev-parse", "--show-toplevel"], cwd=path)
+    return Path(output.strip()).resolve()
 
 
-def get_status_line_for_path(path: Path) -> str | None:
-    output = run_git_command(["git", "status", "--porcelain", "--", str(path)], allow_failure=True)
-    lines = [each for each in output.splitlines() if each]
-    return lines[0] if lines else None
+def get_head(repo_root: Path) -> str | None:
+    result = run_git_command(["git", "rev-parse", "--verify", "HEAD"], cwd=repo_root, allow_failure=True).strip()
+    return result or None
 
 
-def get_added_lines_for_path(path: Path) -> list[str]:
+def normalize_repo_paths(repo_root: Path, paths: list[Path]) -> list[str]:
     result = []
-    for cached in (False, True):
-        result.extend(get_git_diff_lines(path, cached=cached))
-    if result:
-        return list(dict.fromkeys(result))
-    status_line = get_status_line_for_path(path)
-    if status_line and status_line.startswith(UNTRACKED_STATUS_PREFIX):
-        return [f"+{each}" for each in path.read_text(encoding="utf-8").splitlines()]
+    for each in paths:
+        resolved = (repo_root / each).resolve() if not each.is_absolute() else each.resolve()
+        try:
+            relative = resolved.relative_to(repo_root)
+        except ValueError as ex:
+            raise ValueError(f"path is outside repository: {resolved}") from ex
+        result.append(relative.as_posix())
+    return sorted(set(result))
+
+
+def validate_test_scope_paths(paths: list[str]) -> None:
+    invalid = [each for each in paths if not any(marker in each for marker in TEST_SCOPE_MARKERS)]
+    if invalid:
+        raise ValueError(f"path is outside test scope: {invalid[0]}")
+
+
+def fingerprint_path(path: Path) -> str:
+    digest = hashlib.sha256()
+    if path.is_symlink():
+        digest.update(b"symlink\0")
+        digest.update(str(path.readlink()).encode("utf-8", errors="surrogateescape"))
+        return digest.hexdigest()
+    if not path.exists():
+        return "missing"
+    if path.is_dir():
+        return "directory"
+    digest.update(b"file\0")
+    digest.update(str(stat.S_IMODE(path.stat().st_mode)).encode("ascii"))
+    digest.update(b"\0")
+    with path.open("rb") as input_file:
+        while chunk := input_file.read(64 * 1024):
+            digest.update(chunk)
+    return digest.hexdigest()
+
+
+def parse_status_entries(raw: bytes) -> dict[str, str]:
+    records = raw.split(b"\0")
+    result = {}
+    index = 0
+    while index < len(records):
+        record = records[index]
+        index += 1
+        if not record:
+            continue
+        if len(record) < 4 or b" " != record[2:3]:
+            raise ValueError("unexpected git status --porcelain output")
+        status = record[:2].decode("ascii")
+        path = record[3:].decode("utf-8", errors="surrogateescape")
+        result[path] = status
+        if status[0] in "RC" or status[1] in "RC":
+            if index >= len(records) or not records[index]:
+                raise ValueError("incomplete rename entry in git status output")
+            old_path = records[index].decode("utf-8", errors="surrogateescape")
+            result[old_path] = "rename-source"
+            index += 1
     return result
 
 
+def is_maven_target_output(repo_root: Path, path: Path, module_cache: dict[Path, bool]) -> bool:
+    for index, each in enumerate(path.parts):
+        if MAVEN_OUTPUT_DIRECTORY != each:
+            continue
+        module_path = Path(*path.parts[:index])
+        if module_path not in module_cache:
+            module_cache[module_path] = (repo_root / module_path / "pom.xml").is_file()
+        if module_cache[module_path]:
+            return True
+    return False
+
+
+def is_reproducible_verification_output(repo_root: Path, path: str, status: str, module_cache: dict[Path, bool]) -> bool:
+    if status not in ("??", "!!"):
+        return False
+    relative_path = Path(path)
+    python_cache = PYTHON_CACHE_DIRECTORY in relative_path.parts and relative_path.suffix in PYTHON_CACHE_SUFFIXES
+    return python_cache or is_maven_target_output(repo_root, relative_path, module_cache)
+
+
+def collect_worktree_entries(repo_root: Path, allowed_paths: set[str]) -> dict[str, dict[str, str]]:
+    completed = subprocess.run(
+        ["git", "status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=traditional"],
+        cwd=repo_root, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+    )
+    module_cache = {}
+    return {
+        path: {"status": status, "fingerprint": fingerprint_path(repo_root / path)}
+        for path, status in parse_status_entries(completed.stdout).items()
+        if path not in allowed_paths and not is_reproducible_verification_output(repo_root, path, status, module_cache)
+    }
+
+
+def build_scope_snapshot(repo_root: Path, allowed_paths: list[Path]) -> dict:
+    normalized_allowed = normalize_repo_paths(repo_root, allowed_paths)
+    validate_test_scope_paths(normalized_allowed)
+    return {
+        "version": 1,
+        "repo_root": str(repo_root),
+        "head": get_head(repo_root),
+        "allowed_paths": normalized_allowed,
+        "allowed_contents": {
+            each: (repo_root / each).read_text(encoding="utf-8") if each.endswith(".java") and (repo_root / each).is_file() else None
+            for each in normalized_allowed
+        },
+        "outside_entries": collect_worktree_entries(repo_root, set(normalized_allowed)),
+    }
+
+
+def write_scope_baseline(output_path: Path, repo_root: Path, allowed_paths: list[Path]) -> None:
+    repo_root = repo_root.resolve()
+    output_path = output_path.resolve()
+    try:
+        output_path.relative_to(repo_root)
+    except ValueError:
+        pass
+    else:
+        raise ValueError("scope baseline must be stored outside the repository")
+    output_path.parent.mkdir(parents=True, exist_ok=True)
+    payload = json.dumps(build_scope_snapshot(repo_root, allowed_paths), indent=2, sort_keys=True) + "\n"
+    descriptor = os.open(output_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+    with os.fdopen(descriptor, "w", encoding="utf-8") as output_file:
+        output_file.write(payload)
+
+
+def load_scope_baseline(baseline_path: Path) -> dict:
+    result = json.loads(baseline_path.read_text(encoding="utf-8"))
+    if not isinstance(result, dict) or 1 != result.get("version"):
+        raise ValueError(f"invalid scope baseline: {baseline_path}")
+    expected_types = {
+        "repo_root": str,
+        "allowed_paths": list,
+        "allowed_contents": dict,
+        "outside_entries": dict,
+    }
+    if any(not isinstance(result.get(key), expected_type) for key, expected_type in expected_types.items()):
+        raise ValueError(f"invalid scope baseline: {baseline_path}")
+    if result.get("head") is not None and not isinstance(result.get("head"), str):
+        raise ValueError(f"invalid scope baseline: {baseline_path}")
+    return result
+
+
+def check_scope_baseline(baseline_path: Path, allowed_paths: list[Path]) -> list[str]:
+    if not baseline_path.exists():
+        return [f"missing scope baseline: {baseline_path}"]
+    baseline = load_scope_baseline(baseline_path)
+    repo_root = Path(baseline["repo_root"])
+    if get_head(repo_root) != baseline.get("head"):
+        return ["repository HEAD differs from scope baseline"]
+    normalized_allowed = normalize_repo_paths(repo_root, allowed_paths)
+    if normalized_allowed != baseline.get("allowed_paths"):
+        return ["resolved test file set differs from scope baseline"]
+    current = collect_worktree_entries(repo_root, set(normalized_allowed))
+    before = baseline.get("outside_entries", {})
+    return sorted(path for path in set(before) | set(current) if before.get(path) != current.get(path))
+
+
+def get_added_lines_for_path(path: Path, scope_baseline: dict | None = None) -> list[str]:
+    if scope_baseline is None:
+        return []
+    repo_root = Path(scope_baseline["repo_root"])
+    relative_path = normalize_repo_paths(repo_root, [path])[0]
+    before = scope_baseline.get("allowed_contents", {}).get(relative_path) or ""
+    after = path.read_text(encoding="utf-8") if path.exists() else ""
+    return [f"+{each[2:]}" for each in difflib.ndiff(before.splitlines(), after.splitlines()) if each.startswith("+ ")]
+
+
 def get_top_level_class_name(source: str) -> str | None:
     for line in source.splitlines():
         match = TYPE_DECL_LINE_PATTERN.match(line)
@@ -289,37 +514,23 @@ def resolve_target_source_path(path: Path, source: str) -> Path | None:
     target_type_name = get_target_type_name(source)
     if not target_type_name:
         return None
-    path_text = str(path)
-    test_marker = "/src/test/java/"
-    if test_marker not in path_text:
+    path_text = path.as_posix()
+    test_marker = "src/test/java/"
+    marker_index = path_text.find(test_marker)
+    if marker_index < 0:
         return None
-    return Path(path_text.replace(test_marker, "/src/main/java/")).with_name(f"{target_type_name}.java")
+    target_path = path_text[:marker_index] + "src/main/java/" + path_text[marker_index + len(test_marker):]
+    return Path(target_path).with_name(f"{target_type_name}.java")
 
 
 def load_target_public_methods(path: Path, source: str) -> set[str]:
     target_source_path = resolve_target_source_path(path, source)
     if target_source_path is None or not target_source_path.exists():
         return set()
-    target_source = target_source_path.read_text(encoding="utf-8")
+    target_source = mask_java_non_code(target_source_path.read_text(encoding="utf-8"), False)
     return {match.group(1) for match in PUBLIC_METHOD_DECL_PATTERN.finditer(target_source)}
 
 
-def get_after_status_lines() -> set[str]:
-    output = run_git_command(["git", "status", "--porcelain"])
-    return set(each for each in output.splitlines() if each)
-
-
-def is_src_main_path(path: str) -> bool:
-    return "/src/main/" in path or path.startswith("src/main/")
-
-
-def normalize_status_path(line: str) -> str:
-    path = line[3:].strip()
-    if " -> " in path:
-        path = path.split(" -> ", 1)[1].strip()
-    return path
-
-
 def list_distinct(values: list[str]) -> list[str]:
     return list(dict.fromkeys(values))
 
@@ -349,7 +560,8 @@ def infer_candidate_target(test_method_name: str, invoked_methods: list[str], co
     return None
 
 
-def analyze_parameterization_candidates(path: Path, source: str) -> list[CandidateSummary]:
+def analyze_parameterization_candidates(path: Path, source: str, target_public_methods: set[str]) -> list[CandidateSummary]:
+    source = mask_java_non_code(source, False)
     target_type_name = get_target_type_name(source)
     statistics = defaultdict(lambda: {"plain": 0, "parameterized": False})
     for match in TEST_METHOD_DECL_PATTERN.finditer(source):
@@ -357,7 +569,7 @@ def analyze_parameterization_candidates(path: Path, source: str) -> list[Candida
         test_method_name = match.group(2)
         brace_index = opening_brace_index(match)
         body = extract_block(source, brace_index)
-        invoked_methods = extract_invoked_methods(body)
+        invoked_methods = [each for each in extract_invoked_methods(body) if each in target_public_methods]
         constructed_types = extract_constructed_types(body)
         target = infer_candidate_target(test_method_name, invoked_methods, constructed_types, target_type_name)
         if target is None:
@@ -376,17 +588,17 @@ def analyze_parameterization_candidates(path: Path, source: str) -> list[Candida
                 method=method_name,
                 plain_test_count=plain_test_count,
                 parameterized_present=parameterized_present,
-                high_fit=plain_test_count >= 3,
             ))
     return result
 
 
 def describe_candidate(candidate: dict) -> str:
-    decision = "recommend refactor" if candidate["high_fit"] and not candidate["parameterized_present"] else "already parameterized" if candidate["parameterized_present"] else "observe"
+    decision = "already parameterized" if candidate["parameterized_present"] else "manual-review-required"
     return f'{candidate["path"]}: method={candidate["method"]} plainTestCount={candidate["plain_test_count"]} parameterizedPresent={candidate["parameterized_present"]} decision={decision}'
 
 
 def check_parameterized_name(path: Path, source: str) -> list[str]:
+    source = mask_java_non_code(source, False)
     violations = []
     token = "@ParameterizedTest"
     pos = 0
@@ -416,14 +628,6 @@ def check_parameterized_name(path: Path, source: str) -> list[str]:
     return violations
 
 
-def check_r15_a(candidates: list[CandidateSummary]) -> list[str]:
-    result = []
-    for each in candidates:
-        if each.high_fit and not each.parameterized_present:
-            result.append(f"{each.path}: method={each.method} nonParameterizedCount={each.plain_test_count}")
-    return result
-
-
 def check_r15_d(path: Path, source: str, method_bodies: dict[str, str]) -> list[str]:
     violations = []
     for match in PARAM_METHOD_PATTERN.finditer(source):
@@ -435,21 +639,29 @@ def check_r15_d(path: Path, source: str, method_bodies: dict[str, str]) -> list[
             violations.append(f"{path}:{line} method={method_name} missing @MethodSource")
             continue
         total_rows = 0
-        unresolved = []
         for provider in providers:
             body = method_bodies.get(provider)
             if body is None:
-                unresolved.append(provider)
                 continue
             total_rows += len(re.findall(r"\b(?:Arguments\.of|arguments)\s*\(", body))
-        if unresolved:
-            violations.append(f"{path}:{line} method={method_name} unresolvedProviders={','.join(unresolved)}")
+        if any(provider not in method_bodies for provider in providers):
             continue
         if total_rows < 3:
             violations.append(f"{path}:{line} method={method_name} argumentsRows={total_rows}")
     return violations
 
 
+def find_unresolved_method_sources(path: Path, source: str, method_bodies: dict[str, str]) -> list[str]:
+    result = []
+    for match in PARAM_METHOD_PATTERN.finditer(source):
+        method_name = match.group(2)
+        providers = parse_method_sources(method_name, match.group(1))
+        unresolved = [each for each in providers if each not in method_bodies]
+        if unresolved:
+            result.append(f"{path}:{line_number(source, match.start())} method={method_name} unresolvedProviders={','.join(unresolved)}")
+    return result
+
+
 def check_r15_e(path: Path, source: str) -> list[str]:
     violations = []
     for match in PARAM_METHOD_PATTERN.finditer(source):
@@ -478,12 +690,12 @@ def check_r15_f(path: Path, source: str) -> list[str]:
     return violations
 
 
-def check_r15_g(path: Path, source: str) -> list[str]:
+def check_r15_g(path: Path, source: str, added_lines: list[str]) -> list[str]:
     if "@ParameterizedTest" not in source:
         return []
     top_level_class_name = get_top_level_class_name(source)
     violations = []
-    for line in get_added_lines_for_path(path):
+    for line in added_lines:
         if line.startswith("+++") or line.startswith("@@"):
             continue
         if not line.startswith("+"):
@@ -538,23 +750,32 @@ def check_r15_j(context: FileScanContext) -> list[str]:
 
 
 def check_r14(path: Path, source: str) -> list[str]:
+    source = mask_java_non_code(source, True)
     return [f"{path}:{line_number(source, match.start())}" for match in BOOLEAN_ASSERTION_BAN_PATTERN.finditer(source)]
 
 
 def check_r15_h(path: Path, source: str) -> list[str]:
+    source = mask_java_non_code(source, True)
     violations = []
     for match in TEST_METHOD_DECL_PATTERN.finditer(source):
         method_name = match.group(2)
         line = line_number(source, match.start())
         brace_index = opening_brace_index(match)
         body = extract_block(source, brace_index)
-        if R15_H_IF_ELSE_PATTERN.search(body) or R15_H_IF_RETURN_PATTERN.search(body):
+        switch_dispatch = R15_SWITCH_PATTERN.search(body) and "assertTrue" in body and "assertFalse" in body
+        if R15_H_IF_ELSE_PATTERN.search(body) or R15_H_IF_RETURN_PATTERN.search(body) or switch_dispatch:
             violations.append(f"{path}:{line} method={method_name}")
     return violations
 
 
-def check_r15_b(path: Path, source: str) -> list[str]:
-    return [f"{path}:{line_number(source, match.start())}" for match in R15_B_PATTERN.finditer(source)]
+def find_metadata_accessor_test_candidates(path: Path, source: str) -> list[str]:
+    source = mask_java_non_code(source, False)
+    result = []
+    for match in TEST_METHOD_DECL_PATTERN.finditer(source):
+        method_name = match.group(2)
+        if any(method_name.startswith(f"assert{each}") for each in ("GetType", "GetOrder", "GetTypeClass")):
+            result.append(f"{path}:{line_number(source, match.start())} method={method_name}")
+    return result
 
 
 def checkstyle_preview_final_parameters(path: Path, source: str) -> list[str]:
@@ -580,67 +801,33 @@ def collect_precheck_violations(context: FileScanContext) -> dict[str, list[str]
     }
 
 
-def scan_java_file(path: Path, allow_metadata_accessor_tests: bool) -> tuple[dict[str, list[str]], list[CandidateSummary]]:
-    source = path.read_text(encoding="utf-8")
-    method_bodies = parse_method_bodies(source)
-    violations = defaultdict(list)
-    violations["R8"].extend(check_parameterized_name(path, source))
-    violations["R15-A"].extend(check_r15_a(path, source))
-    violations["R15-D"].extend(check_r15_d(path, source, method_bodies))
-    violations["R15-E"].extend(check_r15_e(path, source))
-    violations["R15-F"].extend(check_r15_f(path, source))
-    violations["R15-G"].extend(check_r15_g(path, source))
-    violations["R15-I"].extend(check_r15_i(path, source, method_bodies))
-    violations["R14"].extend(check_r14(path, source))
-    violations["R15-H"].extend(check_r15_h(path, source))
-    if not allow_metadata_accessor_tests:
-        violations["R15-B"].extend(check_r15_b(path, source))
-    return violations, analyze_parameterization_candidates(path, source)
-
-
-def check_r15_c(baseline_before: Path | None) -> list[str]:
-    if baseline_before is None:
-        return []
-    before_lines = baseline_before.read_text(encoding="utf-8").splitlines() if baseline_before.exists() else []
-    before_paths = {
-        normalize_status_path(each) for each in before_lines
-        if each and is_src_main_path(normalize_status_path(each))
-    }
-    after_paths = {
-        normalize_status_path(each) for each in get_after_status_lines()
-        if is_src_main_path(normalize_status_path(each))
-    }
-    return sorted(after_paths - before_paths)
-
-
-def create_file_scan_context(path: Path) -> FileScanContext:
+def create_file_scan_context(path: Path, scope_baseline: dict | None = None) -> FileScanContext:
     source = path.read_text(encoding="utf-8")
     method_blocks = parse_method_blocks(source)
+    target_public_methods = load_target_public_methods(path, source)
     return FileScanContext(
         path=path,
         source=source,
         method_bodies={name: body for name, (_, body) in method_blocks.items()},
         method_blocks=method_blocks,
-        candidates=analyze_parameterization_candidates(path, source),
+        candidates=analyze_parameterization_candidates(path, source, target_public_methods),
         target_type_name=get_target_type_name(source),
-        target_public_methods=load_target_public_methods(path, source),
+        target_public_methods=target_public_methods,
+        added_lines=get_added_lines_for_path(path, scope_baseline),
     )
 
 
-def file_rule_violations(context: FileScanContext, allow_metadata_accessor_tests: bool) -> dict[str, list[str]]:
+def file_rule_violations(context: FileScanContext) -> dict[str, list[str]]:
     violations = defaultdict(list)
     violations["R8"].extend(check_parameterized_name(context.path, context.source))
     violations["R14"].extend(check_r14(context.path, context.source))
-    violations["R15-A"].extend(check_r15_a(context.candidates))
     violations["R15-D"].extend(check_r15_d(context.path, context.source, context.method_bodies))
     violations["R15-E"].extend(check_r15_e(context.path, context.source))
     violations["R15-F"].extend(check_r15_f(context.path, context.source))
-    violations["R15-G"].extend(check_r15_g(context.path, context.source))
+    violations["R15-G"].extend(check_r15_g(context.path, context.source, context.added_lines))
     violations["R15-H"].extend(check_r15_h(context.path, context.source))
     violations["R15-I"].extend(check_r15_i(context.path, context.source, context.method_bodies))
     violations["R15-J"].extend(check_r15_j(context))
-    if not allow_metadata_accessor_tests:
-        violations["R15-B"].extend(check_r15_b(context.path, context.source))
     return violations
 
 
@@ -648,22 +835,32 @@ def build_rule_result(violations_by_rule: dict[str, list[str]]) -> dict[str, dic
     return {
         each.name: {
             "message": each.message,
+            "mode": each.mode,
             "violations": violations_by_rule[each.name],
         }
         for each in RULE_SPECS
     }
 
 
-def collect_scan_result(java_paths: list[Path], baseline_before: Path | None, allow_metadata_accessor_tests: bool) -> dict:
+def collect_scan_result(paths: list[Path], scope_baseline_path: Path | None) -> dict:
     violations_by_rule = defaultdict(list)
     precheck_violations = defaultdict(list)
-    contexts = [create_file_scan_context(each) for each in java_paths]
+    java_paths = [each for each in paths if each.suffix == ".java"]
+    scope_baseline = load_scope_baseline(scope_baseline_path) if scope_baseline_path and scope_baseline_path.exists() else None
+    contexts = [create_file_scan_context(each, scope_baseline) for each in java_paths]
     for context in contexts:
-        for rule, entries in file_rule_violations(context, allow_metadata_accessor_tests).items():
+        for rule, entries in file_rule_violations(context).items():
             violations_by_rule[rule].extend(entries)
         for name, entries in collect_precheck_violations(context).items():
             precheck_violations[name].extend(entries)
-    violations_by_rule["R15-C"].extend(check_r15_c(baseline_before))
+    violations_by_rule["R15-C"].extend(
+        check_scope_baseline(scope_baseline_path, paths) if scope_baseline_path else ["missing scope baseline"]
+    )
+    unresolved_sources = [
+        each
+        for context in contexts
+        for each in find_unresolved_method_sources(context.path, context.source, context.method_bodies)
+    ]
     return {
         "rules": build_rule_result(violations_by_rule),
         "prechecks": {
@@ -674,6 +871,13 @@ def collect_scan_result(java_paths: list[Path], baseline_before: Path | None, al
             for name in PRECHECK_ORDER
         },
         "candidates": [asdict(each) for context in contexts for each in context.candidates],
+        "reviews": {
+            "R15-A": [str(context.path) for context in contexts if not context.target_public_methods],
+            "R15-B": [each for context in contexts for each in find_metadata_accessor_test_candidates(context.path, context.source)],
+            "R15-D": unresolved_sources,
+            "R15-I": unresolved_sources,
+            "R15-J": [str(context.path) for context in contexts if not context.target_public_methods],
+        },
         "java_file_count": len(contexts),
     }
 
@@ -682,11 +886,6 @@ def failed_rule_names(result: dict) -> list[str]:
     return [each.name for each in RULE_SPECS if result["rules"][each.name]["violations"]]
 
 
-def failed_precheck_names(result: dict) -> list[str]:
-    prechecks = result.get("prechecks", {})
-    return [each for each in PRECHECK_ORDER if prechecks.get(each, {}).get("violations")]
-
-
 def print_rule_summary(result: dict) -> int:
     failed_rules = set(failed_rule_names(result))
     for each in RULE_SPECS:
@@ -696,7 +895,14 @@ def print_rule_summary(result: dict) -> int:
             for violation in violations:
                 print(violation)
             continue
-        print(f"[{each.name}] ok")
+        if "automated" == each.mode:
+            print(f"[{each.name}] ok")
+        elif "manual" == each.mode:
+            print(f"[{each.name}] semanticReviewRequired=true")
+        else:
+            print(f"[{each.name}] mechanical=ok semanticReviewRequired=true")
+        for review in result.get("reviews", {}).get(each.name, []):
+            print(f"review: {review}")
     return 1 if failed_rules else 0
 
 
@@ -710,10 +916,12 @@ def print_summary_only(result: dict) -> int:
         print("[R8-CANDIDATES] no candidates")
     failed_rules = [f"{each.name}={len(result['rules'][each.name]['violations'])}" for each in RULE_SPECS if result["rules"][each.name]["violations"]]
     print(f"[summary] javaFiles={result['java_file_count']}")
+    manual_rules = ",".join(each.name for each in RULE_SPECS if "automated" != each.mode)
+    print(f"[summary] semanticReviewRequired={manual_rules}")
     if failed_rules:
         print(f"[summary] violations={' '.join(failed_rules)}")
         return 1
-    print("[summary] all rules ok")
+    print("[summary] all mechanical rules ok")
     return 0
 
 
@@ -736,26 +944,37 @@ def print_precheck_summary(result: dict) -> int:
 
 
 def main() -> int:
-    parser = argparse.ArgumentParser(description="Consolidated quality-rule scan for gen-ut.")
-    parser.add_argument("--baseline-before", help="Path to the baseline git status captured at task start.")
-    parser.add_argument("--allow-metadata-accessor-tests", action="store_true", help="Allow R15-B when user explicitly requested metadata accessor tests.")
+    parser = argparse.ArgumentParser(description="Mechanical quality-rule scan and task-scope guard for gen-ut.")
+    parser.add_argument("--scope-baseline", help="Structured task scope baseline created before editing.")
+    parser.add_argument("--capture-scope-baseline", help="Write a structured task scope baseline to this path, then exit.")
     parser.add_argument("--json", action="store_true", help="Emit JSON output instead of the default text report.")
     parser.add_argument("--summary-only", action="store_true", help="Emit a compact text summary with candidate information.")
     parser.add_argument("--precheck-only", action="store_true", help="Emit only lightweight deterministic prechecks for early edit loops.")
-    parser.add_argument("paths", nargs="+", help="Resolved test file set.")
+    parser.add_argument("paths", nargs="*", help="Resolved test file set.")
     args = parser.parse_args()
 
-    java_paths = [Path(each) for each in args.paths if each.endswith(".java")]
-    baseline_path = Path(args.baseline_before) if args.baseline_before else None
-    result = collect_scan_result(java_paths, baseline_path, args.allow_metadata_accessor_tests)
-    if args.json:
-        print(json.dumps(result, indent=2, sort_keys=True))
-        return 1 if failed_rule_names(result) else 0
-    if args.precheck_only:
-        return print_precheck_summary(result)
-    if args.summary_only:
-        return print_summary_only(result)
-    return print_rule_summary(result)
+    try:
+        if not args.paths:
+            parser.error("at least one resolved test file is required")
+        paths = [Path(each) for each in args.paths]
+        if args.capture_scope_baseline:
+            output_path = Path(args.capture_scope_baseline)
+            write_scope_baseline(output_path, get_repo_root(), paths)
+            print(f"[scope-baseline] path={output_path.resolve()} allowedPathCount={len(paths)}")
+            return 0
+        baseline_path = Path(args.scope_baseline) if args.scope_baseline else None
+        result = collect_scan_result(paths, baseline_path)
+        if args.json:
+            print(json.dumps(result, indent=2, sort_keys=True))
+            return 1 if failed_rule_names(result) else 0
+        if args.precheck_only:
+            return print_precheck_summary(result)
+        if args.summary_only:
+            return print_summary_only(result)
+        return print_rule_summary(result)
+    except (OSError, ValueError, json.JSONDecodeError, subprocess.CalledProcessError) as ex:
+        print(ex, file=sys.stderr)
+        return 2
 
 
 if __name__ == "__main__":
diff --git a/.codex/skills/gen-ut/scripts/verification_gate_state.py b/.codex/skills/gen-ut/scripts/verification_gate_state.py
deleted file mode 100644
index b16d1c1d39a..00000000000
--- a/.codex/skills/gen-ut/scripts/verification_gate_state.py
+++ /dev/null
@@ -1,232 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one or more
-# contributor license agreements.  See the NOTICE file distributed with
-# this work for additional information regarding copyright ownership.
-# The ASF licenses this file to You under the Apache License, Version 2.0
-# (the "License"); you may not use this file except in compliance with
-# the License.  You may obtain a copy of the License at
-#
-#     http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-#!/usr/bin/env python3
-"""
-Verification snapshot digest and reusable gate state for gen-ut.
-"""
-
-import argparse
-import hashlib
-import json
-import sys
-import time
-from pathlib import Path
-
-
-TRACKED_SUFFIXES = {".java", ".xml", ".yaml", ".yml", ".properties"}
-GATES_KEY = "gates"
-TARGET_TEST_GATE = "target-test"
-LEGACY_TARGET_DIGEST_KEY = "latest_green_target_test_digest"
-LEGACY_TARGET_UPDATED_AT_KEY = "latest_green_target_test_updated_at"
-LEGACY_TRACKED_FILE_COUNT_KEY = "tracked_file_count"
-
-
-def normalize_paths(paths: list[str]) -> list[Path]:
-    result = []
-    seen = set()
-    for each in paths:
-        path = Path(each)
-        if path.suffix.lower() not in TRACKED_SUFFIXES:
-            continue
-        resolved = path.resolve()
-        if not resolved.exists():
-            raise ValueError(f"tracked path does not exist: {resolved}")
-        if not resolved.is_file():
-            raise ValueError(f"tracked path is not a file: {resolved}")
-        if resolved in seen:
-            continue
-        seen.add(resolved)
-        result.append(resolved)
-    return sorted(result, key=str)
-
-
-def tracked_paths(paths: list[str]) -> list[Path]:
-    result = normalize_paths(paths)
-    if result:
-        return result
-    raise ValueError("no trackable files found in verification snapshot")
-
-
-def calculate_digest(paths: list[Path]) -> str:
-    digest = hashlib.sha256()
-    for path in paths:
-        digest.update(str(path).encode("utf-8"))
-        digest.update(b"\0")
-        digest.update(path.read_bytes())
-        digest.update(b"\0")
-    return digest.hexdigest()
-
-
-def extend_digest(base_digest: str, tokens: list[str]) -> str:
-    digest = hashlib.sha256()
-    digest.update(base_digest.encode("utf-8"))
-    digest.update(b"\0")
-    for each in tokens:
-        digest.update(each.encode("utf-8"))
-        digest.update(b"\0")
-    return digest.hexdigest()
-
-
-def read_state(state_file: Path) -> dict:
-    if not state_file.exists():
-        return {}
-    result = json.loads(state_file.read_text(encoding="utf-8"))
-    if not isinstance(result, dict):
-        raise ValueError(f"invalid state payload in {state_file}: expected JSON object")
-    return result
-
-
-def write_state(state_file: Path, state: dict) -> None:
-    state_file.parent.mkdir(parents=True, exist_ok=True)
-    state_file.write_text(json.dumps(state, indent=2, sort_keys=True) + "\n", encoding="utf-8")
-
-
-def ensure_gate_map(state: dict) -> dict[str, dict]:
-    gates = state.get(GATES_KEY)
-    if gates is None:
-        gates = {}
-        state[GATES_KEY] = gates
-    if not isinstance(gates, dict):
-        raise ValueError("invalid gate state payload: expected object for `gates`")
-    return gates
-
-
-def legacy_target_entry(state: dict) -> dict | None:
-    digest = state.get(LEGACY_TARGET_DIGEST_KEY)
-    if not digest:
-        return None
-    return {
-        "digest": digest,
-        "updated_at": state.get(LEGACY_TARGET_UPDATED_AT_KEY),
-        "tracked_file_count": state.get(LEGACY_TRACKED_FILE_COUNT_KEY),
-    }
-
-
-def get_gate_entry(state: dict, gate_name: str) -> dict | None:
-    gates = ensure_gate_map(state)
-    result = gates.get(gate_name)
-    if result is not None and not isinstance(result, dict):
-        raise ValueError(f"invalid gate entry for {gate_name}: expected JSON object")
-    if result is None and TARGET_TEST_GATE == gate_name:
-        return legacy_target_entry(state)
-    return result
-
-
-def get_gate_digest(state: dict, gate_name: str) -> str | None:
-    entry = get_gate_entry(state, gate_name)
-    return entry.get("digest") if entry else None
-
-
-def set_gate_digest(state: dict, gate_name: str, digest: str, tracked_file_count: int) -> None:
-    gates = ensure_gate_map(state)
-    updated_at = int(time.time())
-    gates[gate_name] = {
-        "digest": digest,
-        "tracked_file_count": tracked_file_count,
-        "updated_at": updated_at,
-    }
-    if TARGET_TEST_GATE == gate_name:
-        state[LEGACY_TARGET_DIGEST_KEY] = digest
-        state[LEGACY_TARGET_UPDATED_AT_KEY] = updated_at
-        state[LEGACY_TRACKED_FILE_COUNT_KEY] = tracked_file_count
-
-
-def matches_gate_digest(state: dict, gate_name: str, digest: str) -> bool:
-    return get_gate_digest(state, gate_name) == digest
-
-
-def current_digest(paths: list[str]) -> tuple[str, int]:
-    normalized_paths = tracked_paths(paths)
-    return calculate_digest(normalized_paths), len(normalized_paths)
-
-
-def command_digest(paths: list[str]) -> int:
-    digest, _ = current_digest(paths)
-    print(digest)
-    return 0
-
-
-def command_mark_gate_green(state_file: Path, gate_name: str, paths: list[str]) -> int:
-    digest, tracked_file_count = current_digest(paths)
-    state = read_state(state_file)
-    set_gate_digest(state, gate_name, digest, tracked_file_count)
-    write_state(state_file, state)
-    print(digest)
-    return 0
-
-
-def command_match_gate_green(state_file: Path, gate_name: str, paths: list[str]) -> int:
-    digest, _ = current_digest(paths)
-    state = read_state(state_file)
-    latest_green = get_gate_digest(state, gate_name)
-    if latest_green == digest:
-        print(f"MATCH {digest}")
-        return 0
-    if latest_green:
-        print(f"MISMATCH current={digest} recorded={latest_green}")
-    else:
-        print(f"MISSING current={digest}")
-    return 1
-
-
-def execute_command(args: argparse.Namespace) -> int:
-    if "digest" == args.command:
-        return command_digest(args.paths)
-    if "mark-green" == args.command:
-        return command_mark_gate_green(Path(args.state_file), TARGET_TEST_GATE, args.paths)
-    if "match-green" == args.command:
-        return command_match_gate_green(Path(args.state_file), TARGET_TEST_GATE, args.paths)
-    if "mark-gate-green" == args.command:
-        return command_mark_gate_green(Path(args.state_file), args.gate, args.paths)
-    return command_match_gate_green(Path(args.state_file), args.gate, args.paths)
-
-
-def build_parser() -> argparse.ArgumentParser:
-    parser = argparse.ArgumentParser(description="Verification snapshot digest and gate reuse state.")
-    subparsers = parser.add_subparsers(dest="command", required=True)
-    digest_parser = subparsers.add_parser("digest", help="Print the current verification snapshot digest.")
-    digest_parser.add_argument("paths", nargs="+", help="Resolved test file set.")
-    mark_green_parser = subparsers.add_parser("mark-green", help="Record the current digest as the latest green target-test digest.")
-    mark_green_parser.add_argument("--state-file", required=True, help="State file path.")
-    mark_green_parser.add_argument("paths", nargs="+", help="Resolved test file set.")
-    match_green_parser = subparsers.add_parser("match-green", help="Check whether the current digest matches the latest green target-test digest.")
-    match_green_parser.add_argument("--state-file", required=True, help="State file path.")
-    match_green_parser.add_argument("paths", nargs="+", help="Resolved test file set.")
-    mark_gate_green_parser = subparsers.add_parser("mark-gate-green", help="Record the current digest as the latest green digest for a named gate.")
-    mark_gate_green_parser.add_argument("--state-file", required=True, help="State file path.")
-    mark_gate_green_parser.add_argument("--gate", required=True, help="Logical gate name, for example target-test or coverage.")
-    mark_gate_green_parser.add_argument("paths", nargs="+", help="Resolved test file set.")
-    match_gate_green_parser = subparsers.add_parser("match-gate-green", help="Check whether the current digest matches the latest green digest for a named gate.")
-    match_gate_green_parser.add_argument("--state-file", required=True, help="State file path.")
-    match_gate_green_parser.add_argument("--gate", required=True, help="Logical gate name, for example target-test or coverage.")
-    match_gate_green_parser.add_argument("paths", nargs="+", help="Resolved test file set.")
-    return parser
-
-
-def main() -> int:
-    parser = build_parser()
-    args = parser.parse_args()
-    try:
-        return execute_command(args)
-    except (ValueError, OSError, json.JSONDecodeError) as ex:
-        print(ex, file=sys.stderr)
-        return 2
-
-
-if __name__ == "__main__":
-    sys.exit(main())
diff --git a/.codex/skills/gen-ut/tests/test_collect_quality_baseline.py b/.codex/skills/gen-ut/tests/test_collect_quality_baseline.py
new file mode 100644
index 00000000000..5b887d57606
--- /dev/null
+++ b/.codex/skills/gen-ut/tests/test_collect_quality_baseline.py
@@ -0,0 +1,105 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import sys
+import unittest
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[1] / "scripts"
+if str(SCRIPTS_DIR) not in sys.path:
+    sys.path.insert(0, str(SCRIPTS_DIR))
+
+import collect_quality_baseline as baseline
+
+
+class CollectQualityBaselineTest(unittest.TestCase):
+
+    def test_missing_target_class_is_not_covered(self):
+        root = ET.fromstring("<report />")
+        found, counters, missed_branch_lines = baseline.summarize_target_coverage(root, "sample.MissingClass")
+        self.assertFalse(found)
+        self.assertEqual({"CLASS": None, "LINE": None, "BRANCH": None}, counters)
+        self.assertEqual([], missed_branch_lines)
+
+    def test_aggregate_target_and_inner_class_coverage(self):
+        root = ET.fromstring("""
+            <report>
+              <package name="sample">
+                <class name="sample/Target" sourcefilename="Target.java">
+                  <counter type="CLASS" missed="0" covered="1" />
+                  <counter type="LINE" missed="1" covered="4" />
+                  <counter type="BRANCH" missed="1" covered="3" />
+                </class>
+                <class name="sample/Target$Inner" sourcefilename="Target.java">
+                  <counter type="CLASS" missed="0" covered="1" />
+                  <counter type="LINE" missed="0" covered="2" />
+                  <counter type="BRANCH" missed="0" covered="2" />
+                </class>
+                <sourcefile name="Target.java">
+                  <line nr="12" mb="1" cb="1" />
+                </sourcefile>
+              </package>
+            </report>
+        """)
+        found, counters, missed_branch_lines = baseline.summarize_target_coverage(root, "sample.Target")
+        self.assertTrue(found)
+        self.assertEqual((2, 0, 100.0), counters["CLASS"])
+        self.assertEqual((6, 1, 6 * 100.0 / 7), counters["LINE"])
+        self.assertEqual((5, 1, 5 * 100.0 / 6), counters["BRANCH"])
+        self.assertEqual([12], missed_branch_lines)
+
+    def test_branchless_target_satisfies_target(self):
+        root = ET.fromstring("""
+            <report>
+              <package name="sample">
+                <class name="sample/Target" sourcefilename="Target.java">
+                  <counter type="CLASS" missed="0" covered="1" />
+                  <counter type="LINE" missed="0" covered="1" />
+                </class>
+                <sourcefile name="Target.java">
+                  <line nr="1" mb="0" cb="0" />
+                </sourcefile>
+              </package>
+            </report>
+        """)
+        found, counters, missed_branch_lines = baseline.summarize_target_coverage(root, "sample.Target")
+        self.assertTrue(found)
+        self.assertEqual((0, 0, 100.0), counters["BRANCH"])
+        self.assertEqual([], missed_branch_lines)
+        self.assertTrue(baseline.meets_target(found, counters, 100.0))
+
+    def test_missing_line_counter_does_not_satisfy_target(self):
+        root = ET.fromstring("""
+            <report>
+              <package name="sample">
+                <class name="sample/Target" sourcefilename="Target.java">
+                  <counter type="CLASS" missed="0" covered="1" />
+                </class>
+              </package>
+            </report>
+        """)
+        found, counters, _ = baseline.summarize_target_coverage(root, "sample.Target")
+        self.assertTrue(found)
+        self.assertIsNone(counters["LINE"])
+        self.assertEqual((0, 0, 100.0), counters["BRANCH"])
+        self.assertFalse(baseline.meets_target(found, counters, 100.0))
+
+
+if __name__ == "__main__":
+    unittest.main()
diff --git a/.codex/skills/gen-ut/tests/test_scan_quality_rules.py b/.codex/skills/gen-ut/tests/test_scan_quality_rules.py
new file mode 100644
index 00000000000..ce0d738ccfd
--- /dev/null
+++ b/.codex/skills/gen-ut/tests/test_scan_quality_rules.py
@@ -0,0 +1,288 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from dataclasses import asdict
+from pathlib import Path
+
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[1] / "scripts"
+if str(SCRIPTS_DIR) not in sys.path:
+    sys.path.insert(0, str(SCRIPTS_DIR))
+
+import scan_quality_rules as rules
+
+
+class ScanQualityRulesTest(unittest.TestCase):
+
+    def test_candidate_count_requires_manual_decision(self):
+        source = """
+            class TargetTest {
+                @Test void assertTargetFirst() { assertTrue(target.run(1)); }
+                @Test void assertTargetSecond() { assertFalse(target.run(2)); }
+                @Test void assertTargetThird() { assertThat(target.run(3), is(expected)); }
+            }
+        """
+        candidates = rules.analyze_parameterization_candidates(Path("TargetTest.java"), source, {"run"})
+        self.assertEqual(1, len(candidates))
+        self.assertNotIn("high_fit", asdict(candidates[0]))
+        self.assertIn("decision=manual-review-required", rules.describe_candidate(asdict(candidates[0])))
+
+    def test_non_target_invocation_is_not_candidate(self):
+        source = """
+            class TargetTest {
+                @Test void assertFirst() { assertTrue(Collections.singleton("a").isEmpty()); }
+                @Test void assertSecond() { assertTrue(Collections.singleton("b").isEmpty()); }
+                @Test void assertThird() { assertTrue(Collections.singleton("c").isEmpty()); }
+            }
+        """
+        self.assertEqual([], rules.analyze_parameterization_candidates(Path("TargetTest.java"), source, {"run"}))
+
+    def test_external_method_source_requires_review_instead_of_failure(self):
+        source = """
+            class TargetTest {
+                @ParameterizedTest(name = "{0}")
+                @MethodSource("Samples#cases")
+                void assertRun(final String name, final int value) {
+                    assertThat(target.run(value), is(value));
+                }
+            }
+        """
+        method_bodies = {name: body for name, (_, body) in rules.parse_method_blocks(source).items()}
+        self.assertEqual([], rules.check_r15_d(Path("TargetTest.java"), source, method_bodies))
+        reviews = rules.find_unresolved_method_sources(Path("TargetTest.java"), source, method_bodies)
+        self.assertEqual(1, len(reviews))
+
+    def test_ordinary_get_type_is_not_metadata_accessor_violation(self):
+        source = """
+            class TargetTest {
+                @Test void assertRecord() {
+                    assertThat(record.getType(), is(OperationType.INSERT));
+                }
+            }
+        """
+        self.assertEqual([], rules.find_metadata_accessor_test_candidates(Path("TargetTest.java"), source))
+
+    def test_boolean_rule_ignores_comments_and_literals(self):
+        source = '''
+            class TargetTest {
+                // assertEquals(true, target.run());
+                String example = "assertThat(value, is(false))";
+            }
+        '''
+        self.assertEqual([], rules.check_r14(Path("TargetTest.java"), source))
+
+    def test_boolean_rule_detects_code(self):
+        source = "class TargetTest { @Test void assertRun() { assertEquals(true, target.run()); } }"
+        self.assertEqual(["TargetTest.java:1"], rules.check_r14(Path("TargetTest.java"), source))
+
+    def test_parameterized_name_rule_ignores_comment(self):
+        source = "// @ParameterizedTest\nclass TargetTest {}"
+        self.assertEqual([], rules.check_parameterized_name(Path("TargetTest.java"), source))
+
+    def test_boolean_dispatch_rule_detects_switch(self):
+        source = '''
+            class TargetTest {
+                @Test void assertRun() {
+                    switch (value) {
+                        case 1 -> assertTrue(target.run());
+                        default -> assertFalse(target.run());
+                    }
+                }
+            }
+        '''
+        self.assertEqual(["TargetTest.java:3 method=assertRun"], rules.check_r15_h(Path("TargetTest.java"), source))
+
+    def test_resolve_target_source_path_for_root_module(self):
+        source = "class TargetTest {}"
+        actual = rules.resolve_target_source_path(Path("src/test/java/sample/TargetTest.java"), source)
+        self.assertEqual(Path("src/main/java/sample/Target.java"), actual)
+
+    def test_scope_baseline_detects_change_to_preexisting_dirty_file(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            repo_root = Path(temp_dir)
+            self.run_git(repo_root, "init")
+            allowed = repo_root / "module/src/test/java/TargetTest.java"
+            outside = repo_root / "AGENTS.md"
+            allowed.parent.mkdir(parents=True)
+            allowed.write_text("class TargetTest {}\n", encoding="utf-8")
+            outside.write_text("initial\n", encoding="utf-8")
+            self.run_git(repo_root, "add", ".")
+            self.run_git(repo_root, "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "-m", "initial")
+            outside.write_text("dirty before\n", encoding="utf-8")
+            baseline_path = Path(temp_dir).parent / f"{repo_root.name}-scope.json"
+            try:
+                rules.write_scope_baseline(baseline_path, repo_root, [allowed])
+                self.assertEqual([], rules.check_scope_baseline(baseline_path, [allowed]))
+                outside.write_text("changed during task\n", encoding="utf-8")
+                violations = rules.check_scope_baseline(baseline_path, [allowed])
+                self.assertEqual(["AGENTS.md"], violations)
+                allowed.write_text("class TargetTest { }\n", encoding="utf-8")
+                self.assertEqual(["AGENTS.md"], rules.check_scope_baseline(baseline_path, [allowed]))
+            finally:
+                baseline_path.unlink(missing_ok=True)
+
+    def test_scope_baseline_detects_new_ignored_file(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            repo_root = Path(temp_dir)
+            self.run_git(repo_root, "init")
+            allowed = repo_root / "module/src/test/java/TargetTest.java"
+            ignored = repo_root / ".task-cache/generated.bin"
+            allowed.parent.mkdir(parents=True)
+            ignored.parent.mkdir(parents=True)
+            allowed.write_text("class TargetTest {}\n", encoding="utf-8")
+            (repo_root / ".gitignore").write_text(".task-cache/\n", encoding="utf-8")
+            self.run_git(repo_root, "add", ".")
+            self.run_git(repo_root, "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "-m", "initial")
+            baseline_path = Path(temp_dir).parent / f"{repo_root.name}-ignored-scope.json"
+            try:
+                rules.write_scope_baseline(baseline_path, repo_root, [allowed])
+                ignored.write_bytes(b"generated")
+                self.assertEqual([".task-cache/generated.bin"], rules.check_scope_baseline(baseline_path, [allowed]))
+            finally:
+                baseline_path.unlink(missing_ok=True)
+
+    def test_scope_baseline_ignores_verification_outputs(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            repo_root = Path(temp_dir)
+            self.run_git(repo_root, "init")
+            allowed = repo_root / "module/src/test/java/TargetTest.java"
+            allowed.parent.mkdir(parents=True)
+            allowed.write_text("class TargetTest {}\n", encoding="utf-8")
+            (repo_root / "module/pom.xml").write_text("<project />\n", encoding="utf-8")
+            (repo_root / ".gitignore").write_text("target/\n", encoding="utf-8")
+            self.run_git(repo_root, "add", ".")
+            self.run_git(repo_root, "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "-m", "initial")
+            baseline_path = Path(temp_dir).parent / f"{repo_root.name}-verification-output-scope.json"
+            try:
+                rules.write_scope_baseline(baseline_path, repo_root, [allowed])
+                maven_output = repo_root / "module/target/surefire-reports/result.xml"
+                python_output = repo_root / ".codex/skills/gen-ut/scripts/__pycache__/scan.pyc"
+                maven_output.parent.mkdir(parents=True)
+                python_output.parent.mkdir(parents=True)
+                maven_output.write_text("verified\n", encoding="utf-8")
+                python_output.write_bytes(b"compiled")
+                self.assertEqual([], rules.check_scope_baseline(baseline_path, [allowed]))
+            finally:
+                baseline_path.unlink(missing_ok=True)
+
+    def test_scope_baseline_detects_untracked_source_in_target_package(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            repo_root = Path(temp_dir)
+            self.run_git(repo_root, "init")
+            allowed = repo_root / "module/src/test/java/sample/AllowedTest.java"
+            allowed.parent.mkdir(parents=True)
+            allowed.write_text("class AllowedTest {}\n", encoding="utf-8")
+            (repo_root / "module/pom.xml").write_text("<project />\n", encoding="utf-8")
+            self.run_git(repo_root, "add", ".")
+            self.run_git(repo_root, "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "-m", "initial")
+            baseline_path = Path(temp_dir).parent / f"{repo_root.name}-target-package-scope.json"
+            try:
+                rules.write_scope_baseline(baseline_path, repo_root, [allowed])
+                outside = repo_root / "module/src/test/java/target/HiddenTest.java"
+                outside.parent.mkdir(parents=True)
+                outside.write_text("class HiddenTest {}\n", encoding="utf-8")
+                self.assertEqual(["module/src/test/java/target/HiddenTest.java"], rules.check_scope_baseline(baseline_path, [allowed]))
+            finally:
+                baseline_path.unlink(missing_ok=True)
+
+    def test_scope_baseline_detects_untracked_resource_in_python_cache_directory(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            repo_root = Path(temp_dir)
+            self.run_git(repo_root, "init")
+            allowed = repo_root / "module/src/test/java/sample/AllowedTest.java"
+            allowed.parent.mkdir(parents=True)
+            allowed.write_text("class AllowedTest {}\n", encoding="utf-8")
+            self.run_git(repo_root, "add", ".")
+            self.run_git(repo_root, "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "-m", "initial")
+            baseline_path = Path(temp_dir).parent / f"{repo_root.name}-python-cache-resource-scope.json"
+            try:
+                rules.write_scope_baseline(baseline_path, repo_root, [allowed])
+                outside = repo_root / "module/src/test/resources/__pycache__/fixture.bin"
+                outside.parent.mkdir(parents=True)
+                outside.write_bytes(b"fixture")
+                self.assertEqual(["module/src/test/resources/__pycache__/fixture.bin"], rules.check_scope_baseline(baseline_path, [allowed]))
+            finally:
+                baseline_path.unlink(missing_ok=True)
+
+    def test_scope_baseline_detects_tracked_file_in_verification_output_directory(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            repo_root = Path(temp_dir)
+            self.run_git(repo_root, "init")
+            allowed = repo_root / "module/src/test/java/TargetTest.java"
+            tracked = repo_root / "fixtures/target/reference.txt"
+            allowed.parent.mkdir(parents=True)
+            tracked.parent.mkdir(parents=True)
+            allowed.write_text("class TargetTest {}\n", encoding="utf-8")
+            tracked.write_text("before\n", encoding="utf-8")
+            (repo_root / ".gitignore").write_text("target/\n", encoding="utf-8")
+            self.run_git(repo_root, "add", ".")
+            self.run_git(repo_root, "add", "-f", "fixtures/target/reference.txt")
+            self.run_git(repo_root, "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "-m", "initial")
+            baseline_path = Path(temp_dir).parent / f"{repo_root.name}-tracked-output-scope.json"
+            try:
+                rules.write_scope_baseline(baseline_path, repo_root, [allowed])
+                tracked.write_text("after\n", encoding="utf-8")
+                self.assertEqual(["fixtures/target/reference.txt"], rules.check_scope_baseline(baseline_path, [allowed]))
+            finally:
+                baseline_path.unlink(missing_ok=True)
+
+    def test_missing_scope_baseline_is_failure(self):
+        missing = Path(tempfile.gettempdir()) / "missing-gen-ut-scope-baseline.json"
+        missing.unlink(missing_ok=True)
+        self.assertEqual([f"missing scope baseline: {missing}"], rules.check_scope_baseline(missing, []))
+
+    def test_scope_baseline_accepts_binary_test_resource(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            repo_root = Path(temp_dir)
+            self.run_git(repo_root, "init")
+            resource = repo_root / "module/src/test/resources/sample.bin"
+            resource.parent.mkdir(parents=True)
+            resource.write_bytes(b"\xff\x00")
+            baseline_path = Path(temp_dir).parent / f"{repo_root.name}-binary-scope.json"
+            try:
+                rules.write_scope_baseline(baseline_path, repo_root, [resource])
+                baseline = json.loads(baseline_path.read_text(encoding="utf-8"))
+                self.assertIsNone(baseline["allowed_contents"]["module/src/test/resources/sample.bin"])
+            finally:
+                baseline_path.unlink(missing_ok=True)
+
+    def test_scope_baseline_rejects_non_test_path(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            repo_root = Path(temp_dir)
+            self.run_git(repo_root, "init")
+            production = repo_root / "src/main/java/Target.java"
+            production.parent.mkdir(parents=True)
+            production.write_text("class Target {}\n", encoding="utf-8")
+            baseline_path = Path(temp_dir).parent / f"{repo_root.name}-invalid-scope.json"
+            try:
+                with self.assertRaisesRegex(ValueError, "outside test scope"):
+                    rules.write_scope_baseline(baseline_path, repo_root, [production])
+            finally:
+                baseline_path.unlink(missing_ok=True)
+
+    @staticmethod
+    def run_git(repo_root: Path, *args: str) -> None:
+        subprocess.run(["git", *args], cwd=repo_root, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+
+
+if __name__ == "__main__":
+    unittest.main()