Skip to content

refactor(architecture): codebase stylistic and structural drift remediation - #32

Merged
dan-petty merged 10 commits into
release/v0.2.11from
refactor/codebase-drift-remediation
Sep 6, 2026
Merged

dan-petty merged 10 commits into
release/v0.2.11from
refactor/codebase-drift-remediation

Conversation

@dan-petty

Copy link
Copy Markdown
Owner

Summary

This PR remediates accumulated stylistic and structural drift across src/devops_cli, establishing permanent automated architectural gates and aligning the codebase with the engineering principles documented in AGENTS.md.

1. Domain Exception Taxonomy & Elimination of Bare Generic Exceptions

  • Defined strongly-typed domain exception hierarchies under src/devops_cli/exceptions/ inheriting from DevOpsCLIError, providing POSIX exit codes, canonical error codes (CONST_ERROR_CODE_*), and structured context dictionaries.
  • Utilized multiple inheritance (e.g. (VaultError, ValueError)) to maintain full backward compatibility with standard isinstance(exc, ValueError) assertions and existing callers.
  • Replaced bare ValueError, RuntimeError, and TypeError in domain logic across 14 modules:
    • Vault subsystem (src/devops_cli/security/vault_broker.py, src/devops_cli/commands/vault.py)
    • Kubernetes cluster context & chaos runner (src/devops_cli/commands/k8s/cluster_context.py, src/devops_cli/k8s/chaos_runner.py)
    • Docker sandbox (src/devops_cli/docker/sandbox.py)
    • AI model bundler & durable sessions (src/devops_cli/ai/model_bundler.py, src/devops_cli/ai/durable.py)
    • AI harness capabilities (skills.py, workflow.py, planning.py, shell.py, memory.py, os_access.py, compaction.py)

2. Indentation Depth (< 6 indentations / <= 5 nesting levels) & Cyclomatic Complexity (<= 10)

  • Flattened nested control flow across 13 modules using table-driven dispatch, predicate helper extraction, early guard clauses, and list comprehensions.
  • Refactored FileSystem.get_tools in src/devops_cli/ai/harness/filesystem.py, extracting 8 dedicated handler methods and reducing cyclomatic complexity from 49 to $\le 6$.
  • Audited via run_complexity_scan(Path("src/devops_cli"), max_nesting_depth=5): 0 functions exceeding nesting depth 5 across the entire src/devops_cli package.

3. Test Collection Hygiene & Warning Elimination

  • Added __test__ = False to TestModel in src/devops_cli/ai/agents/testing.py to eliminate PytestCollectionWarning.
  • Inspected toolset instructions for coroutines and safely closed unawaited coroutines during synchronous metadata extraction in src/devops_cli/ai/agents/agent.py and src/devops_cli/ai/toolsets/__init__.py, eliminating unawaited coroutine RuntimeWarning notices.

4. Automated Architectural Invariant Testing Suite

  • Authored tests/test_architectural_invariants.py with 6 automated invariant test suites:
    • test_exception_taxonomy_inheritance: Enforces all domain exceptions inherit from DevOpsCLIError.
    • test_domain_specific_exceptions_exist: Enforces canonical error codes and POSIX exit codes across Vault, K8s, Docker, and AI exceptions.
    • test_test_model_pytest_collection_disabled: Asserts TestModel.__test__ is False.
    • test_no_excessive_nesting_in_src: Asserts 0 functions with nesting depth $&gt; 5$ across all of src/devops_cli.
    • test_filesystem_get_tools_complexity: Asserts FileSystem.get_tools cyclomatic complexity $\le 10$.
    • test_no_bare_generic_exceptions_in_refactored_modules: AST inspection verifying 0 bare generic exceptions across domain modules.

Verification

  • Full Quality Gate: uv run devops ci passed 10/10 gates green (python_version, test, coverage $\ge 90%$, lint, format, typecheck, audit, security, actionlint, docs).
  • Synchronized Documentation: Introspected CLI and updated markdown references via devops docs generate --sync-readme.

Copilot AI lite review requested due to automatic review settings September 6, 2026 06:59

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

The invariant test filter for get_tools findings is currently non-matching, and the embeddings refactor uses zip(..., strict=False) without validating vector counts, risking harder-to-diagnose runtime failures.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

This PR reinforces the devops-cli architecture standards by introducing/expanding domain-specific exception taxonomies, refactoring several modules to reduce nesting/complexity, and adding an automated invariant test suite to prevent future stylistic/structural drift.

Changes:

  • Added tests/test_architectural_invariants.py to enforce exception taxonomy, nesting depth, cyclomatic complexity, and “no bare generic exceptions” constraints.
  • Introduced new domain exception modules (Vault/K8s/Docker/AI) and replaced bare ValueError/RuntimeError in several domain paths with typed DevOpsCLIError descendants.
  • Refactored multiple hotspots into helper functions to reduce nesting and complexity, plus updated project docs to reflect the new gates and milestones.
File summaries
File Description
tests/test_architectural_invariants.py Adds CI-enforced architectural invariant tests
src/devops_cli/security/vault_broker.py Uses Vault domain exception + helper
src/devops_cli/security/complexity.py Extracts findings generator helper
src/devops_cli/security/aibom.py Extracts model metadata parsing helpers
src/devops_cli/output/formatters/scalars.py Extracts repo-map symbol formatting helper
src/devops_cli/k8s/credentials.py Flattens Grafana secret search loop
src/devops_cli/k8s/chaos_runner.py Raises typed chaos execution exception
src/devops_cli/exceptions/vault.py Adds Vault exception taxonomy
src/devops_cli/exceptions/k8s.py Adds Kubernetes exception taxonomy
src/devops_cli/exceptions/docker.py Adds Docker exception taxonomy
src/devops_cli/exceptions/ai.py Adds AI bundle/harness exceptions
src/devops_cli/exceptions/init.py Re-exports new exception classes
src/devops_cli/docker/sandbox.py Raises DockerSandboxError for validation
src/devops_cli/config/constants.py Adds canonical error code constants
src/devops_cli/commands/vault.py Raises VaultConfigurationError on validation
src/devops_cli/commands/k8s/cluster_context.py Raises KubernetesContextError for URL/path validation
src/devops_cli/ai/toolsets/init.py Refactors tool extraction + coroutine closing
src/devops_cli/ai/response_repair.py Extracts JSON/tool-arg parsing helpers
src/devops_cli/ai/rag/embeddings.py Refactors probing + embed caching/dispatch
src/devops_cli/ai/providers/init.py Table-driven provider factory dispatch
src/devops_cli/ai/model_bundler.py Raises ModelBundleError for path validation
src/devops_cli/ai/harness/workflow.py Uses harness validation/execution exceptions
src/devops_cli/ai/harness/skills.py Uses harness validation exceptions for parsing
src/devops_cli/ai/harness/shell.py Uses harness validation for config checks
src/devops_cli/ai/harness/planning.py Uses harness validation for task/tool checks
src/devops_cli/ai/harness/os_access.py Uses harness execution for tool-call limits
src/devops_cli/ai/harness/memory.py Uses harness exceptions for memory operations
src/devops_cli/ai/harness/filesystem.py Refactors get_tools closures into methods
src/devops_cli/ai/harness/compaction.py Uses harness validation for parameter checks
src/devops_cli/ai/durable.py Uses harness validation for db_path traversal
src/devops_cli/ai/benchmark/embedding_tasks.py Extracts single-section parser helper
src/devops_cli/ai/ast_stream.py Extracts AST/token parsing helpers
src/devops_cli/ai/analyze/scanner.py Extracts dependency parsing helpers
src/devops_cli/ai/agents/testing.py Disables pytest collection on TestModel
src/devops_cli/ai/agents/runner.py Extracts hook dispatch + timeout runner helpers
src/devops_cli/ai/agents/agent.py Extracts toolset instruction/tools block helpers
docs/ROADMAP.md Updates roadmap milestone completion entries
docs/PENDING_FEATURES.md Updates current milestone and history
docs/LOG.md Logs remediation milestone details
docs/ERRORS.md Documents newly added error codes
docs/agent/task.md Updates internal task tracking text
AGENTS.md Strengthens documented invariants and taxonomy rules
Review details
  • Files reviewed: 42/42 changed files
  • Comments generated: 4
  • Review effort level: Lite

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

Comment thread src/devops_cli/ai/rag/embeddings.py Resolved
Comment thread tests/test_architectural_invariants.py Resolved
Comment thread docs/ERRORS.md Resolved
Comment thread docs/agent/task.md Resolved
@dan-petty
dan-petty merged commit d5dd95a into release/v0.2.11 Sep 6, 2026
4 checks passed
@dan-petty
dan-petty deleted the refactor/codebase-drift-remediation branch September 6, 2026 14:07
dan-petty added a commit that referenced this pull request Sep 6, 2026
…b management (#38)

* feat(k8s): replace redis with valkey across cluster stack manifests (#31)

* feat(k8s): replace redis with valkey across cluster stack manifests

* test(k8s): address copilot feedback on manifest parsing and document assertions

* docs(agent): update task tracking to completed for phase 35

* feat(mcp): expand FastMCP tools, prompt templates, and schema export (#33)

* refactor(exceptions): define domain exception classes and canonical error codes

* test(invariants): author architectural and stylistic invariant test specifications

* fix(exceptions): replace bare generic exceptions with strongly typed domain exceptions

* refactor(complexity): flatten excessive nesting and reduce cyclomatic complexity across modules

* fix(test-hygiene): eliminate pytest collection warning and unawaited coroutines

* docs(standards): update architectural guidelines, task tracking, and roadmap

* docs(agent): update task tracking to monitor PR 32 CI

* fix(review): address copilot feedback on vector validation, invariant checks, and error codes

* test(mcp): author contract and integration test specifications for expanded tools, prompts, and resources

* feat(mcp): expand FastMCP server to 72 tools, prompt templates, and schema export command

* docs(mcp): update MCP_TOOLS, README, ROADMAP, and task tracking for phase 37

* fix(mcp): resolve schema union type parsing and update roadmap resource URIs

* refactor(architecture): codebase stylistic and structural drift remediation (#32)

* refactor(exceptions): define domain exception classes and canonical error codes

* test(invariants): author architectural and stylistic invariant test specifications

* fix(exceptions): replace bare generic exceptions with strongly typed domain exceptions

* refactor(complexity): flatten excessive nesting and reduce cyclomatic complexity across modules

* fix(test-hygiene): eliminate pytest collection warning and unawaited coroutines

* docs(standards): update architectural guidelines, task tracking, and roadmap

* docs(agent): update task tracking to monitor PR 32 CI

* fix(review): address copilot feedback on vector validation, invariant checks, and error codes

* fix(agents): prevent ThreadPoolExecutor blocking on tool timeout in runner

* docs(valkey): expand roadmap and add IT domain knowledge base guide (#34)

* refactor(exceptions): define domain exception classes and canonical error codes

* test(invariants): author architectural and stylistic invariant test specifications

* fix(exceptions): replace bare generic exceptions with strongly typed domain exceptions

* refactor(complexity): flatten excessive nesting and reduce cyclomatic complexity across modules

* fix(test-hygiene): eliminate pytest collection warning and unawaited coroutines

* docs(standards): update architectural guidelines, task tracking, and roadmap

* docs(agent): update task tracking to monitor PR 32 CI

* fix(review): address copilot feedback on vector validation, invariant checks, and error codes

* test(mcp): author contract and integration test specifications for expanded tools, prompts, and resources

* feat(mcp): expand FastMCP server to 72 tools, prompt templates, and schema export command

* docs(mcp): update MCP_TOOLS, README, ROADMAP, and task tracking for phase 37

* fix(mcp): resolve schema union type parsing and update roadmap resource URIs

* feat(kb): add Valkey IT domain knowledge base reference guide and dynamic index counters

* docs(roadmap): expand roadmap and pending features for milestone v0.2.12 Valkey integration

* fix(agents): prevent ThreadPoolExecutor blocking on tool timeout in runner

* docs(roadmap): add library ingestion engine and grounded AI guidance for v0.2.13 (#35)

* refactor(exceptions): define domain exception classes and canonical error codes

* test(invariants): author architectural and stylistic invariant test specifications

* fix(exceptions): replace bare generic exceptions with strongly typed domain exceptions

* refactor(complexity): flatten excessive nesting and reduce cyclomatic complexity across modules

* fix(test-hygiene): eliminate pytest collection warning and unawaited coroutines

* docs(standards): update architectural guidelines, task tracking, and roadmap

* docs(agent): update task tracking to monitor PR 32 CI

* fix(review): address copilot feedback on vector validation, invariant checks, and error codes

* test(mcp): author contract and integration test specifications for expanded tools, prompts, and resources

* feat(mcp): expand FastMCP server to 72 tools, prompt templates, and schema export command

* docs(mcp): update MCP_TOOLS, README, ROADMAP, and task tracking for phase 37

* fix(mcp): resolve schema union type parsing and update roadmap resource URIs

* feat(kb): add Valkey IT domain knowledge base reference guide and dynamic index counters

* docs(roadmap): expand roadmap and pending features for milestone v0.2.12 Valkey integration

* docs(roadmap): expand roadmap and pending features for milestone v0.2.13 library ingestion engine

* fix(mcp): validate integer argument bounds and ensure consistent export-schemas instructions output

* docs(agent): update task tracking for phase 39 completion and pr 35 review resolution

* fix(agents): prevent ThreadPoolExecutor blocking on tool timeout in runner

* feat(sdlc): enterprise SDLC conventions, repository governance, and GitHub automation roadmap (#36)

* feat(governance): establish enterprise SDLC repository templates and community health policies

* docs(sdlc): author enterprise software development life cycle architecture manual

* docs(roadmap): expand roadmap with v0.2.14 enterprise GitHub repository automation

* docs(agent): track phase 40 completion and PR 36 submission

* fix(review): address copilot feedback on private key exclusion, PR template, and task status

* feat(review): executive summary reporting, feedback loop hardening, and findings remediation (#37)

* fix(security): remediate review findings for traversal, protocols, and tool validation

* feat(review): harden self-improvement feedback loop and add report executive summary

* docs(review): synchronize review task manual, SDLC, and working log

* docs(agent): mark phase 41 complete and record PR 37 status

* fix(review): address copilot feedback on secret masking, AST symbol fallback, error message, and dynamic patterns

* docs(agent): note PR 36 merged into release branch

* docs(roadmap): update v0.2.11 completed items and task tracking for merged PR 37

* test

* feat(github): add declarative labels, milestones, projects v2, views and FastMCP tools

* refactor(core): consolidate boilerplate decorators, AST cache, scanners, and table builder

* feat(security): DevSecOps zero-trust hardening, secret sanitizer, fail-closed SSRF, sandbox isolation, and K8s perimeter

* fix(review): address Copilot findings for Checkov exit handling, milestone due_on, gitleaks Windows paths, and symlink semantics

* docs(release): record Phase 47.3 release v0.2.11 PR and Copilot remediation in task tracking and log
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

No open projects

Development

Successfully merging this pull request may close these issues.

2 participants