The user wants a pipeline for "continuous codebase archeology."
The goal of this pipeline is to uncover:
- Dead paths: Unused code, deprecated functions, unreachable branches.
- Historical decisions: Why was it done this way? (Commit messages, comments, ADRs).
- Opportunity for consolidation: Duplicated logic, similar patterns, shared libraries that could be extracted.
The pipeline needs to be "continuous," implying it runs regularly (CI/CD) or as a scheduled job, providing up-to-date insights rather than a one-off report.
Key Components of the Solution:
- Input: The codebase (Git repo) and associated metadata (Issue trackers, CI logs).
- Processing Steps:
- Static Analysis (SAST): Dependency graphs, control flow analysis.
- Dynamic Analysis: Coverage reports, runtime profiling.
- Textual/Historical Analysis: Git history mining, Natural Language Processing (NLP) on comments/docs.
- Similarity Analysis: Clone detection, semantic code search.
- Output/Visualization: Dashboards, alerts, automated PRs.
Structuring the Pipeline:
I should structure this as a data engineering or MLOps pipeline, treating the code as data.
- Stage 1: Ingestion & Hydration (The Excavation)
- Source control (Git).
- CI/CD artifacts (Coverage reports).
- Dependency manifests (package.json, requirements.txt).
- Stage 2: Static & Structural Analysis (Stratigraphy)
- Build the AST (Abstract Syntax Tree).
- Call graph generation.
- Dead code detection.
- Stage 3: Historical & Contextual Analysis (Paleontology)
- Git blame/log analysis.
- Linking commits to tickets (Jira/GitHub Issues).
- Analyzing comments/TODOs/FIXMEs.
- Stage 4: Consolidation & Similarity (The Synthesis)
- Clone detection (Type 1, 2, 3).
- Semantic vector embeddings (using LLMs/Transformers).
- Stage 5: Reporting & Action (The Museum)
- Dashboards (Grafana/Custom).
- Automated Refactor PRs.
Specific Techniques/Tools to Mention:
- Dead Code:
ts-prune, vulture, LLVM coverage data.
- History:
git log, git blame, parsers.
- Consolidation: Semantic search (OpenAI embeddings, specialized code models like CodeBERT).
- Orchestration: GitHub Actions, Jenkins, or Airflow.
Refining the "Continuous" Aspect:
It shouldn't block the build. It's an asynchronous analysis pipeline.
It needs to diff against the previous run to identify new debt or resolved debt.
Drafting the Response Structure:
- High-Level Architecture Diagram (Text description): Flow from Repo -> Analysis -> Insights.
- Phase 1: Data Ingestion (The Site Survey): Git, CI artifacts.
- Phase 2: Dead Path Detection (Graveyarding): Call graphs vs. Coverage.
- Phase 3: Historical Context (Epigraphy): Mining commit messages and linking tickets.
- Phase 4: Consolidation Analysis (Pattern Matching): AST diffing, Semantic embeddings.
- Phase 5: Output & Feedback Loop: The "Archeology Report".
Self-Correction/Refinement:
- Critique: Just running tools isn't a "design."
- Correction: I need to propose a specific architecture, maybe using a graph database (Neo4j) to store the code relationships. This makes the analysis queryable (e.g., "Find all functions modified by Person X that are never called"). This is a strong "Archeology" angle.
Let's flesh out the Graph Database approach:
- Nodes: Files, Functions, Classes, Commits, Authors, Jira Tickets.
- Edges: IMPORTS, CALLS, MODIFIED_BY, AUTHORED_BY, REFERENCES.
- Queries:
- Dead Path:
(Function)<-[:CALLS]-(Function) where the destination is an entry point... wait, reverse that. Root nodes that aren't entry points. Or nodes with 0 inbound edges.
Let's flesh out the LLM/AI angle:
- Use LLMs to summarize why a file hasn't been touched in 3 years based on the last commit message and linked ticket.
- Use LLMs to suggest consolidation strategies for duplicated code blocks.
Final Plan:
- Architecture: Event-driven pipeline.
- Storage: Code Property Graph (CPG) stored in a Graph DB (Neo4j) + Vector DB for semantic search.
- Analyzers:
- Structure (AST/LSP).
- Runtime (Coverage).
- Semantic (Embeddings).
- History (Git).
- The "Dashboard": A set of "Archeology Queries."
Let's write it out.
This pipeline design treats the codebase not just as a set of files, but as a living historical document. By combining Static Analysis, Git Archaeology, and Semantic Analysis, we can create a system that runs continuously (e.g., on every merge or nightly) to surface technical debt.
We will call this pipeline "The Excavator."
High-Level Architecture
The pipeline consists of four distinct stages:
- Excavation (Ingestion): Raw data collection from Git, ASTs, and CI logs.
- Stratigraphy (Graph Construction): mapping relationships between code, authors, and dependencies.
- Carbon Dating (Analysis): Identifying dead paths, decisions, and duplication.
- Curation (Reporting): Actionable dashboards and automated PRs.
1. The Data Store: The Code Graph
Instead of running scripts on a checkout, we persist the codebase state in a queryable format.
- Database: Neo4j (or Amazon Neptune).
- Schema:
- Nodes:
File, Class, Function, Commit, Author, JiraTicket, Dependency.
- Edges:
CALLS, IMPORTS, MODIFIED_BY, AUTHORED_BY, REFERENCES_TICKET.
2. Stage 1: Excavation (Ingestion)
This stage runs asynchronously, triggered by webhooks from GitHub/GitLab/Bitbucket.
A. Structural Ingestion (The Skeleton)
- Tooling:
semgrep, tree-sitter, or language-specific LSPs (Language Server Protocols).
- Action: Parse the Abstract Syntax Tree (AST) of changed files.
- Output: Update the Graph DB with
CALLS and IMPORTS relationships.
- Metric: Cyclomatic complexity and depth of inheritance.
B. Historical Ingestion (The Soil)
- Tooling:
git log --numstat, git blame.
- Action: Ingest commit history.
- Output: Create
COMMIT nodes linked to FILES. Link commits to external IDs (Jira/GitHub Issues) via regex parsing of commit messages.
C. Runtime Ingestion (The Vitals)
- Tooling: Coverage reports (Istanbul/nyc, Coverage.py, JaCoCo).
- Action: Ingest line execution counts from the latest CI test runs.
- Output: Tag
Function nodes with coverage_percentage.
3. Stage 2: Analysis (The Findings)
Here we define the specific algorithms to uncover the three target areas.
A. Uncovering Dead Paths
We need to distinguish between "unused" and "unreachable."
- The Algorithm:
- Identify Entry Points: Mark nodes connected to "Public Interfaces" (API Controllers, Lambda Handlers, Main methods) as
ALIVE.
- Graph Traversal: Perform a Breadth-First Search (BFS) from all
ALIVE nodes traversing CALLS edges.
- Gap Analysis: Any node not visited is technically unreachable code.
- The "Zombie" Filter (Crucial):
- Code that is unreachable by tests but public is "Risk."
- Code that has 0% coverage and hasn't been modified in >180 days is "Dead."
- Query:
MATCH (f:Function) WHERE NOT (f)<-[:CALLS*]-(entry:EntryPoint) AND f.last_modified < date() - 180 RETURN f
B. Uncovering Historical Decisions
We use Git metadata to understand "Why is this weird?"
- Knowledge Fragmentation Detection:
- Calculate the "Bus Factor" per file/module.
- Query: Match files where >80% of lines were written by authors who are no longer active (or have left the org).
- Decision Archaeology:
- Cross-reference code comments (
TODO, FIXME, HACK) with linked Issue tracker IDs.
- Identify "Orphaned Decisions": A
HACK comment exists, but the linked Jira ticket is "Closed/Won't Fix" or deleted.
- Change Coupling (Hidden Dependencies):
- Analyze commit history to find files that are always modified together but do not
IMPORT each other. This indicates hidden coupling or a missing abstraction.
C. Opportunity for Consolidation
Using ASTs and Vector Embeddings to find duplication.
- Structural Clones (Type-2/3 Clones):
- Use tools like
jscpd (Copy-Paste Detector) to find identical code structures with variable renames.
- Semantic Clones (The "Opportunity"):
- Step 1: Generate embeddings for every function body using a code LLM (e.g.,
codebert or openai-embeddings).
- Step 2: Perform cosine similarity search across the vector space.
- Step 3: Flag two functions as "Consolidation Candidates" if they have high semantic similarity but exist in different packages/domains.
- Refinement: Only surface these if both functions have high "Churn" (frequently edited), indicating they are active maintenance burdens.
4. Stage 3: Reporting & Action (The Museum)
Don't just create a PDF report; integrate into the developer workflow.
A. The "Archeology Dashboard" (Grafana/Kibana)
- The Graveyard: A list of files/functions marked as "Dead" (Low coverage + Old + Unreachable).
- The Museum: Code written by departed employees that is still critical (High centrality in graph + Low bus factor).
- The Mirror: Top 10 consolidation opportunities (Potential reduction in LoC).
B. Automated Remediation (The Robots)
- Dead Path PRs: Create a weekly Pull Request.
- Branch Name:
archeology/cleanup-dead-paths-2023-10
- Action: Automatically comment out or delete identified dead code.
- Validation: Run full test suite. If it passes, merge.
- Consolidation Tickets: Automatically create Jira tickets linking two similar functions with a suggested diff.
Implementation Stack (Example)
- Language: Python (for scripting/analysis).
- Orchestration: Prefect or Airflow (to run the pipeline nightly).
- Graph DB: Neo4j (Community Edition is sufficient).
- Static Analysis: Semgrep (fast, multi-language AST parsing).
- Vector DB: Qdrant or Pinecone (for semantic similarity).
- Visualization: Neovis.js (to visualize the graph of dead code).
Summary of Value
By running this continuously, you move from "Big Bang Refactoring" (high risk) to Incremental Gardening.
- Dead Paths are removed before they rot.
- Historical Decisions are documented or closed.
- Consolidation happens when the code is fresh, not years later.