The user wants to build a "Monorepo Change Impact Simulator."
This is a complex software engineering tool. To fulfill the request, I need to design a system that simulates what happens when code changes in a large monorepo.
Key Components requested:
Dependency Inference: How do packages/files relate to each other?
Risk Scoring: How dangerous is a specific change?
Sandbox Execution: Actually running the code/tests in isolation.
Developer UX: How does the developer interact with this?
My Strategy:
I will design this as a comprehensive architectural blueprint, likely code-named "Manticore" (or something similar, let's stick to "Monorepo Impact Simulator" or "MIS"). I need to define the stack, the data flow, and the specific algorithms for each component.
1. Dependency Inference (Static Analysis):
Challenge: Monorepos can be polyglot (JS, TS, Python, Go). We need a generic graph.
Structuring the Solution:
I will provide a high-level architecture, a detailed breakdown of the four modules, and then a "PoC" (Proof of Concept) implementation in Python/TypeScript to demonstrate the logic.
Language: Python is great for the analysis engine. TypeScript for the infra (since monorepos are often JS/TS heavy).
Let's stick to Python for the core logic simulation.
Refining the "Simulation" aspect:
It's not just running tests. It's simulating the state of the repo. I need to model "What if I merge this?"
Drafting the Code Structure:
graph_builder.py: builds the dependency graph.
risk_engine.py: calculates scores.
sandbox_runner.py: docker wrapper.
cli.py: user interface.
Self-Correction during thought process:
Initial thought: Build a full parser.
Correction: Too complex for a single response. Mock the AST parsing or use a simple regex/Tree-sitter example. Focus on the architecture and the glue between static/dynamic analysis.
Dynamic Analysis nuance: Dynamic analysis usually implies running the code. In a "Simulator," this means running the test suite of the impacted nodes.
Specific feature: "Inference":
Monorepos often lack explicit dependencies between internal packages (unlike external ones). I must emphasize inferring internal dependencies (e.g., import { Button } from 'ui-lib').
Let's build the "Manticore" system.
Module 1: The Graph (Inference) - uses a pseudo-parser.
Module 2: The Risk Engine (Logic) - uses a scoring algorithm.
Module 3: The Sandbox (Runtime) - uses Docker SDK.
Module 4: The UX - uses Rich/Textual (Python TUI).
Detailed Plan:
Architecture Overview: Explain the data flow.
The Dependency Graph: Code for building the graph (Static).
The Impact Engine: Code for traversing the graph.
Risk Scoring: Logic for scoring.
Sandbox: Concept and Docker snippet.
UX: ASCII wireframe or description.
Synthesis: How they fit together.
Let's refine the "Sandbox" part. Real sandboxing is hard. I'll propose using Firecracker or Docker with a deterministic file system snapshot to ensure the "Simulation" is reproducible.
Let's write the response. I will structure it as a technical design document followed by a prototype codebase.
Building a Monorepo Change Impact Simulator requires bridging the gap between "what code depends on this" (static) and "what runtime behaviors break if I change this" (dynamic).
Below is a comprehensive design and implementation strategy for a system called "Manticore."
1. High-Level Architecture
The system operates as a CLI tool (and CI check) that ingests a Git Diff and outputs a "Blast Radius" report.
The Stack:
Language: TypeScript/Node.js (for AST manipulation via Babel/SWC) or Python (for ease of graph logic).
Graph Engine: Neo4j (schema-heavy) or a directed graph in memory (NetworkX/XState).
Sandbox: Docker + Firecracker (microVMs) for ultra-fast, secure isolation.
UI: Terminal dashboard (React Ink) + Web view.
2. Module Design
A. Static Analysis: The Dependency Graph
This module builds the structural map of the codebase. In a monorepo, dependency inference is rarely just import statements; it involves inferring relationships between package.json, shared utilities, and configurations.
Strategies:
Explicit Parsing: Parse package.json and tsconfig.jsonpaths to map aliases (e.g., @ui/Button -> packages/ui/Button.tsx).
AST Inference: Parse files to extract dynamic imports and usages.
Repository Visibility: Tag packages as public (consumer-facing) or private (internal).
B. Dynamic Analysis: The Sandbox
Static analysis creates false positives (e.g., changing a comment or a function body without changing the signature). Dynamic analysis validates if the change actually breaks the contract.
Technique:
Test Selection: Use the static graph to find all test files that cover the changed node.
Contract Verification: If Package A changes, run Package A's unit tests.
Consumer Verification (The "Simulation"): Check out the consumer code (Package B) but inject the modified Package A into its dependency tree. Run Package B's tests.
C. Risk Scoring Heuristic
We calculate a RiskScore (0.0 - 1.0) based on:
Coupling Factor: Number of direct dependents.
Change Type: Did the interface (arguments/types) change, or just the internal logic?
Test Coverage: Does the changed package have tests?
Historical Failure Rate: How often has this file caused CI failures in the past?
3. Implementation Prototype (Python/TypeScript)
Here is a condensed implementation of the core logic.
The Data Model
python
# models.py
from dataclasses import dataclass, field
from typing import List, Set
@dataclass
class Package:
id: str
name: str
dependencies: Set[str] = field(default_factory=set)
dependents: Set[str] = field(default_factory=set) # Populated by graph reversal
has_tests: bool = False
risk_score: float = 0.0
@dataclass
class ImpactReport:
changed_packages: List[Package]
affected_consumers: List[Package]
suggested_sandbox_tasks: List[str]
overall_risk: str # LOW, MEDIUM, HIGH, CRITICAL
The Simulation Engine
python
The Sandbox Runner (Dynamic Verification)
This component creates a temporary environment where we "lie" to the consumer packages about their dependencies.
yaml
# sandbox_docker_compose.yaml
# Generated dynamically by the simulator
version: '3.8'
services:
# The consumer package we are testing
consumer-app-test:
image: node:18
working_dir: /app
volumes:
- ./packages/consumer-app:/app
- ./packages/shared-utils:/temp_utils
command: |
bash -c "npm install && rm -rf node_modules/shared-utils && cp -r /temp_utils node_modules/shared-utils && npm test"
4. Developer UX (The "Manticore" CLI)
The goal is to provide feedback before the developer pushes to CI.
Language Server Protocol (LSP) Integration: Instead of Regex/AST parsing files from scratch, run a headless LSP server (like typescript-server) to provide "Go To Definition" references which are more accurate than text-based search.
Graph Fragmentation: In massive monorepos (Google/Facebook scale), you cannot load the whole graph in memory. You need a distributed graph database (Neo4j) or a specialized build system (Bazel/Buck) to query subgraphs.
Non-Determinism: Dynamic analysis can fail due to flaky tests or environment differences. The sandbox must support "Gold Master" recording (record/replay HTTP traffic) to ensure consistency.
Inference Heuristics:
Weak Dependency: Is the import inside a try/catch? (Low risk).
Dynamic Dependency: Is it using require(variable)? (High risk, hard to trace).
6. Summary of Flow
Dev runsmanticore simulate.
Static Phase: System parses code diffs, updates the Dependency Graph, and calculates the Reverse Transitive Closure (the blast radius).
Risk Phase: System looks at the "shape" of the change (types vs implementation) and historical failure rates to compute a score.
Dynamic Phase: If Risk > Threshold, system spins up ephemeral containers, symlinks the changed code into consumer projects, and runs tests.
Result: Pass/Fail report delivered to the developer locally, preventing a broken build from ever reaching main.
# simulator.py
import os
import json
import networkx as nx
class MonorepoSimulator:
def __init__(self, repo_path):
self.repo_path = repo_path
self.graph = nx.DiGraph()
self.packages = {}
self._build_graph()
def _build_graph(self):
"""
Traverses the repo to infer dependencies.
Real implementation would use AST parsing here.
"""
# Pseudo-code for scanning packages
for root, dirs, files in os.walk(self.repo_path):
if "package.json" in files:
# Parse package.json
data = json.load(open(os.path.join(root, "package.json")))
pkg_id = data["name"]
deps = data.get("dependencies", {}).keys()
self.packages[pkg_id] = Package(id=pkg_id, name=pkg_id)
self.graph.add_node(pkg_id)
for dep in deps:
if dep in self.packages: # Internal dep only
self.graph.add_edge(pkg_id, dep) # pkg_id depends on dep
def simulate_change(self, changed_files):
"""
Runs the simulation based on a list of modified file paths.
"""
# 1. Identify impacted packages (Static Analysis)
changed_pkg_names = self._map_files_to_packages(changed_files)
impacted_nodes = set()
for pkg in changed_pkg_names:
# Find all nodes that depend on the changed package (Reverse Graph Traversal)
# Note: In NetworkX, successors are 'dependents' if edge is A->B (A depends on B)
# But we built edge A->B as A depends on B.
# We need Predecessors (who points to me?) or reverse the graph view.
# Using reverse view: B is the changed package. Who points to B?
ancestors = nx.ancestors(self.graph, pkg)
impacted_nodes.update(ancestors)
impacted_nodes.add(pkg)
# 2. Calculate Risk Scores
results = []
for node_id in impacted_nodes:
pkg = self.packages[node_id]
pkg.risk_score = self._calculate_risk(pkg, changed_files)
results.append(pkg)
# 3. Generate Sandbox Execution Plan
tasks = self._generate_sandbox_tasks(results)
return ImpactReport(
changed_packages=[p for p in results if p.id in changed_pkg_names],
affected_consumers=[p for p in results if p.id not in changed_pkg_names],
suggested_sandbox_tasks=tasks,
overall_risk=self._aggregate_risk(results)
)
def _calculate_risk(self, pkg, changed_files):
"""
Heuristic: Higher risk if high connectivity and low test coverage.
"""
connectivity = len(list(self.graph.predecessors(pkg.id))) # How many depend on me?
# Normalize
coupling_score = min(connectivity / 10.0, 1.0)
# Check for test coverage (Mock logic)
test_penalty = 0.0 if pkg.has_tests else 0.5
return min(coupling_score + test_penalty, 1.0)
def _generate_sandbox_tasks(self, impacted_packages):
"""
Decides which tests to run in the sandbox.
"""
tasks = []
for pkg in impacted_packages:
# Only run tests for consumers if the risk is high
if pkg.risk_score > 0.7:
tasks.append(f"docker run --rm test-runner:{pkg.id}")
return tasks