Generated banner for Acquire Codebase Knowledge
Generated logo for Acquire Codebase Knowledge

Acquire Codebase Knowledge

GitHubOfficialFirst committed by SriSatyaLokeshDistributed by GitHub

  • Skill
  • Workflow
  • Software development
  • MIT
  • Low risk
  • Has scripts

From the author

Use this skill when the user explicitly asks to map, document, or onboard into an existing codebase. Trigger for prompts like "map this codebase", "document this architecture", "onboard me to this repo", or "create codebase docs". Do not trigger for routine feature implementation, bug fixes, or narrow code edits unless the user asks for repository-level discovery.
— the description by SriSatyaLokesh

From the skill’s files

Taken from the skill’s own files (its description, section headings and stated usage). Not an AutoGineer summary, and not written by the author as one.

Use this skill when the user explicitly asks to map, document, or onboard into an existing codebase. Trigger for prompts like "map this codebase", "document this architecture", "onboard me to this repo", or "create codebase docs". Do not trigger for routine feature implementation, bug fixes, or narrow code edits unless the user asks for repository-level discovery. Produces seven populated documents in docs/codebase/ covering everything needed to work effectively on the project. Only document what is verifiable from files or terminal output — never infer or assume.

What it does

  • Output Contract (Required)
  • Workflow
  • Focus Area Mode
  • Gotchas
  • Anti-Patterns
  • Enhanced Scan Output Sections

When to use it

  • Use this skill when the user explicitly asks to map, document, or onboard into an existing codebase.
  • Trigger for prompts like "map this codebase", "document this architecture", "onboard me to this repo", or "create codebase docs".

Advantages

The skill’s files do not state this.

Usage examples

The skill’s files do not state this.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/github/acquire-codebase-knowledge/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip acquire-codebase-knowledge.zip -d .agents/skills

Documentation by SriSatyaLokesh

Acquire Codebase Knowledge

Produces seven populated documents in docs/codebase/ covering everything needed to work effectively on the project. Only document what is verifiable from files or terminal output — never infer or assume.

Output Contract (Required)

Before finishing, all of the following must be true:

  1. Exactly these files exist in docs/codebase/: STACK.md, STRUCTURE.md, ARCHITECTURE.md, CONVENTIONS.md, INTEGRATIONS.md, TESTING.md, CONCERNS.md.

  2. Every claim is traceable to source files, config, or terminal output.

  3. Unknowns are marked as [TODO]; intent-dependent decisions are marked [ASK USER].

  4. Every document includes a short "evidence" list with concrete file paths.

  5. Final response includes numbered [ASK USER] questions and intent-vs-reality divergences.

Workflow

Copy and track this checklist:

- [ ] Phase 1: Run scan, read intent documents
- [ ] Phase 2: Investigate each documentation area
- [ ] Phase 3: Populate all seven docs in docs/codebase/
- [ ] Phase 4: Validate docs, present findings, resolve all [ASK USER] items

Focus Area Mode

If the user supplies a focus area (for example: "architecture only" or "testing and concerns"):

  1. Always run Phase 1 in full.

  2. Fully complete focus-area documents first.

  3. For non-focus documents not yet analyzed, keep required sections present and mark unknowns as [TODO].

  4. Still run the Phase 4 validation loop on all seven documents before final output.

Phase 1: Scan and Read Intent
  1. Run the scan script from the target project root:

    python3 "$SKILL_ROOT/scripts/scan.py" --output docs/codebase/.codebase-scan.txt

    Where $SKILL_ROOT is the absolute path to the skill folder. Works on Windows, macOS, and Linux.

    Quick start: If you have the path inline:

    python3 /absolute/path/to/skills/acquire-codebase-knowledge/scripts/scan.py --output docs/codebase/.codebase-scan.txt
  2. Search for PRD, TRD, README, ROADMAP, SPEC, DESIGN files and read them.

  3. Summarise the stated project intent before reading any source code.

Phase 2: Investigate

Use the scan output to answer questions for each of the seven templates. Load references/inquiry-checkpoints.md for the full per-template question list.

If the stack is ambiguous (multiple manifest files, unfamiliar file types, no package.json), load references/stack-detection.md.

Phase 3: Populate Templates

Copy each template from assets/templates/ into docs/codebase/. Fill in this order:

  1. STACK.md — language, runtime, frameworks, all dependencies

  2. STRUCTURE.md — directory layout, entry points, key files

  3. ARCHITECTURE.md — layers, patterns, data flow

  4. CONVENTIONS.md — naming, formatting, error handling, imports

  5. INTEGRATIONS.md — external APIs, databases, auth, monitoring

  6. TESTING.md — frameworks, file organization, mocking strategy

  7. CONCERNS.md — tech debt, bugs, security risks, perf bottlenecks

Use [TODO] for anything that cannot be determined from code. Use [ASK USER] where the right answer requires team intent.

Phase 4: Validate, Repair, Verify

Run this mandatory validation loop before finalizing:

  1. Validate each doc against references/inquiry-checkpoints.md.

  2. For each non-trivial claim, confirm at least one evidence reference exists.

  3. If any required section is missing or unsupported:

  • Fix the document.

  • Re-run validation.

  1. Repeat until all seven docs pass.

Then present a summary of all seven documents, list every [ASK USER] item as a numbered question, and highlight any Intent vs. Reality divergences from Phase 1.

Validation pass criteria:

  • No unsupported claims.

  • No empty required sections.

  • Unknowns use [TODO] rather than assumptions.

  • Team-intent gaps are explicitly marked [ASK USER].


Gotchas

Monorepos: Root package.json may have no source — check for workspaces, packages/, or apps/ directories. Each workspace may have independent dependencies and conventions. Map each sub-package separately.

Outdated README: README often describes intended architecture, not the current one. Cross-reference with actual file structure before treating any README claim as fact.

TypeScript path aliases: tsconfig.json paths config means imports like @/foo don't map directly to the filesystem. Map aliases to real paths before documenting structure.

Generated/compiled output: Never document patterns from dist/, build/, generated/, .next/, out/, or __pycache__/. These are artefacts — document source conventions only.

.env.example reveals required config: Secrets are never committed. Read .env.example, .env.template, or .env.sample to discover required environment variables.

devDependencies ≠ production stack: Only dependencies (or equivalent, e.g. [tool.poetry.dependencies]) runs in production. Document linters, formatters, and test frameworks separately as dev tooling.

Test TODOs ≠ production debt: TODOs inside test/, tests/, __tests__/, or spec/ are coverage gaps, not production technical debt. Separate them in CONCERNS.md.

High-churn files = fragile areas: Files appearing most in recent git history have the highest modification rate and likely hidden complexity. Always note them in CONCERNS.md.


Anti-Patterns

❌ Don't✅ Do instead
"Uses Clean Architecture with Domain/Data layers." (when no such directories exist)State only what directory structure actually shows.
"This is a Next.js project." (without checking package.json)Check dependencies first. State what's actually there.
Guess the database from a variable name like dbUrlCheck manifest for pg, mysql2, mongoose, prisma, etc.
Document dist/ or build/ naming patterns as conventionsSource files only.

Enhanced Scan Output Sections

The scan.py script now produce the following sections in addition to the original output:

  • CODE METRICS — Total files, lines of code by language, largest files (complexity signals)

  • CI/CD PIPELINES — Detected GitHub Actions, GitLab CI, Jenkins, CircleCI, etc.

  • CONTAINERS & ORCHESTRATION — Docker, Docker Compose, Kubernetes, Vagrant configs

  • SECURITY & COMPLIANCE — Snyk, Dependabot, SECURITY.md, SBOM, security policies

  • PERFORMANCE & TESTING — Benchmark configs, profiling markers, load testing tools

Use these sections during Phase 2 to inform investigation questions and identify tool-specific patterns.


Bundled Assets

AssetWhen to load
scripts/scan.pyPhase 1 — run first, before reading any code (Python 3.8+ required)
references/inquiry-checkpoints.mdPhase 2 — load for per-template investigation questions
references/stack-detection.mdPhase 2 — only if stack is ambiguous
assets/templates/STACK.mdPhase 3 step 1
assets/templates/STRUCTURE.mdPhase 3 step 2
assets/templates/ARCHITECTURE.mdPhase 3 step 3
assets/templates/CONVENTIONS.mdPhase 3 step 4
assets/templates/INTEGRATIONS.mdPhase 3 step 5
assets/templates/TESTING.mdPhase 3 step 6
assets/templates/CONCERNS.mdPhase 3 step 7

Template usage mode:

  • Default mode: complete only the "Core Sections (Required)" in each template.

  • Extended mode: add optional sections only when the repo complexity justifies them.

Files

scripts/scan.py

#!/usr/bin/env python3
"""
scan.py — Collect project discovery information for the acquire-codebase-knowledge skill.
Run from the project root directory.

Usage: python3 scan.py [OPTIONS]

Options:
  --output FILE   Write output to FILE instead of stdout
  --help          Show this message and exit

Exit codes:
  0  Success
  1  Usage error
"""

import os
import sys
import argparse
import subprocess
import json
from pathlib import Path
from typing import List, Set
import re

TREE_LIMIT = 200
TREE_MAX_DEPTH = 3
TODO_LIMIT = 60
MANIFEST_PREVIEW_LINES = 80
RECENT_COMMITS_LIMIT = 20
CHURN_LIMIT = 20

EXCLUDE_DIRS = {
    "node_modules", ".git", "dist", "build", "out", ".next", ".nuxt",
    "__pycache__", ".venv", "venv", ".tox", "target", "vendor",
    "coverage", ".nyc_output", "generated", ".cache", ".turbo",
    ".yarn", ".pnp", "bin", "obj"
}

MANIFESTS = [
    # JavaScript/Node.js
    "package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "bun.lockb",
    "deno.json", "deno.jsonc",
    # Python
    "requirements.txt", "Pipfile", "Pipfile.lock", "pyproject.toml", "setup.py", "setup.cfg",
    "poetry.lock", "pdm.lock", "uv.lock",
    # Go
    "go.mod", "go.sum",
    # Rust
    "Cargo.toml", "Cargo.lock",
    # Java/Kotlin
    "pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle", "settings.gradle.kts",
    "gradle.properties",
    # PHP/Composer
    "composer.json", "composer.lock",
    # Ruby
    "Gemfile", "Gemfile.lock", "*.gemspec",
    # Elixir
    "mix.exs", "mix.lock",
    # Dart/Flutter
    "pubspec.yaml", "pubspec.lock",
    # .NET/C#
    "*.csproj", "*.sln", "*.slnx", "global.json", "packages.config",
    # Swift
    "Package.swift", "Package.resolved",
    # Scala
    "build.sbt", "scala-cli.yml",
    # Haskell
    "*.cabal", "stack.yaml", "cabal.project", "cabal.project.local",
    # OCaml
    "dune-project", "opam", "opam.lock",
    # Nim
    "*.nimble", "nim.cfg",
    # Crystal
    "shard.yml", "shard.lock",
    # R
    "DESCRIPTION", "renv.lock",
    # Julia
    "Project.toml", "Manifest.toml",
    # Build systems
    "CMakeLists.txt", "Makefile", "GNUmakefile",
    "SConstruct", "build.xml",
    "BUILD", "BUILD.bazel", "WORKSPACE", "bazel.lock",
    "justfile", ".justfile", "Taskfile.yml",
    "tox.ini", "Vagrantfile"
]

ENTRY_CANDIDATES = [
    # JavaScript/Node.js/TypeScript
    "src/index.ts", "src/index.js", "src/index.mjs",
    "src/main.ts", "src/main.js", "src/main.py",
    "src/app.ts", "src/app.js",
    "src/server.ts", "src/server.js",
    "index.ts", "index.js", "app.ts", "app.js",
    "lib/index.ts", "lib/index.js",
    # Go
    "main.go", "cmd/main.go", "cmd/*/main.go",
    # Python
    "main.py", "app.py", "server.py", "run.py", "cli.py",
    "src/main.py", "src/__main__.py",
    # .NET/C#
    "Program.cs", "src/Program.cs", "Main.cs",
    # Java
    "Main.java", "Application.java", "App.java",
    "src/main/java/Main.java",
    # Kotlin
    "Main.kt", "Application.kt", "App.kt",
    # Rust
    "src/main.rs", "src/lib.rs",
    # Swift
    "main.swift", "Package.swift", "Sources/main.swift",
    # Ruby
    "app.rb", "main.rb", "lib/app.rb",
    # PHP
    "index.php", "app.php", "public/index.php",
    # Go
    "cmd/*/main.go",
    # Scala
    "src/main/scala/Main.scala",
    # Haskell
    "Main.hs", "app/Main.hs",
    # Clojure
    "src/core.clj", "-main.clj",
    # Elixir
    "lib/application.ex", "mix.exs",
]

LINT_FILES = [
    ".eslintrc", ".eslintrc.json", ".eslintrc.js", ".eslintrc.cjs", ".eslintrc.yml", ".eslintrc.yaml",
    "eslint.config.js", "eslint.config.mjs", "eslint.config.cjs",
    ".prettierrc", ".prettierrc.json", ".prettierrc.js", ".prettierrc.yml",
    "prettier.config.js", "prettier.config.mjs",
    ".editorconfig",
    "tsconfig.json", "tsconfig.base.json", "tsconfig.build.json",
    ".golangci.yml", ".golangci.yaml",
    "setup.cfg", ".flake8", ".pylintrc", "mypy.ini",
    ".rubocop.yml", "phpcs.xml", "phpstan.neon",
    "biome.json", "biome.jsonc"
]

ENV_TEMPLATES = [".env.example", ".env.template", ".env.sample", ".env.defaults", ".env.local.example"]

SOURCE_EXTS = [
    "ts", "tsx", "js", "jsx", "mjs", "cjs",
    "py", "go", "java", "kt", "rb", "php",
    "rs", "cs", "cpp", "c", "h", "ex", "exs",
    "swift", "scala", "clj", "cljs", "lua",
    "vim", "vim", "hs", "ml", "ml", "nim", "cr",
    "r", "jl", "groovy", "gradle", "xml", "json"
]

MONOREPO_FILES = ["pnpm-workspace.yaml", "lerna.json", "nx.json", "rush.json", "turbo.json", "moon.yml"]
MONOREPO_DIRS = ["packages", "apps", "libs", "services", "modules"]

CI_CD_CONFIGS = {
    ".github/workflows": "GitHub Actions",
    ".gitlab-ci.yml": "GitLab CI",
    "Jenkinsfile": "Jenkins",
    ".circleci/config.yml": "CircleCI",
    ".travis.yml": "Travis CI",
    "azure-pipelines.yml": "Azure Pipelines",
    "appveyor.yml": "AppVeyor",
    ".drone.yml": "Drone CI",
    ".woodpecker.yml": "Woodpecker CI",
    "bitbucket-pipelines.yml": "Bitbucket Pipelines"
}

CONTAINER_FILES = [
    "Dockerfile", "docker-compose.yml", "docker-compose.yaml",
    ".dockerignore", "Dockerfile.*",
    "k8s", "kustomization.yaml", "Chart.yaml",
    "Vagrantfile", "podman-compose.yml"
]

SECURITY_CONFIGS = [
    ".snyk", "security.txt", "SECURITY.md",
    ".dependabot.yml", ".whitesource",
    "sbom.json", "sbom.spdx", ".bandit.yaml"
]

PERFORMANCE_MARKERS = [
    "benchmark", "bench", "perf.data", ".prof",
    "k6.js", "locustfile.py", "jmeter.jmx"
]


def parse_args():
    """Parse command-line arguments."""
    parser = argparse.ArgumentParser(
        description="Scan the current directory (project root) and output discovery information "
                    "for the acquire-codebase-knowledge skill.",
        add_help=True
    )
    parser.add_argument(
        "--output",
        type=str,
        help="Write output to FILE instead of stdout"
    )
    return parser.parse_args()


def should_exclude(path: Path) -> bool:
    """Check if a path should be excluded from scanning."""
    return any(part in EXCLUDE_DIRS for part in path.parts)


def get_directory_tree(max_depth: int = TREE_MAX_DEPTH) -> List[str]:
    """Get directory tree up to max_depth."""
    files = []

    def walk(path: Path, depth: int):
        if depth > max_depth or should_exclude(path):
            return
        try:
            for item in sorted(path.iterdir()):
                if should_exclude(item):
                    continue
                rel_path = item.relative_to(Path.cwd())
                files.append(str(rel_path))
                if item.is_dir():
                    walk(item, depth + 1)
        except (PermissionError, OSError):
            pass

    walk(Path.cwd(), 0)
    return files[:TREE_LIMIT]


def find_manifest_files() -> List[str]:
    """Find manifest files matching patterns."""
    found = []
    for pattern in MANIFESTS:
        if "*" in pattern:
            # Handle glob patterns
            for path in Path.cwd().glob(pattern):
                if path.is_file() and not should_exclude(path):
                    found.append(path.name)
        else:
            path = Path.cwd() / pattern
            if path.is_file():
                found.append(pattern)
    return sorted(set(found))


def read_file_preview(filepath: Path, max_lines: int = MANIFEST_PREVIEW_LINES) -> str:
    """Read file with line limit."""
    try:
        with open(filepath, 'r', encoding='utf-8', errors='replace') as f:
            lines = f.readlines()

        if not lines:
            return "None found."

        preview = ''.join(lines[:max_lines])
        if len(lines) > max_lines:
            preview += f"\n[TRUNCATED] Showing first {max_lines} of {len(lines)} lines."
        return preview
    except Exception as e:
        return f"[Error reading file: {e}]"


def find_entry_points() -> List[str]:
    """Find entry point candidates."""
    found = []
    for candidate in ENTRY_CANDIDATES:
        if Path(candidate).exists():
            found.append(candidate)
    return found


def find_lint_config() -> List[str]:
    """Find linting and formatting config files."""
    found = []
    for filename in LINT_FILES:
        if Path(filename).exists():
            found.append(filename)
    return found


def find_env_templates() -> List[tuple]:
    """Find environment variable templates."""
    found = []
    for filename in ENV_TEMPLATES:
        path = Path(filename)
        if path.exists():
            found.append((filename, path))
    return found


def search_todos() -> List[str]:
    """Search for TODO/FIXME/HACK comments."""
    todos = []
    patterns = ["TODO", "FIXME", "HACK"]
    exclude_dirs_str = "|".join(EXCLUDE_DIRS | {"test", "tests", "__tests__", "spec", "__mocks__", "fixtures"})

    try:
        for root, dirs, files in os.walk(Path.cwd()):
            # Remove excluded directories from dirs to prevent os.walk from descending
            dirs[:] = [d for d in dirs if d not in EXCLUDE_DIRS and d not in {"test", "tests", "__tests__", "spec", "__mocks__", "fixtures"}]

            for file in files:
                # Check file extension
                ext = Path(file).suffix.lstrip('.')
                if ext not in SOURCE_EXTS:
                    continue

                filepath = Path(root) / file
                try:
                    with open(filepath, 'r', encoding='utf-8', errors='replace') as f:
                        for line_num, line in enumerate(f, 1):
                            for pattern in patterns:
                                if pattern in line:
                                    rel_path = filepath.relative_to(Path.cwd())
                                    todos.append(f"{rel_path}:{line_num}: {line.strip()}")
                except Exception:
                    pass
    except Exception:
        pass

    return todos[:TODO_LIMIT]


def get_git_commits() -> List[str]:
    """Get recent git commits."""
    try:
        result = subprocess.run(
            ["git", "log", "--oneline", "-n", str(RECENT_COMMITS_LIMIT)],
            capture_output=True,
            text=True,
            cwd=Path.cwd()
        )
        if result.returncode == 0:
            return result.stdout.strip().split('\n') if result.stdout.strip() else []
        return []
    except Exception:
        return []


def get_git_churn() -> List[str]:
    """Get high-churn files from last 90 days."""
    try:
        result = subprocess.run(
            ["git", "log", "--since=90 days ago", "--name-only", "--pretty=format:"],
            capture_output=True,
            text=True,
            cwd=Path.cwd()
        )
        if result.returncode == 0:
            files = [f.strip() for f in result.stdout.split('\n') if f.strip()]
            # Count occurrences
            from collections import Counter
            counts = Counter(files)
            churn = sorted(counts.items(), key=lambda x: x[1], reverse=True)
            return [f"{count:4d} {filename}" for filename, count in churn[:CHURN_LIMIT]]
        return []
    except Exception:
        return []


def is_git_repo() -> bool:
    """Check if current directory is a git repository."""
    try:
        subprocess.run(
            ["git", "rev-parse", "--git-dir"],
            capture_output=True,
            cwd=Path.cwd(),
            timeout=2
        )
        return True
    except Exception:
        return False


def detect_monorepo() -> List[str]:
    """Detect monorepo signals."""
    signals = []

    for filename in MONOREPO_FILES:
        if Path(filename).exists():
            signals.append(f"Monorepo tool detected: {filename}")

    for dirname in MONOREPO_DIRS:
        if Path(dirname).is_dir():
            signals.append(f"Sub-package directory found: {dirname}/")

    # Check package.json workspaces
    if Path("package.json").exists():
        try:
            with open("package.json", 'r') as f:
                content = f.read()
                if '"workspaces"' in content:
                    signals.append("package.json has 'workspaces' field (npm/yarn workspaces monorepo)")
        except Exception:
            pass

    return signals


def detect_ci_cd_pipelines() -> List[str]:
    """Detect CI/CD pipeline configurations."""
    pipelines = []

    for config_path, pipeline_name in CI_CD_CONFIGS.items():
        path = Path(config_path)
        if path.is_file():
            pipelines.append(f"CI/CD: {pipeline_name}")
        elif path.is_dir():
            # Check for workflow files in directory
            try:
                if list(path.glob("*.yml")) or list(path.glob("*.yaml")):
                    pipelines.append(f"CI/CD: {pipeline_name}")
            except Exception:
                pass

    return pipelines


def detect_containers() -> List[str]:
    """Detect containerization and orchestration configs."""
    containers = []

    for config in CONTAINER_FILES:
        path = Path(config)
        if path.is_file():
            if "Dockerfile" in config:
                containers.append("Container: Docker found")
            elif "docker-compose" in config:
                containers.append("Orchestration: Docker Compose found")
            elif config.endswith(".yaml") or config.endswith(".yml"):
                containers.append(f"Container/Orchestration: {config}")
        elif path.is_dir():
            if config in ["k8s", "kubernetes"]:
                containers.append("Orchestration: Kubernetes configs found")
            try:
                if list(path.glob("*.yml")) or list(path.glob("*.yaml")):
                    containers.append(f"Container/Orchestration: {config}/ directory found")
            except Exception:
                pass

    return containers


def detect_security_configs() -> List[str]:
    """Detect security and compliance configurations."""
    security = []

    for config in SECURITY_CONFIGS:
        if Path(config).exists():
            config_name = config.replace(".yml", "").replace(".yaml", "").lstrip(".")
            security.append(f"Security: {config_name}")

    return security


def detect_performance_markers() -> List[str]:
    """Detect performance testing and profiling markers."""
    performance = []

    for marker in PERFORMANCE_MARKERS:
        if Path(marker).exists():
            performance.append(f"Performance: {marker} found")
        else:
            # Check for directories
            try:
                if Path(marker).is_dir():
                    performance.append(f"Performance: {marker}/ directory found")
            except Exception:
                pass

    return performance


def collect_code_metrics() -> dict:
    """Collect code metrics: file counts by extension, total LOC."""
    metrics = {
        "total_files": 0,
        "by_extension": {},
        "by_language": {},
        "total_lines": 0,
        "largest_files": []
    }

    # Language mapping
    lang_map = {
        "ts": "TypeScript", "tsx": "TypeScript/React", "js": "JavaScript",
        "jsx": "JavaScript/React", "py": "Python", "go": "Go",
        "java": "Java", "kt": "Kotlin", "rs": "Rust",
        "cs": "C#", "rb": "Ruby", "php": "PHP",
        "swift": "Swift", "scala": "Scala", "ex": "Elixir",
        "cpp": "C++", "c": "C", "h": "C Header",
        "clj": "Clojure", "lua": "Lua", "hs": "Haskell"
    }

    file_sizes = []

    try:
        for root, dirs, files in os.walk(Path.cwd()):
            dirs[:] = [d for d in dirs if d not in EXCLUDE_DIRS]

            for file in files:
                filepath = Path(root) / file
                ext = filepath.suffix.lstrip('.')

                if not ext or ext in {"pyc", "o", "a", "so"}:
                    continue

                try:
                    size = filepath.stat().st_size
                    file_sizes.append((filepath.relative_to(Path.cwd()), size))

                    metrics["total_files"] += 1
                    metrics["by_extension"][ext] = metrics["by_extension"].get(ext, 0) + 1

                    lang = lang_map.get(ext, "Other")
                    metrics["by_language"][lang] = metrics["by_language"].get(lang, 0) + 1

                    # Count lines for text files
                    if ext in SOURCE_EXTS and size < 1_000_000:  # Skip huge files
                        try:
                            with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
                                metrics["total_lines"] += len(f.readlines())
                        except Exception:
                            pass
                except Exception:
                    pass

        # Top 10 largest files
        file_sizes.sort(key=lambda x: x[1], reverse=True)
        metrics["largest_files"] = [
            f"{str(f)}: {s/1024:.1f}KB" for f, s in file_sizes[:10]
        ]

    except Exception:
        pass

    return metrics


def print_section(title: str, content: List[str], output_file=None) -> None:
    """Print a section with title and content."""
    lines = [f"\n=== {title} ==="]

    if isinstance(content, list):
        lines.extend(content if content else ["None found."])
    elif isinstance(content, str):
        lines.append(content)

    text = '\n'.join(lines) + '\n'

    if output_file:
        output_file.write(text)
    else:
        print(text, end='')


def main():
    """Main entry point."""
    args = parse_args()

    output_file = None
    if args.output:
        output_dir = Path(args.output).parent
        output_dir.mkdir(parents=True, exist_ok=True)
        output_file = open(args.output, 'w', encoding='utf-8')
        print(f"Writing output to: {args.output}", file=sys.stderr)

    try:
        # Directory tree
        print_section(
            f"DIRECTORY TREE (max depth {TREE_MAX_DEPTH}, source files only)",
            get_directory_tree(),
            output_file
        )

        # Stack detection
        manifests = find_manifest_files()
        if manifests:
            manifest_content = [""]
            for manifest in manifests:
                manifest_path = Path(manifest)
                manifest_content.append(f"--- {manifest} ---")
                if manifest == "bun.lockb":
                    manifest_content.append("[Binary lockfile — see package.json for dependency details.]")
                else:
                    manifest_content.append(read_file_preview(manifest_path))
            print_section("STACK DETECTION (manifest files)", manifest_content, output_file)
        else:
            print_section("STACK DETECTION (manifest files)", ["No recognized manifest files found in project root."], output_file)

        # Entry points
        entries = find_entry_points()
        if entries:
            entry_content = [f"Found: {e}" for e in entries]
            print_section("ENTRY POINTS", entry_content, output_file)
        else:
            print_section("ENTRY POINTS", ["No common entry points found. Check 'main' or 'scripts.start' in manifest files above."], output_file)

        # Linting config
        lint = find_lint_config()
        if lint:
            lint_content = [f"Found: {l}" for l in lint]
            print_section("LINTING AND FORMATTING CONFIG", lint_content, output_file)
        else:
            print_section("LINTING AND FORMATTING CONFIG", ["No linting or formatting config files found in project root."], output_file)

        # Environment templates
        envs = find_env_templates()
        if envs:
            env_content = []
            for filename, filepath in envs:
                env_content.append(f"--- {filename} ---")
                env_content.append(read_file_preview(filepath))
            print_section("ENVIRONMENT VARIABLE TEMPLATES", env_content, output_file)
        else:
            print_section("ENVIRONMENT VARIABLE TEMPLATES", ["No .env.example or .env.template found. Identify required environment variables by searching the code and config for environment variable reads."], output_file)

        # TODOs
        todos = search_todos()
        if todos:
            print_section("TODO / FIXME / HACK (production code only, test dirs excluded)", todos, output_file)
        else:
            print_section("TODO / FIXME / HACK (production code only, test dirs excluded)", ["None found."], output_file)

        # Git info
        if is_git_repo():
            commits = get_git_commits()
            if commits:
                print_section("GIT RECENT COMMITS (last 20)", commits, output_file)
            else:
                print_section("GIT RECENT COMMITS (last 20)", ["No commits found."], output_file)

            churn = get_git_churn()
            if churn:
                print_section("HIGH-CHURN FILES (last 90 days, top 20)", churn, output_file)
            else:
                print_section("HIGH-CHURN FILES (last 90 days, top 20)", ["None found."], output_file)
        else:
            print_section("GIT RECENT COMMITS (last 20)", ["Not a git repository or no commits yet."], output_file)
            print_section("HIGH-CHURN FILES (last 90 days, top 20)", ["Not a git repository."], output_file)

        # Monorepo detection
        monorepo = detect_monorepo()
        if monorepo:
            print_section("MONOREPO SIGNALS", monorepo, output_file)
        else:
            print_section("MONOREPO SIGNALS", ["No monorepo signals detected."], output_file)

        # Code metrics
        metrics = collect_code_metrics()
        metrics_output = [
            f"Total files scanned: {metrics['total_files']}",
            f"Total lines of code: {metrics['total_lines']}",
            ""
        ]
        if metrics["by_language"]:
            metrics_output.append("Files by language:")
            for lang, count in sorted(metrics["by_language"].items(), key=lambda x: x[1], reverse=True):
                metrics_output.append(f"  {lang}: {count}")
        if metrics["largest_files"]:
            metrics_output.append("")
            metrics_output.append("Top 10 largest files:")
            metrics_output.extend(metrics["largest_files"])
        print_section("CODE METRICS", metrics_output, output_file)

        # CI/CD Detection
        ci_cd = detect_ci_cd_pipelines()
        if ci_cd:
            print_section("CI/CD PIPELINES", ci_cd, output_file)
        else:
            print_section("CI/CD PIPELINES", ["No CI/CD pipelines detected."], output_file)

        # Container Detection
        containers = detect_containers()
        if containers:
            print_section("CONTAINERS & ORCHESTRATION", containers, output_file)
        else:
            print_section("CONTAINERS & ORCHESTRATION", ["No containerization configs detected."], output_file)

        # Security Configs
        security = detect_security_configs()
        if security:
            print_section("SECURITY & COMPLIANCE", security, output_file)
        else:
            print_section("SECURITY & COMPLIANCE", ["No security configs detected."], output_file)

        # Performance Markers
        performance = detect_performance_markers()
        if performance:
            print_section("PERFORMANCE & TESTING", performance, output_file)
        else:
            print_section("PERFORMANCE & TESTING", ["No performance testing configs detected."], output_file)

        # Final message
        final_msg = "\n=== SCAN COMPLETE ===\n"
        if output_file:
            output_file.write(final_msg)
        else:
            print(final_msg, end='')

        return 0

    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        return 1

    finally:
        if output_file:
            output_file.close()


if __name__ == "__main__":
    sys.exit(main())

Requirements and compatibility

Written for: GitHub Copilot, Claude Code

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Claude Code frontmatter, Needs Python

The author says: Cross-platform. Requires Python 3.8+ and git. Run scripts/scan.py from the target project root.

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

First committed by
GitHub avatar of SriSatyaLokeshSriSatyaLokesh
Publisher
GitHub (Official)
Distributed by
GitHub
Source
github/awesome-copilot · skills/acquire-codebase-knowledge · commit 797337f
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Contributors
SriSatyaLokesh, aaronpowell

AutoGineer is not affiliated with or endorsed by SriSatyaLokesh or GitHub.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download acquire-codebase-knowledge.zip