Enforce architecture

From Intense-Visions/harness-engineering · View interactive version

Enforce architecture is an AI agent skill from the GitHub repository Intense-Visions/harness-engineering. > Validate architectural layer boundaries and detect dependency violations. No code may violate layer constraints — this is a hard gate, not a suggestion.

How to use this skill

Skill file

Enforce Architecture

Validate architectural layer boundaries and detect dependency violations. No code may violate layer constraints — this is a hard gate, not a suggestion.

When to Use

Process

Phase 1: Load Constraints

  1. Read harness.config.json to understand the project's architectural constraints. The config defines:
  1. Understand the layer model. In a typical layered architecture:

Graph-Enhanced Context (when available)

When a knowledge graph exists at .harness/graph/, use graph queries for faster, more accurate violation detection:

Graph queries show the complete violation scope (not just the first occurrence per file) and reveal transitive violations that single-file analysis misses. Fall back to file-based commands if no graph is available.

Phase 2: Run Dependency Checks

  1. Run harness check-deps to analyze all import statements against the constraint model. Capture the full JSON output.

1b. Optionally run harness check-arch for comprehensive architecture analysis beyond dependency checking. This covers circular dependencies, complexity, coupling, module size, and dependency depth in addition to layer violations.

  1. Parse the results. Each violation includes:

Phase 3: Analyze Violations

For each violation, determine:

  1. Which layers are involved. Identify the source file's layer and the imported module's layer. Map them to the constraint model.
  1. What rule is violated. Common violation types:
  1. Explain the impact. For each violation, state:

Phase 3.5: Apply Safe Architecture Fixes

Some architecture violations can be auto-fixed. Apply these before surfacing remaining violations.

Import ordering violations:

  1. Identify files where imports are not ordered according to the project's layer convention.
  2. Reorder imports: external packages first, then by layer (lowest to highest), then relative imports.
  3. Verify with lint + typecheck. This is a safe, mechanical fix.

Forbidden import replacement (with configured alternative):

  1. Check harness.config.json for forbiddenImports entries that include an alternative field.
  2. For each violation where an alternative exists, replace the import path with the alternative.
  3. Verify with typecheck + test. This is "probably safe" -- present as a diff for approval in interactive mode, apply silently in CI mode.

Design token substitution (unambiguous mapping):

  1. When a hardcoded value has exactly one matching design token, replace the literal with the token reference.
  2. Verify with typecheck + test.
  3. If the mapping is ambiguous (multiple candidate tokens), surface to user.

Never auto-fix these (always surface to user):

Phase 3.6: Convergence Loop (Standalone)

When running standalone (not through the orchestrator), apply a single-concern convergence loop:

  1. Re-run detection. After applying all safe/probably-safe fixes, run harness check-deps again.
  2. Check if violation count decreased. Compare the new count to the previous count.
  3. If decreased: loop. Fixing one violation can resolve others (e.g., replacing a forbidden import may eliminate a transitive skip-layer violation). Go back to Phase 2 with the new results.
  4. If unchanged: stop. Proceed to Phase 4 (Guide Resolution) for remaining violations.
  5. Maximum iterations: 5. To prevent infinite loops.

Verification gate: After each fix batch, run:

pnpm lint && pnpm tsc --noEmit && pnpm test

If any command fails, revert the batch and reclassify those findings as unsafe.

Phase 4: Guide Resolution

For each violation, provide a specific fix:

Common Violation Patterns

Pattern: "I just need one thing from that layer"

A UI component imports a repository function directly because "it is just one query." Fix: add the query to the Service layer. The extra indirection is the architecture working correctly.

Pattern: "Shared types across layers"

Two layers both need the same type definition. Fix: place shared types in the lowest layer that both depend on, or create a dedicated types or shared module at the bottom of the layer stack.

Pattern: "Test utilities importing production code from wrong layer"

Test helpers import across layer boundaries for convenience. Fix: each layer's tests should only import from that layer and below. Test utilities should follow the same constraints as production code.

Pattern: "Hardcoded colors in components"

A component uses #3b82f6 directly instead of referencing color.primary from the design token system. Fix: import and reference the token. In Tailwind: use the token-mapped utility class. In CSS: use the custom property var(--color-primary).

Pattern: "Circular dependency through re-exports"

Module A re-exports from Module B, and Module B imports from Module A. The circular dependency is hidden by the re-export. Fix: identify the true dependency direction and remove the reverse path.

Harness Integration

Success Criteria

Examples

Example: Service layer importing from UI layer

Violation from harness check-deps:

VIOLATION: Upward dependency
  File: src/services/user-service.ts:12
  Import: import { UserForm } from '../components/UserForm'
  Source layer: service (level 2)
  Target layer: ui (level 3)
  Rule: service layer must not depend on ui layer

Impact: The UserService now depends on a React component. It cannot be used in a CLI tool, a background job, or tested without a DOM. The service layer should be framework-agnostic.

Resolution:

// BEFORE (violating)
import { UserForm } from '../components/UserForm';
const data = UserForm.defaultValues; // using UI defaults in service

// AFTER (fixed)
// Define the defaults where they belong — in the service layer
const DEFAULT_USER_DATA: UserInput = { name: '', email: '' };

Example: Circular dependency between modules

Violation from harness check-deps:

VIOLATION: Circular dependency detected
  Cycle: src/services/order-service.ts -> src/services/inventory-service.ts -> src/services/order-service.ts
  order-service imports checkStock from inventory-service
  inventory-service imports getOrderQuantity from order-service

Resolution: Extract the shared concern into a new module:

// src/services/stock-calculator.ts (new, shared module)
export function calculateRequiredStock(quantity: number, reserved: number): number {
  return quantity - reserved;
}

Both services import from stock-calculator instead of from each other. The cycle is broken.

Gates

These are hard stops. Architecture violations are not warnings — they are errors.

Evidence Requirements

When this skill makes claims about existing code, architecture, or behavior,

it MUST cite evidence using one of:

  1. File reference: file:line format (e.g., src/auth.ts:42)
  2. Code pattern reference: file with description (e.g., src/utils/hash.ts —

"existing bcrypt wrapper")

  1. Test/command output: Inline or referenced output from a test run or CLI command
  2. Session evidence: Write to the evidence session section via manage_state

Uncited claims: Technical assertions without citations MUST be prefixed with

[UNVERIFIED]. Example: [UNVERIFIED] The auth middleware supports refresh tokens.

Red Flags

Universal

These apply to ALL skills. If you catch yourself doing any of these, STOP.

reference. Belief is not evidence.

Search the codebase first. The project may already have a convention.

but do not expand scope beyond the stated task.

Domain-Specific

Rationalizations to Reject

Universal

These reasoning patterns sound plausible but lead to bad outcomes. Reject them.

confirm it applies to this codebase.

with a concrete follow-up plan.

Domain-Specific

| Rationalization | Reality |

| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ |

| "The violation is minor — just one import" | One violation sets a precedent. Enforce the constraint or document an explicit exception with rationale. |

| "It works, so the architecture must be fine" | Working code with bad architecture is technical debt with compound interest. Correct function does not excuse structural violations. |

| "This is a legacy module, different rules apply" | Legacy does not mean exempt. Either the constraint applies or it needs an explicit documented exception. |

Escalation

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.