.
Core Solution
The workflow replaces dependency-centric analysis with a semantic observation pipeline. The process extracts architectural primitives, maps them into a machine-readable structure, applies a policy-driven interpretation layer, and generates a pressure analysis packet.
Step 1: Define Atom Schemas
An Atom is the smallest unit carrying architectural meaning. It is not a function, class, or file. It is a cross-cutting observation that answers: What boundary does this touch? What state does it mutate? What effect does it trigger? Who is authorized? What contract does it promise?
Common Atom families include:
component: architectural unit existence
relation: flow between units
capability: provided operations
state: durable or held data
effect: external side effects
authority: permission scope
trust_relation: boundary for external reliability
contract: preconditions, outputs, failure behavior
semantic: meaning beyond code location
An ArchMap records these observations in a source-grounded, machine-readable format. It is not an AST dump or a full code copy. It is a compressed map of architectural facts.
// archmap-extractor.ts
import { AtomType, ArchMapBuilder, ObservationContext } from '@codcompass/archmap';
interface FulfillmentContext {
orderId: string;
actorId: string;
inventoryService: InventoryGateway;
paymentProcessor: PaymentProvider;
eventBus: AsyncEventEmitter;
}
function extractFulfillmentAtoms(ctx: FulfillmentContext): ArchMap {
const builder = new ArchMapBuilder();
builder.observe({
type: AtomType.COMPONENT,
scope: 'inventory',
units: ['inventoryService', 'paymentProcessor', 'eventBus']
});
builder.observe({
type: AtomType.RELATION,
flow: 'handler -> inventoryService -> paymentProcessor -> eventBus'
});
builder.observe({
type: AtomType.CAPABILITY,
unit: 'inventoryService',
operations: ['reserve', 'release', 'confirm']
});
builder.observe({
type: AtomType.STATE,
entity: 'order',
transitions: ['pending -> reserved -> fulfilled']
});
builder.observe({
type: AtomType.EFFECT,
target: 'paymentProcessor.charge',
durability: 'idempotent',
failureMode: 'retry_with_backoff'
});
builder.observe({
type: AtomType.AUTHORITY,
actor: ctx.actorId,
permission: 'execute_fulfillment',
scope: `order:${ctx.orderId}`
});
builder.observe({
type: AtomType.TRUST_RELATION,
boundary: 'paymentProcessor',
assumption: 'external_failure_does_not_corrupt_order_state',
mitigation: 'compensating_transaction'
});
builder.observe({
type: AtomType.CONTRACT,
precondition: 'inventory_available && payment_valid',
postcondition: 'order_fulfilled && event_published',
failure_behavior: 'rollback_inventory && emit_payment_failed'
});
return builder.build();
}
Step 3: Compose Molecules
A Molecule is a finite composition of Atoms that forms a single responsibility boundary. In practice, molecules represent business workflows or architectural surfaces:
- Authenticated request boundary
- Credential lifecycle
- Repository transaction boundary
- Input-to-artifact pipeline
- External integration ingress
- Privileged governance surface
Molecules are not tied to folder structures. They emerge from how Atoms cluster around authority, state mutation, external effects, and semantic contracts.
Step 4: Apply a LawPolicy
LawPolicy is the interpretation profile. It selects which architectural laws to enforce, defines witness rules, sets signature axes, and determines coverage requirements. The same ArchMap can be analyzed differently depending on organizational priorities:
- Authority boundary enforcement
- State/effect consistency
- Generated output mediation
- Domain cohesion
- Permission coverage
- Repair preconditions
Step 5: Generate Analysis Packet with ArchSig
ArchSig consumes the ArchMap and LawPolicy, then produces an AAT (Algebraic Architecture Theory) analysis packet. AAT treats architecture as an algebraic structure generated from Atoms. It measures:
law: design properties to preserve
witness: observed evidence
obstruction: structures blocking the law
signature axis: direction of pressure
operation: split, move, protect, refactor
path/homotopy: whether change paths preserve structure
curvature/holonomy: local consistency that breaks under loops
The output is not a pass/fail score. It reports pressure metrics, semantic coupling density, workflow risk, state/effect reconciliation gaps, boundary holonomy defects, and explicit review focus areas.
Architecture Decisions & Rationale
- Separation of ArchMap and LawPolicy: Decoupling observation from interpretation allows the same codebase to be analyzed under different governance models without re-extraction.
- Pressure over Scores: Binary compliance masks structural debt. Continuous pressure metrics reveal where refactoring yields the highest architectural ROI.
- Cross-File Atom Resolution: Atoms intentionally span syntactic boundaries because architectural intent rarely respects module lines.
- AAT as Measurement Surface: Algebraic topology metaphors (curvature, holonomy) translate intuitive senior-engineer review patterns into computable invariants.
Pitfall Guide
1. Syntactic Atom Confusion
Explanation: Treating functions, classes, or files as Atoms. This collapses semantic boundaries back into syntactic ones, defeating the purpose of the approach.
Fix: Define Atoms by architectural intent, not code location. A single Atom may span three files if it represents one authority boundary or state transition.
2. Boundary Myopia
Explanation: Ignoring cross-cutting concerns because they don't align with module directories. Authority, trust, and effect boundaries frequently traverse multiple layers.
Fix: Map Atoms to business invariants first, then trace their implementation paths. Use explicit boundary markers in code (e.g., decorators, interface contracts, or explicit gateway patterns) to aid extraction.
3. LawPolicy Overfitting
Explanation: Defining too many laws or overly strict witness rules, resulting in noisy output and alert fatigue.
Fix: Start with 3-5 high-impact laws (e.g., authority isolation, state/effect consistency, external trust boundaries). Iterate based on incident patterns and team feedback. Treat LawPolicy as a living configuration, not a static rulebook.
4. Score Reductionism
Explanation: Treating ArchSig pressure metrics as pass/fail gates. This encourages teams to game the system rather than address structural debt.
Fix: Use pressure metrics as triage signals. High pressure on a specific axis indicates where architectural review should focus. Pair metrics with human review to distinguish between acceptable trade-offs and genuine obstructions.
5. Effect-State Decoupling
Explanation: Analyzing external calls and database mutations in isolation. This misses ordering violations, idempotency gaps, and compensation failures.
Fix: Explicitly model effect and state Atoms together. Verify that external side effects are either idempotent, compensated, or isolated from transactional boundaries. Use ArchSig's state/effect reconciliation pressure metric to detect mismatches.
6. Trust Boundary Neglect
Explanation: Assuming external providers are reliable by default. This leads to silent state corruption when third-party services fail or return malformed data.
Fix: Define trust_relation Atoms for every external integration. Specify failure modes, retry policies, and circuit-breaking boundaries. ArchSig will flag missing trust boundaries as architectural holes.
7. Static Molecule Assumption
Explanation: Treating Molecules as fixed folder structures or package names. Molecules are dynamic compositions that evolve with business logic.
Fix: Re-evaluate Molecule boundaries quarterly or after major feature releases. Use ArchMap clustering algorithms to detect when Atoms have drifted from their original responsibility surface.
Production Bundle
Action Checklist
Decision Matrix
| Scenario | Recommended Approach | Why | Cost Impact |
|---|
| Legacy monolith with blurred boundaries | Start with authority + state/effect laws | Isolates highest-risk coupling before refactoring | Low initial setup, high long-term ROI |
| AI-augmented development team | Enforce strict trust_relation + contract laws | Prevents model-inherited shortcuts from propagating | Medium setup, reduces incident response costs |
| Compliance-heavy system (SOC2, HIPAA) | Prioritize authority + permission coverage laws | Maps directly to audit requirements and least-privilege enforcement | High compliance value, moderate engineering overhead |
| Microservices migration | Focus on effect ordering + boundary holonomy laws | Detects distributed transaction anti-patterns early | High architectural clarity, reduces cross-service debugging |
Configuration Template
# law-policy.yaml
version: 2.1
law_universe:
- id: authority_isolation
description: "Privileged operations must not leak into standard request handlers"
witness_rules:
- match: "authority_atom.scope contains 'admin' OR 'superuser'"
- verify: "no_relation_to: standard_workflow_handler"
obstruction_threshold: 0.3
- id: state_effect_consistency
description: "External effects must be idempotent or compensated before state mutation"
witness_rules:
- match: "effect_atom.target is_external"
- verify: "state_atom.transition follows effect_atom OR compensation_atom exists"
obstruction_threshold: 0.2
- id: contract_mediation
description: "Generated outputs must pass service-level validation before persistence"
witness_rules:
- match: "semantic_atom.type == 'generated_output'"
- verify: "contract_atom.precondition includes validation_layer"
obstruction_threshold: 0.25
signature_axes:
- authority
- state
- effect
- contract
- trust
coverage_requirements:
minimum_atom_density: 0.6
cross_file_resolution: true
molecule_composition: dynamic
Quick Start Guide
- Install the extraction toolkit:
npm install @codcompass/archmap @codcompass/archsig
- Define your Atom schemas: Create a configuration file mapping your domain's authority, state, effect, and contract boundaries to Atom types.
- Run initial extraction: Execute
archsig extract --input ./src --output ./archmap.json to generate your first ArchMap.
- Apply a baseline LawPolicy: Use the provided template, adjust obstruction thresholds to your team's risk tolerance, and run
archsig analyze --map ./archmap.json --policy ./law-policy.yaml.
- Review pressure metrics: Focus on axes with nonzero pressure. Refactor obstructions, update Molecule boundaries, and iterate. Treat the output as a continuous measurement surface, not a one-time audit.