prompts.chatprompts.chatprompts.chat
TeamsBotsSkillsPromptsPromptmasters
BookFor KidsDevelopers
Login
CC0 2026 prompts.chat
DeepWikiHow to...DocsAPIPrivacyTermsSupportAboutGitHub
All Tags

Engineering Prompts

7 prompts
Python Complexity Hotspot Finder
Skill

Finds Python functions that are risky to change: cyclomatic complexity, nesting depth, length, parameters and returns from the AST, optionally ranked by git churn, with a prioritized refactoring plan and safe recipes such as guard clauses and lookup tables. Stdlib Python.

---
name: python-complexity-hotspot-finder
description: Finds Python functions that are risky to change: cyclomatic complexity, nesting depth, length, parameters and returns from the AST, optionally ranked by git churn, with a prioritized refactoring plan and safe recipes such as guard clauses and lookup tables. Stdlib Python.
---

# Python Complexity Hotspot Finder

You help Python developers, tech leads and maintainers find the functions that are hardest to change safely and decide what to refactor first. Big if/elif ladders, deep nesting and functions with seven flags are where bugs hide and where new teammates get stuck, but not every complex function is worth touching. You combine complexity metrics with how often code actually changes, explain the results in plain language, and propose small, test-backed refactoring steps.

You read code locally and never upload it. Metrics are a guide, not a verdict: you say when a high number is fine (for example a flat lookup) and the team makes the final call.

## Files in this skill

- `scripts/complexity_hotspots.py` - walks files or folders (skips .git, venvs, build dirs), measures every function and method with the `ast` module: cyclomatic complexity, nesting depth, lines, parameters, returns; optional `--churn DAYS` adds git commit counts per file and ranks by `cc x (1 + churn)`; findings H01-H07; `--format text|md|json`, `--min-severity`, `--top N`, threshold flags; `--self-test` runs 19 checks (Python 3.8+ standard library only)
- `references/complexity-metrics.md` - how each metric is counted, rough bands, what churn adds and what the numbers do not tell you
- `references/refactoring-recipes.md` - guard clauses, lookup tables, extract function, flag parameters, condition helpers, and what not to do
- `templates/hotspot-report.md` - the review you hand back
- `examples/billing.py` - a fictional billing module with a CC 22, 7-parameter pricing function; `examples/billing_refactored.py` - the same logic after refactoring (CC 5 at most)

## Workflow

### 1. Scope
Ask which package or folders matter, whether it is a git repository (for churn), what is changing soon (upcoming features touch which modules?), and whether there are tests. Exclude generated code, migrations and vendored libraries.

### 2. Run the scan
```
python3 scripts/complexity_hotspots.py src/
python3 scripts/complexity_hotspots.py src/ --churn 90 --top 15
python3 scripts/complexity_hotspots.py src/ --churn 90 --min-severity medium --format md > hotspots.md
python3 scripts/complexity_hotspots.py src/ --format json
python3 scripts/complexity_hotspots.py --self-test
```
Exit code 0 = nothing at or above `--min-severity`, 1 = findings, 2 = bad path or only unparsable files. Files with syntax errors are listed as PARSE ERROR and skipped.

| Code | Severity | Meaning |
|---|---|---|
| H01 | high | CC >= 15 (`--cc-high`) |
| H02 | medium | CC >= 10 (`--cc-warn`) |
| H03 | medium | nesting depth >= 4 |
| H04 | medium | 60+ lines |
| H05 | low | 6+ parameters (self/cls excluded) |
| H06 | low | 6+ return statements |
| H07 | high | hotspot: CC >= warn and file changed in 5+ commits in the churn window |

### 3. Interpret
- Rank by hotspot score when churn is available; a complex function nobody touches is low priority.
- Read the top 3-5 functions yourself before recommending anything. Check whether the complexity is accidental (copy-pasted branches, flags, deep nesting) or essential (real business rules).
- Flat dispatch functions (`invoice_status` with six early returns) are usually fine: say so.
- Check test coverage for each top hotspot; untested hotspots get characterization tests first.

### 4. Plan the refactor
For each top hotspot pick recipes from `references/refactoring-recipes.md`, list small steps (one commit each), estimate effort (S/M/L) and the expected CC afterwards. Never mix behavior changes with refactoring. Re-run the script after the change to show the before/after numbers.

### 5. Report
Fill `templates/hotspot-report.md`: summary, top hotspots table, a step-by-step plan for #1, what you leave alone on purpose and why, and the limits (per-file churn, renames).

## Example
```
python3 scripts/complexity_hotspots.py examples/billing.py
```
flags `calculate_invoice_total` with H01 (CC 22) and H05 (7 parameters) and `invoice_status` with H06 (6 returns, fine for a flat lookup). After extracting `tax_rate`, `line_total`, `apply_coupon` and `loyalty_discount` and moving rates into tables, `examples/billing_refactored.py` peaks at CC 5.

## Rules
- Measure first, then read the code; never recommend a refactor from numbers alone.
- Prefer small, reversible steps behind tests.
- Be honest about trade-offs: tables move complexity into data; helpers add jumps.
- Keep code on the user's machine.

FILE:references/complexity-metrics.md
# Complexity metrics: what they mean and how to read them

## Cyclomatic complexity (CC)
The number of independent paths through a function: 1 plus one for every decision point. `complexity_hotspots.py` counts:

| Construct | Adds |
|---|---|
| `if` / `elif` | 1 each (an `else` adds nothing) |
| `for`, `async for`, `while` | 1 |
| each `except` handler | 1 |
| `and` / `or` | 1 per extra operand (`a and b or c` adds 2) |
| comprehension (`for` part) and each of its `if` filters | 1 each |
| ternary `x if c else y` | 1 |
| `assert` | 1 |
| each `case` in `match` (Python 3.10+) | 1 |

Nested functions, classes and lambdas are measured on their own and do not add to the outer function.

### Rough bands (adjust with `--cc-warn` / `--cc-high`)
| CC | Reading |
|---|---|
| 1-5 | simple, easy to test |
| 6-10 | fine, keep an eye on it |
| 11-15 | hard to test fully; refactor when you next change it (H02) |
| 16+ | high risk; bugs hide here, plan a refactor (H01) |

CC is also the minimum number of test cases needed to cover every branch, which makes it a useful argument when talking to a team about test effort.

## Nesting depth
How many blocks deep the deepest statement sits (`if` inside `for` inside `try` = 3). An `elif` chain stays at the same depth. Depth 4+ (H03) usually means guard clauses or extracted helpers would help readability more than anything else.

## Length, parameters, returns
- **Lines** (H04, default 60): long functions mix several jobs. Length alone is weak; combined with high CC it is strong.
- **Parameters** (H05, default 6, `self`/`cls` excluded, `*args`/`**kwargs` counted): many flags often mean the function does several things; boolean flags are the strongest smell.
- **Returns** (H06, default 6): many exits are fine for a flat lookup (`invoice_status` style) but confusing in a long, nested function.

## Churn and hotspots (H07)
Complexity hurts only where people change code. With `--churn DAYS` the script counts how many commits touched each file in the last DAYS days (`git log --name-only`) and ranks by `score = cc x (1 + churn)`. A function with CC 12 in a file changed 30 times this quarter is a better refactoring target than a CC 25 parser nobody has touched in three years.

Limits: churn is per file, not per function; renames and big formatting commits inflate it; squash-merge workflows deflate it. Mention this when presenting results.

## What these numbers do not tell you
- Whether the code is correct or well tested; pair hotspots with coverage data if you have it.
- Domain complexity: some rules are genuinely complex, and a table-driven rewrite just moves the complexity into data (often still a win: data is easier to review and test).
- Readability of names and comments.

FILE:references/refactoring-recipes.md
# Refactoring recipes for complex Python functions

Always refactor behind tests. If the hotspot has no tests, first write characterization tests that pin today's behavior (including odd cases), then change structure in small commits, running tests after each step.

## 1. Guard clauses (fixes deep nesting, H03)
Return or `continue` early for the invalid or trivial cases instead of wrapping the main path in `if`.
```python
# before
for item in items:
    if item.qty > 0:
        if item.active:
            process(item)
# after
for item in items:
    if item.qty <= 0 or not item.active:
        continue
    process(item)
```

## 2. Lookup table instead of if/elif ladders (fixes H01/H02)
When branches only pick a value (a rate, a label, a handler), move the mapping into a dict.
```python
RATES = {("books", "EU"): 1.05, ("books", "*"): 1.08, ("*", "EU"): 1.2}
rate = RATES.get((cat, region), RATES.get((cat, "*"), 1.0))
```
For branches that run different code, map keys to functions: `HANDLERS[event.type](event)`.

## 3. Extract function (fixes H01, H04)
Give each job its own small, named function (`line_total`, `apply_coupon`, `loyalty_discount`). The parent becomes a readable sequence of steps, and each helper can be tested alone.

## 4. Replace boolean flag parameters (fixes H05)
`rush=False, gift_wrap=False, express=False` -> a small options set, an enum, or separate functions (`send_rush_order`). Group related parameters into a dataclass (`Address`, `PricingContext`).

## 5. Decompose complex conditions
`if customer.get("vip") or customer.get("orders", 0) > 20:` -> `if is_loyal(customer):`. The CC moves into a tiny, well-named function.

## 6. Polymorphism or `match` for type switches
A long `if kind == ...` over object types can become classes with a shared method, or a `match` statement that is easier to scan (CC stays similar but readability improves; say so honestly).

## 7. Split loops that do several things
One loop that filters, transforms, totals and logs -> a comprehension for filtering, a helper for transforming, `sum()` for totals.

## What not to do
- Do not chase a number: a flat 12-case lookup with CC 13 can be perfectly clear. Explain why you leave it.
- Do not refactor and change behavior in the same commit.
- Do not split a function into helpers that only make sense together and must be read in order; that adds jumps without reducing complexity.
- Do not refactor stable, untouched code just because it scores high; prioritize by churn and upcoming work.

FILE:templates/hotspot-report.md
# Complexity hotspot review: {{project}} ({{date}})

**Scope:** {{paths}} - {{function_count}} functions, average CC {{average_cc}}
**Thresholds:** CC warn {{cc_warn}} / high {{cc_high}}, depth {{max_depth}}, lines {{max_lines}}, params {{max_params}}; churn window {{churn_days}} days

## Summary
- {{one_sentence_overall_health}}
- Top risk: `{{top_function}}` ({{top_file}}) - {{why_it_matters}}
- Recommended next step: {{next_step}}

## Top hotspots
| Rank | Function | File | CC | Depth | Lines | Churn | Why it matters | Suggested refactor | Effort |
|---|---|---|---|---|---|---|---|---|---|
| 1 | | | | | | | | | S / M / L |
| 2 | | | | | | | | | |
| 3 | | | | | | | | | |

## Refactoring plan for the #1 hotspot
1. Characterization tests to add first: {{tests}}
2. Steps (one commit each): {{steps}}
3. Expected result: CC {{cc_before}} -> about {{cc_after}}, no behavior change
4. Risks and how we will check them: {{risks}}

## Left as is (on purpose)
- `{{function}}`: {{reason, e.g. flat lookup, stable for 2 years, scheduled for removal}}

## Notes and limits
- Churn is counted per file from git history; renames or formatting commits can inflate it.
- Metrics point to where to look; the team decides what to change.

FILE:examples/billing.py
"""Fictional billing module with typical hotspots (demo data for complexity_hotspots.py)."""


def calculate_invoice_total(customer, items, coupon=None, region="EU", currency="EUR", rush=False, gift_wrap=False):
    total = 0
    for item in items:
        if item.get("qty", 0) <= 0:
            continue
        price = item["price"] * item["qty"]
        if item.get("category") == "books":
            if region == "EU":
                price = price * 1.05
            elif region == "UK":
                price = price
            else:
                price = price * 1.08
        elif item.get("category") == "food":
            if region == "EU" and not customer.get("business"):
                price = price * 1.07
            else:
                price = price * 1.0
        else:
            if region == "EU":
                price = price * 1.2
            elif region == "UK":
                price = price * 1.2
            elif region == "US" and customer.get("state") in ("CA", "NY"):
                price = price * 1.09
            else:
                price = price * 1.0
        total += price
    if coupon:
        if coupon.get("type") == "percent" and coupon.get("value", 0) < 50:
            total = total * (1 - coupon["value"] / 100)
        elif coupon.get("type") == "fixed":
            total = max(0, total - coupon["value"])
    if customer.get("vip") or customer.get("orders", 0) > 20:
        total = total * 0.95
    if rush:
        total += 15 if currency == "EUR" else 18
    if gift_wrap:
        total += 3
    return round(total, 2)


def invoice_status(invoice, today):
    if invoice["paid"]:
        return "paid"
    if invoice.get("disputed"):
        return "disputed"
    days = (today - invoice["due"]).days
    if days <= 0:
        return "open"
    if days <= 30:
        return "overdue"
    if days <= 90:
        return "late"
    return "collections"


def format_amount(value, currency):
    return "%s %.2f" % (currency, value)

FILE:examples/billing_refactored.py
"""The same billing logic after refactoring the hotspot (demo data for complexity_hotspots.py)."""

TAX_RATES = {
    # (category, region) -> rate; "*" means any
    ("books", "EU"): 1.05, ("books", "UK"): 1.0, ("books", "*"): 1.08,
    ("food", "EU"): 1.07, ("food", "*"): 1.0,
    ("*", "EU"): 1.2, ("*", "UK"): 1.2, ("*", "*"): 1.0,
}
US_TAXED_STATES = {"CA": 1.09, "NY": 1.09}
RUSH_FEE = {"EUR": 15, "USD": 18}
GIFT_WRAP_FEE = 3


def tax_rate(category, region, customer):
    if category == "food" and customer.get("business"):
        return 1.0
    if category not in ("books", "food") and region == "US":
        return US_TAXED_STATES.get(customer.get("state"), 1.0)
    key_category = category if category in ("books", "food") else "*"
    return TAX_RATES.get((key_category, region), TAX_RATES[(key_category, "*")])


def line_total(item, region, customer):
    return item["price"] * item["qty"] * tax_rate(item.get("category"), region, customer)


def apply_coupon(total, coupon):
    if not coupon:
        return total
    if coupon.get("type") == "percent" and coupon.get("value", 0) < 50:
        return total * (1 - coupon["value"] / 100)
    if coupon.get("type") == "fixed":
        return max(0, total - coupon["value"])
    return total


def loyalty_discount(total, customer):
    loyal = customer.get("vip") or customer.get("orders", 0) > 20
    return total * 0.95 if loyal else total


def calculate_invoice_total(customer, items, coupon=None, region="EU", currency="EUR", options=()):
    subtotal = sum(line_total(i, region, customer) for i in items if i.get("qty", 0) > 0)
    total = loyalty_discount(apply_coupon(subtotal, coupon), customer)
    if "rush" in options:
        total += RUSH_FEE.get(currency, 18)
    if "gift_wrap" in options:
        total += GIFT_WRAP_FEE
    return round(total, 2)

FILE:scripts/complexity_hotspots.py
#!/usr/bin/env python3
"""complexity_hotspots.py - find Python functions that are hard to change safely.

Measures per function/method (standard library only, Python 3.8+):
  cc       cyclomatic complexity (1 + decision points: if/elif, for/while, except,
           boolean operators, comprehension ifs, ternaries, match cases, assert)
  depth    deepest nesting of blocks inside the function
  lines    function length in source lines
  params   number of parameters (excluding self/cls)
  returns  number of return statements
Optional --churn adds how many commits touched each file in the last N days (git log),
and ranks hotspots by cc x (1 + churn).

Findings (severity):
  H01 cc >= --cc-high (default 15)        high
  H02 cc >= --cc-warn (default 10)         medium
  H03 nesting depth >= --max-depth (4)     medium
  H04 lines >= --max-lines (60)            medium
  H05 params >= --max-params (6)           low
  H06 returns >= --max-returns (6)         low
  H07 hotspot: cc >= cc-warn and file churn >= --churn-min (5)   high

Usage:
  complexity_hotspots.py PATH [PATH ...] [--format text|md|json] [--min-severity low|medium|high]
                         [--churn DAYS] [--top N] [--cc-warn N] [--cc-high N] ...
  complexity_hotspots.py --self-test
Exit codes: 0 no findings at or above min severity, 1 findings present, 2 usage/parse error.
"""
import argparse, ast, json, os, subprocess, sys

SEV = {"low": 1, "medium": 2, "high": 3}
SKIP_DIRS = {".git", ".venv", "venv", "env", "__pycache__", "node_modules", "build", "dist", ".tox", ".mypy_cache"}


class FuncVisitor(ast.NodeVisitor):
    """Computes metrics for one function body without descending into nested defs."""

    BLOCKS = (ast.If, ast.For, ast.AsyncFor, ast.While, ast.Try, ast.With, ast.AsyncWith)

    def __init__(self):
        self.cc = 1
        self.max_depth = 0
        self.returns = 0
        self._depth = 0

    def generic_visit(self, node):
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
            return  # nested definitions are measured separately (lambdas count as 0)
        block = isinstance(node, self.BLOCKS) or type(node).__name__ in ("TryStar", "Match")
        if isinstance(node, (ast.If, ast.For, ast.AsyncFor, ast.While, ast.IfExp, ast.Assert)):
            self.cc += 1
        elif isinstance(node, ast.ExceptHandler):
            self.cc += 1
        elif isinstance(node, ast.BoolOp):
            self.cc += len(node.values) - 1
        elif isinstance(node, ast.comprehension):
            self.cc += 1 + len(node.ifs)
        elif type(node).__name__ == "match_case":
            self.cc += 1
        elif isinstance(node, ast.Return):
            self.returns += 1
        if block:
            # an elif is an If inside orelse; do not count it as deeper nesting
            self._depth += 1
            self.max_depth = max(self.max_depth, self._depth)
        super().generic_visit(node)
        if block:
            self._depth -= 1

    def visit_If(self, node):
        self.cc += 1
        self.visit(node.test)
        self._depth += 1
        self.max_depth = max(self.max_depth, self._depth)
        for n in node.body:
            self.visit(n)
        self._depth -= 1
        orelse = node.orelse
        if len(orelse) == 1 and isinstance(orelse[0], ast.If):
            self.visit_If(orelse[0])  # elif chain: same depth
        else:
            self._depth += 1
            for n in orelse:
                self.visit(n)
            self._depth -= 1


def measure_function(node):
    v = FuncVisitor()
    for stmt in node.body:
        v.visit(stmt)
    args = node.args
    names = [a.arg for a in getattr(args, "posonlyargs", []) + args.args + args.kwonlyargs]
    if args.vararg: names.append(args.vararg.arg)
    if args.kwarg: names.append(args.kwarg.arg)
    params = len([n for n in names if n not in ("self", "cls")])
    end = getattr(node, "end_lineno", node.lineno)
    return {"cc": v.cc, "depth": v.max_depth, "lines": end - node.lineno + 1, "params": params, "returns": v.returns}


def analyze_source(src, filename="<string>"):
    tree = ast.parse(src, filename=filename)
    out = []

    def walk(node, prefix):
        for child in ast.iter_child_nodes(node):
            if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
                name = prefix + child.name
                m = measure_function(child)
                m.update({"file": filename, "function": name, "line": child.lineno})
                out.append(m)
                walk(child, name + ".")
            elif isinstance(child, ast.ClassDef):
                walk(child, prefix + child.name + ".")
            else:
                walk(child, prefix)

    walk(tree, "")
    return out


def iter_py_files(paths):
    for p in paths:
        if os.path.isfile(p):
            if p.endswith(".py"): yield p
            continue
        for root, dirs, files in os.walk(p):
            dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS)
            for f in sorted(files):
                if f.endswith(".py"):
                    yield os.path.join(root, f)


def git_churn(path, days):
    """Commits per file in the last `days` days, keyed by absolute path. Empty dict if not a git repo."""
    base = path if os.path.isdir(path) else os.path.dirname(os.path.abspath(path)) or "."
    try:
        top = subprocess.run(["git", "-C", base, "rev-parse", "--show-toplevel"], capture_output=True, text=True, check=True).stdout.strip()
        log = subprocess.run(["git", "-C", top, "log", "--since=%d.days" % days, "--name-only", "--pretty=format:"],
                             capture_output=True, text=True, check=True).stdout
    except (OSError, subprocess.CalledProcessError):
        return {}
    churn = {}
    for line in log.splitlines():
        line = line.strip()
        if line.endswith(".py"):
            k = os.path.normpath(os.path.join(top, line))
            churn[k] = churn.get(k, 0) + 1
    return churn


def findings_for(m, o):
    f = []
    if m["cc"] >= o.cc_high: f.append(("H01", "high", "cyclomatic complexity %d >= %d" % (m["cc"], o.cc_high)))
    elif m["cc"] >= o.cc_warn: f.append(("H02", "medium", "cyclomatic complexity %d >= %d" % (m["cc"], o.cc_warn)))
    if m["depth"] >= o.max_depth: f.append(("H03", "medium", "nesting depth %d >= %d" % (m["depth"], o.max_depth)))
    if m["lines"] >= o.max_lines: f.append(("H04", "medium", "%d lines >= %d" % (m["lines"], o.max_lines)))
    if m["params"] >= o.max_params: f.append(("H05", "low", "%d parameters >= %d" % (m["params"], o.max_params)))
    if m["returns"] >= o.max_returns: f.append(("H06", "low", "%d return statements >= %d" % (m["returns"], o.max_returns)))
    if m.get("churn") is not None and m["cc"] >= o.cc_warn and m["churn"] >= o.churn_min:
        f.append(("H07", "high", "hotspot: complex (cc %d) and changed in %d commits recently" % (m["cc"], m["churn"])))
    return f


def run(paths, o):
    results, errors = [], []
    churn = {}
    if o.churn:
        for p in paths:
            churn.update(git_churn(p, o.churn))
    for f in iter_py_files(paths):
        try:
            with open(f, encoding="utf-8") as fh:
                ms = analyze_source(fh.read(), f)
        except (SyntaxError, UnicodeDecodeError) as e:
            errors.append("%s: %s" % (f, e)); continue
        for m in ms:
            if o.churn:
                m["churn"] = churn.get(os.path.normpath(os.path.abspath(f)), 0)
            m["score"] = m["cc"] * (1 + m.get("churn", 0))
            m["findings"] = [dict(code=c, severity=s, message=t) for c, s, t in findings_for(m, o)]
            results.append(m)
    results.sort(key=lambda m: (-m["score"], -m["cc"], m["file"], m["line"]))
    return results, errors


def render(results, errors, o):
    minsev = SEV[o.min_severity]
    flagged = [m for m in results if any(SEV[x["severity"]] >= minsev for x in m["findings"])]
    top = flagged[: o.top] if o.top else flagged
    n = len(results)
    avg = sum(m["cc"] for m in results) / n if n else 0
    if o.format == "json":
        return json.dumps({"functions": n, "average_cc": round(avg, 2), "flagged": len(flagged), "errors": errors,
                           "hotspots": top}, indent=2)
    churn_col = o.churn is not None and o.churn > 0
    if o.format == "md":
        head = "| Rank | Function | File:line | CC | Depth | Lines | Params |" + (" Churn |" if churn_col else "") + " Findings |"
        sep = "|---|---|---|---|---|---|---|" + ("---|" if churn_col else "") + "---|"
        rows = [head, sep]
        for i, m in enumerate(top, 1):
            fs = "; ".join("%s %s" % (x["code"], x["message"]) for x in m["findings"])
            rows.append("| %d | `%s` | %s:%d | %d | %d | %d | %d |%s %s |" % (i, m["function"], m["file"], m["line"], m["cc"], m["depth"], m["lines"], m["params"],
                        (" %d |" % m.get("churn", 0)) if churn_col else "", fs))
        rows.append("")
        rows.append("%d functions, average CC %.1f, %d flagged at %s+." % (n, avg, len(flagged), o.min_severity))
        return "\n".join(rows)
    lines = ["Complexity hotspots: %d functions, average CC %.1f, %d flagged (min severity %s)" % (n, avg, len(flagged), o.min_severity), ""]
    for i, m in enumerate(top, 1):
        extra = (" churn=%d" % m["churn"]) if "churn" in m else ""
        lines.append("%2d. %s  (%s:%d)  cc=%d depth=%d lines=%d params=%d returns=%d%s score=%d" % (
            i, m["function"], m["file"], m["line"], m["cc"], m["depth"], m["lines"], m["params"], m["returns"], extra, m["score"]))
        for x in m["findings"]:
            lines.append("      [%s] %s %s" % (x["severity"].upper(), x["code"], x["message"]))
    if not top: lines.append("No functions above the thresholds.")
    for e in errors: lines.append("PARSE ERROR " + e)
    return "\n".join(lines)


def parser():
    p = argparse.ArgumentParser(description="Find complex, frequently changed Python functions.")
    p.add_argument("paths", nargs="*")
    p.add_argument("--format", choices=["text", "md", "json"], default="text")
    p.add_argument("--min-severity", choices=list(SEV), default="low")
    p.add_argument("--churn", type=int, metavar="DAYS", help="add git churn for the last DAYS days")
    p.add_argument("--churn-min", type=int, default=5)
    p.add_argument("--top", type=int, default=0, help="show only the top N flagged functions")
    p.add_argument("--cc-warn", type=int, default=10)
    p.add_argument("--cc-high", type=int, default=15)
    p.add_argument("--max-depth", type=int, default=4)
    p.add_argument("--max-lines", type=int, default=60)
    p.add_argument("--max-params", type=int, default=6)
    p.add_argument("--max-returns", type=int, default=6)
    p.add_argument("--self-test", action="store_true")
    return p


def self_test():
    o = parser().parse_args([])
    def cc(src):
        return {m["function"]: m for m in analyze_source(src)}
    checks = []
    def check(name, cond): checks.append((name, bool(cond)))
    m = cc("def f():\n    return 1\n")["f"]
    check("straight-line function has cc 1", m["cc"] == 1 and m["depth"] == 0)
    m = cc("def f(x):\n    if x:\n        return 1\n    return 2\n")["f"]
    check("one if gives cc 2", m["cc"] == 2 and m["returns"] == 2)
    m = cc("def f(x):\n    if x == 1:\n        a = 1\n    elif x == 2:\n        a = 2\n    elif x == 3:\n        a = 3\n    else:\n        a = 0\n    return a\n")["f"]
    check("elif chain adds 1 each, depth stays 1", m["cc"] == 4 and m["depth"] == 1)
    m = cc("def f(a, b, c):\n    return a and b or c\n")["f"]
    check("boolean operators add per operand", m["cc"] == 3)
    m = cc("def f(xs):\n    return [x for x in xs if x if x > 2]\n")["f"]
    check("comprehension and its ifs count", m["cc"] == 4)
    m = cc("def f():\n    try:\n        g()\n    except ValueError:\n        pass\n    except KeyError:\n        pass\n")["f"]
    check("each except handler counts", m["cc"] == 3)
    m = cc("def f(x):\n    return 1 if x else 2\n")["f"]
    check("ternary counts", m["cc"] == 2)
    m = cc("def f(x):\n    while x:\n        for i in x:\n            if i:\n                with open(i) as h:\n                    pass\n")["f"]
    check("nesting depth 4", m["depth"] == 4 and m["cc"] == 4)
    r = cc("def outer():\n    def inner(x):\n        if x: return 1\n    return inner\n")
    check("nested function measured separately", r["outer"]["cc"] == 1 and r["outer.inner"]["cc"] == 2)
    r = cc("class A:\n    def m(self, a, b):\n        pass\n")
    check("method name and self excluded from params", r["A.m"]["params"] == 2)
    r = cc("def f(a, b, c, d, e, f, *args, **kw):\n    pass\n")
    check("varargs counted as params", r["f"]["params"] == 8)
    m = cc("def f(x):\n    assert x\n    return x\n")["f"]
    check("assert counts", m["cc"] == 2)
    if sys.version_info >= (3, 10):
        m = cc("def f(x):\n    match x:\n        case 1:\n            return 1\n        case _:\n            return 0\n")["f"]
        check("match cases count", m["cc"] == 3)
    else:
        check("match cases count (skipped < 3.10)", True)
    big = "def big(x):\n" + "".join("    if x == %d:\n        return %d\n" % (i, i) for i in range(16)) + "    return -1\n"
    m = cc(big)["big"]
    fs = [c for c, _, _ in findings_for(m, o)]
    check("cc 17 gives H01 and many returns H06", m["cc"] == 17 and "H01" in fs and "H06" in fs and "H02" not in fs)
    m = dict(cc=11, depth=1, lines=10, params=1, returns=1)
    check("cc 11 gives H02 only", [c for c, _, _ in findings_for(m, o)] == ["H02"])
    m = dict(cc=11, depth=1, lines=10, params=1, returns=1, churn=7)
    check("complex + churn gives H07", "H07" in [c for c, _, _ in findings_for(m, o)])
    m = dict(cc=3, depth=1, lines=10, params=1, returns=1, churn=40)
    check("simple + churn is not a hotspot", findings_for(m, o) == [])
    m = dict(cc=2, depth=5, lines=80, params=7, returns=1)
    check("depth, length, params flagged", [c for c, _, _ in findings_for(m, o)] == ["H03", "H04", "H05"])
    try:
        analyze_source("def broken(:\n")
        check("syntax error raised", False)
    except SyntaxError:
        check("syntax error raised", True)
    ok = all(c for _, c in checks)
    for n, c in checks:
        print(("PASS  " if c else "FAIL  ") + n)
    print("%d/%d checks passed" % (sum(c for _, c in checks), len(checks)))
    return 0 if ok else 1


def main(argv=None):
    o = parser().parse_args(argv)
    if o.self_test:
        return self_test()
    if not o.paths:
        parser().print_usage(sys.stderr); return 2
    for p in o.paths:
        if not os.path.exists(p):
            print("no such path: " + p, file=sys.stderr); return 2
    results, errors = run(o.paths, o)
    print(render(results, errors, o))
    if errors and not results:
        return 2
    minsev = SEV[o.min_severity]
    return 1 if any(SEV[x["severity"]] >= minsev for m in results for x in m["findings"]) else 0


if __name__ == "__main__":
    sys.exit(main())
Best PracticesRefactoringEngineering+3
F@f
0
Internal Hackathon Plan Builder (YAML)
Text

Plan an internal hackathon as one YAML document: theme and success measures, a timeline from 4 weeks before to 2 weeks after, idea prompts and cross-functional teams, logistics and data rules, a judging rubric, follow-through for winning ideas, budget, ready-to-post messages and risks.

1role: >-
2 You are an experienced engineering leader and event organizer who has run internal
3 hackathons for small startups and for product teams inside larger companies. You design
4 hackathons that are fun, inclusive and safe, that do not burn people out, and that end with
5 a few ideas that actually ship instead of a pile of forgotten demos.
6
7context:
8 company: "${company:a 60-person B2B SaaS company, about 25 engineers}"
9 format: "${format:hybrid; office in one city plus remote people in 3 time zones}"
10 dates_and_length: "${dates:2 days, Thursday-Friday, during working hours}"
...+81 more lines
YAMLCollaborationEngineering+5
F@f
0
Python Exception Handling Smell Finder
Skill

Finds risky exception handling in Python code offline: bare and swallowed excepts, errors turned into silent return values, raise without from, caught KeyboardInterrupt, return in finally, logs without traceback and oversized try blocks, with file:line, severity and fix recipes. Stdlib Python.

---
name: python-exception-handling-smell-finder
description: Finds risky exception handling in Python code offline: bare and swallowed excepts, errors turned into silent return values, raise without from, caught KeyboardInterrupt, return in finally, logs without traceback and oversized try blocks, with file:line, severity and fix recipes. Stdlib Python.
---

# Python Exception Handling Smell Finder

You help developers find the places where a Python codebase hides its own failures: `except: pass`, broad handlers that return `None` or `[]`, re-raised errors that lose their cause, logs without a traceback, `return` inside `finally`, and workers that swallow Ctrl+C. These smells turn crashes that would be fixed in a day into silent data loss that is found weeks later. You scan the code, explain which findings can really hurt in production, and propose small, safe fixes.

You work on the user's code locally and never upload it. The script only parses files with `ast`; it never imports or runs project code. You suggest changes and explain the behavior difference (which errors will now propagate), but you do not rewrite large parts of the code without the user's go-ahead.

## Files in this skill

- `scripts/exception_smells.py` - scans files or folders (skips venvs, build and cache folders) and reports EX01-EX08 with file:line, severity, the source line and a fix hint; `--format text|json|md`, `--min-severity`, `--ignore EX07,EX08`, `--max-try-statements N`, inline `# smell: ignore[EX03]` comments; `--self-test` runs 23 checks (Python 3.8+ standard library only)
- `references/smell-catalog.md` - every code, why it hurts, what is deliberately not reported, and the known limits of static analysis
- `references/fix-recipes.md` - eight before/after fixes: narrow the type, `raise ... from err`, `logger.exception`, cleanup-only `finally`, letting shutdown signals through, smaller try blocks, loud retries, visible catch-all boundaries
- `templates/exception-report.md` - the review summary you hand back
- `examples/sync_orders.py` - a fictional nightly order sync with eight findings (3 high); `examples/sync_orders_fixed.py` - the same job with every smell fixed (0 findings)

## Workflow

### 1. Scope
Ask what to scan (a PR diff, a package, a whole repo), the Python version, how the code reports errors today (logging setup, error tracker such as Sentry) and whether any module is a deliberate catch-all boundary (web handler, job runner, CLI `main`). For a PR, scan only the changed files first.

### 2. Run the scanner
```
python3 scripts/exception_smells.py path/to/package
python3 scripts/exception_smells.py src tests --min-severity medium
python3 scripts/exception_smells.py src --format md > exception-report-table.md
python3 scripts/exception_smells.py --self-test
```
Exit 0 = no high findings, 1 = at least one high finding, 2 = bad input. Without a shell, search the code for `except:`, `except Exception`, `except BaseException`, `finally:` and `raise ` inside except blocks, and apply `references/smell-catalog.md` by hand.

### 3. Triage
Read each finding in context before proposing a fix:
- **High (EX01, EX02, EX05, EX06)**: fix these first; they hide failures or break shutdown.
- **Medium (EX03, EX04)**: fix when the function is not a deliberate boundary; at a boundary, make sure it logs with a traceback.
- **Low (EX07, EX08)**: cheap improvements; batch them or suppress with a reason.
- Ask "what did the author expect to fail here?" and narrow the handler to that type.
- Mark a finding as accepted only with a reason, and add `# smell: ignore[CODE] - reason` on the line.

### 4. Fix
Use `references/fix-recipes.md`. Keep each change small and explain the new behavior: "a malformed `sync.json` now raises `JSONDecodeError` instead of silently using defaults". Suggest a test for every error path that now propagates.

### 5. Verify
Re-run the scanner until no high findings remain, run the test suite, and check that a forced failure now shows up in logs with a traceback. Suggest adding the scanner to CI with `--min-severity high` so new swallowed errors fail the build.

### 6. Report
Fill `templates/exception-report.md`: counts, the fixes for high and medium findings, accepted findings with reasons, behavior changes and what was verified.

## Rules
- Never execute or import the user's code to analyze it.
- Do not "fix" a smell by catching more broadly or adding `# smell: ignore` without a reason.
- A narrow `except SomeError: pass` can be correct; do not flag it as a bug without context.
- Call out that static analysis cannot see which exceptions a call raises or how custom logging wrappers behave.

FILE:references/smell-catalog.md
# Exception handling smell catalog

Each code below is reported by `scripts/exception_smells.py`. Severity says how likely the smell is to hide a real failure in production, not how ugly it looks.

| Code | Severity | Smell | Why it hurts |
|---|---|---|---|
| EX01 | high | bare `except:` | Also catches `KeyboardInterrupt`, `SystemExit` and `GeneratorExit`, so Ctrl+C, `sys.exit()` and clean shutdown stop working, and every bug inside the try becomes "handled". |
| EX02 | high | broad except whose body only `pass`es, `continue`s or returns a constant | The error disappears without a log line, metric or return signal. The caller sees success. This is the classic "it silently did nothing" bug. |
| EX03 | medium | broad except that neither re-raises nor logs | The error is turned into a normal value (`None`, `[]`, `{"ok": False}`) that callers often ignore. Not always wrong at a boundary, but it must be deliberate and visible. |
| EX04 | medium | `raise NewError(...)` inside `except` without `from` | Python still shows "During handling of the above exception, another exception occurred", but the link reads like a second bug. `raise ... from err` states the cause; `from None` hides it on purpose (for example to avoid leaking secrets). |
| EX05 | high | `except BaseException` / `KeyboardInterrupt` / `SystemExit` without re-raise | Swallows shutdown signals. Workers that ignore SIGINT or `sys.exit()` hang deploys and leave half-finished work. |
| EX06 | high | `return`, `break` or `continue` inside `finally` | Silently cancels any exception raised in the try or except block, including ones you never expected. Python 3.14 warns about this (PEP 765). |
| EX07 | low | `logger.error(...)` / `warning` in `except` without traceback | The message says what failed but not where. Use `logger.exception(...)` (ERROR level with traceback) or pass `exc_info=True`. |
| EX08 | low | broad except around a large try body (default > 8 statements) | One handler covers many operations, so a bug in any of them is treated like the expected failure. Wrap only the call that can fail. |
| EX00 | error | file could not be parsed | Syntax error or a newer syntax than the running Python; the file was not checked. |

## What is NOT reported
- Narrow handlers that pass: `except FileNotFoundError: pass` is often correct (for example optional config). Review them, but they are not smells by default.
- Handlers that re-raise (`raise`, `raise err`, `raise X from err`).
- Handlers that log with a traceback or report to an error tracker (`logger.exception`, `exc_info=True`, `sentry_sdk.capture_exception`, `traceback.print_exc`).
- `break` / `continue` inside a loop that itself lives in the `finally` block.

## Known limits
- Static analysis only: the scanner cannot know which exceptions a call raises, whether a custom logger wrapper logs tracebacks, or whether a returned error value is checked by callers.
- Logger detection is by name (`log`, `logger`, `logging`, `LOG`, `_logger`, `self.logger`, ...). A differently named logger looks like "no logging" and may produce EX03 instead of EX07.
- `contextlib.suppress(Exception)` is not reported; search for it separately if the codebase uses it.

## Suppressing a finding on purpose
Add a trailing comment on the reported line with a reason in the code review:

```python
except Exception:  # smell: ignore[EX03] - top-level boundary, error returned to the API client as 500
```

FILE:references/fix-recipes.md
# Fix recipes

Pick the smallest change that makes the failure visible to the right place: the caller, the log, or the user.

## 1. Catch what you expect, let the rest propagate (EX01, EX02, EX03)
```python
# before
try:
    cfg = json.load(open(path))
except:
    cfg = {}

# after
try:
    with open(path) as fh:
        cfg = json.load(fh)
except FileNotFoundError:
    logger.info("no %s, using defaults", path)
    cfg = {}
# a broken JSON file now raises json.JSONDecodeError instead of silently using defaults
```
Ask: "Which failure did the author have in mind?" Catch exactly that type.

## 2. Keep the cause when translating errors (EX04)
```python
except KeyError as err:
    raise OrderError(f"order {order_id} is missing {err}") from err
```
Use `from None` only when the original exception would leak secrets or confuse the user, and say so in a comment.

## 3. Log with the traceback, once (EX07)
```python
except PaymentError:
    logger.exception("payment %s failed", payment_id)   # ERROR level + traceback
    raise
```
Log at the boundary that handles the error, not at every layer it passes through (otherwise one failure becomes five log lines).

## 4. Never return from finally (EX06)
```python
# before
try:
    process()
finally:
    if pushed == 0:
        return {"ok": True}

# after
try:
    process()
finally:
    client.close()          # cleanup only
return {"ok": True, "pushed": pushed}
```
`finally` is for cleanup. Move results and decisions after the try statement.

## 5. Let shutdown signals through (EX05)
```python
except KeyboardInterrupt:
    save_checkpoint()
    raise
```
In worker loops, catch `Exception` for per-item failures and let `BaseException` subclasses stop the process.

## 6. Shrink the try body (EX08)
Wrap only the line that can raise the expected error. Put the "happy path" after the try in an `else:` block or after the statement.

```python
try:
    resp = session.get(url, timeout=10)
except requests.RequestException as err:
    raise FetchError(url) from err
else:
    data = resp.json()
```

## 7. Retries: fail loudly after the last attempt
```python
for attempt in range(3):
    try:
        return client.send(msg)
    except (ConnectionError, TimeoutError):
        logger.debug("retry %d", attempt + 1)
        time.sleep(2 ** attempt)
raise DeliveryError(f"message {msg.id} not sent after 3 attempts")
```

## 8. Boundaries are allowed to catch everything, visibly
A web request handler, a job runner or a CLI `main()` may catch `Exception` to turn it into a 500 response, a failed job status or exit code 1, as long as it logs with the traceback (or reports to the error tracker) and does not hide `KeyboardInterrupt`/`SystemExit`.

FILE:templates/exception-report.md
# Exception handling review: {{project_or_pr}}

**Scanned:** {{files_scanned}} files ({{paths}}) on {{date}}, `exception_smells.py` {{options}}
**Result:** {{high}} high, {{medium}} medium, {{low}} low, {{parse_errors}} parse errors

## Fix first (high)
| # | Location | Code | What can go wrong in production | Proposed fix |
|---|---|---|---|---|
| 1 | `{{file}}:{{line}}` | {{code}} | {{impact}} | {{fix}} |

## Fix in this PR if cheap (medium)
| # | Location | Code | Proposed fix |
|---|---|---|---|
| 1 | `{{file}}:{{line}}` | {{code}} | {{fix}} |

## Low / accepted on purpose
- `{{file}}:{{line}}` {{code}}: {{reason it is fine, or suppress comment added}}

## Behavior changes to check
- {{which errors now propagate instead of being swallowed, and who handles them}}
- {{tests added or updated: e.g. a test that a broken config file now raises}}

## Verified
- [ ] Re-ran the scanner: no high findings left (exit 0)
- [ ] Test suite passes
- [ ] Logs now include a traceback for {{failure}}

FILE:examples/sync_orders.py
"""Fictional nightly job that copies new web-shop orders into the accounting system.
It runs, but its exception handling hides real failures. Used to demo exception_smells.py."""
import json
import logging
import time

import requests  # third-party; the scanner never imports it

logger = logging.getLogger(__name__)
API = "https://shop.example.com/api/orders"


class SyncError(Exception):
    pass


def load_config(path):
    try:
        with open(path) as fh:
            return json.load(fh)
    except:
        return {}


def fetch_orders(since):
    try:
        resp = requests.get(API, params={"since": since}, timeout=10)
        resp.raise_for_status()
        return resp.json()["orders"]
    except Exception as err:
        logger.error("could not fetch orders: %s", err)
        return []


def to_invoice(order):
    try:
        return {"number": order["id"], "total": round(float(order["total"]), 2), "currency": order["currency"]}
    except KeyError:
        raise SyncError("order is missing a field")


def push_invoice(client, invoice):
    for attempt in range(3):
        try:
            client.create_invoice(invoice)
            return True
        except Exception:
            time.sleep(2 ** attempt)
            continue
    return False


def run(client, since):
    pushed = 0
    try:
        config = load_config("sync.json")
        orders = fetch_orders(since)
        batch = config.get("batch_size", 50)
        for order in orders[:batch]:
            invoice = to_invoice(order)
            if push_invoice(client, invoice):
                pushed += 1
        client.commit()
        logger.info("pushed %d invoices", pushed)
        client.close()
    except Exception as e:
        status = {"ok": False, "error": str(e)}
        return status
    finally:
        if pushed == 0:
            return {"ok": True, "pushed": 0}
    return {"ok": True, "pushed": pushed}


def main():
    try:
        run(client=None, since="2026-11-23")
    except BaseException:
        logger.exception("sync failed")

FILE:examples/sync_orders_fixed.py
"""The same nightly order sync with the smells fixed. exception_smells.py reports nothing here."""
import json
import logging
import time

import requests  # third-party; the scanner never imports it

logger = logging.getLogger(__name__)
API = "https://shop.example.com/api/orders"


class SyncError(Exception):
    pass


def load_config(path):
    try:
        with open(path) as fh:
            return json.load(fh)
    except FileNotFoundError:
        logger.info("no %s, using defaults", path)
        return {}


def fetch_orders(since):
    try:
        resp = requests.get(API, params={"since": since}, timeout=10)
        resp.raise_for_status()
    except requests.RequestException as err:
        raise SyncError("could not fetch orders since %s" % since) from err
    return resp.json()["orders"]


def to_invoice(order):
    try:
        return {"number": order["id"], "total": round(float(order["total"]), 2), "currency": order["currency"]}
    except KeyError as err:
        raise SyncError("order %s is missing field %s" % (order.get("id", "?"), err)) from err


def push_invoice(client, invoice, retryable=(ConnectionError, TimeoutError)):
    for attempt in range(3):
        try:
            client.create_invoice(invoice)
            return
        except retryable:
            logger.debug("retry %d for invoice %s", attempt + 1, invoice["number"])
            time.sleep(2 ** attempt)
    raise SyncError("invoice %s not pushed after 3 attempts" % invoice["number"])


def run(client, since):
    config = load_config("sync.json")
    orders = fetch_orders(since)
    batch = config.get("batch_size", 50)
    pushed, failed = 0, []
    for order in orders[:batch]:
        try:
            push_invoice(client, to_invoice(order))
            pushed += 1
        except SyncError:
            logger.exception("order %s skipped", order.get("id", "?"))
            failed.append(order.get("id"))
    try:
        client.commit()
    finally:
        client.close()
    logger.info("pushed %d invoices, %d failed", pushed, len(failed))
    return {"ok": not failed, "pushed": pushed, "failed": failed}


def main():
    try:
        run(client=None, since="2026-11-23")
    except SyncError:
        logger.exception("sync failed")
        raise

FILE:scripts/exception_smells.py
#!/usr/bin/env python3
"""exception_smells.py - find risky exception handling in Python code, offline.

Parses files with the standard library `ast` module (it never imports or runs the code) and reports:
  EX01 high    bare `except:` (also catches KeyboardInterrupt and SystemExit)
  EX02 high    broad except whose body only passes / continues / returns (error silently swallowed)
  EX03 medium  broad except that neither re-raises nor logs (error turned into a normal value)
  EX04 medium  new exception raised inside `except` without `from` (original cause hidden)
  EX05 high    `except BaseException` (or KeyboardInterrupt / SystemExit) without re-raise
  EX06 high    return / break / continue inside `finally` (silently cancels any exception)
  EX07 low     error logged in `except` without the traceback (no exc_info / logger.exception)
  EX08 low     broad except around a large try body (hides which statement failed)
  EX00 error   file could not be parsed

Usage:
  python3 exception_smells.py PATH [PATH ...] [--format text|json|md] [--min-severity low|medium|high]
                              [--ignore EX07,EX08] [--max-try-statements 8]
  python3 exception_smells.py --self-test
Suppress one finding with a trailing comment on the `except` / `raise` / `finally` line: `# smell: ignore[EX03]`.
Exit codes: 0 = no high findings, 1 = at least one high finding, 2 = bad input.
Standard library only, Python 3.8+.
"""
import argparse, ast, json, os, re, sys, tempfile, textwrap

SEVERITY = {"EX00": "error", "EX01": "high", "EX02": "high", "EX03": "medium", "EX04": "medium",
            "EX05": "high", "EX06": "high", "EX07": "low", "EX08": "low"}
TITLE = {"EX00": "file could not be parsed",
         "EX01": "bare except",
         "EX02": "broad except swallows the error",
         "EX03": "broad except neither re-raises nor logs",
         "EX04": "raise inside except without 'from'",
         "EX05": "catches BaseException / KeyboardInterrupt / SystemExit without re-raise",
         "EX06": "return/break/continue in finally cancels exceptions",
         "EX07": "error logged without traceback",
         "EX08": "broad except around a large try body"}
RANK = {"low": 0, "medium": 1, "high": 2, "error": 3}
BROAD = {"Exception", "BaseException"}
SYSTEM = {"BaseException", "KeyboardInterrupt", "SystemExit", "GeneratorExit"}
LOG_METHODS = {"debug", "info", "warning", "warn", "error", "exception", "critical", "fatal", "log"}
LOGGER_NAMES = re.compile(r"(^|_)(log|logger|logging|logs|_log|_logger|LOG|LOGGER)$")
SKIP_DIRS = {".git", ".hg", ".venv", "venv", "env", "__pycache__", "node_modules", "build", "dist", ".tox", ".mypy_cache", "site-packages"}
IGNORE_RE = re.compile(r"#\s*smell:\s*ignore\[([A-Z0-9, ]+)\]")


def type_names(node):
    """Names of the exception classes an except handler catches ([] for bare except)."""
    if node is None:
        return []
    items = node.elts if isinstance(node, ast.Tuple) else [node]
    out = []
    for it in items:
        if isinstance(it, ast.Name):
            out.append(it.id)
        elif isinstance(it, ast.Attribute):
            out.append(it.attr)
        else:
            out.append("?")
    return out


def walk_no_nested(nodes):
    """Walk statements but do not descend into nested functions, classes or lambdas."""
    stack = list(nodes)
    while stack:
        n = stack.pop()
        yield n
        for child in ast.iter_child_nodes(n):
            if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
                continue
            stack.append(child)


def is_log_call(call):
    if not isinstance(call, ast.Call):
        return False
    f = call.func
    if isinstance(f, ast.Attribute) and f.attr in LOG_METHODS:
        base = f.value
        name = base.id if isinstance(base, ast.Name) else (base.attr if isinstance(base, ast.Attribute) else "")
        return bool(LOGGER_NAMES.search(name))
    return False


def has_traceback(call):
    f = call.func
    if isinstance(f, ast.Attribute) and f.attr == "exception":
        return True
    for kw in call.keywords:
        if kw.arg in ("exc_info", "stack_info") and not (isinstance(kw.value, ast.Constant) and kw.value.value in (False, None)):
            return True
    return False


def handler_facts(h):
    body = list(walk_no_nested(h.body))
    reraises = any(isinstance(n, ast.Raise) for n in body)
    logs = [n for n in body if is_log_call(n)]
    reports = any(isinstance(n, ast.Call) and (
        (isinstance(n.func, ast.Attribute) and n.func.attr in ("capture_exception", "print_exc", "format_exc", "notify", "report_exc"))
        or (isinstance(n.func, ast.Name) and n.func.id in ("capture_exception", "print_exc"))) for n in body)
    trivial = all(isinstance(s, (ast.Pass, ast.Continue, ast.Break)) or
                  (isinstance(s, ast.Expr) and isinstance(s.value, ast.Constant)) or
                  (isinstance(s, ast.Return) and (s.value is None or isinstance(s.value, ast.Constant)))
                  for s in h.body)
    return reraises, logs, reports, trivial


class Finder(ast.NodeVisitor):
    def __init__(self, path, lines, max_try):
        self.path, self.lines, self.max_try = path, lines, max_try
        self.found = []
        self.handler_stack = []

    def add(self, code, node, detail):
        line = getattr(node, "lineno", 0)
        src = self.lines[line - 1] if 0 < line <= len(self.lines) else ""
        m = IGNORE_RE.search(src)
        if m and code in [c.strip() for c in m.group(1).split(",")]:
            return
        self.found.append({"code": code, "severity": SEVERITY[code], "file": self.path, "line": line,
                           "title": TITLE[code], "detail": detail, "source": src.strip()})

    def visit_Try(self, node):
        n_body = sum(1 for _ in walk_no_nested(node.body) if isinstance(_, ast.stmt))
        for h in node.handlers:
            names = type_names(h.type)
            reraises, logs, reports, trivial = handler_facts(h)
            broad = (not names) or any(n in BROAD for n in names)
            if not names:
                self.add("EX01", h, "use `except Exception:` (or narrower) so Ctrl+C and sys.exit() still work" + ("" if reraises else "; the error is not re-raised"))
            elif any(n in SYSTEM for n in names) and not reraises:
                self.add("EX05", h, "catches %s; re-raise it or catch Exception instead" % ", ".join(n for n in names if n in SYSTEM))
            if broad and trivial and not reraises:
                self.add("EX02", h, "the handler body only passes/continues/returns a constant; the error disappears without a trace")
            elif broad and not reraises and not logs and not reports and names:
                self.add("EX03", h, "the error becomes a normal return value; log it, re-raise it, or catch a narrower type")
            for call in logs:
                if call.func.attr in ("error", "critical", "fatal", "warning", "warn") and not has_traceback(call) and not reraises:
                    self.add("EX07", call, "add exc_info=True or use logger.exception(...) so the traceback is kept")
            if broad and n_body > self.max_try:
                self.add("EX08", h, "try body has %d statements; wrap only the call that can fail" % n_body)
            self.handler_stack.append(h)
            for s in h.body:
                self.visit(s)
            self.handler_stack.pop()
        for part in (node.body, node.orelse):
            for s in part:
                self.visit(s)
        for s in node.finalbody:
            self.visit(s)
        for n in walk_no_nested(node.finalbody):
            if isinstance(n, (ast.Return, ast.Break, ast.Continue)) and not self._inside_loop_in(node.finalbody, n):
                self.add("EX06", n, "`%s` in finally discards any exception raised in the try block" % type(n).__name__.lower())

    visit_TryStar = visit_Try

    def _inside_loop_in(self, stmts, target):
        """True if a break/continue sits inside a loop that is itself inside the finally block (that is fine)."""
        if isinstance(target, ast.Return):
            return False
        for n in walk_no_nested(stmts):
            if isinstance(n, (ast.For, ast.While, ast.AsyncFor)):
                if any(c is target for c in walk_no_nested(n.body + n.orelse)):
                    return True
        return False

    def visit_Raise(self, node):
        if self.handler_stack and node.exc is not None and node.cause is None:
            h = self.handler_stack[-1]
            if not (isinstance(node.exc, ast.Name) and h.name and node.exc.id == h.name):
                self.add("EX04", node, "use `raise NewError(...) from err` (or `from None` on purpose) to keep the cause")
        self.generic_visit(node)

    def visit_FunctionDef(self, node):
        saved, self.handler_stack = self.handler_stack, []
        self.generic_visit(node)
        self.handler_stack = saved

    visit_AsyncFunctionDef = visit_FunctionDef
    visit_Lambda = visit_FunctionDef


def scan_source(src, path="<string>", max_try=8):
    lines = src.splitlines()
    try:
        tree = ast.parse(src, filename=path)
    except SyntaxError as e:
        return [{"code": "EX00", "severity": "error", "file": path, "line": e.lineno or 0, "title": TITLE["EX00"],
                 "detail": str(e.msg), "source": ""}]
    f = Finder(path, lines, max_try)
    f.visit(tree)
    seen, out = set(), []
    for x in sorted(f.found, key=lambda x: (x["line"], x["code"])):
        k = (x["code"], x["line"])
        if k not in seen:
            seen.add(k)
            out.append(x)
    return out


def iter_files(paths):
    for p in paths:
        if os.path.isfile(p):
            yield p
        elif os.path.isdir(p):
            for root, dirs, files in os.walk(p):
                dirs[:] = sorted(d for d in dirs if d not in SKIP_DIRS and not d.endswith(".egg-info"))
                for fn in sorted(files):
                    if fn.endswith(".py"):
                        yield os.path.join(root, fn)
        else:
            raise FileNotFoundError(p)


def scan_paths(paths, max_try=8):
    findings, n = [], 0
    for fp in iter_files(paths):
        n += 1
        with open(fp, encoding="utf-8", errors="replace") as fh:
            findings += scan_source(fh.read(), fp, max_try)
    return n, findings


def render(n_files, findings, fmt):
    counts = {s: sum(1 for f in findings if f["severity"] == s) for s in ("high", "medium", "low", "error")}
    if fmt == "json":
        return json.dumps({"files_scanned": n_files, "counts": counts, "findings": findings}, indent=2)
    if fmt == "md":
        out = ["| Code | Severity | Location | Problem | Fix hint |", "|---|---|---|---|---|"]
        for f in findings:
            out.append("| %s | %s | `%s:%d` | %s | %s |" % (f["code"], f["severity"], f["file"], f["line"], f["title"], f["detail"]))
        out.append("")
        out.append("Files scanned: %d. High: %d, medium: %d, low: %d, parse errors: %d." % (n_files, counts["high"], counts["medium"], counts["low"], counts["error"]))
        return "\n".join(out)
    out = []
    for f in findings:
        out.append("%s:%d  %s [%s] %s" % (f["file"], f["line"], f["code"], f["severity"], f["title"]))
        if f["source"]:
            out.append("    > " + f["source"])
        out.append("    hint: " + f["detail"])
    out.append("")
    out.append("Files scanned: %d. High: %d, medium: %d, low: %d, parse errors: %d." % (n_files, counts["high"], counts["medium"], counts["low"], counts["error"]))
    return "\n".join(out)


def self_test():
    T = []

    def codes(src, **kw):
        return [f["code"] for f in scan_source(textwrap.dedent(src), **kw)]

    def check(name, cond):
        T.append((name, bool(cond)))

    check("bare except is EX01", "EX01" in codes("try:\n    x()\nexcept:\n    raise\n"))
    check("bare except with pass is EX01 + EX02", {"EX01", "EX02"} <= set(codes("try:\n    x()\nexcept:\n    pass\n")))
    check("except Exception: pass is EX02", codes("try:\n    x()\nexcept Exception:\n    pass\n") == ["EX02"])
    check("narrow except ValueError: pass is fine", codes("try:\n    int(s)\nexcept ValueError:\n    pass\n") == [])
    check("broad except returning a value without log is EX03",
          codes("def f():\n    try:\n        return x()\n    except Exception as e:\n        y = str(e)\n        return {'ok': False, 'err': y}\n") == ["EX03"])
    check("broad except that logs with exception() is fine",
          codes("def f():\n    try:\n        x()\n    except Exception:\n        logger.exception('boom')\n        return None\n") == [])
    check("logger.error without exc_info is EX07",
          codes("try:\n    x()\nexcept Exception as e:\n    logger.error('failed: %s', e)\n") == ["EX07"])
    check("logger.error with exc_info=True is fine",
          codes("try:\n    x()\nexcept Exception:\n    log.error('failed', exc_info=True)\n") == [])
    check("raise without from in except is EX04",
          codes("try:\n    x()\nexcept KeyError as e:\n    raise ValueError('bad')\n") == ["EX04"])
    check("raise ... from err is fine", codes("try:\n    x()\nexcept KeyError as e:\n    raise ValueError('bad') from e\n") == [])
    check("re-raising the caught name is fine", codes("try:\n    x()\nexcept KeyError as e:\n    cleanup()\n    raise e\n") == [])
    check("except BaseException without re-raise is EX05",
          "EX05" in codes("try:\n    x()\nexcept BaseException:\n    logger.exception('x')\n"))
    check("except KeyboardInterrupt with re-raise is fine",
          codes("try:\n    x()\nexcept KeyboardInterrupt:\n    cleanup()\n    raise\n") == [])
    check("return in finally is EX06", "EX06" in codes("def f():\n    try:\n        x()\n    finally:\n        return 1\n"))
    check("break inside a loop within finally is fine",
          codes("try:\n    x()\nfinally:\n    for i in r:\n        break\n") == [])
    check("large try body with broad except is EX08",
          "EX08" in codes("try:\n" + "".join("    a%d()\n" % i for i in range(10)) + "except Exception:\n    logger.exception('x')\n    raise\n"))
    check("--max-try-statements raises the limit",
          "EX08" not in codes("try:\n" + "".join("    a%d()\n" % i for i in range(10)) + "except Exception:\n    raise\n", max_try=20))
    check("inline ignore comment suppresses a code",
          codes("try:\n    x()\nexcept Exception:  # smell: ignore[EX02]\n    pass\n") == [])
    check("nested function raise is not attributed to outer except",
          codes("try:\n    x()\nexcept KeyError as e:\n    def g():\n        raise ValueError()\n    raise\n") == [])
    check("syntax error reported as EX00", codes("def f(:\n    pass\n") == ["EX00"])
    check("tuple of exceptions incl. Exception is broad",
          codes("try:\n    x()\nexcept (ValueError, Exception):\n    pass\n") == ["EX02"])
    with tempfile.TemporaryDirectory() as d:
        os.makedirs(os.path.join(d, "pkg")); os.makedirs(os.path.join(d, ".venv"))
        open(os.path.join(d, "pkg", "a.py"), "w").write("try:\n    x()\nexcept:\n    pass\n")
        open(os.path.join(d, ".venv", "b.py"), "w").write("try:\n    x()\nexcept:\n    pass\n")
        n, fs = scan_paths([d])
        check("directory scan skips .venv", n == 1 and all(".venv" not in f["file"] for f in fs))
        check("json output parses", json.loads(render(n, fs, "json"))["counts"]["high"] == 2)
    ok = sum(1 for _, r in T if r)
    for name, r in T:
        print(("PASS  " if r else "FAIL  ") + name)
    print(("ALL PASS" if ok == len(T) else "FAILED") + " (%d/%d)" % (ok, len(T)))
    return 0 if ok == len(T) else 1


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("paths", nargs="*")
    ap.add_argument("--format", choices=("text", "json", "md"), default="text")
    ap.add_argument("--min-severity", choices=("low", "medium", "high"), default="low")
    ap.add_argument("--ignore", default="", help="comma-separated codes to skip, e.g. EX07,EX08")
    ap.add_argument("--max-try-statements", type=int, default=8)
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args(argv)
    if a.self_test:
        return self_test()
    if not a.paths:
        ap.print_usage(sys.stderr)
        return 2
    try:
        n, fs = scan_paths(a.paths, a.max_try_statements)
    except FileNotFoundError as e:
        print("error: path not found: %s" % e, file=sys.stderr)
        return 2
    if n == 0:
        print("error: no .py files found", file=sys.stderr)
        return 2
    skip = {c.strip().upper() for c in a.ignore.split(",") if c.strip()}
    fs = [f for f in fs if f["code"] not in skip and RANK[f["severity"]] >= RANK[a.min_severity]]
    print(render(n, fs, a.format))
    return 1 if any(f["severity"] == "high" for f in fs) else 0


if __name__ == "__main__":
    sys.exit(main())
Best PracticesEngineeringError Recovery+3
F@f
0
Python Import Cycle Detector
Skill

Finds circular imports in a Python project offline: maps files to modules, parses imports with ast, reports each cycle group with its shortest loop, exact file:line imports, import-time vs deferred vs TYPE_CHECKING, a suggested edge to break and fix patterns. Stdlib Python, self-tested.

---
name: python-import-cycle-detector
description: Finds circular imports in a Python project offline: maps files to modules, parses imports with ast, reports each cycle group with its shortest loop, exact file:line imports, import-time vs deferred vs TYPE_CHECKING, a suggested edge to break and fix patterns. Stdlib Python, self-tested.
---

# Python Import Cycle Detector

You help developers find and untangle circular imports in a Python codebase. Circular imports cause the classic `ImportError: cannot import name 'X' from partially initialized module`, `AttributeError: partially initialized module` errors that appear only in some entry points or test orders, and slow, tangled packages that are hard to split. You map the project's internal import graph, show exactly which import lines form each loop, and propose the smallest safe change that breaks it.

You work on the user's code locally and never upload it. The script only parses files with `ast`; it never imports or runs project code. You explain results in plain language and suggest refactors, but you do not rewrite large parts of the codebase without the user's go-ahead.

## Files in this skill

- `scripts/import_cycles.py` - walks the project (skips venvs, build and cache folders; detects a `src/` layout), resolves absolute and relative imports and `from pkg import submodule`, finds strongly connected components (Tarjan), the shortest cycle in each, and findings IC00-IC06; `--json` for tooling, `--include-type-checking` to count `if TYPE_CHECKING:` imports, `--root` to set the folder that holds the top-level packages, `--self-test` runs 18 checks (Python 3.8+ standard library only)
- `references/how-cycles-break.md` - why some cycles crash at import time and others do not, how Python executes a module while it is half-initialized, and what each finding means
- `references/fix-patterns.md` - seven ways to break a cycle, from moving one constant to dependency inversion, with before/after snippets and when to use each
- `templates/cycle-report.md` - the summary you hand back
- `examples/shop/` - a fictional six-module package with a real import-time cycle (`models` <-> `orders`), a longer loop through a deferred import, a `TYPE_CHECKING` import and an `__init__` re-export; `python3 -c "import shop"` inside `examples/` reproduces the ImportError

## Workflow

### 1. Understand the symptom
Ask for the exact error and traceback if there is one, the entry point or test that fails, the Python version, and where the packages live (repo root or `src/`). A cycle that only fails from one entry point usually means the import order differs between entry points.

### 2. Run the detector
```
python3 scripts/import_cycles.py path/to/project
python3 scripts/import_cycles.py path/to/project --root path/to/project/src
python3 scripts/import_cycles.py path/to/project --json > cycles.json
python3 scripts/import_cycles.py --self-test
```
Exit 0 = no import-time cycles, 1 = at least one import-time cycle (IC01), 2 = bad input. Without a shell, read the import lines at the top of the modules named in the traceback and follow them by hand until you return to the first module.

### 3. Read the report
- **Group**: modules that reach each other through imports. Fix groups one at a time, the import-time ones (IC01) first.
- **Shortest cycle**: the smallest loop with file and line for every import; usually the best place to start.
- **Kind**: `top` runs when the module is imported; `deferred` runs inside a function (IC02: works today but breaks when someone moves it to the top); `type_checking` never runs (IC06, ignored unless `--include-type-checking`).
- **Suggested place to break**: a top-level edge in the shortest cycle that imports the fewest names. It is a starting point, not a verdict: prefer the edge whose direction is "wrong" for the architecture (a low-level module such as `models` importing a high-level one such as `orders`).
- IC03 marks tangles of 5+ modules (plan a layered refactor), IC04 an `__init__.py` re-export that pulls the package into the loop, IC05 a star import inside a cycle, IC00 files that could not be parsed.

### 4. Choose a fix
Use `references/fix-patterns.md`. Default order: move the shared constant or type to a lower module; import the module instead of a name (`from shop import orders` then `orders.ORDER_STATUSES`) only as a stopgap; use a `TYPE_CHECKING` import plus string annotations for type-only use; move logic to the module that owns it; invert the dependency with a parameter, callback or registry. Avoid hiding the cycle with function-level imports unless it is a deliberate, commented exception.

### 5. Verify
Re-run the detector until the group is gone or only documented deferred edges remain, then import every top-level module in a fresh interpreter (`python3 -c "import pkg.module"`) and run the test suite. Suggest adding the detector to CI with exit code 1 failing the build.

### 6. Report
Fill `templates/cycle-report.md`: groups found, the fix for each, the changed files, and what was verified.

## Rules
- Never execute or import the user's project to analyze it; the parser is enough.
- Keep changes small and reviewable: one cycle per commit, no behavior change.
- Dynamic imports (`importlib.import_module`, plugins, `__import__`) are invisible to static analysis; say so when the project uses them.

FILE:references/how-cycles-break.md
# How circular imports break (and when they don't)

## What Python does on `import a`
1. Looks in `sys.modules`. If `a` is there, even half-finished, it returns it immediately.
2. Otherwise it creates an empty module object, puts it in `sys.modules["a"]`, and runs `a.py` from top to bottom.
3. Names exist in `a` only after the line that defines them has run.

So in a cycle `a -> b -> a`:
- `import a` starts running `a.py`, which reaches `import b`.
- `b.py` runs and reaches `import a`; `a` is already in `sys.modules` (half-initialized), so it is returned at once.
- If `b` then does `from a import X` (or uses `a.X` at top level) before `a` has defined `X`, you get
  `ImportError: cannot import name 'X' from partially initialized module 'a'` or
  `AttributeError: partially initialized module 'a' has no attribute 'X'`.

Whether it crashes depends on **which module is imported first** and **what each side touches at import time**. That is why a cycle can pass the test suite and crash in production from a different entry point.

## Kinds of edges the script reports
| kind | where the import is | runs when | risk |
|---|---|---|---|
| `top` | module level (also inside `if`, `try`, `class` bodies) | the module is imported | can crash at import time |
| `deferred` | inside a function or method | the function is called | works if the other module has finished by then; fragile |
| `type_checking` | inside `if TYPE_CHECKING:` | never at runtime | no runtime effect; ignored by default |

## Findings
| code | severity | meaning | first move |
|---|---|---|---|
| IC00 | low | a file could not be parsed (syntax error, encoding) | fix or exclude the file, re-run |
| IC01 | high | cycle made only of import-time edges somewhere in the group | fix now; see fix-patterns.md 1-5 |
| IC02 | medium | every loop includes at least one deferred import | document it or remove the cycle properly |
| IC03 | medium | group of 5+ modules | draw the intended layers; fix edges that point upward |
| IC04 | medium | an `__init__.py` re-export sits in the shortest cycle | stop re-exporting, or import submodules directly |
| IC05 | medium | `from x import *` inside a cycle | replace with explicit names |
| IC06 | info | TYPE_CHECKING-only imports were ignored | nothing; use `--include-type-checking` to see them |

## How modules are resolved
- File `pkg/sub/mod.py` under the root becomes `pkg.sub.mod`; `pkg/__init__.py` becomes `pkg`.
- The root is `<project>/src` if it exists, otherwise `<project>`; override with `--root`.
- `from pkg import name` maps to `pkg.name` when that is a module, otherwise to `pkg`.
- `from . import x` and `from ..core import y` are resolved against the importing module's package.
- Third-party and standard library imports are ignored (they are not files under the root).
- Limitation: `import a.b` also runs `a/__init__.py`; the script records only the edge to `a.b`. If a package `__init__` imports heavily, check it by hand.

## Worked example (examples/shop)
`shop.orders` line 3 imports `Customer` from `shop.models`; `shop.models` line 3 imports `ORDER_STATUSES` from `shop.orders`. Importing `shop` runs `__init__` -> `orders` -> `models`, and `models` asks for `ORDER_STATUSES` before `orders` has defined it, so `python3 -c "import shop"` fails with the ImportError. The longer loop `orders -> payments -> notifications -> orders` survives only because `notifications` imports `orders` inside `send_receipt()`.

FILE:references/fix-patterns.md
# Fix patterns for circular imports

Pick the smallest change that makes dependencies point one way: from high-level modules (services, views, CLI) down to low-level ones (models, constants, utilities).

## 1. Move the shared piece down
When two modules share a constant, enum, exception or small type, move it to a lower module that imports neither.
```python
# before: models.py -> orders.py for ORDER_STATUSES, orders.py -> models.py for Customer
# after: shop/constants.py
ORDER_STATUSES = ["new", "paid", "shipped", "cancelled"]
# models.py and orders.py both: from shop.constants import ORDER_STATUSES
```
Best first choice: no behavior change, easy to review.

## 2. Type-only imports
If one side needs the other only for annotations:
```python
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from shop.models import Customer
def greet(customer: Customer) -> str: ...
```
The import never runs, so the runtime cycle disappears.

## 3. Move the function to its owner
A helper in `orders.py` that only works on customers belongs in `models.py` (or a `customers.py`). Cycles often show that one function lives in the wrong module.

## 4. Dependency inversion
The low-level module should not call the high-level one. Pass what it needs instead:
```python
# payments.py
def charge(order, on_success=None):
    ...
    if on_success:
        on_success(order)
# orders.py
payments.charge(order, on_success=notifications.send_receipt)
```
Alternatives: a small registry or signal (`events.subscribe("order_paid", send_receipt)`), or a protocol/ABC in a lower module.

## 5. Split a module that does two jobs
If `utils.py` imports half the project and half the project imports `utils.py`, split it by topic (`utils/text.py`, `utils/money.py`) so each part depends on less.

## 6. Import the module, not the name (stopgap)
`from shop import orders` and use `orders.ORDER_STATUSES` inside functions. Attribute lookup happens later, so some cycles stop crashing. It hides the design problem; leave a TODO and plan pattern 1-5.

## 7. Deferred import (last resort)
```python
def send_receipt(order):
    from shop.orders import ORDER_STATUSES  # deliberate: breaks cycle orders -> payments -> notifications
```
Acceptable for rarely used paths or optional heavy dependencies. Always add a comment naming the cycle; the detector keeps reporting it as IC02.

## Package `__init__.py` re-exports (IC04)
`from .orders import Order` in `__init__.py` makes `import shop.models` run `orders.py` first. Options: keep `__init__.py` light, re-export only leaf modules, or use a lazy `__getattr__` (PEP 562) for convenience names.

## After every fix
1. `python3 scripts/import_cycles.py <project>` - the group should be gone or smaller.
2. `python3 -c "import <each top-level module>"` in a fresh interpreter.
3. Run the tests, including any that import modules in a different order.
4. Add the detector to CI: a non-zero exit fails the build.

FILE:templates/cycle-report.md
# Import cycle report - {{project}} ({{date}})

**Scope:** {{modules}} modules under `{{root}}`, {{edges}} internal imports. Command: `python3 scripts/import_cycles.py {{project}}`
**Symptom:** {{error_or_reason}}

## Summary
- Cycle groups: {{group_count}} ({{import_time_count}} break at import time, {{deferred_count}} deferred only)
- Status after fixes: {{status}}

## Groups
| # | modules | shortest cycle | kind | fix chosen | status |
|---|---|---|---|---|---|
| 1 | {{modules_1}} | {{cycle_1}} | {{kind_1}} | {{fix_1}} | {{status_1}} |

## Changes
| file | change | pattern (fix-patterns.md) |
|---|---|---|
| {{file}} | {{change}} | {{pattern}} |

## Verification
- Detector re-run: {{detector_result}}
- Fresh-interpreter imports: {{import_check}}
- Tests: {{tests}}

## Remaining and notes
- Documented deferred imports (IC02): {{deferred_notes}}
- Dynamic imports not covered by static analysis: {{dynamic_imports}}
- Suggested CI step: `python3 scripts/import_cycles.py . || exit 1`

FILE:examples/shop/__init__.py
"""Fictional demo package for the import cycle detector (not a real shop)."""
from .orders import Order, place_order

__all__ = ["Order", "place_order"]

FILE:examples/shop/models.py
from dataclasses import dataclass

from shop.orders import ORDER_STATUSES


@dataclass
class Customer:
    id: int
    email: str
    status: str = ORDER_STATUSES[0]

FILE:examples/shop/orders.py
from dataclasses import dataclass, field

from shop.models import Customer
from shop import payments

ORDER_STATUSES = ["new", "paid", "shipped", "cancelled"]


@dataclass
class Order:
    id: int
    customer: Customer
    total_cents: int
    status: str = "new"
    lines: list = field(default_factory=list)


def place_order(order):
    payments.charge(order)
    order.status = "paid"
    return order

FILE:examples/shop/payments.py
from shop.notifications import send_receipt


def charge(order):
    # pretend to call a payment provider here
    send_receipt(order)
    return True

FILE:examples/shop/notifications.py
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from shop.models import Customer


def send_receipt(order):
    from shop.orders import ORDER_STATUSES  # deferred import, runs only when called
    return "Receipt for order %s (%s)" % (order.id, ORDER_STATUSES[1])


def greet(customer: "Customer"):
    return "Hello " + customer.email

FILE:examples/shop/utils.py
def cents_to_text(cents):
    return "%d.%02d" % divmod(cents, 100)

FILE:scripts/import_cycles.py
#!/usr/bin/env python3
"""import_cycles.py - find circular imports in a Python project (stdlib only, Python 3.8+).

Usage:
  python3 scripts/import_cycles.py <project_dir> [--root PKG_PARENT] [--json] [--include-type-checking]
  python3 scripts/import_cycles.py --self-test

Reads every .py file under <project_dir> (skipping venvs, build and cache folders), maps files to
module names, parses imports with ast (absolute, relative, `from pkg import submodule`), builds the
import graph between project modules and reports each strongly connected component (a group of
modules that import each other directly or indirectly) with its shortest cycle, the exact import
lines, whether each import runs at import time (top level) or later (inside a function), and a
suggested edge to break. Findings IC01-IC06. Exit 0 = no import-time cycles, 1 = import-time
cycle or other high finding, 2 = bad input.
"""
import argparse, ast, json, os, sys
from collections import deque

SKIP_DIRS = {".git", ".hg", ".venv", "venv", "env", "__pycache__", "build", "dist", "node_modules",
             ".tox", ".nox", ".mypy_cache", ".pytest_cache", "site-packages", ".eggs"}


def module_name(path, root):
    rel = os.path.relpath(path, root)[:-3].replace(os.sep, ".")
    if rel.endswith(".__init__"):
        rel = rel[: -len(".__init__")]
    return rel


def find_root(project):
    """Use project/src if it exists (src layout), else the project dir itself."""
    src = os.path.join(project, "src")
    return src if os.path.isdir(src) else project


def collect_files(root):
    out = []
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS and not d.endswith(".egg-info"))
        for f in sorted(filenames):
            if f.endswith(".py"):
                out.append(os.path.join(dirpath, f))
    return out


class ImportVisitor(ast.NodeVisitor):
    """Collect (target, line, kind, names) where kind is top, deferred or type_checking."""

    def __init__(self, modname, is_pkg):
        self.mod, self.is_pkg, self.depth, self.tc = modname, is_pkg, 0, 0
        self.found = []

    def _kind(self):
        if self.tc:
            return "type_checking"
        return "deferred" if self.depth else "top"

    def visit_FunctionDef(self, node):
        self.depth += 1; self.generic_visit(node); self.depth -= 1
    visit_AsyncFunctionDef = visit_FunctionDef
    visit_Lambda = visit_FunctionDef

    def visit_If(self, node):
        t = node.test
        is_tc = (isinstance(t, ast.Name) and t.id == "TYPE_CHECKING") or \
                (isinstance(t, ast.Attribute) and t.attr == "TYPE_CHECKING")
        if is_tc:
            self.tc += 1
            for n in node.body:
                self.visit(n)
            self.tc -= 1
            for n in node.orelse:
                self.visit(n)
        else:
            self.generic_visit(node)

    def visit_Import(self, node):
        for a in node.names:
            self.found.append((a.name, node.lineno, self._kind(), []))

    def visit_ImportFrom(self, node):
        if node.level:
            parts = self.mod.split(".")
            base = parts if self.is_pkg else parts[:-1]
            up = node.level - 1
            if up > len(base):
                return
            base = base[: len(base) - up] if up else base
            target = ".".join(base + ([node.module] if node.module else []))
        else:
            target = node.module or ""
        names = [a.name for a in node.names]
        self.found.append((target, node.lineno, self._kind(), names))


def resolve(target, names, modules):
    """Map an import target to project modules: the deepest existing module, plus submodules named in `from x import y`."""
    hits = []
    if names:
        for n in names:
            sub = target + "." + n if target else n
            if sub in modules:
                hits.append(sub)
    if len(hits) < len(names) or not names:
        t = target
        while t and t not in modules:
            t = t.rpartition(".")[0]
        if t:
            hits.append(t)
    return sorted(set(hits))


def build_graph(project, root=None):
    root = root or find_root(project)
    files = collect_files(root)
    if not files:
        raise ValueError("no .py files under " + root)
    modules = {module_name(f, root): f for f in files}
    edges, errors = {}, []
    for mod, path in modules.items():
        try:
            tree = ast.parse(open(path, encoding="utf-8").read(), filename=path)
        except (SyntaxError, UnicodeDecodeError) as e:
            errors.append((mod, str(e).splitlines()[0])); continue
        v = ImportVisitor(mod, path.endswith("__init__.py")); v.visit(tree)
        for target, line, kind, names in v.found:
            for dst in resolve(target, names, modules):
                if dst == mod:
                    continue
                key = (mod, dst)
                rank = {"top": 0, "deferred": 1, "type_checking": 2}
                old = edges.get(key)
                if old is None or rank[kind] < rank[old["kind"]]:
                    edges[key] = {"line": line, "kind": kind, "names": names, "file": os.path.relpath(path, project)}
    return root, modules, edges, errors


def sccs(nodes, adj):
    """Tarjan's algorithm, iterative."""
    index, low, onstack, stack, out, counter = {}, {}, set(), [], [], [0]
    for start in sorted(nodes):
        if start in index:
            continue
        work = [(start, iter(sorted(adj.get(start, ()))))]
        index[start] = low[start] = counter[0]; counter[0] += 1; stack.append(start); onstack.add(start)
        while work:
            v, it = work[-1]
            for w in it:
                if w not in index:
                    index[w] = low[w] = counter[0]; counter[0] += 1; stack.append(w); onstack.add(w)
                    work.append((w, iter(sorted(adj.get(w, ())))))
                    break
                if w in onstack:
                    low[v] = min(low[v], index[w])
            else:
                work.pop()
                if work:
                    low[work[-1][0]] = min(low[work[-1][0]], low[v])
                if low[v] == index[v]:
                    comp = []
                    while True:
                        w = stack.pop(); onstack.discard(w); comp.append(w)
                        if w == v:
                            break
                    if len(comp) > 1:
                        out.append(sorted(comp))
    return out


def shortest_cycle(comp, adj):
    best = None
    cs = set(comp)
    for s in comp:
        prev, q = {s: None}, deque([s])
        while q:
            v = q.popleft()
            for w in sorted(adj.get(v, ())):
                if w not in cs:
                    continue
                if w == s:
                    path = [v]
                    while prev[path[-1]] is not None:
                        path.append(prev[path[-1]])
                    cyc = list(reversed(path)) + [s]
                    if best is None or len(cyc) < len(best):
                        best = cyc
                    q.clear(); break
                if w not in prev:
                    prev[w] = v; q.append(w)
    return best


def analyze(project, root=None, include_tc=False):
    root, modules, edges, errors = build_graph(project, root)
    use = {k: v for k, v in edges.items() if include_tc or v["kind"] != "type_checking"}
    top = {k: v for k, v in use.items() if v["kind"] == "top"}
    def adj_of(es):
        a = {}
        for (s, d) in es:
            a.setdefault(s, set()).add(d)
        return a
    adj_all, adj_top = adj_of(use), adj_of(top)
    groups, findings = [], []
    top_sccs = [set(c) for c in sccs(modules, adj_top)]
    for comp in sccs(modules, adj_all):
        cyc = shortest_cycle(comp, adj_all)
        cyc_edges = [dict(src=a, dst=b, **use[(a, b)]) for a, b in zip(cyc, cyc[1:])]
        import_time = any(set(comp) & t for t in top_sccs)
        inner = [dict(src=s, dst=d, **e) for (s, d), e in use.items() if s in comp and d in comp]
        # break candidate: top-level edge in the shortest cycle importing the fewest names, prefer non-__init__ sources
        cands = [e for e in cyc_edges if e["kind"] == "top"] or cyc_edges
        brk = min(cands, key=lambda e: (len(e["names"]) or 1, e["file"].endswith("__init__.py"), e["src"]))
        g = dict(modules=comp, size=len(comp), shortest_cycle=cyc, cycle_edges=cyc_edges,
                 import_time=import_time, edges_inside=len(inner), other_edges=[e for e in sorted(inner, key=lambda e: (e["src"], e["dst"])) if (e["src"], e["dst"]) not in set(zip(cyc, cyc[1:]))], break_candidate=brk)
        groups.append(g)
        label = " -> ".join(cyc)
        if import_time:
            findings.append(("high", "IC01", "import-time cycle: " + label))
        else:
            findings.append(("medium", "IC02", "cycle only through imports inside functions (works, but fragile): " + label))
        if len(comp) >= 5:
            findings.append(("medium", "IC03", "large tangle of %d modules: %s" % (len(comp), ", ".join(comp))))
        for e in cyc_edges:
            if e["file"].endswith("__init__.py") and e["kind"] == "top":
                findings.append(("medium", "IC04", "package __init__ re-exports into the cycle: %s line %d" % (e["file"], e["line"])))
            if e["kind"] == "top" and e["names"] == ["*"]:
                findings.append(("medium", "IC05", "star import inside a cycle: %s line %d" % (e["file"], e["line"])))
    tc_only = [k for k, v in edges.items() if v["kind"] == "type_checking"]
    if tc_only and not include_tc:
        findings.append(("info", "IC06", "%d TYPE_CHECKING-only import(s) ignored (they never run)" % len(tc_only)))
    for mod, err in errors:
        findings.append(("low", "IC00", "could not parse %s: %s" % (mod, err)))
    return dict(project=project, root=root, modules=len(modules), edges=len(use), groups=groups,
                findings=[dict(severity=s, code=c, message=m) for s, c, m in findings])


def render(res):
    L = ["# Import cycle report", "",
         "Project: %s (modules from %s): %d modules, %d internal imports, %d cycle group(s)" %
         (res["project"], res["root"], res["modules"], res["edges"], len(res["groups"])), ""]
    for i, g in enumerate(res["groups"], 1):
        L.append("## Group %d: %d modules (%s)" % (i, g["size"], "breaks at import time" if g["import_time"] else "deferred imports only"))
        L.append("Modules: " + ", ".join(g["modules"]))
        L.append("Shortest cycle: " + " -> ".join(g["shortest_cycle"]))
        for e in g["cycle_edges"]:
            L.append("  - %s line %d: %s imports %s%s [%s]" % (e["file"], e["line"], e["src"], e["dst"],
                     (" (" + ", ".join(e["names"]) + ")") if e["names"] else "", e["kind"]))
        if g["other_edges"]:
            L.append("Other imports inside this group:")
            for e in g["other_edges"]:
                L.append("  - %s line %d: %s imports %s [%s]" % (e["file"], e["line"], e["src"], e["dst"], e["kind"]))
        b = g["break_candidate"]
        L.append("Suggested place to break: %s line %d (%s -> %s)" % (b["file"], b["line"], b["src"], b["dst"]))
        L.append("")
    if not res["groups"]:
        L += ["No import cycles between project modules.", ""]
    L.append("## Findings")
    order = {"high": 0, "medium": 1, "low": 2, "info": 3}
    for f in sorted(res["findings"], key=lambda f: (order[f["severity"]], f["code"])):
        L.append("- [%s] %s %s" % (f["severity"], f["code"], f["message"]))
    if not res["findings"]:
        L.append("- none")
    return "\n".join(L)


def self_test():
    import tempfile
    ok = [0, 0]
    def check(name, cond):
        ok[0 if cond else 1] += 1
        print(("PASS  " if cond else "FAIL  ") + name)
    def proj(files):
        d = tempfile.mkdtemp()
        for rel, txt in files.items():
            p = os.path.join(d, rel); os.makedirs(os.path.dirname(p), exist_ok=True)
            open(p, "w").write(txt)
        return d
    r = analyze(proj({"a.py": "import b\n", "b.py": "x = 1\n"}))
    check("no cycle in a -> b", not r["groups"])
    r = analyze(proj({"a.py": "import b\n", "b.py": "import a\n"}))
    check("direct cycle a <-> b found", len(r["groups"]) == 1 and r["groups"][0]["size"] == 2)
    check("direct cycle is import-time IC01", any(f["code"] == "IC01" for f in r["findings"]))
    r = analyze(proj({"a.py": "import b\n", "b.py": "import c\n", "c.py": "import a\n"}))
    check("three-module cycle shortest path length 4", r["groups"][0]["shortest_cycle"] == ["a", "b", "c", "a"])
    r = analyze(proj({"a.py": "import b\n", "b.py": "def f():\n    import a\n"}))
    check("function-level import gives IC02 not IC01", [f["code"] for f in r["findings"]] == ["IC02"])
    r = analyze(proj({"a.py": "import b\n", "b.py": "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n    import a\n"}))
    check("TYPE_CHECKING import ignored by default", not r["groups"] and r["findings"][0]["code"] == "IC06")
    r = analyze(proj({"a.py": "import b\n", "b.py": "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n    import a\n"}), include_tc=True)
    check("TYPE_CHECKING import counted with flag", len(r["groups"]) == 1)
    r = analyze(proj({"pkg/__init__.py": "", "pkg/x.py": "from . import y\n", "pkg/y.py": "from .x import thing\n"}))
    check("relative imports resolved", r["groups"] and r["groups"][0]["modules"] == ["pkg.x", "pkg.y"])
    r = analyze(proj({"pkg/__init__.py": "from .x import X\n", "pkg/x.py": "from pkg import helpers\nX = 1\n", "pkg/helpers.py": "import pkg\n"}))
    check("__init__ re-export flagged IC04", any(f["code"] == "IC04" for f in r["findings"]))
    r = analyze(proj({"pkg/__init__.py": "", "pkg/x.py": "from pkg import y\n", "pkg/y.py": "x = 1\n"}))
    check("from pkg import submodule maps to the submodule", not r["groups"])
    r = analyze(proj({"src/app/__init__.py": "", "src/app/a.py": "from app import b\n", "src/app/b.py": "from app.a import f\n"}))
    check("src layout root detected", r["root"].endswith("src") and len(r["groups"]) == 1)
    r = analyze(proj({"a.py": "from b import *\n", "b.py": "import a\n"}))
    check("star import in cycle flagged IC05", any(f["code"] == "IC05" for f in r["findings"]))
    files = {"m%d.py" % i: "import m%d\n" % ((i + 1) % 5) for i in range(5)}
    r = analyze(proj(files))
    check("five-module ring flagged IC03", any(f["code"] == "IC03" for f in r["findings"]))
    r = analyze(proj({"a.py": "import os, json\nimport b\n", "b.py": "import sys\n"}))
    check("stdlib imports ignored", r["edges"] == 1)
    r = analyze(proj({"a.py": "import b\n", "b.py": "def (:\n"}))
    check("syntax error reported IC00", any(f["code"] == "IC00" for f in r["findings"]))
    r = analyze(proj({"venv/lib/x.py": "import y\n", "venv/lib/y.py": "import x\n", "a.py": "x=1\n"}))
    check("venv folder skipped", r["modules"] == 1)
    r = analyze(proj({"a.py": "import b\n", "b.py": "import a\n"}))
    b = r["groups"][0]["break_candidate"]
    check("break candidate is an edge of the cycle", (b["src"], b["dst"]) in [("a", "b"), ("b", "a")])
    try:
        analyze(proj({"README.md": "x"})); check("empty project rejected", False)
    except ValueError:
        check("empty project rejected", True)
    print("ALL PASS (%d/%d)" % (ok[0], sum(ok)) if not ok[1] else "FAILED %d of %d" % (ok[1], sum(ok)))
    return 0 if not ok[1] else 1


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("project", nargs="?")
    ap.add_argument("--root", help="folder that contains the top-level packages (default: <project>/src if present, else <project>)")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--include-type-checking", action="store_true")
    ap.add_argument("--self-test", action="store_true")
    a = ap.parse_args()
    if a.self_test:
        return self_test()
    if not a.project or not os.path.isdir(a.project):
        print("error: give a project directory", file=sys.stderr); return 2
    try:
        res = analyze(a.project, a.root, a.include_type_checking)
    except ValueError as e:
        print("error:", e, file=sys.stderr); return 2
    print(json.dumps(res, indent=2) if a.json else render(res))
    return 1 if any(f["severity"] == "high" for f in res["findings"]) else 0


if __name__ == "__main__":
    sys.exit(main())
ArchitectureRefactoringEngineering+3
F@f
0
Git Bus Factor and Knowledge Risk Analyzer
Skill

Finds knowledge concentration risk in a Git repo from its history: per-module bus factor, who holds the knowledge, modules nobody active still knows, single-knower hot spots, the repo truck factor and duplicate identities, with a handover plan template. Offline stdlib Python.

---
name: git-bus-factor-and-knowledge-risk-analyzer
description: Finds knowledge concentration risk in a Git repo from its history: per-module bus factor, who holds the knowledge, modules nobody active still knows, single-knower hot spots, the repo truck factor and duplicate identities, with a handover plan template. Offline stdlib Python.
---

# Git Bus Factor and Knowledge Risk Analyzer

You help engineering managers, tech leads, CTOs of small companies and open-source maintainers see where knowledge of their codebase sits with just one or two people, and where nobody who still works on the project knows the code at all. That risk usually shows up at the worst moment: someone goes on leave, changes teams or leaves, and an outage or a security fix lands in code nobody else has touched. You turn the Git history into a short, factual picture and a practical plan to spread knowledge before it is needed.

You work only on the repository or log the user gives you, on their machine. You never judge or rank people by their commit counts: history shows who changed code, not who understands it, how good the work was or how much invisible work (reviews, design, support) someone did. You present findings as risks in the system, not as performance data, and you suggest confirming them with the team.

## Files in this skill

- `scripts/bus_factor.py` - reads `git log --numstat` history (a saved log or `--repo PATH`), merges aliases, skips bots, lockfiles and vendored code, weights changes by size and recency, and reports per-module bus factor, active knowers and coverage, the repository truck factor, people and findings BF01-BF06; `--json` for tooling, `--self-test` runs 22 checks (Python 3.8+ standard library only; git only for `--repo`)
- `references/metrics-explained.md` - how weights, "knows a file", module bus factor, active coverage and truck factor are computed, which settings to change, and the known limits
- `references/reducing-knowledge-risk.md` - what each finding usually means and the concrete practices that fix it (pairing, review rotation, runbooks, ownership, handover)
- `templates/knowledge-risk-report.md` - the report and 90-day plan you hand back
- `examples/git-history.log`, `examples/aliases.csv` - history of a fictional shop API with five people and a bot: a payments module written by someone who left, a frontend only one person changes, an author with two emails

## Workflow

### 1. Agree the scope
Ask which repository (or monorepo folders) matter, what counts as "active" (default: committed in the last 120 days), how old history should count (default half-life 365 days), and who has left or is about to go on long leave. Ask whether a CODEOWNERS file or team map exists to compare with afterwards.

### 2. Get the history
Inside the repository:
```
git log --no-merges --numstat --date=short --format='@@%H%x09%an%x09%ae%x09%ad' > history.log
```
or let the script run git with `--repo PATH`. Build `aliases.csv` (`alias,canonical`) for people with several emails or names; the first run lists likely duplicates as BF05.

### 3. Run the analysis
```
python3 scripts/bus_factor.py examples/git-history.log --aliases examples/aliases.csv
python3 scripts/bus_factor.py --repo . --aliases aliases.csv --depth 2 --since 2024-01-01
python3 scripts/bus_factor.py history.log --aliases aliases.csv --json > knowledge.json
python3 scripts/bus_factor.py --self-test
```
Use `--depth 2` for monorepos (`services/payments`), `--exclude 'docs/*'` for folders that do not matter, `--as-of` to reproduce a past date. Exit 0 = no high findings, 1 = high findings, 2 = bad input.

### 4. Interpret with the team
- High: BF01 repository truck factor 1-2 (losing one or two people orphans most files), BF02 a module where most files have no active person who knows them.
- Medium: BF03 module bus factor 1, BF04 a hot spot that changed a lot in the last 90 days and is known by one person.
- Low: BF05 duplicate identities (fix aliases and re-run), BF06 only one person ever changed the module.
Before reporting, check each high finding with the team lead: generated code, a recent rewrite or pair-programmed work can make history misleading. Map modules to business impact (payments, auth and data pipelines first).

### 5. Report and plan
Fill `templates/knowledge-risk-report.md`: the module table, the top 3-5 risks ranked by business impact, and a 90-day plan from `references/reducing-knowledge-risk.md` with an owner and a check for each action. Re-run the script monthly or quarterly and compare coverage.

## Rules
- Never present the people table as a productivity ranking or share it outside the team leads; it is there to find single points of failure.
- Treat findings as questions; confirm with the people involved before reassigning work.
- Work locally; do not upload the repository or its history anywhere.

FILE:references/metrics-explained.md
# How bus_factor.py measures knowledge

## Inputs and filters
- History comes from `git log --no-merges --numstat`. Each commit gives author name, email, date and lines added and deleted per file. Binary files (`-`) are skipped; renames keep the new path.
- Bots are skipped unless `--include-bots` (name or email containing `[bot]`, `bot@`, or a name ending in " bot").
- Default excludes: lockfiles (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `poetry.lock`, `Cargo.lock`, `go.sum`, `composer.lock`, `Gemfile.lock`), `vendor/`, `node_modules/`, `dist/`, `build/`, minified files and images. Add more with `--exclude GLOB`.
- Aliases: `aliases.csv` maps an email or a name to one canonical person. Without it, the same person with two emails counts as two people and looks less concentrated than reality.

## Weight of a change
    weight = ln(1 + lines added + lines deleted) * 0.5 ^ (age_days / half_life_days)

- The logarithm stops one huge generated diff from outweighing years of small careful changes.
- The half-life (default 365 days) makes old work count less; people forget code they have not touched.

## Knows a file
An author knows a file when they hold at least `--knows-share` (default 0.25) of the file's total weight. A file can have several knowers.

## Active
An author is active if their last commit is within `--active-days` (default 120) of `--as-of` (default: the newest commit). Tell the script about people who left recently by moving `--as-of` or shortening `--active-days`; history cannot know about resignations.

## Module metrics
- **Module**: the first `--depth` folders of the path (default 1); files at the root form "(root)".
- **Top author / top share**: the person with the largest share of the module's total weight.
- **Bus factor**: the smallest number of people who together hold more than half of the module's weight. 1 means one person holds most of it.
- **Active knowers**: active people who know at least one file in the module.
- **Active coverage**: the share of the module's files with at least one active knower.

## Repository truck factor
A greedy estimate in the spirit of published truck factor research: repeatedly remove the active person who knows the most still-covered files, until more than half of all files have no active knower. The number of people removed is the truck factor. 0 means more than half of the files already have no active knower.

## Findings
| code | severity | rule |
|---|---|---|
| BF01 | high | truck factor is 0, 1 or 2 |
| BF02 | high | active coverage of a module is under 50% |
| BF03 | medium | module bus factor 1 and the module has 3 or more files |
| BF04 | medium | bus factor 1 and the module's line changes in the last 90 days are in the top quarter of modules (needs 4+ modules) |
| BF05 | low | one name appears with several emails and no alias |
| BF06 | low | only one person ever changed the module |

## Limits
- Commits show authorship, not understanding: reviewers, pair partners and people who designed or operate the code are invisible.
- Squash merges credit one author for a team's work; large refactors and formatting commits inflate one person's share (exclude them with `--since` or by filtering the log).
- Co-authored-by trailers are not counted.
- Small repositories and modules with few files give noisy numbers; read them with the team.

FILE:references/reducing-knowledge-risk.md
# Reducing knowledge risk

## By finding
| finding | usual meaning | first actions |
|---|---|---|
| BF01 truck factor 1-2 | most of the codebase depends on one or two people | pick the 2-3 most business-critical modules and start the actions below there; make it a quarterly goal, not extra work on top |
| BF02 orphaned module | the people who wrote it left or moved on | name an owner now; schedule a code walkthrough with anyone who remembers it; write a short runbook; add tests around the risky paths before the next change |
| BF03 bus factor 1 | one person does almost all changes | rotate reviews so a second person reviews every change; pair on the next feature; the main author writes a one-page architecture note |
| BF04 single-knower hot spot | the busiest code is known by one person | highest priority after orphaned modules: pair every second change, add a second reviewer as required, keep a changelog of decisions |
| BF05 duplicate identity | one person with several emails | add alias lines and re-run; ask people to set `user.email` per repository |
| BF06 one person ever | nobody else has touched it at all | give a small, real task in that module to a second person with the author as reviewer |

## Practices that work
- **Review rotation**: the second reviewer for a module comes from outside its usual authors; track it for a month.
- **Pairing or mob sessions** on the next real change, not on toy tasks; 60-90 minutes per week per risky module is often enough.
- **Runbooks** for operating the module: how to deploy, roll back, read its dashboards and handle its common alerts.
- **Architecture notes**: one page per module (purpose, data flow, sharp edges, why decisions were made), kept next to the code.
- **Ownership**: a team (not one person) as owner in CODEOWNERS, with at least two people able to approve.
- **On-call shadowing** for modules that page people.
- **Handover plans** when someone gives notice or goes on long leave: list their modules from this report, schedule walkthroughs, and pair on open work in their last weeks.

## Measuring progress
Re-run monthly with the same settings and compare: active coverage per critical module (target 100% with at least two active knowers), module bus factor (target 2+), and the repository truck factor (target 3+ for a small team).

FILE:templates/knowledge-risk-report.md
# Knowledge risk report: {{repository}} - {{date}}

Settings: active = committed in the last {{active_days}} days; half-life {{half_life_days}} days; knows-share {{knows_share}}; module depth {{depth}}. History since {{since}}.

## Summary
- Repository truck factor: {{truck_factor}} ({{people}})
- Modules with low active coverage: {{bf02_modules}}
- Single-knower modules: {{bf03_modules}}
- Hot spots known by one person: {{bf04_modules}}

## Module table
(paste the module table from bus_factor.py)

## Top risks (ranked by business impact)
| # | module | why it matters | finding | confirmed with |
|---|---|---|---|---|
| 1 | {{module}} | {{impact, e.g. checkout payments}} | {{code}} | {{lead}} |

## 90-day plan
| action | module | owner | by | done when |
|---|---|---|---|---|
| {{e.g. pair on next two changes}} | {{module}} | {{name}} | {{date}} | {{second person merged a change alone}} |

## Caveats
- History shows who changed code, not who understands it; reviewers, pair partners and operators are not counted.
- {{anything specific: squash merges, a big refactor, generated code}}

## Next check
{{date}} with the same settings.

FILE:examples/git-history.log
@@58f5d4cce18a5ce4e3f9aa12d9767dcfd74b25ee	Ben Okafor	ben@shop.example	2026-11-14

5	0	web/src/api.ts
32	0	web/src/checkout.tsx
@@4cbab3078c9e5e9fac0a6d3627c6e022739f96e1	Eli Novak	eli@shop.example	2026-11-12

12	0	core/config.py
40	0	core/db.py
@@a0d3945429639f6c562a88444476839744d9453e	Ana Silva	ana.silva@shop.example	2026-11-10

10	0	core/db.py
29	0	orders/api.py
@@faa0aacf2cd46c8e74c9bd98cf5921fb50dd6c6b	Ana Silva	ana.silva@shop.example	2026-10-20

15	0	payments/webhooks.py
@@b579089fdf73b4d2bc6598a4ee680b3839743088	Ben Okafor	ben@shop.example	2026-10-11

9	0	web/src/cart.tsx
6	0	web/src/checkout.tsx
@@50b03245d12d83ddb1e9ae1c66a2d45178051021	Eli Novak	eli@shop.example	2026-10-10

15	0	core/config.py
11	0	search/query.py
@@7214f7c5b6154585c695eaf02e978b3464b8dc02	dependabot[bot]	49699333+dependabot[bot]@users.noreply.github.com	2026-10-01

150	0	web/package-lock.json
150	0	web/package.json
@@16652d4b388444019ca413263b86cbfd87baed7a	Ana Silva	ana.silva@shop.example	2026-09-24

37	0	orders/api.py
7	0	orders/service.py
@@8290901896c8e9f9611cff8466cf7966b25eb76d	Ben Okafor	ben@shop.example	2026-09-15

5	0	README.md
@@fffb9688a48be4a6e95b08b16cba70e17e9f4b9b	Eli Novak	eli@shop.example	2026-09-07

15	0	orders/api.py
31	0	search/query.py
@@e841c7d0bbed56f4725d681b6587a1808123c893	Ben Okafor	ben@shop.example	2026-09-07

24	0	web/src/api.ts
25	0	web/src/cart.tsx
@@88ccae50a361536da22fe6b5e96cc008385ccccb	Ana Silva	ana.silva@shop.example	2026-08-09

25	0	orders/models.py
14	0	orders/service.py
@@000ed52a381b54ba901092d2050c6165b8441de8	Eli Novak	eli@shop.example	2026-08-06

37	0	core/db.py
27	0	orders/api.py
@@c548efcb90ebc04644b4f9d761bb0a96bc9be56d	Ben Okafor	ben@shop.example	2026-08-04

4	0	web/src/api.ts
13	0	web/src/checkout.tsx
@@b9a4d1e4e28cda2113d8ac51cdff3389910dc14e	Eli Novak	eli@shop.example	2026-07-04

32	0	core/config.py
15	0	core/db.py
@@a003bffd397e386e00c745b4393ca3c509859e35	Ben O.	ben.okafor@gmail.example	2026-07-01

3	0	web/src/cart.tsx
9	0	web/src/checkout.tsx
@@10e0e7b09f2d37b0c7055c4a7a17af09dc945e91	Ana Silva	ana.silva@shop.example	2026-06-24

18	0	core/db.py
28	0	orders/models.py
@@d0076f938d1899cc368d2cc627220682762e6516	Eli Novak	eli@shop.example	2026-06-02

35	0	core/config.py
15	0	search/query.py
@@b70911cb2b187c324a78b2af770bff9c354ed222	Ben Okafor	ben@shop.example	2026-05-29

28	0	web/src/api.ts
6	0	web/src/cart.tsx
@@c77843f7c87f8d6ad35d107e4ad625e4559cf306	Chen Wei	chen@shop.example	2026-05-15

30	0	core/config.py
9	0	search/query.py
@@faeb60ed9f9ec1faaf33e8393463027d45666e4a	Ana Silva	ana.silva@shop.example	2026-05-09

25	0	core/db.py
31	0	orders/api.py
@@09c4044f954ffd84dc15713518cc1532a6c5cc6f	Ben Okafor	ben@shop.example	2026-04-25

8	0	web/src/api.ts
8	0	web/src/checkout.tsx
@@efcdcc32cc592412a5a7dd1796fa0149aff7094a	dependabot[bot]	49699333+dependabot[bot]@users.noreply.github.com	2026-04-01

150	0	web/package-lock.json
150	0	web/package.json
@@ae3fc07a50e237c4a8b98c1df55da1f5e8155aa6	Ana Silva	ana.silva@shop.example	2026-03-24

30	0	orders/api.py
36	0	orders/service.py
@@eb7130d2a61f5f297762462e5ea807f5c601b827	Ben Okafor	ben@shop.example	2026-03-22

36	0	web/src/cart.tsx
30	0	web/src/checkout.tsx
@@bdadf66c0528166414b20facd6e0bc6490dc50c4	Chen Wei	chen@shop.example	2026-03-14

38	0	search/index.py
37	0	search/query.py
@@9dd045964286f69e2630aa8d2492d9cb8b126f45	Ben Okafor	ben@shop.example	2026-02-16

22	0	web/src/api.ts
39	0	web/src/cart.tsx
@@e5b16b9f4a0600bb1303545da56d8ec5b775a71d	Ana Silva	ana.silva@shop.example	2026-02-06

40	0	orders/models.py
4	0	orders/service.py
@@9f3ce69e27b7d9c169f07879450c79faffb917e9	Ben Okafor	ben@shop.example	2026-01-14

28	0	web/src/api.ts
26	0	web/src/checkout.tsx
@@87c36c4896129acc5b4dacb88498e10394a0dfaf	Chen Wei	chen@shop.example	2026-01-11

22	0	core/config.py
39	0	search/index.py
@@8ef82e501b1097d202e79c324d4a6118e855f852	Ana Silva	ana.silva@shop.example	2025-12-22

28	0	core/db.py
14	0	orders/models.py
@@3433f75f61d9493c5cb9d48d7a5fb86ef241bea0	Ben Okafor	ben@shop.example	2025-12-11

36	0	web/src/cart.tsx
29	0	web/src/checkout.tsx
@@304e9fd851a7b0cdd05780fe452310a5d3d86abc	Chen Wei	chen@shop.example	2025-11-11

21	0	core/config.py
35	0	search/query.py
@@98d8c4bbb5f3b6604cfd38bc5dda9f08736c64ed	Ben Okafor	ben@shop.example	2025-11-07

29	0	web/src/api.ts
19	0	web/src/cart.tsx
@@03290d9ed4de0c842c7b378220f9a385b4135a4d	Ana Silva	ana@personal.example	2025-11-06

5	0	core/db.py
37	0	orders/api.py
@@f1e157a039fbe041730b8f1137c684027f0e7c32	Ben Okafor	ben@shop.example	2025-10-04

24	0	web/src/api.ts
6	0	web/src/checkout.tsx
@@5622224adaa507aa5490d234b1840d20477c3575	dependabot[bot]	49699333+dependabot[bot]@users.noreply.github.com	2025-09-30

150	0	web/package-lock.json
150	0	web/package.json
@@f658dbaddfcc5963b8e27a6f36a1903d4b3db6e6	Ana Silva	ana.silva@shop.example	2025-09-21

30	0	orders/api.py
14	0	orders/service.py
@@bac00f633bef75ed05866ccc8d6d31fb9e071e3e	Chen Wei	chen@shop.example	2025-09-10

20	0	search/index.py
20	0	search/query.py
@@c460c69d03be963f77b2524616dfde637254e72f	Ben Okafor	ben@shop.example	2025-09-01

35	0	web/src/cart.tsx
12	0	web/src/checkout.tsx
@@65153a48d22bf9b981f3680e6f9917b64a43ec35	Ana Silva	ana.silva@shop.example	2025-08-06

28	0	orders/models.py
22	0	orders/service.py
@@bc8cbd6bf9daee0d05449afbbaccb64f56bfb29a	Chen Wei	chen@shop.example	2025-07-11

19	0	core/config.py
14	0	search/index.py
@@6a34d862b912eb393cf7f8ca55c028b9010173be	Ana Silva	ana.silva@shop.example	2025-06-21

23	0	core/db.py
24	0	orders/models.py
@@6059e786b3ab3482031920657fecf929a4a58bd4	Dana Kim	dana@shop.example	2025-05-20

6	0	payments/stripe_client.py
39	0	payments/webhooks.py
@@e7cb62d4ed5198d9ce0a3fe0b1c938113a67ad97	Chen Wei	chen@shop.example	2025-05-10

36	0	core/config.py
40	0	search/query.py
@@9fd0749dd73e35beb76f65b7e3657463d44c7e54	Ana Silva	ana.silva@shop.example	2025-05-06

10	0	core/db.py
14	0	orders/api.py
@@a0c736ff9075a594896ca5bf024440a12c35c115	Dana Kim	dana@shop.example	2025-05-03

29	0	payments/refunds.py
15	0	payments/webhooks.py
@@1e40d5f4b152a88dbd317ede961bf06ae2a0a742	Dana Kim	dana@shop.example	2025-04-17

22	0	payments/refunds.py
19	0	payments/stripe_client.py
@@ab3f7a3a2d1bea59b43fc959a0b3e1116dcf247f	dependabot[bot]	49699333+dependabot[bot]@users.noreply.github.com	2025-04-01

150	0	web/package-lock.json
150	0	web/package.json
@@fb0a311f7267f495367425518ef25dbf365f5ae1	Dana Kim	dana@shop.example	2025-03-31

40	0	payments/stripe_client.py
4	0	payments/webhooks.py
@@cd493d2263836828dcb0be8e4c4140125c965850	Ana Silva	ana.silva@shop.example	2025-03-21

39	0	orders/api.py
6	0	orders/service.py
@@3c743484d0dd4bca3905f9686bba1f48b22de580	Dana Kim	dana@shop.example	2025-03-15

38	0	payments/refunds.py
30	0	payments/webhooks.py
@@981e4f06309729c1da359503aed2ba7acd1a8e8b	Chen Wei	chen@shop.example	2025-03-10

23	0	search/index.py
14	0	search/query.py
@@c9168c14828d2c382e334aa604064471d5d0cd63	Dana Kim	dana@shop.example	2025-02-26

6	0	payments/refunds.py
20	0	payments/stripe_client.py
@@4e20074f7f1b7bddfda1949cc23b0852c36ec61a	Dana Kim	dana@shop.example	2025-02-10

17	0	payments/stripe_client.py
8	0	payments/webhooks.py
@@d53da3ddd6680b9335a63352e7b365c79f62c028	Ana Silva	ana.silva@shop.example	2025-02-03

10	0	orders/models.py
25	0	orders/service.py
@@3e657197ddd176ccb02ab859abd3f8416459b665	Dana Kim	dana@shop.example	2025-01-24

31	0	payments/refunds.py
14	0	payments/webhooks.py
@@8590bef42bccc66937a1dcbc79275ed93099cef7	Dana Kim	dana@shop.example	2025-01-08

4	0	payments/refunds.py
18	0	payments/stripe_client.py
@@f67141a910fd0594c02e23adbc41e740d373506c	Ana Silva	ana.silva@shop.example	2025-01-06

11	0	README.md

FILE:examples/aliases.csv
alias,canonical
ben.okafor@gmail.example,Ben Okafor
Ben O.,Ben Okafor

FILE:scripts/bus_factor.py
#!/usr/bin/env python3
"""bus_factor.py - find knowledge concentration ("bus factor") risk in a Git repository from its history.

Reads `git log --numstat` history (from a saved log file or by running git on a repo), merges author
aliases, skips bots, lockfiles and vendored code, and weights each change by lines touched and how
recent it is. Per module (top-level folder by default) it reports who holds the knowledge, the module
bus factor (fewest people holding more than half of it), whether any active person still knows it,
and the repository truck factor (how many people would have to leave before more than half of the
files have no active person who knows them). Standard library only.

Usage:
  python3 bus_factor.py LOGFILE [options]
  python3 bus_factor.py --repo PATH [options]          (runs git log for you)
  python3 bus_factor.py --self-test
Make LOGFILE with:
  git log --no-merges --numstat --date=short --format='@@%H%x09%an%x09%ae%x09%ad' > history.log
Options:
  --aliases FILE       CSV alias,canonical  (alias = an email or a name; canonical = the person's name)
  --depth N            module = first N folders of the path (default 1; root files = "(root)")
  --since YYYY-MM-DD   ignore older commits
  --as-of YYYY-MM-DD   reference date (default: newest commit in the log)
  --active-days N      an author is active if they committed within N days of --as-of (default 120)
  --half-life-days N   a change loses half its weight after N days (default 365)
  --knows-share X      an author "knows" a file when they hold at least X of its weight (default 0.25)
  --exclude GLOB       extra path pattern to skip (repeatable); defaults skip lockfiles, vendor, dist, minified
  --include-bots       keep authors whose name or email contains [bot] or "bot@"
  --json               machine-readable output
Exit codes: 0 no high findings, 1 high findings, 2 bad input.
"""
import csv, datetime as dt, fnmatch, json, math, os, subprocess, sys
from collections import defaultdict

DEFAULT_EXCLUDES = ["*package-lock.json", "*yarn.lock", "*pnpm-lock.yaml", "*poetry.lock", "*Cargo.lock", "*go.sum",
                    "*composer.lock", "*Gemfile.lock", "vendor/*", "*/vendor/*", "node_modules/*", "dist/*",
                    "build/*", "*.min.js", "*.min.css", "*.svg", "*.png", "*.jpg", "*.pdf"]
SEV = {"BF01": "high", "BF02": "high", "BF03": "medium", "BF04": "medium", "BF05": "low", "BF06": "low"}
NAMES = {"BF01": "repository truck factor is 1 or 2",
         "BF02": "orphaned module: most files have no active person who knows them",
         "BF03": "module bus factor 1: one person holds most of the knowledge",
         "BF04": "hot spot with a single knower (busy recently, one person)",
         "BF05": "possible duplicate identity (same name, different emails)",
         "BF06": "only one person has ever changed this module"}


class InputError(Exception):
    pass


def parse_date(s, what):
    try:
        return dt.date.fromisoformat(s.strip()[:10])
    except (ValueError, AttributeError):
        raise InputError("bad %s date: %r" % (what, s))


def parse_log(lines):
    """Return list of commits: dict(sha, name, email, date, files=[(path, added, deleted)])."""
    commits, cur = [], None
    for n, raw in enumerate(lines, 1):
        line = raw.rstrip("\n")
        if line.startswith("@@"):
            parts = line[2:].split("\t")
            if len(parts) < 4:
                raise InputError("line %d: header needs sha, name, email, date separated by tabs" % n)
            cur = {"sha": parts[0], "name": parts[1].strip(), "email": parts[2].strip().lower(),
                   "date": parse_date(parts[3], "commit"), "files": []}
            commits.append(cur)
        elif line.strip():
            if cur is None:
                raise InputError("line %d: numstat line before any @@ commit header (wrong --format?)" % n)
            parts = line.split("\t")
            if len(parts) != 3:
                raise InputError("line %d: expected 'added<TAB>deleted<TAB>path'" % n)
            a, d, path = parts
            if a == "-" or d == "-":      # binary file
                continue
            path = path.strip()
            if " => " in path:            # rename: keep the new path
                if "{" in path:
                    pre, rest = path.split("{", 1)
                    mid, post = rest.split("}", 1)
                    path = (pre + mid.split(" => ")[1] + post).replace("//", "/")
                else:
                    path = path.split(" => ")[1]
            try:
                cur["files"].append((path, int(a), int(d)))
            except ValueError:
                raise InputError("line %d: added/deleted must be numbers" % n)
    if not commits:
        raise InputError("no commits found (expected lines starting with @@)")
    return commits


def git_log(repo, since=None):
    cmd = ["git", "-C", repo, "log", "--no-merges", "--numstat", "--date=short", "--format=@@%H%x09%an%x09%ae%x09%ad"]
    if since:
        cmd.append("--since=" + since)
    try:
        out = subprocess.run(cmd, capture_output=True, text=True, check=True).stdout
    except (OSError, subprocess.CalledProcessError) as e:
        raise InputError("git log failed: %s" % (getattr(e, "stderr", "") or e))
    return out.splitlines()


def load_aliases(path):
    m = {}
    if not path:
        return m
    try:
        for row in csv.DictReader(open(path, encoding="utf-8", newline="")):
            a, c = (row.get("alias") or "").strip(), (row.get("canonical") or "").strip()
            if a and c:
                m[a.lower()] = c
    except OSError as e:
        raise InputError("cannot read aliases: %s" % e)
    return m


def module_of(path, depth):
    parts = path.split("/")
    if len(parts) == 1:
        return "(root)"
    return "/".join(parts[:min(depth, len(parts) - 1)])


def analyse(commits, aliases=None, depth=1, since=None, as_of=None, active_days=120, half_life=365,
            knows_share=0.25, excludes=None, include_bots=False):
    aliases = aliases or {}
    pats = DEFAULT_EXCLUDES + list(excludes or [])
    since_d = parse_date(since, "--since") if since else None
    as_of_d = parse_date(as_of, "--as-of") if as_of else max(c["date"] for c in commits)
    emails_by_name = defaultdict(set)
    last_seen = {}
    fw = defaultdict(lambda: defaultdict(float))       # file -> author -> weight
    f_last = {}
    f_recent = defaultdict(float)                       # lines in last 90 days
    commits_per_module = defaultdict(set)
    authors_ever = defaultdict(set)                     # module -> authors (unweighted)
    used = 0
    for c in commits:
        if since_d and c["date"] < since_d:
            continue
        if c["date"] > as_of_d:
            continue
        if not include_bots and ("[bot]" in c["name"].lower() or "bot@" in c["email"] or c["name"].lower().endswith(" bot")):
            continue
        who = aliases.get(c["email"]) or aliases.get(c["name"].lower()) or c["name"]
        if who == c["name"] and not aliases.get(c["email"]):
            emails_by_name[c["name"]].add(c["email"])
        last_seen[who] = max(last_seen.get(who, c["date"]), c["date"])
        age = (as_of_d - c["date"]).days
        w = 0.5 ** (age / float(half_life)) if half_life > 0 else 1.0
        touched = False
        for path, a, d in c["files"]:
            if any(fnmatch.fnmatch(path, p) for p in pats):
                continue
            lines = a + d
            if lines == 0:
                continue
            touched = True
            fw[path][who] += math.log1p(lines) * w     # log damps huge generated diffs
            f_last[path] = max(f_last.get(path, c["date"]), c["date"])
            if age <= 90:
                f_recent[path] += lines
            mod = module_of(path, depth)
            commits_per_module[mod].add(c["sha"])
            authors_ever[mod].add(who)
        used += touched
    if not fw:
        raise InputError("no usable file changes after filters")
    active = {a for a, d in last_seen.items() if (as_of_d - d).days <= active_days}

    def knowers(path):
        tot = sum(fw[path].values())
        return {a for a, v in fw[path].items() if v / tot >= knows_share}

    files = sorted(fw)
    mods = defaultdict(list)
    for p in files:
        mods[module_of(p, depth)].append(p)
    recent_by_mod = {m: sum(f_recent[p] for p in ps) for m, ps in mods.items()}
    hot_cut = sorted(recent_by_mod.values())[int(len(recent_by_mod) * 0.75)] if recent_by_mod else 0
    out_mods, findings = [], []
    for m in sorted(mods):
        ps = mods[m]
        aw = defaultdict(float)
        for p in ps:
            for a, v in fw[p].items():
                aw[a] += v
        tot = sum(aw.values())
        ranked = sorted(aw.items(), key=lambda x: -x[1])
        acc, bf = 0.0, 0
        for a, v in ranked:
            acc += v; bf += 1
            if acc > tot / 2:
                break
        kn = set().union(*(knowers(p) for p in ps))
        act_kn = sorted(kn & active)
        covered = sum(1 for p in ps if knowers(p) & active)
        top, share = ranked[0][0], ranked[0][1] / tot
        row = {"module": m, "files": len(ps), "commits": len(commits_per_module[m]), "authors": len(aw),
               "top_author": top, "top_share": round(share, 3), "bus_factor": bf,
               "active_knowers": act_kn, "active_coverage": round(covered / len(ps), 3),
               "last_change": max(f_last[p] for p in ps).isoformat(), "recent_lines_90d": int(recent_by_mod[m]),
               "top_author_active": top in active, "findings": []}
        if covered / len(ps) < 0.5:
            row["findings"].append("BF02")
        if bf == 1 and len(ps) >= 3:
            row["findings"].append("BF03")
        if bf == 1 and recent_by_mod[m] > 0 and recent_by_mod[m] >= hot_cut and len(mods) >= 4:
            row["findings"].append("BF04")
        if len(authors_ever[m]) == 1:
            row["findings"].append("BF06")
        out_mods.append(row)
    # repository truck factor: greedily remove the author who knows most still-covered files
    file_kn = {p: knowers(p) & active for p in files}
    removed, tf = [], 0
    remaining = {p: set(k) for p, k in file_kn.items()}
    def orphaned():
        return sum(1 for k in remaining.values() if not k)
    if orphaned() > len(files) / 2:
        tf = 0
    else:
        while orphaned() <= len(files) / 2:
            cnt = defaultdict(int)
            for k in remaining.values():
                for a in k:
                    cnt[a] += 1
            if not cnt:
                break
            a = sorted(cnt.items(), key=lambda x: (-x[1], x[0]))[0][0]
            removed.append(a); tf += 1
            for k in remaining.values():
                k.discard(a)
    if tf <= 2:
        findings.append({"code": "BF01", "detail": "truck factor %d (%s)" % (tf, ", ".join(removed) or "already orphaned")})
    for name, em in sorted(emails_by_name.items()):
        if len(em) > 1:
            findings.append({"code": "BF05", "detail": "%s uses %s; add an alias line" % (name, ", ".join(sorted(em)))})
    for r in out_mods:
        for code in r["findings"]:
            findings.append({"code": code, "module": r["module"], "detail": "top %s %.0f%%, active knowers: %s" % (
                r["top_author"], r["top_share"] * 100, ", ".join(r["active_knowers"]) or "none")})
    people = sorted(({"author": a, "last_commit": d.isoformat(), "active": a in active,
                      "files_known": sum(1 for p in files if a in knowers(p))} for a, d in last_seen.items()),
                    key=lambda x: -x["files_known"])
    return {"as_of": as_of_d.isoformat(), "commits_used": used, "files": len(files), "modules": out_mods,
            "truck_factor": tf, "truck_factor_people": removed, "people": people,
            "settings": {"depth": depth, "active_days": active_days, "half_life_days": half_life, "knows_share": knows_share},
            "findings": findings}


def render(a):
    L = ["# Knowledge risk report (as of %s)" % a["as_of"], "",
         "Commits used: %d | files: %d | repository truck factor: %d (%s)" % (
             a["commits_used"], a["files"], a["truck_factor"], ", ".join(a["truck_factor_people"]) or "-"), "",
         "| module | files | commits | authors | top author | top share | bus factor | active knowers | active coverage | last change |",
         "|---|---|---|---|---|---|---|---|---|---|"]
    for r in a["modules"]:
        L.append("| %s | %d | %d | %d | %s%s | %.0f%% | %d | %s | %.0f%% | %s |" % (
            r["module"], r["files"], r["commits"], r["authors"], r["top_author"], "" if r["top_author_active"] else " (inactive)",
            r["top_share"] * 100, r["bus_factor"], ", ".join(r["active_knowers"]) or "none", r["active_coverage"] * 100,
            r["last_change"]))
    L += ["", "## People", "", "| author | last commit | active | files known |", "|---|---|---|---|"]
    for p in a["people"]:
        L.append("| %s | %s | %s | %d |" % (p["author"], p["last_commit"], "yes" if p["active"] else "no", p["files_known"]))
    L += ["", "## Findings"]
    order = {"high": 0, "medium": 1, "low": 2}
    for f in sorted(a["findings"], key=lambda f: (order[SEV[f["code"]]], f["code"], f.get("module", ""))):
        L.append("- [%s] %s %s%s: %s" % (SEV[f["code"]], f["code"], NAMES[f["code"]],
                                         (" - " + f["module"]) if f.get("module") else "", f["detail"]))
    if not a["findings"]:
        L.append("- none")
    L += ["", "History shows who changed code, not who understands it; confirm with the team before acting."]
    return "\n".join(L)


def self_test():
    T = []
    def check(name, cond):
        T.append((name, bool(cond)))
    log = """@@a1\tAna\tana@x.io\t2026-01-10
10\t2\tapi/orders.py
5\t0\tapi/users.py
@@a2\tBen\tben@x.io\t2026-03-01
20\t5\tweb/app.js
3\t1\tapi/orders.py
@@a3\tAna\tana@home.io\t2026-06-01
4\t4\tapi/users.py
-\t-\tweb/logo.png
@@a4\tdependabot[bot]\t49699333+dependabot[bot]@users.noreply.github.com\t2026-06-02
200\t180\tpackage-lock.json
1\t1\tweb/package.json
@@a5\tCara\tcara@x.io\t2025-01-05
50\t0\tbilling/{old => new}/invoice.py
@@a6\tBen\tben@x.io\t2026-06-10
2\t2\tREADME.md
""".splitlines()
    c = parse_log(log)
    check("parses 6 commits", len(c) == 6)
    check("binary numstat rows skipped", all(f[0] != "web/logo.png" for x in c for f in x["files"]))
    check("brace rename resolved to new path", c[4]["files"][0][0] == "billing/new/invoice.py")
    check("module of root file is (root)", module_of("README.md", 1) == "(root)")
    check("module depth 2", module_of("src/api/x/y.py", 2) == "src/api")
    a = analyse(c, as_of="2026-06-10")
    mods = {m["module"]: m for m in a["modules"]}
    check("bot commits skipped", "web" in mods and mods["web"]["authors"] == 1)
    check("lockfile excluded", all(m["module"] != "(root)" or m["files"] == 1 for m in a["modules"]))
    check("duplicate identity flagged BF05", any(f["code"] == "BF05" and "Ana" in f["detail"] for f in a["findings"]))
    a2 = analyse(c, aliases={"ana@home.io": "Ana"}, as_of="2026-06-10")
    check("alias removes BF05", not any(f["code"] == "BF05" for f in a2["findings"]))
    check("inactive author makes billing orphaned BF02", "BF02" in mods["billing"]["findings"])
    check("single-author module flagged BF06", "BF06" in mods["web"]["findings"])
    check("api bus factor is 1 (Ana holds most)", mods["api"]["bus_factor"] == 1 and mods["api"]["top_author"] == "Ana")
    check("truck factor small -> BF01", any(f["code"] == "BF01" for f in a["findings"]))
    a3 = analyse(c, as_of="2026-06-10", since="2026-02-01")
    check("--since drops older commits", a3["commits_used"] == 3)
    a4 = analyse(c, as_of="2026-06-10", active_days=600)
    check("long active window: billing has an active knower", "BF02" not in {m["module"]: m for m in a4["modules"]}["billing"]["findings"])
    check("BF02 uses active coverage under 50%", all(("BF02" in m["findings"]) == (m["active_coverage"] < 0.5) for m in a["modules"]))
    check("recency weight halves after half-life", abs(0.5 ** (365 / 365.0) - 0.5) < 1e-9)
    for bad, label in [(["10\t2\tx.py"], "numstat before header rejected"), (["@@x\tA\ta@b\tnot-a-date"], "bad date rejected"),
                       (["@@x\tA\ta@b\t2026-01-01", "ten\t2\tx.py"], "non-numeric counts rejected"), ([], "empty log rejected")]:
        try:
            parse_log(bad); check(label, False)
        except InputError:
            check(label, True)
    try:
        analyse(parse_log(["@@x\tA\ta@b\t2026-01-01", "3\t1\tyarn.lock"])); check("only excluded files rejected", False)
    except InputError:
        check("only excluded files rejected", True)
    for name, ok in T:
        print(("PASS  " if ok else "FAIL  ") + name)
    good = all(ok for _, ok in T)
    print("ALL PASS" if good else "SOME FAILED", "(%d/%d)" % (sum(ok for _, ok in T), len(T)))
    return 0 if good else 1


def main(argv):
    if "--self-test" in argv:
        return self_test()
    opts = {"aliases": None, "depth": "1", "since": None, "as-of": None, "active-days": "120", "half-life-days": "365",
            "knows-share": "0.25", "repo": None}
    excludes, pos, i = [], [], 0
    while i < len(argv):
        x = argv[i]
        if x in ("--json", "--include-bots"):
            i += 1; continue
        if x.startswith("--"):
            k = x[2:]
            if i + 1 >= len(argv) or (k not in opts and k != "exclude"):
                print("error: unknown or incomplete option %s" % x, file=sys.stderr); return 2
            if k == "exclude":
                excludes.append(argv[i + 1])
            else:
                opts[k] = argv[i + 1]
            i += 2; continue
        pos.append(x); i += 1
    try:
        if opts["repo"]:
            lines = git_log(opts["repo"], opts["since"])
        elif len(pos) == 1:
            try:
                lines = open(pos[0], encoding="utf-8", errors="replace").read().splitlines()
            except OSError as e:
                raise InputError("cannot read %s: %s" % (pos[0], e))
        else:
            print(__doc__, file=sys.stderr); return 2
        try:
            depth, ad, hl, ks = int(opts["depth"]), int(opts["active-days"]), int(opts["half-life-days"]), float(opts["knows-share"])
        except ValueError:
            raise InputError("--depth, --active-days and --half-life-days need whole numbers, --knows-share a decimal")
        if depth < 1 or not 0 < ks <= 1:
            raise InputError("--depth must be >= 1 and --knows-share between 0 and 1")
        a = analyse(parse_log(lines), load_aliases(opts["aliases"]), depth, opts["since"], opts["as-of"], ad, hl, ks,
                    excludes, "--include-bots" in argv)
    except InputError as e:
        print("error: %s" % e, file=sys.stderr); return 2
    print(json.dumps(a, indent=2) if "--json" in argv else render(a))
    return 1 if any(SEV[f["code"]] == "high" for f in a["findings"]) else 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
RiskEngineeringGit+3
F@f
0
ALDC RAG Lifecycle Doc Generator (.md)
Text

Generates production-grade, RAG-optimized Markdown (.md) documentation aligned with the 16-Phase Enterprise Lifecycle and 10-Phase ADLC. Enforces YAML frontmatter for metadata filtering, H1–H4 header breadcrumbs, self-contained semantic chunks, Gherkin acceptance criteria, and cross-cutting governance—ready for direct ingestion into Obsidian, Git, and vector databases (ChromaDB, Qdrant, pgvector).

---
You are a Principal Technical Product Manager, Data & BI Solutions Architect, and Technical Writer. Your task is to generate a complete, production-grade, RAG-optimized Markdown (`.md`) artifact aligned with the **16-Phase Enterprise Lifecycle** and **10-Phase Analytics Development Lifecycle (ADLC)**.

---

### INPUT PARAMETERS
* **Target Phase (01–16):** {{PHASE}}
* **Document Filename:** {{FILENAME}}
* **Project / Product Name:** {{PROJECT_NAME}}
* **Domain & Tech Stack:** {{DOMAIN_AND_STACK}}
* **Target Audience:** {{TARGET_AUDIENCE}}
* **Raw Context / Requirements / Notes:** {{RAW_CONTEXT}}

---

### MANDATORY RAG & MARKDOWN ARCHITECTURE RULES
1. **YAML Frontmatter Block (Top of File):** Begin immediately with valid YAML frontmatter containing:
   - `id`: Unique uppercase document ID (e.g., `DOC-PHASE-04-PRD`)
   - `title`: Full formal title of the artifact
   - `phase`: Exact phase code and name (e.g., `04_Design`)
   - `lifecycle_tier`: `Tier_1_Core_Delivery` (Phases 01–10), `Tier_2_Commercial_Portfolio` (Phases 11–14), or `Tier_3_Cross_Cutting_Governance` (Phases 15–16)
   - `stage_gate`: Applicable gate (`Gate_0` through `Gate_6`, `Sprint`, or `Continuous`)
   - `adlc_mapping`: Equivalent Data/BI ADLC stage
   - `target_audience`: YAML list of stakeholder roles
   - `version`: `"1.0.0"`
   - `classification`: `"Confidential - Internal"` (or `"Investor Restricted"` for Phases 11–12)
   - `retrieval_tags`: 6–10 high-signal semantic keywords
   - `semantic_summary`: A single dense, factual sentence summarizing the document's scope for embedding models.
2. **Context Breadcrumb:** Immediately below the `# H1` title, include:
   `> **Context Breadcrumb:** Enterprise Lifecycle > [Tier] > [Phase] > [Artifact Title]`
3. **Self-Contained Semantic Chunking (350–700 Tokens per Section):**
   - Use strict `## H2` and `### H3` nesting so Markdown header splitters preserve parent-child context.
   - **Zero Anaphoric References:** Never write *"as mentioned above"*, *"this table"*, or *"the previous section"*. Always restate explicit proper nouns, metric names, and system components so every chunk retrieves accurately in isolation.
4. **Zero Placeholders or Stubs:** Populate every table, schema, formula, and acceptance criterion with concrete, domain-accurate content derived from `{{RAW_CONTEXT}}` and `{{DOMAIN_AND_STACK}}`. Never output `[Insert X]`, `TBD`, or filler text.
5. **Cross-Cutting Governance:** Embed relevant controls across **Documentation, Data Governance, Data Quality, Change Management, Security (RBAC/PII), Project Management, and Configuration Management** directly into the artifact.

---

### PHASE-SPECIFIC DELIVERABLE REQUIREMENTS
Automatically enforce the required structural blocks for `{{PHASE}}`:
* **01 Define (Gate 0):** Project Charter, Problem Statement, Business Case (ROI/NPV/Payback), Voice of Customer (VoC) Matrix, Stakeholder Power-Interest Grid, and Hard Scope Boundaries.
* **02 Measure (Gate 1A):** BRD/FRD/DRD Requirements, Source-to-Target Data Mapping Table, Data Quality Profiling Rules, Telemetry Event Instrumentation Plan, Baseline Metrics, and Mathematical KPI Dictionary.
* **03 Plan (Gate 1B):** Work Breakdown Structure (WBS) & Dictionary, Phased Roadmap, Resource Capacity Allocation, and RAID Log (Risks, Assumptions, Issues, Dependencies with mitigations).
* **04 Design (Gate 2A):** Product Requirement Document (PRD) with Gherkin (`Given-When-Then`) Acceptance Criteria, System Architecture Document (SAD), ERD / Dimensional Star Schema, Semantic Layer & Row-Level Security (RLS) Rules, and Non-Functional Requirements (NFRs).
* **05 Implement (Sprint):** Sprint Backlog Breakdown, OpenAPI 3.0 / gRPC Interface Contracts, ETL/ELT Transformation Specs, Environment Configuration Keys, and Pull Request Definition of Done (DoD).
* **06 Analysis (Gate 2B):** Source-to-Target Data Reconciliation Report, Root Cause Analysis (5-Whys / Ishikawa), Cohort Retention Analysis, and Unit Economics (LTV, CAC, Gross Margin, Sensitivity Table).
* **07 Execute (Gate 3A):** Tier-1/Tier-2 Operations & Escalation Runbook, ADKAR Change Management & Enablement Plan, Steering Committee Executive Summary, and RACI Matrix.
* **08 Test (Gate 3B):** Master Test Strategy, Technical QA & Data Reconciliation Sign-Off Criteria, Business UAT Sign-Off Checklist, Security/Pen-Test Audit Controls, and AI Model Card / Drift Evaluation (if AI/ML is present).
* **09 Control (Gate 4A):** Statistical Process Control (SPC) Thresholds, SLA/SLO Error Budgets, Observability & PagerDuty Alert Escalation Runbook, and RBAC/PII Audit Schedule.
* **10 Deploy (Gate 4B):** Release Notes, Step-by-Step Deployment Runbook, Automated Canary/Blue-Green Rollback Triggers, Smoke Test Verification Checklist, and Infrastructure-as-Code (IaC) Manifest Summary.
* **11 Pitch (Gate 5):** 12-Slide Pitch Deck Narrative Blueprint, 1-Page Executive Investment Teaser, TAM/SAM/SOM Market Sizing, Go-To-Market (GTM) Distribution Playbook, and Live Demo Script.
* **12 Investor (Gate 5):** Tiered Virtual Data Room (VDR) Index (Tiers 1–3), Fully Diluted Capitalization Table Structure, Term Sheet / SHA / SSA Key Clauses, and KYC/AML & IP Assignment Checklist.
* **13 Product LC (Quarterly):** BCG Growth-Share Portfolio Assessment, Annual Product P&L Structure, Market Expansion/Localization Matrix, and 180-Day Feature Sunset & Deprecation Policy.
* **14 Project LC (Gate 6A):** Approved Scope Baseline, Vendor SOW/MSA Governance Register, Earned Value Management (EVM) Variance Summary, and Blameless Post-Mortem & Lessons Learned Archive.
* **15 Documents (Continuous):** Standard Operating Procedures (SOPs), Enterprise Data Dictionary & Lineage Catalog, API Developer Reference, and RAG Vector Ingestion Metadata Schema.
* **16 Submission (Gate 6B):** RFP Compliance Response Matrix, SOC 2 Type II / ISO 27001 / Regulatory Audit Evidence Pack, Stage-Gate Sign-Off Dossier, and Formal Legal Transmittal Attestation.

---

### OUTPUT FORMAT
Output **only** the raw, valid Markdown document enclosed in a single `markdown` code block, starting with `---` (YAML frontmatter) and ending with a **Stage-Gate Exit & RACI Sign-Off Table**. Do not include conversational filler before or after the code block.
---

# Unified Enterprise SDLC, ADLC & 16-Phase Lifecycle Guidance Document

## 1. Purpose & Architectural Scope

This guidance document establishes a single, end-to-end delivery and governance standard for Data Engineering, Business Intelligence (BI), ThoughtSpot Centers of Excellence (COE), and production SaaS product organizations[cite: 2, 5]. It synthesizes traditional Software Development Lifecycle (SDLC) mechanics [cite: 1, 3], the 10-phase Analytics Development Lifecycle (ADLC / ALDC) [cite: 2, 3], and the 16-phase enterprise lifecycle spanning technical delivery, venture commercialization, and continuous compliance [cite: 4, 5].

*   **Terminology Standard (ADLC vs. ALDC):** While internal BI and data engineering teams frequently use the acronym ALDC (Analytics Lifecycle Development Cycle), **ADLC (Analytics Development Lifecycle)** is the recognized industry-standard terminology for analytics delivery frameworks[cite: 3]. Both terms map identically within this standard to govern traceability from business requirements through ingestion, semantic modeling, testing, deployment, and ongoing governance[cite: 2, 3].
*   **Definition of Production Readiness:** A production release is valid only when technical deployment succeeds *and* underlying data assets are accurate, traceable, governed, and trusted by business consumers[cite: 3].

---

## 2. Cross-Attachment Audit & Breaking-Point Reconciliation

Before executing against this standard, teams must account for structural contradictions and visual anomalies across the four baseline artifacts so legacy defects are not propagated into production workflows:

| Source Artifact | Structural Contribution | Identified Breaking Points & Visual Anomalies | Canonical Resolution Enforced in This Guide |
| :--- | :--- | :--- | :--- |
| **`SDLC_Roadmap_Infographic.png`**[cite: 1] | Establishes visual station routing and the left-hand **Bypass Loop (For Refinement)** connecting testing/operations back to upstream stages[cite: 1]. | **1. Inverted Causality:** Places `01 Requirements`, `02 Analysis`, and `03 Planning` before `04 Define`[cite: 1].<br>**2. Triple Build Redundancy:** Splits coding across `06 Implement`, `07 Build`, and `08 Development`[cite: 1].<br>**3. Duplicate Exit Nodes:** Repeats `11 Maintenance` and `12 Feedback / Finish` twice[cite: 1]. | Enforce `01 Define` and `02 Measure` prior to `03 Plan`[cite: 4, 5]; consolidate engineering into `04 Design` and `05 Implement`[cite: 4, 5]; replace duplicate exit nodes with commercial and governance tiers[cite: 4, 5]. |
| **` List ALDC Phases.pdf`**[cite: 2, 3] | Provides the 10-phase Data Engineering, BI, and ThoughtSpot COE framework, SDLC crosswalk, 4-stage pipeline, and 7 cross-cutting governance pillars[cite: 2, 3]. | **1. Non-Standard Acronym:** Uses `ALDC` instead of industry-standard `ADLC`[cite: 3].<br>**2. Commercial Blind Spot:** Stops at `10 Continuous Improvement` without covering investor due diligence, Cap Tables, RFP tenders, or product sunsetting[cite: 2, 3]. | Adopt `ADLC` as the formal acronym[cite: 3] and map all 10 ADLC phases onto Phases `01–10` and `13–15` of the 16-phase enterprise lifecycle[cite: 2, 3, 5]. |
| **`5ff82eb8.jpeg`** *(Isometric 16-Phase Roadmap)*[cite: 4] | Translates the 16 phases into an isometric campus flow featuring the **Continuous Refinement Loop** and sequential `01 Define` through `10 Deploy` stations[cite: 4]. | **1. Visual Badge Duplication:** Renders `13 PRODUCT LC` twice on the lower-right interchange while omitting visible badges for `14 PROJECT LC` and `15 DOCUMENT`[cite: 4]. | Use `5ff82eb8.jpeg` strictly for executive conceptual storytelling[cite: 4]; rely on the canonical 16-phase sequence (`11 Pitch` → `12 Investor` → `13 Product LC` → `14 Project LC` → `15 Document` → `16 Submission`) for operational governance[cite: 5]. |
| **`fd218dcf.png`** *(Swimlane Architecture)*[cite: 5] | Organizes all 16 phases into three functional swimlanes (**Tier 1 Core Delivery**, **Tier 2 Commercial & Portfolio**, **Tier 3 Cross-Cutting Governance**)[cite: 5]. | **1. Gate Numbering Drift:** Visual diamond markers jump from `GATE 2` (after `04 Design`) to `GATE 5` (after `10 Deploy`), and repeat `GATE 6` twice in Tier 2[cite: 5]. | Enforce strict sequential Stage-Gates: **Gate 0** (`01`), **Gate 1** (`02–03`), **Gate 2** (`04–06`), **Gate 3** (`07–08`), **Gate 4** (`09–10`), **Gate 5** (`11–12`), and **Gate 6** (`13–16`). |

---

## 3. Master Multi-Framework Crosswalk Matrix

This crosswalk unifies the **16-Phase Lifecycle**[cite: 4, 5], the **10-Phase ADLC / BI COE Framework**[cite: 2, 3], **Traditional SDLC**[cite: 1, 2, 3], and **dbt Labs' 8-Stage ADLC**[cite: 3]:

| 16-Phase Lifecycle Station | Swimlane Tier & Canonical Gate | 10-Phase ADLC / BI COE Equivalent[cite: 2, 3] | Traditional SDLC Equivalent[cite: 1, 2] | dbt Labs 8-Stage ADLC Equivalent[cite: 3] | Primary Output Artifacts[cite: 2, 3] |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **01. Define** | **Tier 1** • Gate 0[cite: 5] | **1. Initiation & Discovery**[cite: 2] | Planning / Initiation[cite: 1, 2] | Discover[cite: 3] | Project Charter, Business Case, VoC Matrix[cite: 2] |
| **02. Measure** | **Tier 1** • Gate 1[cite: 5] | **2. Requirements Gathering & 3. Data Assessment**[cite: 2] | Requirements & Analysis[cite: 1, 2] | Analyze[cite: 3] | BRD, FRD, DRD, Source-to-Target Mapping, KPI Dictionary[cite: 2, 3] |
| **03. Plan** | **Tier 1** • Gate 1[cite: 5] | **Project Management Track** *(Continuous)*[cite: 3] | Planning[cite: 1, 2] | Plan[cite: 3] | WBS, Product Roadmap, Capacity Plan, RAID Log[cite: 3] |
| **04. Design** | **Tier 1** • Gate 2[cite: 5] | **4. Solution Architecture & Data Modelling**[cite: 2, 3] | Design[cite: 1, 2] | Plan / Architect[cite: 3] | PRD, System Architecture (SAD), ERD, ThoughtSpot Semantic Model[cite: 2, 3] |
| **05. Implement** | **Tier 1** • Sprint[cite: 5] | **5. Development & Configuration**[cite: 2, 3] | Build / Implement[cite: 1, 2] | Develop[cite: 3] | ETL/ELT Pipelines, Semantic Layers, Liveboards, OpenAPI Contracts[cite: 2, 3] |
| **06. Analysis** | **Tier 1** • Gate 2[cite: 5] | **Data Quality & Analytical Diagnostics**[cite: 3] | Analysis[cite: 1, 2] | Analyze / Observe[cite: 3] | Root Cause Analysis (5 Whys), Data Reconciliation, LTV/CAC Model[cite: 3] |
| **07. ** Execute** | **Tier 1** • Gate 3[cite: 5] | **10. Change Management & Enablement**[cite: 2, 3] | Implementation / Rollout[cite: 1] | Operate[cite: 3] | Operations Runbook, ADKAR Enablement Plan, RACI Matrix[cite: 3] |
| **08. Test** | **Tier 1** • Gate 3[cite: 5] | **6. Quality Assurance & 7. Business UAT**[cite: 2, 3] | Testing & Acceptance[cite: 1, 2] | Test[cite: 3] | Master Test Plan, QA Sign-Off, Business UAT Sign-Off, Security Audit[cite: 2, 3] |
| **09. ** Control** | **Tier 1** • Gate 4[cite: 5] | **9. Operations, Monitoring & Security**[cite: 2, 3] | Maintenance[cite: 1, 2] | Observe[cite: 3] | SPC Control Charts, SLA/SLO Budgets, RBAC/PII Audit, Drift Alerts[cite: 3] |
| **10. Deploy** | **Tier 1** • Gate 4[cite: 5] | **8. Release & Production Deployment**[cite: 2, 3] | Deployment / Release[cite: 1, 2] | Deploy[cite: 3] | Deployment Runbook, Canary/Rollback Protocol, Smoke Test Logs[cite: 3] |
| **11. Pitch** | **Tier 2** • Gate 5[cite: 5] | *Value Realization & Executive Showcase* | — | — | Pitch Deck, Investment Teaser, Commercial GTM Strategy |
| **12. Investor** | **Tier 2** • Gate 5[cite: 5] | *Fiduciary & Capital Governance* | — | — | Virtual Data Room (VDR) Index, Cap Table, SHA/SSA, KYC/AML |
| **13. Product LC** | **Tier 2** • Quarterly[cite: 5] | **10. Continuous Improvement & Enhancements**[cite: 2, 3] | Continuous Development[cite: 2] | Discover[cite: 3] | BCG Portfolio Strategy, Market Localization, Feature Sunset Policy |
| **14. ** Project LC** | **Tier 2** • Gate 6[cite: 5] | *Lifecycle Governance & Closure*[cite: 3] | Project Closure | — | Scope Baseline, Vendor SOW/MSA, Earned Value (EVM), Post-Mortem |
| **15. Document** | **Tier 3** • Continuous[cite: 5] | **Documentation & Metadata Governance**[cite: 3] | Documentation | — | BRD/FRD/DRD/TDD, SOPs, Metadata & Lineage Catalog, RAG `.md` Files[cite: 3] |
| **16. Submission** | **Tier 3** • Gate 6[cite: 5] | *Regulatory Compliance & Audit Attestation*[cite: 3] | Governance Audit | — | RFP Tender Dossier, SOC 2 / ISO 27001 Filing, Gate Sign-Off Pack |

---

## 4. Operational Guidance by Tier & Phase

### Tier 1: Core Delivery & ADLC Pipeline (`01 Define` → `10 Deploy`)[cite: 5]

#### Phase 01: Define *(ADLC Phase 1 — Initiation & Discovery)*[cite: 2, 5]
*   **Objective:** Identify core business problems, commercial objectives, executive sponsors, technical feasibility, and measurable outcomes before committing build capacity[cite: 2].
*   **Key Activities:** Conduct discovery workshops; map stakeholder authority; establish hard scope boundaries; validate strategic alignment[cite: 2].
*   **Mandatory Documents:** `01_define_charter_business_case.md` (Project Charter, Business Case with NPV/ROI assumptions, Voice of Customer Matrix, Stakeholder Power-Interest Grid)[cite: 2].
*   **Stage-Gate Exit Criterion (Gate 0):** Signed Project Charter authorizing discovery budget and naming accountable business and technical owners[cite: 2, 5].

#### Phase 02: Measure *(ADLC Phase 2 — Requirements & Phase 3 — Data Assessment)*[cite: 2, 5]
*   **Objective:** Elicit functional, technical, data, reporting, and non-functional requirements while auditing source systems for data availability, quality, lineage, and dependencies[cite: 2].
*   **Key Activities:** Profile source database tables and columns; benchmark current baseline latencies or conversion drop-offs; define canonical KPI formulas; instrument telemetry SDKs[cite: 2].
*   **Mandatory Documents:** `02_measure_telemetry_kpi_dictionary.md` (Business Requirements Document [BRD], Functional Requirements Document [FRD], Data Requirements Document [DRD], Source-to-Target Mapping, KPI Dictionary, Baseline Metrics Report)[cite: 2, 3].
*   **Stage-Gate Exit Criterion (Gate 1A):** Verified Source-to-Target mapping and signed-off BRD/FRD/DRD confirming all required source columns exist and meet baseline quality thresholds[cite: 2, 3].

#### Phase 03: Plan *(Continuous Project Management Track)*[cite: 3, 5]
*   **Objective:** Decompose validated requirements into deterministic work packages, critical-path schedules, resource capacity allocations, and risk mitigation plans[cite: 3].
*   **Key Activities:** Build the Work Breakdown Structure (WBS); sequence dependencies across data engineering, semantic modeling, and frontend teams; initialize the RAID log[cite: 3].
*   **Mandatory Documents:** `03_plan_wbs_roadmap_raid_log.md` (WBS & Dictionary, Product/COE Roadmap, Resource Capacity Plan, Risk Management Matrix / RAID Log)[cite: 3].
*   **Stage-Gate Exit Criterion (Gate 1B):** Approved scope baseline, sprint schedule, and resource allocation plan[cite: 3, 5].

#### Phase 04: Design *(ADLC Phase 4 — Solution Architecture, Data Modelling & Semantic Design)*[cite: 2, 3, 5]
*   **Objective:** Architect end-to-end cloud infrastructure, relational/dimensional schemas, transformation logic, and semantic-layer definitions[cite: 2, 3].
*   **Key Activities:** Model star/snowflake fact and dimension tables; define join cardinalities, row-level security (RLS) rules, and ThoughtSpot worksheet/semantic formulas; draft API contracts and UI wireframes[cite: 2, 3].
*   **Mandatory Documents:** `04_design_prd_system_architecture.md` (Product Requirement Document [PRD] with Gherkin acceptance criteria, System Architecture Document [SAD], Entity-Relationship Diagrams [ERD], Technical Design Document [TDD], Semantic Layer Spec)[cite: 2, 3].
*   **Stage-Gate Exit Criterion (Gate 2A — Architecture Freeze):** Peer-reviewed SAD, ERD, and Semantic Model specification signed off by Principal Architecture and Data Governance[cite: 2, 3, 5].

#### Phase 05: Implement *(ADLC Phase 5 — Development & Configuration)*[cite: 2, 5]
*   **Objective:** Construct ingestion pipelines, ETL/ELT transformations, database tables, semantic layers, KPI formulas, interactive Liveboards, and application microservices[cite: 2, 3].
*   **Key Activities:** Execute Agile sprints using version-controlled Git workflows; enforce peer Pull Request reviews; build automated unit tests alongside pipeline and API code[cite: 3].
*   **Mandatory Documents:** `05_implement_sprint_api_contract.md` (Sprint Backlogs, OpenAPI/Swagger Contracts, Environment Configuration Guides, Repository READMEs).
*   **Stage-Gate Exit Criterion (Sprint Acceptance):** All sprint stories pass static linting, unit tests, and peer code reviews in the development environment.

#### Phase 06: Analysis *(ADLC Data Quality & Analytical Diagnostics)*[cite: 3, 5]
*   **Objective:** Reconcile transformed datasets against source systems, diagnose performance bottlenecks, and validate commercial unit economics[cite: 3].
*   **Key Activities:** Execute row-count, checksum, and aggregate metric reconciliations; run 5-Whys Root Cause Analysis (RCA) on pipeline anomalies; evaluate cohort retention and LTV/CAC models[cite: 3].
*   **Mandatory Documents:** `06_analysis_rca_cohort_economics.md` (Data Reconciliation Report, Root Cause Analysis Dossier, Cohort & Retention Analysis, Unit Economics & Sensitivity Model)[cite: 3].
*   **Stage-Gate Exit Criterion (Gate 2B — Viability Sign-Off):** Zero unexplained data variance between source systems and target semantic models, plus validated commercial unit economics[cite: 3, 5].

#### Phase 07: Execute *(ADLC Phase 10 — Operational Rollout & Change Enablement)*[cite: 2, 3, 5]
*   **Objective:** Prepare operational support teams, business users, and executive stakeholders for organizational adoption before production cutover[cite: 3].
*   **Key Activities:** Deliver enablement training for BI consumers and tier-1/tier-2 support engineers; publish change communications; finalize escalation trees[cite: 3].
*   **Mandatory Documents:** `07_execute_operations_change_mgmt.md` (Operations & Support Runbook, ADKAR Change Management Plan, Steering Committee Deck, RACI Execution Matrix)[cite: 3].
*   **Stage-Gate Exit Criterion (Gate 3A — Operational Readiness):** Support runbooks published and user enablement sessions completed.

#### Phase 08: Test *(ADLC Phase 6 — Technical QA & Phase 7 — Business UAT)*[cite: 2, 3, 5]
*   **Objective:** Verify technical integrity (schema, data types, relationships, performance) and validate business KPI calculations, report outputs, and access permissions with end users[cite: 2, 3].
*   **Key Activities:** Run automated integration, regression, load, and security penetration tests; conduct structured Business UAT sessions validating ThoughtSpot Liveboards and SaaS workflows against BRD/PRD acceptance criteria[cite: 2, 3].
*   **Mandatory Documents:** `08_test_strategy_uat_security_audit.md` (Master Test Plan, Technical QA Sign-Off, Business UAT Sign-Off, Security/Pen-Test Audit, AI Model Card)[cite: 2, 3].
*   **Stage-Gate Exit Criterion (Gate 3B — Quality & Security Sign-Off):** Formal written QA Sign-Off and Business UAT Sign-Off with zero unresolved Severity-1 or Severity-2 defects[cite: 2, 3, 5].

#### Phase 09: Control *(ADLC Phase 9 — Operations, Monitoring & Security Governance)*[cite: 2, 3, 5]
*   **Objective:** Enforce continuous pipeline reliability, refresh schedules, data quality thresholds, role-based access control (RBAC), and drift alerting in production[cite: 2, 3].
*   **Key Activities:** Configure automated SLA/SLO alerts; enforce PII masking and RBAC policies; monitor data freshness, query latency, and model drift via Statistical Process Control (SPC) charts[cite: 3].
*   **Mandatory Documents:** `09_control_spc_slo_drift_runbook.md` (Statistical Process Control Plan, SLA/SLO Error Budget Framework, Observability & PagerDuty Escalation Runbook, RBAC/PII Compliance Log)[cite: 3].
*   **Stage-Gate Exit Criterion (Gate 4A — Stability Check):** Automated monitoring dashboards and synthetic alerts verified active in staging/pre-prod[cite: 3].

#### Phase 10: Deploy *(ADLC Phase 8 — Release & Production Deployment)*[cite: 2, 5]
*   **Objective:** Obtain final release approvals, promote validated assets from QA to production, and execute post-deployment smoke tests[cite: 2, 3].
*   **Key Activities:** Execute CI/CD canary or blue-green deployments; validate database migrations; run automated production smoke tests; verify rollback readiness[cite: 2, 3].
*   **Mandatory Documents:** `10_deploy_release_rollback_iac.md` (Release Notes, Deployment Runbook, Automated Rollback Protocol, Infrastructure-as-Code [Terraform/Helm] Manifests)[cite: 3].
*   **Stage-Gate Exit Criterion (Gate 4B — Production Release Sign-Off):** Verified production smoke tests passing 100%, and release approval logged[cite: 2, 3, 5].

---

### Tier 2: Commercial, Venture & Portfolio Lifecycle (`11 Pitch` → `14 Project LC`)[cite: 5]

#### Phase 11: Pitch *(Commercialization & Value Realization)*[cite: 5]
*   **Objective:** Package verified production traction, unit economics, and technical differentiation into persuasive commercial and investor narratives.
*   **Key Activities:** Synthesize TAM/SAM/SOM sizing, live product demos, and customer ROI case studies; run red-team Q&A drills.
*   **Mandatory Documents:** `11_pitch_deck_gtm_commercial.md` (12–15 Slide Investor Pitch Deck, 1-Page Executive Teaser, Commercial Go-To-Market [GTM] Playbook, Demo Walkthrough Script).

#### Phase 12: Investor *(Investor Onboarding & Fiduciary Diligence)*[cite: 5]
*   **Objective:** Execute institutional due diligence, capitalization table modeling, definitive legal agreements, and capital disbursement.
*   **Key Activities:** Structure tiered Virtual Data Room (VDR) access; reconcile diluted equity and ESOP pools; complete KYC/AML and IP assignment audits.
*   **Mandatory Documents:** `12_investor_vdr_cap_table_term_sheet.md` (Tiered VDR Index, Fully Diluted Cap Table, Term Sheet, Shareholders' Agreement [SHA], Share Subscription Agreement [SSA]).
*   **Stage-Gate Exit Criterion (Gate 5):** Executed definitive agreements and cleared escrow capital transfer[cite: 5].

#### Phase 13: Product Life Cycle *(ADLC Phase 10 — Continuous Improvement & Portfolio Stewardship)*[cite: 2, 5]
*   **Objective:** Govern product and analytics portfolio evolution across Introduction, Growth, Maturity, and Decline stages[cite: 2, 3].
*   **Key Activities:** Prioritize enhancement backlogs and impact assessments; allocate R&D capital via BCG growth-share reviews; manage orderly deprecation and migration of legacy reports or APIs[cite: 2, 3].
*   **Mandatory Documents:** `13_plc_portfolio_sunset_strategy.md` (Product Portfolio Strategy, Annual Product P&L, Market Localization Dossier, Feature Sunset & Deprecation Policy)[cite: 2, 3].

#### Phase 14: Project Life Cycle *(Governance, Vendor Management & Closure)*[cite: 3, 5]
*   **Objective:** Maintain contractual governance over bounded initiatives from scope baseline through vendor management and formal post-mortem closure[cite: 3].
*   **Key Activities:** Track Earned Value Management (EVM) cost/schedule variances; audit vendor Statements of Work (SOW); conduct blameless post-mortems and archive lessons learned[cite: 3].
*   **Mandatory Documents:** `14_project_lifecycle_sow_closure.md` (Project Scope Baseline, Vendor SOW/MSA Register, RAID Escalation Archive, Project Closure & Lessons Learned Report)[cite: 3].
*   **Stage-Gate Exit Criterion (Gate 6A):** Formal stakeholder project acceptance and financial closeout[cite: 5].

---

### Tier 3: Cross-Cutting Governance & Compliance Foundation (`15 Document` & `16 Submission`)[cite: 3, 5]

Rather than executing solely at the end of a project, Tier 3 operates continuously beneath Tiers 1 and 2 to enforce institutional memory and regulatory compliance[cite: 3, 5]:

#### Phase 15: Document *(Continuous Knowledge & Metadata Governance)*[cite: 3, 5]
*   **Objective:** Maintain living, version-controlled technical documentation, data lineage catalogs, Standard Operating Procedures (SOPs), and RAG-ready Markdown knowledge bases[cite: 3].
*   **Key Activities:** Enforce docs-as-code in Git alongside every Pull Request; update data dictionaries, lineage graphs, and ThoughtSpot metric definitions whenever schemas evolve; index `.md` files with YAML frontmatter into enterprise vector stores[cite: 3].
*   **Mandatory Documents:** `15_document_sop_api_data_catalog.md` (BRD/FRD/DRD/TDD Templates, Operational SOPs, Enterprise Data Dictionary & Lineage Catalog, Developer API Hub)[cite: 3].

#### Phase 16: Submission *(Institutional Audits, Regulatory Filings & RFP Tenders)*[cite: 3, 5]
*   **Objective:** Assemble, verify, and formally transmit compliance attestations, regulatory filings, enterprise RFP responses, and Stage-Gate audit packages[cite: 3, 5].
*   **Key Activities:** Compile SOC 2 Type II, ISO 27001, GDPR/DPDP, or financial regulatory evidence; execute legal compliance sign-offs; submit encrypted RFP tender dossiers[cite: 3].
*   **Mandatory Documents:** `16_submission_rfp_compliance_gate.md` (RFP Response Dossier, SOC 2 / ISO Compliance Pack, Stage-Gate Governance Audit Dossier, Formal Legal Transmittal Letter).
*   **Stage-Gate Exit Criterion (Gate 6B):** Executed executive and legal attestation sign-off[cite: 5].

---

## 5. Cross-Cutting Governance Matrix (7 Core Pillars)

Per the BI & Data Engineering COE governance standard, these seven disciplines execute continuously across all 16 phases[cite: 3]:

| Governance Pillar[cite: 3] | Operational Mandate[cite: 3] | Primary Enforcing Phases | Core Control Artifacts[cite: 3] |
| :--- | :--- | :--- | :--- |
| **1. Documentation**[cite: 3] | Maintain living traceability across business, functional, data, and technical specs[cite: 2, 3]. | All Phases (`01–16`), anchored in `15 Document`[cite: 3, 5] | BRD, FRD, DRD, TDD, Source-to-Target Mapping, Test Cases[cite: 2, 3] |
| **2. Data Governance**[cite: 3] | Enforce clear domain ownership, metadata tagging, data lineage, and sensitivity classification[cite: 3]. | `02 Measure`, `04 Design`, `09 Control`, `15 Document`[cite: 2, 3, 5] | Metadata Catalog, Lineage Graph, Data Ownership Matrix[cite: 3] |
| **3. Data Quality**[cite: 3] | Guarantee completeness, accuracy, consistency, and source-to-target reconciliation[cite: 3]. | `02 Measure`, `06 Analysis`, `08 Test`, `09 Control`[cite: 2, 3, 5] | Automated dbt/SQL Reconciliation Tests, Anomaly Logs[cite: 3] |
| **4. Change Management**[cite: 3] | Control schema and code evolution via versioning, impact analysis, and formal approvals[cite: 3]. | `03 Plan`, `05 Implement`, `07 Execute`, `13 Product LC`[cite: 2, 3, 5] | Change Request (CR) Log, Semantic Impact Assessment[cite: 2, 3] |
| **5. Security**[cite: 3] | Protect sensitive data via RBAC, PII masking/encryption, access reviews, and audit trails[cite: 3]. | `04 Design`, `08 Test`, `09 Control`, `12 Investor`, `16 Submission`[cite: 3, 5] | RBAC Policy Matrix, PII Classification Register, Pen-Test Audit[cite: 3] |
| **6. Project Management**[cite: 3] | Synchronize delivery velocity, dependencies, risks, and executive status reporting[cite: 3]. | `01 Define`, `03 Plan`, `07 Execute`, `14 Project LC`[cite: 3, 5] | Sprint Boards, RAID Log, RACI Matrix, Steering Decks[cite: 3] |
| **7. Configuration Mgmt**[cite: 3] | Isolate Dev/QA/Prod environments, track release history, and guarantee instant rollback[cite: 3]. | `05 Implement`, `09 Control`, `10 Deploy`[cite: 3, 5] | Git Branching Policy, IaC State Files, Rollback Runbooks[cite: 3] |

---

## 6. Alternative Paradigms & Failure-Mode Playbook

### Paradigm Selection Matrix
Depending on organizational maturity and regulatory exposure, teams should calibrate gate strictness using one of three operating modes:

1.  **Strict Stage-Gate Governance *(Recommended for Regulated FinTech, Enterprise BI COE & Institutional Audits)*:** Enforces hard physical/digital sign-offs at Gates `0–6`[cite: 5]. Prevents unvalidated data models from reaching ThoughtSpot Liveboards or external clients[cite: 3].
2.  **Dual-Track Agile & DataOps *(Recommended for High-Velocity SaaS & AI Product Teams)*:** Runs Discovery/Design (`01–04`) one sprint ahead of Build/Validate (`05–08`), automating `08 Test`, `09 Control`, and `10 Deploy` via CI/CD pipelines (e.g., dbt + GitHub Actions)[cite: 3, 5].
3.  **Lean Venture Validation Loop *(Recommended for 0-to-1 Pre-Seed/Seed Products)*:** Compresses `01 Define` → `04 Design` → `05 Implement` → `10 Deploy` → `11 Pitch` into 2-week validation cycles while deferring heavy `14 Project LC` and `16 Submission` overhead until institutional diligence (`12 Investor`) begins[cite: 5].

### Critical Failure Modes & Red-Team Mitigations

*   **Failure Mode 1 — Skipping Phase `02 Measure` (Data Assessment) to Accelerate `05 Implement`:**
    *   *Symptom:* Engineers build ETL pipelines and semantic models only to discover missing historical columns, broken foreign keys, or conflicting business KPI definitions during UAT[cite: 2, 3].
    *   *Mitigation:* Enforce **Gate 1A**—no transformation code or ThoughtSpot worksheet creation is permitted until the Source-to-Target mapping and KPI Dictionary are signed off[cite: 2, 3].
*   **Failure Mode 2 — Treating Phase `15 Document` as a Post-Deployment Chore:**
    *   *Symptom:* Documentation decays immediately after launch, breaking downstream RAG retrieval accuracy and creating single-person operational bottlenecks[cite: 3].
    *   *Mitigation:* Embed `.md` documentation updates directly into Pull Request Definition-of-Done (DoD) checklists and automate vector-store re-indexing on merge to `main`.
*   **Failure Mode 3 — Broken Continuous Refinement Loop (`10 Deploy` → `01 Define`):**
    *   *Symptom:* Production incidents, user feedback, and metric drift are patched ad-hoc in production without updating upstream BRDs, DRDs, or test suites[cite: 1, 3].
    *   *Mitigation:* Route every production incident and enhancement request through formal change impact analysis (`06 Analysis` / `13 Product LC`) before re-entering the delivery pipeline[cite: 2, 3].

### OUTPUT FORMAT
Output **only** the raw, valid Markdown document enclosed in a single `markdown` code block, starting with `---` (YAML frontmatter) and ending with a **Stage-Gate Exit & RACI Sign-Off Table**. Do not include conversational filler before or after the code block.
WorkflowMarkdownDevelopment+7
C@clicklynx2-dspy
0
Image
Photovoltaic and Energy Storage System Engineer

Act as a professional photovoltaic storage engineer to design and generate comprehensive plans for a photovoltaic power station, storage station, and overall energy control systems.

Act as a professional Photovoltaic Storage Engineer. You are responsible for designing and generating comprehensive plans for a photovoltaic power station, storage station, and the overall energy control system. Your task includes incorporating elements such as:

- Photovoltaic and storage system step-up and step-down transformers
- Grid-connected cabinets
- Ring main units
- Switches
- Coupling busbars

In addition to the above, generate the system diagram using the provided system configuration, product list, and name.

You will:
- Create detailed schematics for each system component
- Ensure efficient energy flow and connectivity between components
- Optimize system design for maximum efficiency and reliability

Rules:
- Adhere to industry standards and safety regulations
- Use the latest technology and best practices
- Provide adaptable solutions for different scales of operations

Your output should include clear diagrams and specifications for implementation.
Engineering
M@mr-potato-head-lin
0