Skip to content

Refactor architecture guards into a sharded Python linter - #2739

Merged
Daniel Meppiel (danielmeppiel) merged 15 commits into
mainfrom
danielmeppiel-architecture-guard-refactor
Sep 1, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 15 commits into
mainfrom
danielmeppiel-architecture-guard-refactor

Conversation

@danielmeppiel

@danielmeppiel Daniel Meppiel (danielmeppiel) commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

refactor(architecture): shard ownership metadata and consolidate linting

TL;DR

Moves executable canonical-owner metadata from an always-loaded Markdown table
into a strict index plus six cohesive JSON shards. Replaces the 2,102-line shell
linter and 25 live helper authorities with one fail-closed Python process while
preserving exact-revision legacy compatibility. Against current main, warm
median runtime falls from 50.69s to 12.48s (75.4% faster).

Important

This is one atomic cutover: registry, compatibility gate, canonical linter,
mutation coverage, generated projections, and empirical evidence ship together.

Problem (WHY)

  • A routine owner addition rewrote both instruction projections and their
    apm.lock.yaml deployment hash.
  • The shell linter launched 25 standalone checker authorities, repeating
    full-tree scans and AST work.
  • The first Python candidate reduced wall time but retained about 1 GiB peak
    RSS through duplicated AST and tree-index representations.
  • Legacy helper implementations remained executable beside their ports,
    recreating split authority.
  • [!] Historical AC numbers were duplicated, coupling stable semantics to
    ambiguous display aliases.
  • [!] Long-lived branches need exact base/head interpretation without silently
    falling back from malformed JSON to legacy Markdown.

The design follows "Favor small, chainable primitives over monolithic frameworks."
and makes the proof executable because "Grounding outputs in deterministic tool execution transforms probabilistic generation into verifiable action.".
The concise instruction applies "Context arrives just-in-time, not just-in-case.".

Approach (WHAT)

# Fix
1 Define one versioned registry index and six merge-friendly metadata shards.
2 Validate the global union, selectors, shard listing, guard references, and semantic hash.
3 Build one inventory and shared read/parse/AST fact service for six explicit rule groups.
4 Retire all duplicate helper authorities behind one stable shell entrypoint.
5 Load JSON at exact revisions when present; use Markdown only when that revision predates the registry.
6 Prove every rule with semantic mutations, bounded scaling, conflict simulation, and fail-closed fault injection.

Implementation (HOW)

Surface Change
.apm/architecture/owners/ Adds the stable v1 index and six domain shards. Unknown fields, unsafe or duplicate selectors, missing/unlisted shards, and unmatched revision selectors fail closed.
scripts/architecture_linter/ Owns deterministic inventory, read-once/parse-once facts, compact tree indexes, explicit group loading, failure aggregation, diagnostics, and global registry/rule validation.
scripts/architecture_linter/facts.py Keeps hot source facts resident, spills cold test facts to a private cache, and retains facts after injected spill failures so no rule can trigger another AST walk.
scripts/architecture_linter/checks/tree_index.py Keys qualified function names by stable preorder position, preserving exact nested names after spill reload; missing indexed names fail closed.
scripts/lint_architecture_boundaries.py and scripts/lint-architecture-boundaries.sh Provide the standalone CLI and tiny stable exec python3 wrapper.
scripts/check_* and legacy architecture tests Deletes 25 duplicate checker entrypoints and their implementation-coupled tests; a static inventory test prevents their return.
packages/shepherd-driver/scripts/owner_touch_gate.py Preserves schema v1 while adding exact-revision JSON loading, genuine legacy fallback, removal/copy/rename detection, and semantic hashing.
.apm/instructions/ and .github/instructions/ Keep concise human guidance and expand canonical quality coverage to the linter package and entrypoint.
.github/workflows/ci.yml Runs Ruff, format, file length, and R0801 over the new package and enforces a bounded production-catalog scaling gate.
tests/**/test_architecture_* Adds registry, entrypoint, spill-reload, cache-failure, mutation, conflict, metrics, and 0/N/10N scaling contracts.
tests/perf/ Tracks raw ABBA/scaling evidence and a 103-row independent legacy/candidate parity matrix.

Diagrams

Legend: every semantic rule consumes one shared inventory and fact service; cold
test facts spill only after their one successful parse.

flowchart LR
    subgraph Registry[Owner registry]
        I[index.json]
        S[Six domain shards]
        I --> S
    end
    subgraph Engine[Single process]
        V[Strict validation]
        N[Deterministic inventory]
        F[Read-once and parse-once facts]
        T[Compact tree index]
        C[Bounded cold-fact spill]
        G[Six explicit rule groups]
    end
    subgraph Result[Result]
        A[Aggregate violations and failures]
        D[Ruff-style diagnostics and metrics]
    end
    S --> V
    V --> N
    N --> F
    F --> T
    T --> C
    C --> G
    G --> A
    A --> D
    classDef new stroke-dasharray: 5 5;
    class I,S,V,N,F,T,C,G,A,D new;
Loading

Legend: each Git revision selects exactly one ownership format; present but
invalid JSON never falls back to Markdown.

flowchart LR
    R[Exact Git revision] --> P{Registry index present}
    P -->|Yes| J[Load and validate JSON union]
    P -->|No| L[Parse legacy Markdown table]
    J --> Q{Complete and valid}
    Q -->|No| X[Fail closed]
    Q -->|Yes| O[Revision owner records]
    L --> O
    O --> C[Combine exact base and head]
    C --> E[Recompute fresh evidence]
    E --> Z[Schema-compatible report v1]
    classDef new stroke-dasharray: 5 5;
    class P,J,Q,X,O,C,E new;
Loading

Trade-offs

  • Disk-backed cold facts. Chose private same-process spill files for
    high-volume tests; rejected retaining every test AST. Peak RSS is about
    332 MiB: 67-69% below the rejected 1 GiB candidate, but still 76.7% above
    the 188 MiB legacy baseline.
  • JSON metadata, not an analyzer DSL. Chose strict records and Python rules;
    rejected grep/AST expressions in registry files.
  • Six groups, not one module per owner. Chose cohesive domains; rejected
    both a replacement god module and one file per owner.
  • Semantic IDs with AC aliases. Chose stable rule IDs; retained historical
    AC labels only as display metadata because they are not one-to-one.
  • Exact-revision compatibility. Chose Markdown fallback only for revisions
    that genuinely predate JSON; malformed or removed JSON remains fatal.

Benefits

  1. Median wall time is 12.48s versus 50.69s on current main, a 75.4% reduction.
  2. Every requested file is read at most once and every Python file is parsed and
    indexed at most once; the linter spawns zero child processes.
  3. Fixed-cost-adjusted production-catalog scaling is 1.36x wall and exactly
    10.00x deterministic work for 10x added files, below the 15x gate.
  4. Two owner additions in separate shards merge without changing either
    instruction projection or its lock hash.
  5. The candidate detects 103/103 independent semantic mutations; current main
    detects 100/103, so three boundaries are strengthened and none are weakened.

Validation

/usr/bin/time -lp bash scripts/lint-architecture-boundaries.sh (six ABBA
samples per implementation):

baseline median=50.69s p90=57.60s peak RSS max=187.83 MiB
candidate median=12.48s p90=13.64s peak RSS max=331.98 MiB
wall reduction=75.4%

PYTEST_PERF=1 ... test_real_six_group_catalog_wall_time_scales_below_fifteen_x:

sizes=0/80/800, samples=3 per size
fixed-cost-adjusted wall ratio=1.358
fixed-cost-adjusted work ratio=10.000
max reads per file=1; max parses per file=1
Full quality and test evidence
ruff check: All checks passed
ruff format --check: 1756 files already formatted
pylint R0801: 10.00/10
auth-signal lint: clean
architecture lint: clean
APM audit: All 10 checks passed; no drift
PR-time unit/red-team/console union:
  20936 passed, 3 skipped, 21 xfailed
  total coverage 88.71%
architecture correctness slice: 722 passed in 406.08s
current-main nested-Git compile/guard slice: 226 passed, 4 skipped in 23.02s
focused facts/tree tests: 72 passed
qualname-dependent rule mutations: 3 passed
request-default and owner-rule suites: 227 passed in 78.62s
bounded CI scaling gate: 1 passed in 60.70s
architecture ratchets: 81 passed
independent mutation matrix:
  current main 100/103 detected
  candidate 103/103 detected, zero runner failures

Comparable architecture command with eight xdist workers:

current main: 317 passed, 10 failed in 1104.02s
candidate: 717 passed in 388.67s

Seven baseline failures are the stale plugin fixtures identified in review;
three are legacy Agent Plugin projection assertions. The candidate fixture
constructor writes the current minimal plugin apm.yml; no product behavior
was changed.

Raw timestamps, wall/user/sys/RSS samples, environment, scaling counters, and
methodology are tracked in
tests/perf/ARCHITECTURE_LINTER_PR2739_EVIDENCE.md.

Scenario Evidence

# Scenario (user promise) Principle(s) Test(s) proving it Type
1 Maintainers run one stable architecture command and receive every violation in one deterministic report. Governed by policy, DevX tests/integration/test_architecture_linter_entrypoint.py integration
2 A spill round trip preserves exact nested function ownership, and spill failures block enforcement without duplicate work. Secure by default, Governed by policy tests/unit/scripts/test_architecture_runner.py::test_spill_reload_preserves_nested_function_qualnames
::test_spill_write_failure_keeps_facts_without_rewalking
::test_spill_load_failure_never_rebuilds_or_hides_the_failure
unit
3 Contributors add independent owners without generated instruction or lock-hash conflicts. OSS / community-driven tests/unit/scripts/test_architecture_registry_conflicts.py unit
4 Long-lived branches created before JSON still receive exact owner-touch classification. Governed by policy tests/unit/test_shepherd_owner_touch_gate.py unit
5 A malformed, missing, or unlisted registry shard blocks enforcement. Secure by default, Governed by policy tests/unit/scripts/test_architecture_registry.py unit
6 Every registered owner and semantic boundary detects its surgical mutation. Governed by policy tests/integration/test_architecture_owner_rule_mutations.py
tests/integration/test_architecture_semantic_rule_mutations.py
integration

How to test

  • Run bash scripts/lint-architecture-boundaries.sh; expect exit 0 and no diagnostics.
  • Run the registry, runner, conflict, and owner-gate suites; expect all selected tests to pass.
  • Run the spill tests; expect exact nested qualnames after reload and one read, parse, walk, and index build.
  • Run the bounded scaling CI node with PYTEST_PERF=1; expect a ratio below 15x.
  • Run uv run --frozen apm audit --ci; expect all 10 checks and drift replay to pass.

Co-authored-by: Copilot [email protected]

Copilot AI lite review requested due to automatic review settings August 31, 2026 13:47

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

Review tier: Lite
Findings: 2 Medium severity

New issues introduced by this change (2)
Severity Finding
Medium severity scripts/​architecture_linter/​checks/​install_request_and_source.py — _wrapper_default_args() slices wrapper.args.args[-default_count:] even when default_count == 0. In…
Medium severity scripts/​architecture_linter/​checks/​install_deployment_shared.py — _duplicate_definition_lines() currently skips files with read_error, which can silently miss…
What changed in this PR

This PR refactors the architecture ownership “canonical owner” guardrail from a large shell-driven lint pipeline into a sharded JSON registry plus a single-process Python linter, and updates tests/docs to assert the new rule-catalog contracts while preserving legacy/exact-revision behavior.

Changes:

  • Introduces .apm/architecture/owners/index.json plus six JSON shards for ownership metadata and updates guard consumption accordingly.
  • Adds a new scripts/architecture_linter/ engine (inventory, facts, rule groups, diagnostics, metrics) and a Python CLI entrypoint (scripts/lint_architecture_boundaries.py), replacing legacy ad-hoc scripts.
  • Migrates/updates integration and unit tests to assert rule IDs/descriptions and to use run_selected_rules() + source_overrides instead of shell execution.
File Description
tests/​unit/​scripts/​test_architecture_registry_conflicts.py New unit test proving shard-level owner additions merge without destabilizing projections/hashes.
tests/​integration/​test_architecture_marketplace_tag_pattern.py Switches marketplace tag-pattern tests from shell guard text to rule-catalog + run_selected_rules.
tests/​integration/​test_architecture_marketplace_output_path.py Switches output-path authority tests to rule-catalog + in-memory mutation via source_overrides.
tests/​integration/​test_architecture_intent_guards.py Updates meta-guard assertion to check a registered semantic rule description instead of shell source.
tests/​integration/​test_architecture_hash_visible_lf_writes.py Replaces subprocess checks with rule execution and in-memory mutation for LF-writer authority.
tests/​integration/​test_architecture_frontmatter_bom.py Updates frontmatter BOM authority assertions to validate both registry ownership and rule catalog.
tests/​integration/​test_architecture_exemption_policies.py New integration test enforcing explicit exemption-policy wiring in migrated checks.
tests/​integration/​test_architecture_contract_guards.py Shifts contract guard assertions from legacy shell strings to registered rule metadata.
tests/​integration/​test_architecture_contract_compound_mutations.py New mutation suite for executable-contract authority branches using run_selected_rules.
tests/​integration/​test_architecture_confirmed_bypass_mutations.py New mutation regression suite covering previously-identified bypass shapes.
tests/​integration/​test_architecture_apply_to_patterns.py Updates applyTo + compile-inventory authority tests to registry/rule-catalog APIs.
tests/​integration/​test_architecture_agents_footer.py Updates footer authority tests to registry + rule execution with source_overrides.
scripts/​lint_architecture_boundaries.py New Python CLI entrypoint for full-catalog execution + deterministic metrics output.
scripts/​check_agents_footer_authority.py Removes legacy standalone footer-authority script (now enforced via rule catalog).
scripts/​architecture_linter/​process_audit.py Adds child-process audit counting to enforce “single-process” contract.
scripts/​architecture_linter/​models.py Adds frozen dataclasses for facts, rules, violations, failures, and run report/metrics.
scripts/​architecture_linter/​metrics.py Deterministic JSON serialization/writing for run metrics (fail-closed on I/O).
scripts/​architecture_linter/​inventory.py Deterministic, excluded-roots-aware repository inventory builder (fail-closed anchors).
scripts/​architecture_linter/​groups/​transport_platform.py Group catalog composing transport/platform check families.
scripts/​architecture_linter/​groups/​registry_delegation.py Group catalog composing registry delegation checks.
scripts/​architecture_linter/​groups/​mutation_writes.py Group catalog composing mutation/write check families.
scripts/​architecture_linter/​groups/​marketplace_integrations.py Group catalog for marketplace/integration checks.
scripts/​architecture_linter/​groups/​install_deployment.py Group catalog for install/deployment checks.
scripts/​architecture_linter/​groups/​contracts_tests.py Group catalog for contracts/tests checks and structural helpers.
scripts/​architecture_linter/​groups/​common.py Shared helper primitives (inventory selection, lexical scans, consistent violation shaping).
scripts/​architecture_linter/​groups/​__init__.py Documents explicit (non-discovered) group import strategy.
scripts/​architecture_linter/​checks/​transport_sparse_and_updates.py Ports sparse/self-update transport checks into facts-based rule implementations.
scripts/​architecture_linter/​checks/​transport_platform_shared.py Shared transport check helpers (lexical require/forbid/count, inventory scoping).
scripts/​architecture_linter/​checks/​transport_cache_identity.py Ports cache-identity rule including structural analyzer integration.
scripts/​architecture_linter/​checks/​registry_shared.py Shared helpers/constants for registry delegation checks.
scripts/​architecture_linter/​checks/​python_semantics.py Shared tree-index queries for semantic rules (no extra traversals).
scripts/​architecture_linter/​checks/​mutation_write_shared.py Shared helpers for hook/MCP mutation-write analyzers.
scripts/​architecture_linter/​checks/​mutation_hook_membership.py Implements hook membership / cleanup scope / user-root scope rules.
scripts/​architecture_linter/​checks/​marketplace_integration_shared.py Shared helper primitives for marketplace/integration analyzers.
scripts/​architecture_linter/​checks/​marketplace_integration_analyzers.py Thin catalog composing marketplace check-family modules in registration order.
scripts/​architecture_linter/​checks/​marketplace_component_and_admission.py Implements producer-admission checks (portable-surface gating, write_text_lf invariants).
scripts/​architecture_linter/​checks/​install_request_and_source.py Implements install request-defaults/source-plan/outcome authority checks.
scripts/​architecture_linter/​checks/​install_policy_shared.py Shared primitives for policy/intent lexical scans (configured vs scanned paths).
scripts/​architecture_linter/​checks/​install_policy_plugin_and_approval.py Implements semantic policy/approval/install-intent rules (guard-less).
scripts/​architecture_linter/​checks/​install_policy_intent.py Thin semantic rule catalog spliced into install/deployment analyzers.
scripts/​architecture_linter/​checks/​install_policy_gitlab_and_bundle.py Implements semantic GitLab/bundle/policy/winner-selection checks.
scripts/​architecture_linter/​checks/​install_deployment_shared.py Shared install/deployment helper primitives (lexical scanning, summaries, AST helpers).
scripts/​architecture_linter/​checks/​install_deployment_analyzers.py Thin rule catalog assembling install/deployment guard rules + semantic splice.
scripts/​architecture_linter/​checks/​contracts_test_shared.py Shared helper primitives for contract/test rule families.
scripts/​architecture_linter/​checks/​contracts_generation_footer.py New rule implementing footer wording authority within rule catalog.
scripts/​architecture_linter/​checks/​agent_plugin_shared.py Shared constants for agent-plugin boundary checks.
scripts/​architecture_linter/​checks/​agent_plugin_scan_primitives.py AST scan primitives for agent-plugin boundary enforcement.
scripts/​architecture_linter/​checks/​__init__.py Declares checks package purpose (pure analyzers).
scripts/​architecture_linter/​__init__.py Declares architecture-linter package purpose.
docs/​src/​content/​docs/​contributing/​development-guide.md Documents new architecture guardrails workflow and stable lint command.
CHANGELOG.md Adds an Unreleased changelog entry describing the new architecture linter/registry.
apm.lock.yaml Updates generated lock metadata/hashes reflecting regenerated projections.
.apm/​architecture/​owners/​index.json Adds the registry index listing the six shard files.
.apm/​architecture/​owners/​core-runtime.json Adds v1 core-runtime ownership shard entries.
.apm/​architecture/​owners/​install-deployment.json Adds v1 install/deployment ownership shard entries.
.apm/​architecture/​owners/​hooks-integrations.json Adds v1 hooks/integrations ownership shard entries.
.apm/​architecture/​owners/​transport-auth-platform.json Adds v1 transport/auth/platform ownership shard entries.
.apm/​architecture/​owners/​marketplace-plugins.json Adds v1 marketplace/plugins ownership shard entries.
.apm/​architecture/​owners/​contracts-tooling.json Adds v1 contracts/tooling ownership shard entries.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +112 to +114
facts = provider.file_facts(path)
if getattr(facts, "read_error", None) is not None:
continue
Consolidate legacy checker authorities into the registered catalog, bound retained AST facts, extend quality gates, and replace implementation-coupled tests with canonical mutation contracts.

Co-authored-by: Copilot App <[email protected]>
Add an opt-in report output for the production-catalog 0/N/10N benchmark so fixed-cost-adjusted wall and deterministic-work evidence is reproducible.

Co-authored-by: Copilot App <[email protected]>
Persist current-main ABBA, bounded RSS, 0/N/10N scaling, comparable test-slice, mutation parity, and conflict-reduction evidence; refresh only the generated linting instruction hash.

Co-authored-by: Copilot App <[email protected]>
Keep failed spills cached without repeated AST walks, retire the final duplicate projection checker, replace brittle count contracts, and persist independent per-mutation legacy/candidate outcomes.

Co-authored-by: Copilot App <[email protected]>
Record that the candidate worktree measured by the matrix is the commit containing the generated artifact, while retaining the pre-commit base SHA for provenance.

Co-authored-by: Copilot App <[email protected]>
Port the nested Git compile boundary from the retired checker into the canonical registered rule and registry without instruction or lock churn.

Co-authored-by: Copilot App <[email protected]>
@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit 18e0da7 into main Sep 1, 2026
17 checks passed
@danielmeppiel
Daniel Meppiel (danielmeppiel) deleted the danielmeppiel-architecture-guard-refactor branch September 1, 2026 04:03
Sergio Sisternes (sergio-sisternes-epam) pushed a commit that referenced this pull request Sep 1, 2026
…-apmignore-file-exclusion

Port .apmignore canonical-owner AC35 onto the sharded architecture
linter registry from #2739.

Co-authored-by: Copilot App <[email protected]>
Copilot AI mentioned this pull request Sep 4, 2026
3 of 12 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants