diff --git a/.aihealth-tests.toml b/.aihealth-tests.toml new file mode 100644 index 0000000..d948798 --- /dev/null +++ b/.aihealth-tests.toml @@ -0,0 +1,20 @@ +# ai-health profile "strict" for the python-tests component (see .aihealth.toml). +# pytest fixtures arrive as arguments and test classes group cases, so the argument, +# primitive and cohesion smells are off here. + +[thresholds] +large_file = 600 +primitive_obsession = 0.3 + +[score] +decay = 8 +symbol_cap = 4 +density_loc = 100000 + +[delta] +tolerance = 0.0 + +[weights] +excess_arguments = 0 +primitive_obsession = 0 +low_cohesion = 0 diff --git a/.aihealth.toml b/.aihealth.toml new file mode 100644 index 0000000..c8ac171 --- /dev/null +++ b/.aihealth.toml @@ -0,0 +1,23 @@ +# ai-health profile "strict" (owner decision 2026-11-23, Q15): CodeScene thresholds, +# decay 8, no density relief for large files. Components: python-cli and shell use +# this file, python-tests uses .aihealth-tests.toml, which must repeat [thresholds], +# [score] and [delta] unchanged (tests/unit/test_aihealth_config.py checks that) until +# ai-health supports overrides per path (epatel/ai-health#4); then both merge into one file. +# Always pass --config: `aihealth scan ` otherwise reads /.aihealth.toml. +# Ansible has no score (ansible-lint only). See docs/code-health.md. + +[thresholds] +large_file = 600 # Python; ai-health default 1000 +primitive_obsession = 0.3 # CodeScene + +[score] +decay = 8 +symbol_cap = 4 +density_loc = 100000 # large files are not relieved by their smell density + +[delta] +tolerance = 0.0 + +[scan] +# .claude/skills/ holds third-party skills pinned in skills-lock.json. +exclude = ["tests/*", "openspec/*", ".claude/skills/*"] diff --git a/.claude/skills/github-actions-hardening/SKILL.md b/.claude/skills/github-actions-hardening/SKILL.md new file mode 100644 index 0000000..61fa956 --- /dev/null +++ b/.claude/skills/github-actions-hardening/SKILL.md @@ -0,0 +1,160 @@ +--- +name: github-actions-hardening +description: Security hardening reviewer for GitHub Actions workflow files (.github/workflows/*.yml). Reasons about the Actions threat model that pattern matchers and general code linters miss — untrusted-input script injection, privileged triggers running fork code, mutable action references, and over-scoped tokens. Use this skill when asked to review, audit, harden, or secure a GitHub Actions workflow, when writing a new workflow, or for any request like "is this workflow safe?", "review my CI for security issues", "why is pull_request_target dangerous here?", "pin my actions", or "lock down GITHUB_TOKEN permissions". Covers script injection via ${{ }} interpolation, pull_request_target / workflow_run privilege escalation, SHA-pinning of third-party actions, least-privilege permissions, GITHUB_ENV/GITHUB_OUTPUT injection, secret exposure, OIDC over long-lived credentials, and self-hosted runner exposure on public repositories. +--- + +# GitHub Actions Hardening + +A focused security reviewer for GitHub Actions workflows. It reasons about the *Actions-specific* +threat model — where trust boundaries live in trigger types, token scopes, and string +interpolation — rather than the application-code vulnerabilities a general security scanner looks +for. Most workflow risks are invisible to language linters because the dangerous code is the YAML +itself and the way GitHub expands `${{ }}` expressions into a shell before your script runs. + +## When to Use This Skill + +Use this skill when the request involves: + +* Reviewing, auditing, or hardening any file under `.github/workflows/` +* Authoring a new workflow and wanting it secure by default +* A workflow that uses `pull_request_target`, `workflow_run`, or `issue_comment` triggers +* Questions about `GITHUB_TOKEN` permissions or the `permissions:` key +* Pinning actions to commit SHAs vs tags vs branches +* Handling untrusted input (issue titles, PR bodies, branch names, commit messages) in `run:` steps +* OIDC / cloud authentication from Actions, or secret handling in CI +* Self-hosted runners on public repositories +* Any request like "is this workflow safe?", "secure my CI", or "review this GitHub Action" + +## The Core Insight + +In a workflow, **`${{ }}` is expanded by the runner into the script *before* the shell +executes it.** So a step like: + +```yaml +- run: echo "Title: ${{ github.event.issue.title }}" +``` + +is not passing a variable — it is *pasting attacker-controlled text directly into your shell +command*. An issue titled `"; #` is concatenated into the script and executed. +This single mechanism is the most common real-world Actions vulnerability, and models routinely +generate it. Treat every +`${{ }}` that contains data an outside contributor can influence as a code-injection sink. + +## Execution Workflow + +Follow these steps **in order** for every workflow reviewed. + +### Step 1 — Map the Triggers and Trust Level + +Read every `on:` trigger and classify the workflow's privilege: + +* `push`, `pull_request` (from same repo) → runs with the contributor's own trust +* `pull_request` from a **fork** → runs with a **read-only** token, **no secrets** (safe by design) +* `pull_request_target`, `workflow_run`, `issue_comment`, `issues` → run in the context of the + **base repository** with a **read/write token and full access to secrets**, but can be + **triggered by outside contributors**. These are the dangerous triggers. + +Read `references/triggers-and-privilege.md` for the full trust matrix. + +### Step 2 — Hunt for Script Injection + +For every `run:` block, every `script:` in `actions/github-script`, and every input to a custom +action, list the `${{ }}` expressions and check whether any resolve to attacker-controllable data. +High-risk contexts include: + +* `github.event.issue.title`, `github.event.issue.body` +* `github.event.pull_request.title`, `github.event.pull_request.body`, `.head.ref`, `.head.label` +* `github.event.comment.body`, `github.event.review.body` +* `github.event.pages.*.page_name`, `github.event.commits.*.message`, `github.event.head_commit.*` +* `github.head_ref` and any `github.event.*` field a fork author can set + +Read `references/injection.md` for the complete sink list and the safe-pattern fixes. + +### Step 3 — Check Privileged Triggers Don't Execute Untrusted Code + +If a `pull_request_target` or `workflow_run` workflow checks out PR/fork code +(`ref: ${{ github.event.pull_request.head.sha }}`) **and then runs it** (build, test, install +scripts, `npm install` with lifecycle scripts, etc.), that is remote code execution against a +privileged token. Flag it as CRITICAL. The safe pattern is to split into two workflows: an +unprivileged `pull_request` workflow that runs the untrusted code, and a privileged +`workflow_run` workflow that only consumes its results. + +### Step 4 — Audit `permissions:` + +* If there is **no** `permissions:` block, the workflow inherits the repository default, which may + be read/write to everything. Flag it. +* Recommend a top-level `permissions: {}` (deny-all) or `contents: read`, then grant the minimum + per job (e.g. `pull-requests: write` only on the job that comments). +* Flag any `permissions: write-all` or broad `write` scopes that the steps don't actually need. + +Read `references/permissions-and-tokens.md` for the per-scope guidance and OIDC setup. + +### Step 5 — Audit Action References (Supply Chain) + +For every `uses:`: + +* **Third-party actions** (not `actions/*` or `github/*`) MUST be pinned to a full 40-character + commit SHA, not a tag or branch. Tags and branches are mutable; a compromised upstream action + can rewrite `v1` to malicious code that runs with your token and secrets. +* First-party `actions/*` are lower risk but SHA-pinning is still the hardened recommendation. +* Flag `@main`, `@master`, or any branch reference as HIGH — that is "latest" and can change under + you at any time. +* Note the human-readable version in a trailing comment: `uses: foo/bar@ # v2.1.0`. + +Read `references/supply-chain.md` for pinning, Dependabot for actions, and artifact/cache risks. + +### Step 6 — Check Secret and Output Handling + +* No secrets echoed, printed, or written to logs; no `set -x` / `bash -x` in steps that touch + secrets. +* Secrets must not be passed to steps that run untrusted code or to untrusted third-party actions. +* Untrusted multiline data written to `$GITHUB_ENV` or `$GITHUB_OUTPUT` can inject environment + variables or step outputs — use the random-delimiter heredoc form and never write raw user input. +* `actions/checkout` leaves a token on disk by default; set `persist-credentials: false` when the + job later runs untrusted code. + +### Step 7 — Produce the Report + +Output findings using the format in `references/report-format.md`: a severity summary table first, +then grouped findings with file, the exact offending YAML, the risk in plain English, and a +concrete before/after fix. Never auto-apply changes — present them for review. + +## Severity Guide + +| Severity | Meaning | Example | +| --- | --- | --- | +| 🔴 CRITICAL | Token/secret theft or RCE reachable by an outside contributor | `pull_request_target` checking out and running fork code; `${{ github.event.* }}` in a `run:` on a privileged trigger | +| 🟠 HIGH | Exploitable supply-chain or scope problem | Third-party action on a mutable tag/branch; `write-all` permissions; injection sink on `issue_comment` | +| 🟡 MEDIUM | Risk under conditions or chaining | Missing `permissions:` block; secret reachable by a non-fork PR author | +| 🔵 LOW | Hardening gap, low direct risk | First-party action not SHA-pinned; `persist-credentials` left default on a non-privileged job | +| ⚪ INFO | Observation, not a vulnerability | Version comment missing next to a pinned SHA | + +## Output Rules + +* **Always** show a findings summary table (counts by severity) first. +* **Group by issue type**, not by file. +* **Be exact** — quote the offending line and give the line location. +* **Always** pair every CRITICAL/HIGH with a concrete corrected YAML snippet. +* **Never** claim a fork `pull_request` is dangerous just because it runs untrusted code — it has + no secrets and a read-only token. Reserve CRITICAL for the privileged triggers. +* If the workflow is already hardened, say so and list what was checked. + +## Reference Files + +Load these as needed: + +* `references/triggers-and-privilege.md` — Trust matrix for every trigger, why `pull_request_target` + and `workflow_run` are privileged, and the two-workflow safe pattern. + + Search patterns: `pull_request_target`, `workflow_run`, `issue_comment`, `fork`, `secrets`, `read-only token`, `trust boundary` +* `references/injection.md` — Full list of attacker-controllable `${{ }}` contexts and the + `env:`-variable safe pattern for each sink (`run`, `github-script`, action inputs). + + Search patterns: `script injection`, `github.event`, `head_ref`, `issue title`, `env`, `intermediate variable`, `actions/github-script` +* `references/permissions-and-tokens.md` — `GITHUB_TOKEN` scopes, least-privilege `permissions:` + recipes per job type, and OIDC for cloud auth instead of long-lived secrets. + + Search patterns: `permissions`, `GITHUB_TOKEN`, `write-all`, `contents: read`, `id-token`, `OIDC`, `least privilege` +* `references/supply-chain.md` — SHA-pinning third-party actions, Dependabot for `github-actions`, + artifact and cache poisoning across `workflow_run`, and self-hosted runner exposure. + + Search patterns: `SHA pin`, `uses`, `mutable tag`, `Dependabot`, `download-artifact`, `cache`, `self-hosted runner` +* `references/report-format.md` — Output template: summary table, finding cards, and before/after + remediation blocks. + + Search patterns: `report`, `format`, `finding`, `summary`, `remediation`, `before`, `after` diff --git a/.claude/skills/github-actions-hardening/references/injection.md b/.claude/skills/github-actions-hardening/references/injection.md new file mode 100644 index 0000000..113ff1a --- /dev/null +++ b/.claude/skills/github-actions-hardening/references/injection.md @@ -0,0 +1,86 @@ +# Script Injection + +`${{ }}` is substituted into the script **as text, before the shell runs**. Any expression +that resolves to data an outside contributor controls is therefore a command-injection sink. + +## Attacker-Controllable Contexts + +These can be set by anyone who can open an issue, PR, or comment: + +| Context | Set by | +| --- | --- | +| `github.event.issue.title` / `.body` | Issue author | +| `github.event.pull_request.title` / `.body` | PR author | +| `github.event.pull_request.head.ref` / `.head.label` | PR author (branch name) | +| `github.head_ref` | PR author (branch name) | +| `github.event.comment.body` | Commenter | +| `github.event.review.body` / `.review_comment.body` | Reviewer | +| `github.event.commits.*.message` / `head_commit.message` | Commit author | +| `github.event.commits.*.author.email` / `.name` | Commit author | +| `github.event.pages.*.page_name` | Wiki editor | + +A branch named `$()` or an issue titled `"; #` becomes shell +when interpolated into a `run:` step. + +## The Vulnerable Pattern + +```yaml +# VULNERABLE +- run: | + echo "Reviewing PR: ${{ github.event.pull_request.title }}" + git checkout ${{ github.head_ref }} +``` + +## The Safe Pattern — Pass Through `env:` + +Bind the untrusted value to an environment variable, then reference the *shell* variable (quoted). +The shell variable is data, never re-parsed as workflow syntax: + +```yaml +# SAFE +- env: + PR_TITLE: ${{ github.event.pull_request.title }} + HEAD_REF: ${{ github.head_ref }} + run: | + echo "Reviewing PR: $PR_TITLE" + git checkout "$HEAD_REF" +``` + +`${{ }}` now appears only on the `env:` side, where it is assigned as a value rather than spliced +into a command. Always quote the shell variable (`"$PR_TITLE"`) to prevent word-splitting and +globbing. + +## `actions/github-script` + +The same rule applies. Do not interpolate `${{ }}` into the `script:` body — pass it through the +environment and read `process.env`: + +```yaml +# VULNERABLE +- uses: actions/github-script@ + with: + script: console.log("${{ github.event.issue.title }}") + +# SAFE +- uses: actions/github-script@ + env: + TITLE: ${{ github.event.issue.title }} + with: + script: console.log(process.env.TITLE) +``` + +## Custom Action Inputs + +Passing untrusted `${{ }}` into a composite or JS action's `with:` inputs can be safe or not +depending on whether the action itself interpolates the input into a shell. When in doubt, pass via +`env:` and have the action read the environment, or sanitize/validate first (e.g. a branch name +should match `^[A-Za-z0-9._/-]+$`). + +## Quick Audit Checklist + +1. Grep every `run:` and `script:` for `${{`. +2. For each, resolve what the expression points to. +3. If it can be set by a non-collaborator → rewrite via `env:` with a quoted shell variable. +4. `github.actor`, `github.repository`, `github.sha`, `github.ref` (for branch protection contexts) + and similar server-controlled values are not attacker-set, but a defense-in-depth `env:` rewrite + costs nothing. diff --git a/.claude/skills/github-actions-hardening/references/permissions-and-tokens.md b/.claude/skills/github-actions-hardening/references/permissions-and-tokens.md new file mode 100644 index 0000000..784ea92 --- /dev/null +++ b/.claude/skills/github-actions-hardening/references/permissions-and-tokens.md @@ -0,0 +1,76 @@ +# Permissions and Tokens + +Every workflow run gets an automatic `GITHUB_TOKEN`. Its scope is the blast radius if a step is +compromised, so scope it to the minimum. + +## The Default Is Too Broad + +If a workflow has no `permissions:` block, it inherits the repository/organization default. On +older or permissive repos that default is **read/write to most scopes**. A single injected command +or malicious dependency then runs with the ability to push code, publish releases, or approve PRs. + +## Least-Privilege Recipe + +Set a restrictive default at the top level, then elevate per job only where needed. + +```yaml +# Deny by default +permissions: {} + +jobs: + build: + permissions: + contents: read # checkout only + runs-on: ubuntu-latest + steps: [...] + + comment: + permissions: + contents: read + pull-requests: write # this job posts a comment; nothing else + runs-on: ubuntu-latest + steps: [...] +``` + +Common scopes: `contents`, `pull-requests`, `issues`, `actions`, `packages`, `id-token`, +`deployments`, `checks`, `statuses`. Each is `read`, `write`, or `none`. + +## Findings to Flag + +* No `permissions:` block anywhere → MEDIUM (inherits possibly-broad default). +* `permissions: write-all` → HIGH. +* A `write` scope the job's steps never use → HIGH (drop it). +* Top-level `write` that should live on one job → MEDIUM (move it down). + +## OIDC Instead of Long-Lived Cloud Secrets + +Storing static cloud keys (`AWS_ACCESS_KEY_ID`, etc.) as repo secrets means a leak is permanent +until manually rotated. Prefer OpenID Connect: the workflow requests a short-lived token the cloud +provider trusts, scoped to that repo/branch, expiring in minutes. + +```yaml +permissions: + id-token: write # required to request the OIDC token + contents: read +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - uses: aws-actions/configure-aws-credentials@ + with: + role-to-assume: arn:aws:iam::123456789012:role/my-ci-role + aws-region: us-east-1 + # no AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY secrets needed +``` + +The same pattern exists for Azure (`azure/login`), GCP (`google-github-actions/auth`), HashiCorp +Vault, and others. On the cloud side, scope the trust policy to the specific repo and ideally a +specific branch/environment so a fork or another repo cannot assume the role. + +## Secret Hygiene + +* Reference secrets only in the jobs that need them. +* Never `echo` a secret or enable shell tracing (`set -x`) in a step that handles one. +* Don't pass secrets into third-party actions you haven't pinned and reviewed. +* Remember fork `pull_request` runs get no secrets — don't try to "fix" that by switching to + `pull_request_target` (see `triggers-and-privilege.md`). diff --git a/.claude/skills/github-actions-hardening/references/report-format.md b/.claude/skills/github-actions-hardening/references/report-format.md new file mode 100644 index 0000000..20f9f06 --- /dev/null +++ b/.claude/skills/github-actions-hardening/references/report-format.md @@ -0,0 +1,65 @@ +# Report Format + +Use this structure for every workflow hardening review. + +## 1. Summary Table (always first) + +``` +GitHub Actions Hardening — + +| Severity | Count | +| ---------- | ----- | +| 🔴 CRITICAL | 1 | +| 🟠 HIGH | 2 | +| 🟡 MEDIUM | 1 | +| 🔵 LOW | 1 | +| ⚪ INFO | 0 | +``` + +If nothing was found: `No issues found. Checked: triggers, injection sinks, permissions, action +pinning, secret handling.` + +## 2. Findings (grouped by issue type, not by file) + +For each finding use a card: + +``` +### 🔴 CRITICAL — Script injection via PR title on a privileged trigger + +File: .github/workflows/triage.yml (line 14) +Trigger: pull_request_target + +Offending code: + - run: echo "New PR: ${{ github.event.pull_request.title }}" + +Risk: pull_request_target runs with a read/write token and repository secrets, and any +contributor can open a PR with a title like "; # which is executed as shell. +This allows secret exfiltration and pushes with the workflow token. + +Fix: + - env: + PR_TITLE: ${{ github.event.pull_request.title }} + run: echo "New PR: $PR_TITLE" + +Confidence: High +``` + +## 3. Remediation Blocks + +Every CRITICAL and HIGH finding includes a concrete before/after. Preserve the author's +indentation, step names, and surrounding structure — change only what fixes the issue, and add a +one-line comment explaining the change where it isn't obvious. + +## 4. Closing Note + +End with the explicit line: + +> Review each change before committing. Nothing has been modified. + +## Style Rules + +* Quote the exact offending line and give its location. +* Explain risk in plain English — what an attacker actually does, not just the rule name. +* Per-finding confidence: High / Medium / Low. +* Don't inflate severity: a fork `pull_request` (read-only token, no secrets) running untrusted + code is not CRITICAL on its own. diff --git a/.claude/skills/github-actions-hardening/references/supply-chain.md b/.claude/skills/github-actions-hardening/references/supply-chain.md new file mode 100644 index 0000000..6cb0547 --- /dev/null +++ b/.claude/skills/github-actions-hardening/references/supply-chain.md @@ -0,0 +1,71 @@ +# Supply Chain + +A workflow runs other people's code every time it `uses:` an action. Those actions execute with +your token and (on privileged triggers) your secrets, so their integrity is your integrity. + +## Pin Third-Party Actions to a Commit SHA + +Tags (`@v4`) and branches (`@main`) are **mutable** — the upstream owner (or anyone who compromises +them) can repoint them to new code without you changing a line. A full 40-character commit SHA is +immutable. + +```yaml +# Mutable — the tag can be moved to malicious code +- uses: some-org/some-action@v3 + +# Pinned — this exact tree, forever +- uses: some-org/some-action@3f1e0a9c8b7d6e5f4a3b2c1d0e9f8a7b6c5d4e3f # v3.2.1 +``` + +Rules: + +* Third-party actions (anything not `actions/*` or `github/*`) → **MUST** be SHA-pinned. Flag tags + and branches as HIGH. +* `@main` / `@master` → HIGH regardless of publisher; that is unversioned "latest". +* First-party `actions/*` → SHA-pinning is the hardened recommendation (LOW if only tag-pinned). +* Keep a trailing `# vX.Y.Z` comment so humans and Dependabot can read the intended version. + +This is not theoretical: real incidents have seen popular actions' tags repointed to code that +exfiltrated secrets from every workflow that referenced the mutable tag. + +## Let Dependabot Update the Pins + +SHA pins go stale. Enable Dependabot for the `github-actions` ecosystem so updates arrive as +reviewable PRs (it understands the `# vX.Y.Z` comment and bumps the SHA): + +```yaml +# .github/dependabot.yml +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly +``` + +## Artifact and Cache Poisoning + +* An artifact uploaded by an untrusted `pull_request` build is **untrusted data**. A privileged + `workflow_run` may download it, but must treat it as data only — never execute it, and validate + paths when extracting (a crafted artifact can contain `../` path-traversal entries). +* Caches are keyed and can be populated by less-privileged runs; do not trust cached build outputs + to be untampered in a privileged context. + +## Self-Hosted Runners on Public Repos + +Default (GitHub-hosted) runners are ephemeral — a fresh VM per job, destroyed after. **Self-hosted +runners persist**, so untrusted fork PR code running on one can: + +* Leave behind tools/backdoors for the next job, +* Read other repositories' checkouts or credentials on the same machine, +* Pivot into your network. + +Never use self-hosted runners for workflows that public forks can trigger. If you must, use +ephemeral, isolated, single-use runners and never expose secrets to fork-triggered jobs. + +## `checkout` Credential Persistence + +`actions/checkout` writes the token into `.git/config` by default so later `git` steps can push. +If the job subsequently runs untrusted code, that code can read the token. Set +`persist-credentials: false` when you don't need to push, especially before running build/test of +untrusted code. diff --git a/.claude/skills/github-actions-hardening/references/triggers-and-privilege.md b/.claude/skills/github-actions-hardening/references/triggers-and-privilege.md new file mode 100644 index 0000000..3081d91 --- /dev/null +++ b/.claude/skills/github-actions-hardening/references/triggers-and-privilege.md @@ -0,0 +1,89 @@ +# Triggers and Privilege + +The single most important question for workflow security is: **can an outside contributor trigger +this workflow, and if so, what token and secrets does it get?** GitHub answers this differently per +trigger. + +## Trust Matrix + +| Trigger | Who can fire it | `GITHUB_TOKEN` | Secrets available | Risk | +| --- | --- | --- | --- | --- | +| `push` | Repo collaborators | read/write | yes | Low — trusted authors | +| `pull_request` (same-repo branch) | Collaborators | read/write | yes | Low | +| `pull_request` (from a fork) | **Anyone** | **read-only** | **no** | Low by design — even malicious code can't steal anything | +| `pull_request_target` | **Anyone with a fork** | **read/write** | **yes** | **High** — runs in base-repo context | +| `workflow_run` | Fires after another workflow | **read/write** | **yes** | **High** | +| `issue_comment`, `issues` | **Anyone** | **read/write** | **yes** | **High** | + +The trap: `pull_request` from a fork is *safe* because GitHub deliberately strips the token down +and withholds secrets. Maintainers who find that "the secrets don't work on fork PRs" often switch +to `pull_request_target` to get them back — and in doing so hand a write token and every secret to +arbitrary contributors. + +## Why `pull_request_target` Is Dangerous + +`pull_request_target` checks out the **base** repository's workflow definition (so a fork can't +change what runs), but it runs with full privileges. The danger is when the workflow then +explicitly checks out the **fork's** code and executes it: + +```yaml +# DANGEROUS — RCE with a write token + secrets +on: pull_request_target +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@ + with: + ref: ${{ github.event.pull_request.head.sha }} # fork's code + - run: npm install && npm test # runs the fork's code + scripts +``` + +`npm install` alone runs arbitrary lifecycle scripts from the PR. With `pull_request_target` those +scripts can read `secrets.*` and push commits with the write token. + +## The Safe Two-Workflow Pattern + +Split responsibilities. An **unprivileged** workflow runs the untrusted code; a **privileged** +workflow consumes only the trusted *output*. + +```yaml +# 1) Unprivileged: runs untrusted code, no secrets, read-only token +name: PR Build +on: pull_request +permissions: + contents: read +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@ + - run: npm ci && npm run build + - uses: actions/upload-artifact@ + with: { name: pr, path: dist/ } +``` + +```yaml +# 2) Privileged: triggered by the first, never runs fork code +name: PR Comment +on: + workflow_run: + workflows: ["PR Build"] + types: [completed] +permissions: + pull-requests: write +jobs: + comment: + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@ # data only, not executed + # post results, using the trusted token — but never execute the artifact +``` + +## Rules + +* Treat `pull_request_target`, `workflow_run`, `issue_comment`, and `issues` as privileged. +* In a privileged workflow, **never** check out and execute PR/fork code. +* If you only need to label, comment, or triage based on metadata, that is fine — just don't run + the contributor's code. +* Prefer `pull_request` (with its safe read-only/no-secrets defaults) whenever possible. diff --git a/.claude/skills/python-testing-patterns/SKILL.md b/.claude/skills/python-testing-patterns/SKILL.md new file mode 100644 index 0000000..4fe8a42 --- /dev/null +++ b/.claude/skills/python-testing-patterns/SKILL.md @@ -0,0 +1,278 @@ +--- +name: python-testing-patterns +description: Implement comprehensive testing strategies with pytest, fixtures, mocking, and test-driven development. Use when writing Python tests, setting up test suites, or implementing testing best practices. +--- + +# Python Testing Patterns + +Comprehensive guide to implementing robust testing strategies in Python using pytest, fixtures, mocking, parameterization, and test-driven development practices. + +## When to Use This Skill + +- Writing unit tests for Python code +- Setting up test suites and test infrastructure +- Implementing test-driven development (TDD) +- Creating integration tests for APIs and services +- Mocking external dependencies and services +- Testing async code and concurrent operations +- Setting up continuous testing in CI/CD +- Implementing property-based testing +- Testing database operations +- Debugging failing tests + +## Core Concepts + +### 1. Test Types + +- **Unit Tests**: Test individual functions/classes in isolation +- **Integration Tests**: Test interaction between components +- **Functional Tests**: Test complete features end-to-end +- **Performance Tests**: Measure speed and resource usage + +### 2. Test Structure (AAA Pattern) + +- **Arrange**: Set up test data and preconditions +- **Act**: Execute the code under test +- **Assert**: Verify the results + +### 3. Test Coverage + +- Measure what code is exercised by tests +- Identify untested code paths +- Aim for meaningful coverage, not just high percentages + +### 4. Test Isolation + +- Tests should be independent +- No shared state between tests +- Each test should clean up after itself + +## Quick Start + +```python +# test_example.py +def add(a, b): + return a + b + +def test_add(): + """Basic test example.""" + result = add(2, 3) + assert result == 5 + +def test_add_negative(): + """Test with negative numbers.""" + assert add(-1, 1) == 0 + +# Run with: pytest test_example.py +``` + +## Detailed patterns and worked examples + +Detailed pattern documentation lives in `references/details.md`. Read that file when the navigation tier above is insufficient. + +## Testing Best Practices + +### Test Organization + +```python +# tests/ +# __init__.py +# conftest.py # Shared fixtures +# test_unit/ # Unit tests +# test_models.py +# test_utils.py +# test_integration/ # Integration tests +# test_api.py +# test_database.py +# test_e2e/ # End-to-end tests +# test_workflows.py +``` + +### Test Naming Convention + +A common pattern: `test___`. Adapt to your team's preferences. + +```python +# Pattern: test___ +def test_create_user_with_valid_data_returns_user(): + ... + +def test_create_user_with_duplicate_email_raises_conflict(): + ... + +def test_get_user_with_unknown_id_returns_none(): + ... + +# Good test names - clear and descriptive +def test_user_creation_with_valid_data(): + """Clear name describes what is being tested.""" + pass + +def test_login_fails_with_invalid_password(): + """Name describes expected behavior.""" + pass + +def test_api_returns_404_for_missing_resource(): + """Specific about inputs and expected outcomes.""" + pass + +# Bad test names - avoid these +def test_1(): # Not descriptive + pass + +def test_user(): # Too vague + pass + +def test_function(): # Doesn't explain what's tested + pass +``` + +### Testing Retry Behavior + +Verify that retry logic works correctly using mock side effects. + +```python +from unittest.mock import Mock + +def test_retries_on_transient_error(): + """Test that service retries on transient failures.""" + client = Mock() + # Fail twice, then succeed + client.request.side_effect = [ + ConnectionError("Failed"), + ConnectionError("Failed"), + {"status": "ok"}, + ] + + service = ServiceWithRetry(client, max_retries=3) + result = service.fetch() + + assert result == {"status": "ok"} + assert client.request.call_count == 3 + +def test_gives_up_after_max_retries(): + """Test that service stops retrying after max attempts.""" + client = Mock() + client.request.side_effect = ConnectionError("Failed") + + service = ServiceWithRetry(client, max_retries=3) + + with pytest.raises(ConnectionError): + service.fetch() + + assert client.request.call_count == 3 + +def test_does_not_retry_on_permanent_error(): + """Test that permanent errors are not retried.""" + client = Mock() + client.request.side_effect = ValueError("Invalid input") + + service = ServiceWithRetry(client, max_retries=3) + + with pytest.raises(ValueError): + service.fetch() + + # Only called once - no retry for ValueError + assert client.request.call_count == 1 +``` + +### Mocking Time with Freezegun + +Use freezegun to control time in tests for predictable time-dependent behavior. + +```python +from freezegun import freeze_time +from datetime import datetime, timedelta + +@freeze_time("2026-01-15 10:00:00") +def test_token_expiry(): + """Test token expires at correct time.""" + token = create_token(expires_in_seconds=3600) + assert token.expires_at == datetime(2026, 1, 15, 11, 0, 0) + +@freeze_time("2026-01-15 10:00:00") +def test_is_expired_returns_false_before_expiry(): + """Test token is not expired when within validity period.""" + token = create_token(expires_in_seconds=3600) + assert not token.is_expired() + +@freeze_time("2026-01-15 12:00:00") +def test_is_expired_returns_true_after_expiry(): + """Test token is expired after validity period.""" + token = Token(expires_at=datetime(2026, 1, 15, 11, 30, 0)) + assert token.is_expired() + +def test_with_time_travel(): + """Test behavior across time using freeze_time context.""" + with freeze_time("2026-01-01") as frozen_time: + item = create_item() + assert item.created_at == datetime(2026, 1, 1) + + # Move forward in time + frozen_time.move_to("2026-01-15") + assert item.age_days == 14 +``` + +### Test Markers + +```python +# test_markers.py +import pytest + +@pytest.mark.slow +def test_slow_operation(): + """Mark slow tests.""" + import time + time.sleep(2) + + +@pytest.mark.integration +def test_database_integration(): + """Mark integration tests.""" + pass + + +@pytest.mark.skip(reason="Feature not implemented yet") +def test_future_feature(): + """Skip tests temporarily.""" + pass + + +@pytest.mark.skipif(os.name == "nt", reason="Unix only test") +def test_unix_specific(): + """Conditional skip.""" + pass + + +@pytest.mark.xfail(reason="Known bug #123") +def test_known_bug(): + """Mark expected failures.""" + assert False + + +# Run with: +# pytest -m slow # Run only slow tests +# pytest -m "not slow" # Skip slow tests +# pytest -m integration # Run integration tests +``` + +### Coverage Reporting + +```bash +# Install coverage +pip install pytest-cov + +# Run tests with coverage +pytest --cov=myapp tests/ + +# Generate HTML report +pytest --cov=myapp --cov-report=html tests/ + +# Fail if coverage below threshold +pytest --cov=myapp --cov-fail-under=80 tests/ + +# Show missing lines +pytest --cov=myapp --cov-report=term-missing tests/ +``` + +For advanced patterns (async testing, monkeypatching, property-based testing, database testing, CI/CD integration, and configuration), see [references/advanced-patterns.md](references/advanced-patterns.md) diff --git a/.claude/skills/python-testing-patterns/references/advanced-patterns.md b/.claude/skills/python-testing-patterns/references/advanced-patterns.md new file mode 100644 index 0000000..da186a9 --- /dev/null +++ b/.claude/skills/python-testing-patterns/references/advanced-patterns.md @@ -0,0 +1,411 @@ +# Python Testing Patterns — Advanced Reference + +Advanced testing patterns including async code, monkeypatching, temporary files, conftest setup, property-based testing, database testing, CI/CD integration, and configuration. + +## Pattern 6: Testing Async Code + +```python +# test_async.py +import pytest +import asyncio + +async def fetch_data(url: str) -> dict: + """Fetch data asynchronously.""" + await asyncio.sleep(0.1) + return {"url": url, "data": "result"} + + +@pytest.mark.asyncio +async def test_fetch_data(): + """Test async function.""" + result = await fetch_data("https://api.example.com") + assert result["url"] == "https://api.example.com" + assert "data" in result + + +@pytest.mark.asyncio +async def test_concurrent_fetches(): + """Test concurrent async operations.""" + urls = ["url1", "url2", "url3"] + tasks = [fetch_data(url) for url in urls] + results = await asyncio.gather(*tasks) + + assert len(results) == 3 + assert all("data" in r for r in results) + + +@pytest.fixture +async def async_client(): + """Async fixture.""" + client = {"connected": True} + yield client + client["connected"] = False + + +@pytest.mark.asyncio +async def test_with_async_fixture(async_client): + """Test using async fixture.""" + assert async_client["connected"] is True +``` + +## Pattern 7: Monkeypatch for Testing + +```python +# test_environment.py +import os +import pytest + +def get_database_url() -> str: + """Get database URL from environment.""" + return os.environ.get("DATABASE_URL", "sqlite:///:memory:") + + +def test_database_url_default(): + """Test default database URL.""" + # Will use actual environment variable if set + url = get_database_url() + assert url + + +def test_database_url_custom(monkeypatch): + """Test custom database URL with monkeypatch.""" + monkeypatch.setenv("DATABASE_URL", "postgresql://localhost/test") + assert get_database_url() == "postgresql://localhost/test" + + +def test_database_url_not_set(monkeypatch): + """Test when env var is not set.""" + monkeypatch.delenv("DATABASE_URL", raising=False) + assert get_database_url() == "sqlite:///:memory:" + + +class Config: + """Configuration class.""" + + def __init__(self): + self.api_key = "production-key" + + def get_api_key(self): + return self.api_key + + +def test_monkeypatch_attribute(monkeypatch): + """Test monkeypatching object attributes.""" + config = Config() + monkeypatch.setattr(config, "api_key", "test-key") + assert config.get_api_key() == "test-key" +``` + +## Pattern 8: Temporary Files and Directories + +```python +# test_file_operations.py +import pytest +from pathlib import Path + +def save_data(filepath: Path, data: str): + """Save data to file.""" + filepath.write_text(data) + + +def load_data(filepath: Path) -> str: + """Load data from file.""" + return filepath.read_text() + + +def test_file_operations(tmp_path): + """Test file operations with temporary directory.""" + # tmp_path is a pathlib.Path object + test_file = tmp_path / "test_data.txt" + + # Save data + save_data(test_file, "Hello, World!") + + # Verify file exists + assert test_file.exists() + + # Load and verify data + data = load_data(test_file) + assert data == "Hello, World!" + + +def test_multiple_files(tmp_path): + """Test with multiple temporary files.""" + files = { + "file1.txt": "Content 1", + "file2.txt": "Content 2", + "file3.txt": "Content 3" + } + + for filename, content in files.items(): + filepath = tmp_path / filename + save_data(filepath, content) + + # Verify all files created + assert len(list(tmp_path.iterdir())) == 3 + + # Verify contents + for filename, expected_content in files.items(): + filepath = tmp_path / filename + assert load_data(filepath) == expected_content +``` + +## Pattern 9: Custom Fixtures and Conftest + +```python +# conftest.py +"""Shared fixtures for all tests.""" +import pytest + +@pytest.fixture(scope="session") +def database_url(): + """Provide database URL for all tests.""" + return "postgresql://localhost/test_db" + + +@pytest.fixture(autouse=True) +def reset_database(database_url): + """Auto-use fixture that runs before each test.""" + # Setup: Clear database + print(f"Clearing database: {database_url}") + yield + # Teardown: Clean up + print("Test completed") + + +@pytest.fixture +def sample_user(): + """Provide sample user data.""" + return { + "id": 1, + "name": "Test User", + "email": "test@example.com" + } + + +@pytest.fixture +def sample_users(): + """Provide list of sample users.""" + return [ + {"id": 1, "name": "User 1"}, + {"id": 2, "name": "User 2"}, + {"id": 3, "name": "User 3"}, + ] + + +# Parametrized fixture +@pytest.fixture(params=["sqlite", "postgresql", "mysql"]) +def db_backend(request): + """Fixture that runs tests with different database backends.""" + return request.param + + +def test_with_db_backend(db_backend): + """This test will run 3 times with different backends.""" + print(f"Testing with {db_backend}") + assert db_backend in ["sqlite", "postgresql", "mysql"] +``` + +## Pattern 10: Property-Based Testing + +```python +# test_properties.py +from hypothesis import given, strategies as st +import pytest + +def reverse_string(s: str) -> str: + """Reverse a string.""" + return s[::-1] + + +@given(st.text()) +def test_reverse_twice_is_original(s): + """Property: reversing twice returns original.""" + assert reverse_string(reverse_string(s)) == s + + +@given(st.text()) +def test_reverse_length(s): + """Property: reversed string has same length.""" + assert len(reverse_string(s)) == len(s) + + +@given(st.integers(), st.integers()) +def test_addition_commutative(a, b): + """Property: addition is commutative.""" + assert a + b == b + a + + +@given(st.lists(st.integers())) +def test_sorted_list_properties(lst): + """Property: sorted list is ordered.""" + sorted_lst = sorted(lst) + + # Same length + assert len(sorted_lst) == len(lst) + + # All elements present + assert set(sorted_lst) == set(lst) + + # Is ordered + for i in range(len(sorted_lst) - 1): + assert sorted_lst[i] <= sorted_lst[i + 1] +``` + +## Testing Database Code + +```python +# test_database_models.py +import pytest +from sqlalchemy import create_engine, Column, Integer, String +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker, Session + +Base = declarative_base() + + +class User(Base): + """User model.""" + __tablename__ = "users" + + id = Column(Integer, primary_key=True) + name = Column(String(50)) + email = Column(String(100), unique=True) + + +@pytest.fixture(scope="function") +def db_session() -> Session: + """Create in-memory database for testing.""" + engine = create_engine("sqlite:///:memory:") + Base.metadata.create_all(engine) + + SessionLocal = sessionmaker(bind=engine) + session = SessionLocal() + + yield session + + session.close() + + +def test_create_user(db_session): + """Test creating a user.""" + user = User(name="Test User", email="test@example.com") + db_session.add(user) + db_session.commit() + + assert user.id is not None + assert user.name == "Test User" + + +def test_query_user(db_session): + """Test querying users.""" + user1 = User(name="User 1", email="user1@example.com") + user2 = User(name="User 2", email="user2@example.com") + + db_session.add_all([user1, user2]) + db_session.commit() + + users = db_session.query(User).all() + assert len(users) == 2 + + +def test_unique_email_constraint(db_session): + """Test unique email constraint.""" + from sqlalchemy.exc import IntegrityError + + user1 = User(name="User 1", email="same@example.com") + user2 = User(name="User 2", email="same@example.com") + + db_session.add(user1) + db_session.commit() + + db_session.add(user2) + + with pytest.raises(IntegrityError): + db_session.commit() +``` + +## CI/CD Integration + +```yaml +# .github/workflows/test.yml +name: Tests + +on: [push, pull_request] + +jobs: + test: + runs-on: ubuntu-latest + + strategy: + matrix: + python-version: ["3.9", "3.10", "3.11", "3.12"] + + steps: + - uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + + - name: Install dependencies + run: | + pip install -e ".[dev]" + pip install pytest pytest-cov + + - name: Run tests + run: | + pytest --cov=myapp --cov-report=xml + + - name: Upload coverage + uses: codecov/codecov-action@v3 + with: + file: ./coverage.xml +``` + +## Configuration Files + +```ini +# pytest.ini +[pytest] +testpaths = tests +python_files = test_*.py +python_classes = Test* +python_functions = test_* +addopts = + -v + --strict-markers + --tb=short + --cov=myapp + --cov-report=term-missing +markers = + slow: marks tests as slow + integration: marks integration tests + unit: marks unit tests + e2e: marks end-to-end tests +``` + +```toml +# pyproject.toml +[tool.pytest.ini_options] +testpaths = ["tests"] +python_files = ["test_*.py"] +addopts = [ + "-v", + "--cov=myapp", + "--cov-report=term-missing", +] + +[tool.coverage.run] +source = ["myapp"] +omit = ["*/tests/*", "*/migrations/*"] + +[tool.coverage.report] +exclude_lines = [ + "pragma: no cover", + "def __repr__", + "raise AssertionError", + "raise NotImplementedError", +] +``` diff --git a/.claude/skills/python-testing-patterns/references/details.md b/.claude/skills/python-testing-patterns/references/details.md new file mode 100644 index 0000000..bf296f1 --- /dev/null +++ b/.claude/skills/python-testing-patterns/references/details.md @@ -0,0 +1,350 @@ +# python-testing-patterns — detailed patterns and worked examples + +## Fundamental Patterns + +### Pattern 1: Basic pytest Tests + +```python +# test_calculator.py +import pytest + +class Calculator: + """Simple calculator for testing.""" + + def add(self, a: float, b: float) -> float: + return a + b + + def subtract(self, a: float, b: float) -> float: + return a - b + + def multiply(self, a: float, b: float) -> float: + return a * b + + def divide(self, a: float, b: float) -> float: + if b == 0: + raise ValueError("Cannot divide by zero") + return a / b + + +def test_addition(): + """Test addition.""" + calc = Calculator() + assert calc.add(2, 3) == 5 + assert calc.add(-1, 1) == 0 + assert calc.add(0, 0) == 0 + + +def test_subtraction(): + """Test subtraction.""" + calc = Calculator() + assert calc.subtract(5, 3) == 2 + assert calc.subtract(0, 5) == -5 + + +def test_multiplication(): + """Test multiplication.""" + calc = Calculator() + assert calc.multiply(3, 4) == 12 + assert calc.multiply(0, 5) == 0 + + +def test_division(): + """Test division.""" + calc = Calculator() + assert calc.divide(6, 3) == 2 + assert calc.divide(5, 2) == 2.5 + + +def test_division_by_zero(): + """Test division by zero raises error.""" + calc = Calculator() + with pytest.raises(ValueError, match="Cannot divide by zero"): + calc.divide(5, 0) +``` + +### Pattern 2: Fixtures for Setup and Teardown + +```python +# test_database.py +import pytest +from typing import Generator + +class Database: + """Simple database class.""" + + def __init__(self, connection_string: str): + self.connection_string = connection_string + self.connected = False + + def connect(self): + """Connect to database.""" + self.connected = True + + def disconnect(self): + """Disconnect from database.""" + self.connected = False + + def query(self, sql: str) -> list: + """Execute query.""" + if not self.connected: + raise RuntimeError("Not connected") + return [{"id": 1, "name": "Test"}] + + +@pytest.fixture +def db() -> Generator[Database, None, None]: + """Fixture that provides connected database.""" + # Setup + database = Database("sqlite:///:memory:") + database.connect() + + # Provide to test + yield database + + # Teardown + database.disconnect() + + +def test_database_query(db): + """Test database query with fixture.""" + results = db.query("SELECT * FROM users") + assert len(results) == 1 + assert results[0]["name"] == "Test" + + +@pytest.fixture(scope="session") +def app_config(): + """Session-scoped fixture - created once per test session.""" + return { + "database_url": "postgresql://localhost/test", + "api_key": "test-key", + "debug": True + } + + +@pytest.fixture(scope="module") +def api_client(app_config): + """Module-scoped fixture - created once per test module.""" + # Setup expensive resource + client = {"config": app_config, "session": "active"} + yield client + # Cleanup + client["session"] = "closed" + + +def test_api_client(api_client): + """Test using api client fixture.""" + assert api_client["session"] == "active" + assert api_client["config"]["debug"] is True +``` + +### Pattern 3: Parameterized Tests + +```python +# test_validation.py +import pytest + +def is_valid_email(email: str) -> bool: + """Check if email is valid.""" + local, sep, domain = email.partition("@") + return bool(local) and bool(sep) and "." in domain and "@" not in domain + + +@pytest.mark.parametrize("email,expected", [ + ("user@example.com", True), + ("test.user@domain.co.uk", True), + ("invalid.email", False), + ("@example.com", False), + ("user@domain", False), + ("", False), +]) +def test_email_validation(email, expected): + """Test email validation with various inputs.""" + assert is_valid_email(email) == expected + + +@pytest.mark.parametrize("a,b,expected", [ + (2, 3, 5), + (0, 0, 0), + (-1, 1, 0), + (100, 200, 300), + (-5, -5, -10), +]) +def test_addition_parameterized(a, b, expected): + """Test addition with multiple parameter sets.""" + from test_calculator import Calculator + calc = Calculator() + assert calc.add(a, b) == expected + + +# Using pytest.param for special cases +@pytest.mark.parametrize("value,expected", [ + pytest.param(1, True, id="positive"), + pytest.param(0, False, id="zero"), + pytest.param(-1, False, id="negative"), +]) +def test_is_positive(value, expected): + """Test with custom test IDs.""" + assert (value > 0) == expected +``` + +### Pattern 4: Mocking with unittest.mock + +```python +# test_api_client.py +import pytest +from unittest.mock import Mock, patch, MagicMock +import requests + +class APIClient: + """Simple API client.""" + + def __init__(self, base_url: str): + self.base_url = base_url + + def get_user(self, user_id: int) -> dict: + """Fetch user from API.""" + response = requests.get(f"{self.base_url}/users/{user_id}") + response.raise_for_status() + return response.json() + + def create_user(self, data: dict) -> dict: + """Create new user.""" + response = requests.post(f"{self.base_url}/users", json=data) + response.raise_for_status() + return response.json() + + +def test_get_user_success(): + """Test successful API call with mock.""" + client = APIClient("https://api.example.com") + + mock_response = Mock() + mock_response.json.return_value = {"id": 1, "name": "John Doe"} + mock_response.raise_for_status.return_value = None + + with patch("requests.get", return_value=mock_response) as mock_get: + user = client.get_user(1) + + assert user["id"] == 1 + assert user["name"] == "John Doe" + mock_get.assert_called_once_with("https://api.example.com/users/1") + + +def test_get_user_not_found(): + """Test API call with 404 error.""" + client = APIClient("https://api.example.com") + + mock_response = Mock() + mock_response.raise_for_status.side_effect = requests.HTTPError("404 Not Found") + + with patch("requests.get", return_value=mock_response): + with pytest.raises(requests.HTTPError): + client.get_user(999) + + +@patch("requests.post") +def test_create_user(mock_post): + """Test user creation with decorator syntax.""" + client = APIClient("https://api.example.com") + + mock_post.return_value.json.return_value = {"id": 2, "name": "Jane Doe"} + mock_post.return_value.raise_for_status.return_value = None + + user_data = {"name": "Jane Doe", "email": "jane@example.com"} + result = client.create_user(user_data) + + assert result["id"] == 2 + mock_post.assert_called_once() + call_args = mock_post.call_args + assert call_args.kwargs["json"] == user_data +``` + +### Pattern 5: Testing Exceptions + +```python +# test_exceptions.py +import pytest + +def divide(a: float, b: float) -> float: + """Divide a by b.""" + if b == 0: + raise ZeroDivisionError("Division by zero") + if not isinstance(a, (int, float)) or not isinstance(b, (int, float)): + raise TypeError("Arguments must be numbers") + return a / b + + +def test_zero_division(): + """Test exception is raised for division by zero.""" + with pytest.raises(ZeroDivisionError): + divide(10, 0) + + +def test_zero_division_with_message(): + """Test exception message.""" + with pytest.raises(ZeroDivisionError, match="Division by zero"): + divide(5, 0) + + +def test_type_error(): + """Test type error exception.""" + with pytest.raises(TypeError, match="must be numbers"): + divide("10", 5) + + +def test_exception_info(): + """Test accessing exception info.""" + with pytest.raises(ValueError) as exc_info: + int("not a number") + + assert "invalid literal" in str(exc_info.value) +``` + +For advanced patterns including async testing, monkeypatching, temporary files, conftest setup, property-based testing, database testing, CI/CD integration, and configuration files, see [references/advanced-patterns.md](./advanced-patterns.md) + +## Test Design Principles + +### One Behavior Per Test + +Each test should verify exactly one behavior. This makes failures easy to diagnose and tests easy to maintain. + +```python +# BAD - testing multiple behaviors +def test_user_service(): + user = service.create_user(data) + assert user.id is not None + assert user.email == data["email"] + updated = service.update_user(user.id, {"name": "New"}) + assert updated.name == "New" + +# GOOD - focused tests +def test_create_user_assigns_id(): + user = service.create_user(data) + assert user.id is not None + +def test_create_user_stores_email(): + user = service.create_user(data) + assert user.email == data["email"] + +def test_update_user_changes_name(): + user = service.create_user(data) + updated = service.update_user(user.id, {"name": "New"}) + assert updated.name == "New" +``` + +### Test Error Paths + +Always test failure cases, not just happy paths. + +```python +def test_get_user_raises_not_found(): + with pytest.raises(UserNotFoundError) as exc_info: + service.get_user("nonexistent-id") + + assert "nonexistent-id" in str(exc_info.value) + +def test_create_user_rejects_invalid_email(): + with pytest.raises(ValueError, match="Invalid email format"): + service.create_user({"email": "not-an-email"}) +``` diff --git a/.claude/skills/receiving-code-review/SKILL.md b/.claude/skills/receiving-code-review/SKILL.md new file mode 100644 index 0000000..950da7b --- /dev/null +++ b/.claude/skills/receiving-code-review/SKILL.md @@ -0,0 +1,205 @@ +--- +name: receiving-code-review +description: Use when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation +--- + +# Code Review Reception + +## Overview + +Code review requires technical evaluation, not emotional performance. + +**Core principle:** Verify before implementing. Ask before assuming. Technical correctness over social comfort. + +## The Response Pattern + +``` +WHEN receiving code review feedback: + +1. READ: Complete feedback without reacting +2. UNDERSTAND: Restate requirement in own words (or ask) +3. VERIFY: Check against codebase reality +4. EVALUATE: Technically sound for THIS codebase? +5. RESPOND: Technical acknowledgment or reasoned pushback +6. IMPLEMENT: One item at a time, test each +``` + +## Forbidden Responses + +**NEVER:** +- "You're absolutely right!" (explicit instruction-file violation) +- "Great point!" / "Excellent feedback!" (performative) +- "Let me implement that now" (before verification) + +**INSTEAD:** +- Restate the technical requirement +- Ask clarifying questions +- Push back with technical reasoning if wrong +- Just start working (actions > words) + +## Handling Unclear Feedback + +``` +IF any item is unclear: + STOP - do not implement anything yet + ASK for clarification on unclear items + +WHY: Items may be related. Partial understanding = wrong implementation. +``` + +**Example:** +``` +your human partner: "Fix 1-6" +You understand 1,2,3,6. Unclear on 4,5. + +❌ WRONG: Implement 1,2,3,6 now, ask about 4,5 later +✅ RIGHT: "I understand items 1,2,3,6. Need clarification on 4 and 5 before proceeding." +``` + +## Source-Specific Handling + +### From your human partner +- **Trusted** - implement after understanding +- **Still ask** if scope unclear +- **No performative agreement** +- **Skip to action** or technical acknowledgment + +### From External Reviewers +``` +BEFORE implementing: + 1. Check: Technically correct for THIS codebase? + 2. Check: Breaks existing functionality? + 3. Check: Reason for current implementation? + 4. Check: Works on all platforms/versions? + 5. Check: Does reviewer understand full context? + +IF suggestion seems wrong: + Push back with technical reasoning + +IF can't easily verify: + Say so: "I can't verify this without [X]. Should I [investigate/ask/proceed]?" + +IF conflicts with your human partner's prior decisions: + Stop and discuss with your human partner first +``` + +**your human partner's rule:** "External feedback - be skeptical, but check carefully" + +## YAGNI Check for "Professional" Features + +``` +IF reviewer suggests "implementing properly": + grep codebase for actual usage + + IF unused: "This endpoint isn't called. Remove it (YAGNI)?" + IF used: Then implement properly +``` + +**your human partner's rule:** "You and reviewer both report to me. If we don't need this feature, don't add it." + +## Implementation Order + +``` +FOR multi-item feedback: + 1. Clarify anything unclear FIRST + 2. Then implement in this order: + - Blocking issues (breaks, security) + - Simple fixes (typos, imports) + - Complex fixes (refactoring, logic) + 3. Test each fix individually + 4. Verify no regressions +``` + +## When To Push Back + +Push back when: +- Suggestion breaks existing functionality +- Reviewer lacks full context +- Violates YAGNI (unused feature) +- Technically incorrect for this stack +- Legacy/compatibility reasons exist +- Conflicts with your human partner's architectural decisions + +**How to push back:** +- Use technical reasoning, not defensiveness +- Ask specific questions +- Reference working tests/code +- Involve your human partner if architectural + +**If you're uncomfortable pushing back out loud:** Name that tension, then tell your partner about the issue you've seen. They'll appreciate your honesty. + +## Acknowledging Correct Feedback + +When feedback IS correct: +``` +✅ "Fixed. [Brief description of what changed]" +✅ "Good catch - [specific issue]. Fixed in [location]." +✅ [Just fix it and show in the code] + +❌ "You're absolutely right!" +❌ "Great point!" +❌ "Thanks for catching that!" +❌ "Thanks for [anything]" +❌ ANY gratitude expression +``` + +**Why no thanks:** Actions speak. Just fix it. The code itself shows you heard the feedback. + +**If you catch yourself about to write "Thanks":** DELETE IT. State the fix instead. + +## Gracefully Correcting Your Pushback + +If you pushed back and were wrong: +``` +✅ "You were right - I checked [X] and it does [Y]. Implementing now." +✅ "Verified this and you're correct. My initial understanding was wrong because [reason]. Fixing." + +❌ Long apology +❌ Defending why you pushed back +❌ Over-explaining +``` + +State the correction factually and move on. + +## Common Mistakes + +| Mistake | Fix | +|---------|-----| +| Performative agreement | State requirement or just act | +| Blind implementation | Verify against codebase first | +| Batch without testing | One at a time, test each | +| Assuming reviewer is right | Check if breaks things | +| Avoiding pushback | Technical correctness > comfort | +| Partial implementation | Clarify all items first | +| Can't verify, proceed anyway | State limitation, ask for direction | + +## Real Examples + +**Performative Agreement (Bad):** +``` +Reviewer: "Remove legacy code" +❌ "You're absolutely right! Let me remove that..." +``` + +**Technical Verification (Good):** +``` +Reviewer: "Remove legacy code" +✅ "Checking... build target is 10.15+, this API needs 13+. Need legacy for backward compat. Current impl has wrong bundle ID - fix it or drop pre-13 support?" +``` + +**YAGNI (Good):** +``` +Reviewer: "Implement proper metrics tracking with database, date filters, CSV export" +✅ "Grepped codebase - nothing calls this endpoint. Remove it (YAGNI)? Or is there usage I'm missing?" +``` + +**Unclear Item (Good):** +``` +your human partner: "Fix items 1-6" +You understand 1,2,3,6. Unclear on 4,5. +✅ "Understand 1,2,3,6. Need clarification on 4 and 5 before implementing." +``` + +## GitHub Thread Replies + +When replying to inline review comments on GitHub, reply in the comment thread (`gh api repos/{owner}/{repo}/pulls/{pr}/comments/{id}/replies`), not as a top-level PR comment. diff --git a/.claude/skills/refactoring-patterns/SKILL.md b/.claude/skills/refactoring-patterns/SKILL.md new file mode 100644 index 0000000..a5f58c2 --- /dev/null +++ b/.claude/skills/refactoring-patterns/SKILL.md @@ -0,0 +1,212 @@ +--- +name: refactoring-patterns +description: 'Apply named refactoring transformations to improve code structure without changing behavior. Use when the user mentions "refactor this", "code smells", "extract method", "replace conditional", "technical debt", "move method", "inline variable", "decompose conditional", or "clean up this messy code". Also trigger when cleaning up legacy code, preparing code for new features by restructuring, or identifying which transformation fits a specific code smell. Covers smell-driven refactoring, safe transformation sequences, and testing guards. For code-quality foundations, see clean-code. For managing complexity, see software-design-philosophy.' +license: MIT +metadata: + author: wondelai + version: "1.4.1" +--- + +# Refactoring Patterns Framework + +A disciplined approach to improving the internal structure of existing code without changing its observable behavior. Every refactoring follows the same loop: verify tests pass, apply one small structural change, verify tests still pass. + +## Core Principle + +**Refactoring is not rewriting. It is a sequence of small, behavior-preserving transformations, each backed by tests.** You never change what the code does — only how it is organized. Big-bang rewrites fail because they combine structural change with behavioral change, making it impossible to know which broke things. + +**The foundation:** Bad code is a natural consequence of delivering under time pressure, not a character flaw. Code smells are objective signals of degraded structure; the smell catalog tells you *where* to look, and the refactoring catalog tells you *what to do*. + +## Scoring + +**Goal: 10/10.** Score structural quality by how many of the eight [Quick Diagnostic](#quick-diagnostic) rows pass — `score = round(passed / 8 × 10)`, adjusting down when a single smell is severe. Bands: +- **9-10**: no obvious smells remain, each function does one thing, names reveal intent, duplication is eliminated, conditionals use polymorphism where apt, and tests cover the refactored paths. +- **5-6**: a few smells remain (a Long Method, some duplication) but structure is mostly sound. +- **≤3**: pervasive smells — tangled conditionals, God classes, duplication everywhere — or no tests to refactor safely. + +Always state the current score, name the smells driving it down, and list the specific refactorings needed to reach 10/10. + +## The Refactoring Patterns Framework + +Six areas of focus for systematically improving code structure: + +### 1. Code Smells as Triggers + +**Core concept:** Code smells are surface indicators of deeper structural problems — not bugs, but signals that the design makes code harder to understand, extend, or maintain. Each smell maps to named refactorings that fix it. + +**Why it works:** Named smells give teams objective criteria instead of subjective "I don't like this" — "This is Feature Envy" points directly at the fix. + +**Key insights:** +- Smells cluster into five families: Bloaters, Object-Orientation Abusers, Change Preventers, Dispensables, Couplers +- Long Method is the most common smell; Duplicate Code is the most expensive +- A method that needs a comment to explain *what* it does is a smell — extract and name the block instead +- Shotgun Surgery (one change, many classes) and Divergent Change (one class, many reasons to change) are opposite signals of misplaced responsibilities +- Primitive Obsession — raw strings/ints instead of small domain objects — spreads errors and duplication + +**Code applications:** + +| Context | Pattern | Example | +|---------|---------|---------| +| Method > 10 lines | Extract Method | Pull loop body into `calculateLineTotal()` | +| One change touches many classes (Shotgun Surgery) | Move Method/Field | Gather the scattered behavior into one class | +| Same params in many methods | Introduce Parameter Object | `startDate, endDate` → `DateRange` | +| Copy-pasted logic | Extract Method + Pull Up Method | Share via common method or base class | + +See [references/smell-catalog.md](references/smell-catalog.md) when you need to name a smell and its fix — all five families (Bloaters, OO Abusers, Change Preventers, Dispensables, Couplers) with detection heuristics and the refactoring each maps to. + +### 2. Composing Methods + +**Core concept:** Most refactoring starts here: break long methods into smaller, well-named pieces that read like prose — high-level steps delegating to clearly named helpers. + +**Why it works:** Short methods with intention-revealing names eliminate comments, make bugs obvious at a glance, and enable reuse; a method call costs nothing to read when the name says everything. + +**Key insights:** +- Extract Method is the single most important refactoring — master it first +- Urge to write a comment? Extract the block and use the comment as the method name +- Inline Method when the body is as clear as the name — indirection without value is noise +- Replace Temp with Query for computed values used in multiple places; Split Temporary Variable when one temp serves two purposes +- Replace Method with Method Object when locals are too tangled to extract — they become fields + +**Code applications:** + +| Context | Pattern | Example | +|---------|---------|---------| +| Block with a comment | Extract Method | `// check eligibility` → `isEligible()` | +| Temp used once | Inline Variable | Drop `const price = order.getPrice()` | +| Trivial delegating method | Inline Method | Inline `return deliveries > 5` if used once | +| Method with many tangled locals | Replace Method with Method Object | Locals become fields in a new class | + +See [references/composing-methods.md](references/composing-methods.md) when applying any method-level transformation — step-by-step mechanics and before/after code for Extract/Inline Method, Extract/Inline Variable, Replace Temp with Query, Split Temporary Variable, and Replace Method with Method Object. + +### 3. Moving Features Between Objects + +**Core concept:** The key OO design decision is where responsibilities live. When Feature Envy, excessive coupling, or unbalanced class sizes show a method or field is in the wrong class, move it where it belongs. + +**Why it works:** A method placed away from the data it uses creates invisible cross-class dependencies, so one logical change ripples across many files — Shotgun Surgery. Co-locating method and data confines the change to one class. + +**Key insights:** +- Move Method when a method uses more of another class's features than its own; Move Field likewise +- Extract Class when one class does two things — split along the axis of change; Inline Class when one does too little +- Hide Delegate enforces the Law of Demeter; Remove Middle Man undoes it when forwarding becomes the whole class +- Resolve that tension case by case: hide the delegate when the chain is unstable, remove the middle man when it's pure forwarding + +**Code applications:** + +| Context | Pattern | Example | +|---------|---------|---------| +| Method envies another class | Move Method | `calculateShipping()` from `Order` to `ShippingPolicy` | +| God class 500+ lines | Extract Class | Pull `Address` fields/methods into own class | +| Client calls `a.getB().getC()` | Hide Delegate | Add `a.getCThroughB()` | +| Class only forwards calls | Remove Middle Man | Let client call the delegate directly | + +See [references/moving-features.md](references/moving-features.md) when deciding where a responsibility belongs — mechanics for Move Method/Field, Extract/Inline Class, Hide Delegate, and Remove Middle Man. + +### 4. Organizing Data + +**Core concept:** Raw data — magic numbers, exposed fields, integer type codes — creates subtle bugs and scatters domain knowledge. Replace primitives with objects that encapsulate behavior and enforce invariants. + +**Why it works:** An `int` amount has no rounding rules or currency code; a `Money` object encapsulates all of it, so business rules live in one place and the type system catches errors at compile time. + +**Key insights:** +- Replace Magic Number with Symbolic Constant — the simplest data refactoring; it names intent +- Replace Data Value with Object cures Primitive Obsession (`EmailAddress`, `Money`, `Temperature`) +- Encapsulate Field and Encapsulate Collection — never expose raw fields or mutable internal lists +- Replace Type Code with Subclasses when the code affects behavior; with Strategy when subclassing is impractical +- Change Value to Reference when you need identity semantics (one shared `Customer`, not copies) + +**Code applications:** + +| Context | Pattern | Example | +|---------|---------|---------| +| `if (status == 2)` | Replace Magic Number | `if (status == ORDER_SHIPPED)` | +| `String email` passed everywhere | Replace Data Value with Object | `EmailAddress` class with validation | +| Getter returns mutable list | Encapsulate Collection | Return `Collections.unmodifiableList(items)` | +| `int typeCode` with switch | Replace Type Code with Subclasses | `Employee` → `Engineer`, `Manager` | + +See [references/organizing-data.md](references/organizing-data.md) when replacing primitives with objects — mechanics for Replace Data Value with Object, Change Value to Reference, Replace Magic Number, Encapsulate Field/Collection, and the Replace Type Code variants. + +### 5. Simplifying Conditional Logic + +**Core concept:** Deeply nested if/else trees, long switches, and scattered null checks are the hardest code to read and the most bug-prone. Named refactorings decompose, consolidate, and replace conditionals with clearer structures. + +**Why it works:** A six-branch conditional forces readers to simulate every path mentally; well-named extracted branches are self-documenting, and polymorphism eliminates whole categories of "forgot this case" bugs. + +**Key insights:** +- Decompose Conditional: extract condition, then-branch, and else-branch into named methods +- Consolidate Conditional Expression: merge conditions with the same result into one named check +- Replace Nested Conditional with Guard Clauses: handle edge cases early and return, keeping the main path unindented +- Replace Conditional with Polymorphism is the gold standard for type-based conditionals +- Introduce Special Case (Null Object) eliminates scattered `if (x == null)` checks; Introduce Assertion makes assumptions fail fast + +**Code applications:** + +| Context | Pattern | Example | +|---------|---------|---------| +| Long `if` with complex condition | Decompose Conditional | Extract `isSummer(date)` and `summerCharge()` | +| Deeply nested `if/else` | Replace with Guard Clauses | Edge cases first, return early, flat main path | +| Switch on object type | Replace Conditional with Polymorphism | Each type implements its own `calculatePay()` | +| `if (customer == null)` everywhere | Introduce Special Case | `NullCustomer` with safe default behavior | + +See [references/simplifying-conditionals.md](references/simplifying-conditionals.md) when untangling branches — before/after examples for Decompose/Consolidate Conditional, Guard Clauses, Replace Conditional with Polymorphism, Special Case, and Assertions. + +### 6. Safe Refactoring Workflow + +**Core concept:** Refactoring is only safe when wrapped in tests. The workflow is mechanical: run tests (green), apply one small transformation, run tests (green), commit. If tests go red, revert — don't debug a broken refactoring. + +**Why it works:** Small steps make the failure obvious (it was the last thing you did) and reverting costs seconds; debugging a failed big-bang rewrite costs days. + +**Key insights:** +- Rule of Three: tolerate duplication once, note it twice, refactor on the third occurrence +- Preparatory refactoring: restructure to make the feature easy *before* adding it; comprehension and litter-pickup refactoring keep code improving as you read and touch it +- When NOT to refactor: rewriting is easier, no tests and adding them isn't feasible, or the code will be deleted soon +- Refactor for clarity first, then profile and optimize the measured bottleneck — clear code is easier to tune +- Branch by Abstraction and Parallel Change enable large refactorings in production without long-lived branches + +**Code applications:** + +| Context | Pattern | Example | +|---------|---------|---------| +| About to add a feature | Preparatory Refactoring | Clean the insertion point first | +| Third copy of same logic | Rule of Three | Extract shared logic now | +| Large API change in production | Branch by Abstraction | Add abstraction layer, migrate callers, remove old path | +| Renaming a widely-used method | Parallel Change | Add new, deprecate old, migrate, remove | + +See [references/refactoring-workflow.md](references/refactoring-workflow.md) before a large or risky refactoring — the full green-to-green cycle, when (not) to refactor, performance, Branch by Abstraction, and Parallel Change. + +## Common Mistakes + +| Mistake | Why It Fails | Fix | +|---------|-------------|-----| +| Refactoring without tests | No safety net to detect behavior change | Write characterization tests first | +| Big-bang rewrite | Mixes structural and behavioral change; undebuggable | Smallest possible steps, tests after each | +| Refactoring while adding features | Two hats at once — neither change verifiable | Refactor first (commit), then add feature (commit) | +| Renaming without updating callers | Broken build or dead code | Use IDE rename; search all references | +| Extracting too many tiny methods | Indirection without clarity when names are poor | Each name must remove the need to read the body | +| Ignoring the smell catalog | Reinvents fixes instead of applying proven recipes | Learn named smells; each maps to refactorings | +| Refactoring doomed code | Polish on condemned code is waste | Check the code's lifespan justifies the investment | +| Optimizing while refactoring | Conflates clarity with performance | Clarity first, then profile, then optimize hot path | + +## Quick Diagnostic + +| Question | If No | Action | +|----------|-------|--------| +| Do tests pass before you start? | No safety net | Write or fix tests first — never refactor red | +| Can you name the smell you're fixing? | Refactoring by instinct, not catalog | Identify the smell, apply its prescribed refactoring | +| Is each method under ~10 lines? | Long Methods likely | Extract Method into named steps | +| Does each class have one reason to change? | Divergent Change or Large Class | Extract Class to separate responsibilities | +| Are there duplicated code blocks? | The most expensive smell | Extract shared logic into common method/base class | +| Do conditionals use polymorphism where apt? | Switch Statements remain | Replace Conditional with Polymorphism | +| Are you committing after each step? | Risk losing work, mixing changes | Commit after every green-to-green transformation | +| Is the code easier to read after your change? | Refactoring added complexity | Revert and try a different approach | + +## Further Reading + +The definitive guides to improving existing code: + +- [*"Refactoring: Improving the Design of Existing Code (2nd Edition)"*](https://www.amazon.com/Refactoring-Improving-Existing-Addison-Wesley-Signature/dp/0134757599?tag=wondelai00-20) by Martin Fowler +- [*"Working Effectively with Legacy Code"*](https://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052?tag=wondelai00-20) by Michael Feathers (companion for code without tests) +- [*"Clean Code: A Handbook of Agile Software Craftsmanship"*](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882?tag=wondelai00-20) by Robert C. Martin (complementary naming and style principles) + +## About the Author + +**Martin Fowler** is Chief Scientist at Thoughtworks, a signatory of the Agile Manifesto, and author of *Refactoring: Improving the Design of Existing Code* (1999; 2nd edition 2018), which introduced catalog-based, named refactorings to mainstream development. His catalog underpins the automated refactoring tools in every major IDE. diff --git a/.claude/skills/refactoring-patterns/references/composing-methods.md b/.claude/skills/refactoring-patterns/references/composing-methods.md new file mode 100644 index 0000000..e6b5658 --- /dev/null +++ b/.claude/skills/refactoring-patterns/references/composing-methods.md @@ -0,0 +1,399 @@ +# Composing Methods + +Detailed reference for the refactorings that break down long methods into well-named, cohesive pieces. These are the most frequently used refactorings and the foundation of all code improvement. + +## Table of Contents +1. [Extract Method](#extract-method) +2. [Inline Method](#inline-method) +3. [Extract Variable](#extract-variable) +4. [Inline Variable](#inline-variable) +5. [Replace Temp with Query](#replace-temp-with-query) +6. [Split Temporary Variable](#split-temporary-variable) +7. [Remove Assignments to Parameters](#remove-assignments-to-parameters) +8. [Replace Method with Method Object](#replace-method-with-method-object) +9. [Decision Guide: Which Composing Refactoring to Use](#decision-guide-which-composing-refactoring-to-use) + +--- + +## Extract Method + +The single most important refactoring. Turn a code fragment into a method whose name explains the purpose of the fragment. + +### Motivation + +You have a code fragment that can be grouped together. The longer a method, the harder it is to understand. When you see a comment explaining what the next block does, that's a signal to extract. The comment becomes the method name. + +### Mechanics + +1. Create a new method and name it after the *intention* of the code (what it does, not how) +2. Copy the extracted code into the new method +3. Scan the extracted code for references to local variables -- these become parameters or return values +4. Declare any local-scope variables as local to the new method if they're only used within the extracted code +5. Pass any remaining local variables as parameters +6. If more than one value needs to be returned, consider returning an object or extracting further +7. Replace the original code with a call to the new method +8. Run tests + +### Example + +**Before:** +```javascript +function printOwing(invoice) { + let outstanding = 0; + + // print banner + console.log("***********************"); + console.log("**** Customer Owes ****"); + console.log("***********************"); + + // calculate outstanding + for (const order of invoice.orders) { + outstanding += order.amount; + } + + // print details + console.log(`name: ${invoice.customer}`); + console.log(`amount: ${outstanding}`); + console.log(`due: ${invoice.dueDate.toLocaleDateString()}`); +} +``` + +**After:** +```javascript +function printOwing(invoice) { + printBanner(); + const outstanding = calculateOutstanding(invoice); + printDetails(invoice, outstanding); +} + +function printBanner() { + console.log("***********************"); + console.log("**** Customer Owes ****"); + console.log("***********************"); +} + +function calculateOutstanding(invoice) { + let result = 0; + for (const order of invoice.orders) { + result += order.amount; + } + return result; +} + +function printDetails(invoice, outstanding) { + console.log(`name: ${invoice.customer}`); + console.log(`amount: ${outstanding}`); + console.log(`due: ${invoice.dueDate.toLocaleDateString()}`); +} +``` + +### Naming Guidelines + +| Bad Name | Good Name | Why | +|----------|-----------|-----| +| `doStuff()` | `calculateMonthlyTotal()` | Names the intent, not the vagueness | +| `process()` | `validateAndSaveOrder()` | Specific about what it does | +| `handleData()` | `parseCSVRow()` | Names the domain concept | +| `helper()` | `formatCurrencyForDisplay()` | Describes the transformation | +| `step2()` | `applyDiscountRules()` | Names the business concept | + +**Rule of thumb:** If you can't find a good name, the extraction boundaries may be wrong. Try extracting a different fragment. + +--- + +## Inline Method + +The inverse of Extract Method. Replace a method call with the method's body when the body is as clear as the name, or when you need to regroup poorly factored code. + +### Motivation + +Sometimes a method body is as obvious as the method name. Indirection without value is noise. Also useful as an intermediate step: inline a badly decomposed method, then re-extract along better boundaries. + +### Mechanics + +1. Check that the method is not polymorphic (no subclass overrides it) +2. Find all callers +3. Replace each call with the method body +4. Delete the method +5. Run tests + +### Example + +**Before:** +```python +def get_rating(self): + return 2 if self.more_than_five_late_deliveries() else 1 + +def more_than_five_late_deliveries(self): + return self.late_deliveries > 5 +``` + +**After:** +```python +def get_rating(self): + return 2 if self.late_deliveries > 5 else 1 +``` + +### When NOT to Inline + +- When the method name communicates domain meaning the code doesn't +- When the method is used in multiple places (DRY) +- When the method is overridden in subclasses + +--- + +## Extract Variable + +Introduce a local variable for a complex expression to make it self-documenting. + +### Motivation + +Expressions can become hard to read. A well-named variable for a sub-expression acts as inline documentation and makes debugging easier. + +### Mechanics + +1. Identify a complex expression or sub-expression +2. Declare a variable named for the intent of the expression +3. Replace the expression with the variable +4. Run tests + +### Example + +**Before:** +```javascript +return order.quantity * order.itemPrice - + Math.max(0, order.quantity - 500) * order.itemPrice * 0.05 + + Math.min(order.quantity * order.itemPrice * 0.1, 100); +``` + +**After:** +```javascript +const basePrice = order.quantity * order.itemPrice; +const quantityDiscount = Math.max(0, order.quantity - 500) * order.itemPrice * 0.05; +const shippingCap = Math.min(basePrice * 0.1, 100); +return basePrice - quantityDiscount + shippingCap; +``` + +--- + +## Inline Variable + +The inverse of Extract Variable. Remove a variable when the expression is just as clear. + +### When to Use + +- The variable name adds no information beyond what the expression says +- The variable is assigned once and used once +- The variable is blocking another refactoring (e.g., you need to inline it to then Extract Method) + +### Example + +**Before:** +```python +base_price = order.base_price() +return base_price > 1000 +``` + +**After:** +```python +return order.base_price() > 1000 +``` + +--- + +## Replace Temp with Query + +Turn a temporary variable into a method call so the computation is reusable and the original method becomes shorter. + +### Motivation + +Temporaries can only be seen within a single method. If the same computation is needed elsewhere, it gets duplicated. A query method is visible to the whole class (or can be extracted to another class). + +### Mechanics + +1. Check that the variable is assigned once and the expression has no side effects +2. Extract the right-hand side of the assignment into a new method +3. Replace all references to the temp with calls to the new method +4. Remove the temp declaration and assignment +5. Run tests + +### Example + +**Before:** +```javascript +class Order { + getPrice() { + const basePrice = this.quantity * this.itemPrice; + if (basePrice > 1000) { + return basePrice * 0.95; + } else { + return basePrice * 0.98; + } + } +} +``` + +**After:** +```javascript +class Order { + getPrice() { + if (this.basePrice() > 1000) { + return this.basePrice() * 0.95; + } else { + return this.basePrice() * 0.98; + } + } + + basePrice() { + return this.quantity * this.itemPrice; + } +} +``` + +### Performance Note + +Calling the method multiple times instead of caching in a temp may seem wasteful. In practice, the performance impact is negligible for most code. Profile before optimizing. Refactored code is easier to optimize later because the hot path is isolated. + +--- + +## Split Temporary Variable + +When a temporary variable is assigned more than once (and it's not a loop counter or collecting variable), it's doing two different jobs. Give each job its own variable. + +### Motivation + +A temp assigned twice for different purposes misleads the reader into thinking the assignments are related. Each role deserves its own variable with a descriptive name. + +### Mechanics + +1. Rename the first assignment to reflect its purpose +2. Declare it as `const`/`final` if possible +3. Find all uses that refer to the first assignment's value and make sure they use the new name +4. Repeat for each subsequent assignment with a different name +5. Run tests + +### Example + +**Before:** +```javascript +let temp = 2 * (height + width); // perimeter +console.log(temp); +temp = height * width; // area +console.log(temp); +``` + +**After:** +```javascript +const perimeter = 2 * (height + width); +console.log(perimeter); +const area = height * width; +console.log(area); +``` + +--- + +## Remove Assignments to Parameters + +Never assign to a parameter inside a method body. It confuses readers about whether the change is visible to the caller (it isn't in pass-by-value languages; it is in pass-by-reference for object mutations). + +### Mechanics + +1. Create a new local variable for the parameter +2. Replace all assignments to the parameter with assignments to the new variable +3. Run tests + +### Example + +**Before:** +```python +def discount(input_val, quantity): + if quantity > 50: + input_val -= 2 + if quantity > 100: + input_val -= 1 + return input_val +``` + +**After:** +```python +def discount(input_val, quantity): + result = input_val + if quantity > 50: + result -= 2 + if quantity > 100: + result -= 1 + return result +``` + +--- + +## Replace Method with Method Object + +When a method is too tangled with local variables to extract from, move the entire method into its own class where the local variables become fields. Then you can freely extract sub-methods. + +### Motivation + +Sometimes a long method has so many interrelated local variables that Extract Method is impossible (too many parameters would be needed). By turning the method into its own class, all locals become fields, accessible to any extracted method without parameters. + +### Mechanics + +1. Create a new class named after the method's purpose +2. Add a field for the original object and for every local variable and parameter +3. Create a constructor that takes the original object and all parameters +4. Copy the method body into a `compute()` (or similar) method +5. Replace the original method with: create the new object, call `compute()` +6. Now freely extract methods within the new class -- locals are fields, no parameter passing needed +7. Run tests + +### Example + +**Before:** +```python +class Account: + def gamma(self, input_val, quantity, year_to_date): + # 50 lines of tangled computation using all three params + # plus self.fields -- too intertwined to extract + ... +``` + +**After:** +```python +class GammaCalculation: + def __init__(self, account, input_val, quantity, year_to_date): + self.account = account + self.input_val = input_val + self.quantity = quantity + self.year_to_date = year_to_date + + def compute(self): + # Now extract freely -- all variables are fields + self._apply_quantity_adjustment() + self._apply_yearly_factor() + return self.input_val + + def _apply_quantity_adjustment(self): + # can access self.quantity, self.input_val freely + ... + + def _apply_yearly_factor(self): + ... + +class Account: + def gamma(self, input_val, quantity, year_to_date): + return GammaCalculation(self, input_val, quantity, year_to_date).compute() +``` + +--- + +## Decision Guide: Which Composing Refactoring to Use + +| Situation | Refactoring | +|-----------|-------------| +| Code block can be named by intent | Extract Method | +| Method body is trivial and name adds nothing | Inline Method | +| Complex expression needs explanation | Extract Variable | +| Variable adds no meaning beyond the expression | Inline Variable | +| Same computation needed in multiple methods | Replace Temp with Query | +| One variable serves two purposes | Split Temporary Variable | +| Parameter is reassigned inside method | Remove Assignments to Parameters | +| Long method with too many entangled locals | Replace Method with Method Object | diff --git a/.claude/skills/refactoring-patterns/references/moving-features.md b/.claude/skills/refactoring-patterns/references/moving-features.md new file mode 100644 index 0000000..1ec52e0 --- /dev/null +++ b/.claude/skills/refactoring-patterns/references/moving-features.md @@ -0,0 +1,389 @@ +# Moving Features Between Objects + +Detailed reference for refactorings that redistribute responsibilities between classes. The fundamental question of object-oriented design is: where should this behavior live? These refactorings provide the mechanical steps to move things to the right place. + +## Table of Contents +1. [Move Method](#move-method) +2. [Move Field](#move-field) +3. [Extract Class](#extract-class) +4. [Inline Class](#inline-class) +5. [Hide Delegate](#hide-delegate) +6. [Remove Middle Man](#remove-middle-man) +7. [Introduce Foreign Method](#introduce-foreign-method) +8. [Introduce Local Extension](#introduce-local-extension) +9. [Decision Guide: Where Does This Behavior Belong?](#decision-guide-where-does-this-behavior-belong) + +--- + +## Move Method + +Move a method to the class it uses most. A method that accesses more features of another class than its own has Feature Envy and belongs somewhere else. + +### Motivation + +The most common reason for moving a method is Feature Envy -- when a method spends most of its time talking to another object. Moving the method reduces coupling: the method now lives where its data lives, so changes to that data don't ripple outward. + +### Mechanics + +1. Examine all features (fields and methods) used by the method. Determine which class has the most features used by the method. +2. Check for related methods in the source class. If other methods also use the same target class, consider moving them together. +3. Check superclasses and subclasses for overrides or related declarations. +4. Declare the method in the target class. Copy the body and adjust references -- `this` now refers to the target; the source object may need to be passed as a parameter. +5. Turn the source method into a delegating method (call the target). +6. Run tests. +7. Consider removing the delegating method if no other callers need it. +8. Run tests. + +### Example + +**Before:** +```javascript +class Account { + overdraftCharge() { + if (this.type.isPremium()) { + let result = 10; + if (this.daysOverdrawn > 7) { + result += (this.daysOverdrawn - 7) * 0.85; + } + return result; + } else { + return this.daysOverdrawn * 1.75; + } + } +} +``` + +The method depends heavily on `this.type` (an `AccountType` object). Move it there. + +**After:** +```javascript +class AccountType { + overdraftCharge(daysOverdrawn) { + if (this.isPremium()) { + let result = 10; + if (daysOverdrawn > 7) { + result += (daysOverdrawn - 7) * 0.85; + } + return result; + } else { + return daysOverdrawn * 1.75; + } + } +} + +class Account { + overdraftCharge() { + return this.type.overdraftCharge(this.daysOverdrawn); + } +} +``` + +### Decision Criteria + +Move a method when: +- It uses more fields/methods of another class than its own +- The target class is likely to change in ways that affect this method +- Related methods already live in the target class + +Don't move when: +- The method uses features from multiple classes equally (keep it in the most stable location) +- Polymorphism on the source class is needed + +--- + +## Move Field + +Move a field to the class that uses it more. Similar to Move Method but for data. + +### Motivation + +A field used more by another class signals that the data model is out of alignment with the behavior model. Moving the field keeps data and behavior together. + +### Mechanics + +1. If the field is public, encapsulate it first (Encapsulate Field) +2. Create the field in the target class with a getter and setter +3. Determine how to reference the target from the source (usually an existing association) +4. Update the source getter to delegate to the target +5. Run tests +6. Remove the field from the source class +7. Run tests + +### Example + +**Before:** +```python +class Customer: + def __init__(self): + self.discount_rate = 0.0 + +class Order: + def discounted_total(self): + return self.base_total() - (self.base_total() * self.customer.discount_rate) +``` + +`discount_rate` is only read by `Order` through `Customer`. If most logic involving `discount_rate` lives in the customer's pricing context, keep it in `Customer`. But if `Order` is the primary consumer and `discount_rate` is really about order pricing policy, consider moving it. + +--- + +## Extract Class + +Split a class that does two things into two classes that each do one thing. + +### Motivation + +A class with too many responsibilities grows too large and becomes hard to understand. If you can identify a coherent subset of fields and methods that relate to each other more than to the rest of the class, that subset deserves its own class. + +### Mechanics + +1. Identify the subset of responsibilities to split out +2. Create a new class named after the split-out responsibility +3. Add a link from the old class to the new class +4. Use Move Field for each field in the subset +5. Use Move Method for each method in the subset +6. Review the interfaces of both classes. Remove unneeded methods, rename as appropriate. +7. Decide whether to expose the new class or hide it behind the original +8. Run tests + +### Example + +**Before:** +```javascript +class Person { + constructor() { + this.name = ''; + this.officeAreaCode = ''; + this.officeNumber = ''; + } + + get telephoneNumber() { + return `(${this.officeAreaCode}) ${this.officeNumber}`; + } +} +``` + +**After:** +```javascript +class TelephoneNumber { + constructor() { + this.areaCode = ''; + this.number = ''; + } + + toString() { + return `(${this.areaCode}) ${this.number}`; + } +} + +class Person { + constructor() { + this.name = ''; + this.telephoneNumber = new TelephoneNumber(); + } + + get telephone() { + return this.telephoneNumber.toString(); + } +} +``` + +### Signals That Suggest Extraction + +| Signal | What to Extract | +|--------|----------------| +| Field name prefix groups (e.g., `shippingStreet`, `shippingCity`) | `ShippingAddress` class | +| Methods that only use a subset of fields | The subset + its methods = new class | +| Subsets change at different rates | The faster-changing subset deserves its own class | +| Subsets have different collaborators | Each collaborator relationship = potential class boundary | + +--- + +## Inline Class + +The inverse of Extract Class. Merge a class that no longer carries its weight back into another class. + +### Motivation + +A class that does too little -- perhaps after previous refactorings moved its responsibilities elsewhere -- adds complexity without value. Fold it back into the class that uses it. + +### Mechanics + +1. For each public method and field of the source class, create a corresponding member in the target class +2. Change all references to the source class to use the target class instead +3. Run tests +4. Delete the source class +5. Run tests + +### When to Use + +- The class has only one or two trivial methods +- The class was created by Extract Class but subsequent refactorings emptied it +- The class adds indirection without any logic, validation, or behavior of its own + +--- + +## Hide Delegate + +Encapsulate the fact that one object delegates to another. Create a method on the server that hides the delegate from the client, enforcing the Law of Demeter. + +### Motivation + +When a client calls `person.getDepartment().getManager()`, the client knows about the `Department` class -- it's coupled to the navigation structure. If `Department` changes its interface, the client breaks. By adding `person.getManager()` (which internally calls `department.getManager()`), the client only knows about `Person`. + +### Mechanics + +1. For each method the client calls on the delegate, create a simple delegating method on the server +2. Change the client to call the server method instead +3. If no client needs the delegate accessor anymore, remove it +4. Run tests + +### Example + +**Before:** +```python +# Client code: +manager = person.department.manager +``` + +**After:** +```python +class Person: + @property + def manager(self): + return self.department.manager + +# Client code: +manager = person.manager +``` + +### The Trade-Off + +Hiding every delegate leads to the Middle Man smell -- a class that does nothing but forward calls. The right balance: + +| Situation | Action | +|-----------|--------| +| Delegate's interface is unstable | Hide it (protect callers from change) | +| Client uses many delegate methods | Consider Hide Delegate for each | +| Server is becoming pure forwarding | Remove Middle Man | +| Chain is deep (a.b.c.d) | Definitely hide | + +--- + +## Remove Middle Man + +The inverse of Hide Delegate. When a class consists primarily of methods that delegate to another class, let the client call the delegate directly. + +### Motivation + +As a system evolves, more and more delegating methods accumulate until the "server" class adds no value -- it's just a pass-through. At that point, remove the indirection. + +### Mechanics + +1. Create a getter for the delegate on the server (if one doesn't exist) +2. For each delegating method that adds no value, redirect the client to call the delegate directly +3. Remove the delegating method from the server +4. Run tests + +### Example + +**Before:** +```javascript +class Person { + get manager() { return this.department.manager; } + get budget() { return this.department.budget; } + get headcount() { return this.department.headcount; } + get location() { return this.department.location; } + // ... 10 more forwarding methods +} +``` + +**After:** +```javascript +class Person { + get department() { return this._department; } +} + +// Client: +const manager = person.department.manager; +``` + +--- + +## Introduce Foreign Method + +When a server class needs an additional method but you can't modify it (third-party library, frozen module), create the method in the client class and pass the server object as the first argument. + +### Motivation + +A utility method that "should" be on the server class but can't be added there. The foreign method is a workaround -- mark it as such, so if the server class is ever opened for modification, the method can be moved. + +### Example + +```python +# Server class (third-party, can't modify): +# date = Date(year, month, day) + +# Foreign method in client: +def next_day(date): + """Foreign method -- should be on Date class.""" + return Date(date.year, date.month, date.day + 1) +``` + +--- + +## Introduce Local Extension + +When you need several foreign methods on a server class you can't modify, create a new class -- either a subclass or a wrapper -- that adds the missing methods. + +### Subclass vs. Wrapper + +| Approach | When to Use | +|----------|-------------| +| Subclass | When you can subclass the server; simplest approach | +| Wrapper (Decorator) | When you can't subclass (final class); forward all original methods | + +### Example (Wrapper) + +```javascript +class EnhancedDate { + constructor(date) { + this._original = date; + } + + // Forward original methods + getYear() { return this._original.getYear(); } + getMonth() { return this._original.getMonth(); } + + // New methods + nextDay() { + return new EnhancedDate( + new Date(this._original.getTime() + 86400000) + ); + } + + isWeekend() { + const day = this._original.getDay(); + return day === 0 || day === 6; + } +} +``` + +--- + +## Decision Guide: Where Does This Behavior Belong? + +Use these questions to decide whether and where to move code: + +| Question | If Yes | Action | +|----------|--------|--------| +| Does this method use more of another class's features? | Feature Envy | Move Method to that class | +| Is this field used more by another class? | Misplaced data | Move Field to that class | +| Does this class have two groups of fields that don't interact? | Multiple responsibilities | Extract Class | +| Is this class just a thin wrapper with no logic? | Unnecessary indirection | Inline Class | +| Is the client navigating through an object chain? | Tight coupling | Hide Delegate | +| Is this class just forwarding calls? | Middle Man smell | Remove Middle Man | +| Need to add a method to a class you can't modify? | Missing feature | Introduce Foreign Method or Local Extension | + +### The Responsibility Placement Heuristic + +When unsure where to put a method, ask: **"If the data this method uses changes, which class should need to be updated?"** The method belongs in that class. This keeps data and behavior together, minimizing the ripple effect of change. diff --git a/.claude/skills/refactoring-patterns/references/organizing-data.md b/.claude/skills/refactoring-patterns/references/organizing-data.md new file mode 100644 index 0000000..cdb7bb8 --- /dev/null +++ b/.claude/skills/refactoring-patterns/references/organizing-data.md @@ -0,0 +1,433 @@ +# Organizing Data + +Detailed reference for refactorings that improve how data is represented. Raw primitives, magic numbers, exposed fields, and mutable collections create subtle bugs and scatter domain knowledge. These refactorings replace primitive representations with objects that encapsulate behavior and enforce invariants. + +## Table of Contents +1. [Replace Data Value with Object](#replace-data-value-with-object) +2. [Change Value to Reference](#change-value-to-reference) +3. [Replace Array with Object](#replace-array-with-object) +4. [Replace Magic Number with Symbolic Constant](#replace-magic-number-with-symbolic-constant) +5. [Encapsulate Field](#encapsulate-field) +6. [Encapsulate Collection](#encapsulate-collection) +7. [Replace Type Code with Class](#replace-type-code-with-class) +8. [Decision Guide: Which Data Refactoring to Use](#decision-guide-which-data-refactoring-to-use) + +--- + +## Replace Data Value with Object + +Wrap a primitive data item in a class when it has behavior or validation associated with it. This is the cure for Primitive Obsession. + +### Motivation + +A data value starts life as a simple string or number. Then you add validation. Then formatting. Then comparison logic. Then the same validation appears in three places. At that point, the value deserves to be an object. + +### Mechanics + +1. Create a class for the value with a constructor that takes the primitive +2. Add validation in the constructor +3. Add any behavior methods (formatting, comparison, etc.) +4. Change the field type from primitive to the new class +5. Update all code that sets the field to create an instance of the new class +6. Update all code that reads the field to use the object's methods +7. Run tests + +### Example + +**Before:** +```javascript +class Order { + constructor(customer) { + this.customer = customer; // just a string name + } +} + +// Scattered validation in multiple places: +if (order.customer === '') throw new Error('no customer'); +if (otherOrder.customer === '') throw new Error('no customer'); +``` + +**After:** +```javascript +class Customer { + constructor(name) { + if (!name || name.trim() === '') { + throw new Error('Customer name is required'); + } + this._name = name.trim(); + } + + get name() { return this._name; } + + equals(other) { + return other instanceof Customer && this._name === other._name; + } +} + +class Order { + constructor(customer) { + this.customer = new Customer(customer); + } +} +``` + +### Common Primitive-to-Object Upgrades + +| Primitive | Object | Behavior It Gains | +|-----------|--------|-------------------| +| `String email` | `EmailAddress` | Format validation, domain extraction | +| `number cents` | `Money` | Currency, rounding rules, arithmetic | +| `String phone` | `PhoneNumber` | Formatting, country code parsing | +| `number lat, number lng` | `Coordinates` | Distance calculation, validation | +| `String startDate, String endDate` | `DateRange` | Contains, overlaps, duration | +| `number celsius` | `Temperature` | Unit conversion, comparison | +| `String hex` | `Color` | Parsing, lightness, contrast | +| `number status` | `OrderStatus` | Valid transitions, display name | + +--- + +## Change Value to Reference + +Convert a value object into a reference object when you need identity semantics -- when changes to one instance should be visible everywhere that instance is used. + +### Motivation + +When you have multiple copies of the same customer, changing the phone number on one doesn't change it on the others. If business rules require a single shared instance, convert value to reference using a registry or repository. + +### Mechanics + +1. Determine or create a factory method for the object +2. Set up a registry (map, repository, or lookup service) to store instances +3. Change the factory to check the registry before creating new instances +4. Change client code to use the factory instead of the constructor +5. Run tests + +### Example + +```javascript +// Registry pattern: +class CustomerRepository { + constructor() { + this._customers = new Map(); + } + + get(id) { + if (!this._customers.has(id)) { + this._customers.set(id, new Customer(id)); + } + return this._customers.get(id); + } +} + +// All orders for customer #123 now share the same Customer object +const repo = new CustomerRepository(); +const order1 = new Order(repo.get(123)); +const order2 = new Order(repo.get(123)); +// order1.customer === order2.customer // true (same reference) +``` + +### Value vs. Reference: Decision Guide + +| Question | Value | Reference | +|----------|-------|-----------| +| Do you need identity (same object everywhere)? | No | Yes | +| Is the object immutable? | Typically | May be mutable | +| Do you compare by content? | Yes (`equals()`) | No (identity `===`) | +| Examples | Money, DateRange, Color | Customer, Account, Product | + +--- + +## Replace Array with Object + +Replace an array used as a record (where each position has a different meaning) with an object with named fields. + +### Motivation + +`row[0]` is the name, `row[1]` is the age, `row[2]` is the department. This is fragile, unreadable, and type-unsafe. Named fields make the structure self-documenting. + +### Mechanics + +1. Create a class with a field for each array position +2. Add getters and setters for each field +3. Replace array creation with object construction +4. Replace positional access with named access +5. Run tests + +### Example + +**Before:** +```python +performance = ["Liverpool", 15, 2] +name = performance[0] +wins = performance[1] +losses = performance[2] +``` + +**After:** +```python +class Performance: + def __init__(self, name, wins, losses): + self.name = name + self.wins = wins + self.losses = losses + +performance = Performance("Liverpool", 15, 2) +name = performance.name +wins = performance.wins +losses = performance.losses +``` + +--- + +## Replace Magic Number with Symbolic Constant + +Replace a literal number that has a particular meaning with a named constant. + +### Motivation + +`9.81` means nothing in code. `GRAVITATIONAL_ACCELERATION = 9.81` communicates intent, prevents typos (the constant name is checked by the compiler), and centralizes the value for easy change. + +### Mechanics + +1. Declare a constant and set it to the magic number +2. Find all occurrences of the magic number +3. Replace each occurrence with the constant (check that each occurrence represents the same concept -- the number `100` might mean "percentage" in one place and "max items" in another) +4. Run tests + +### Common Magic Number Categories + +| Category | Before | After | +|----------|--------|-------| +| Physics | `9.81` | `GRAVITATIONAL_ACCELERATION` | +| Business rules | `0.08` | `SALES_TAX_RATE` | +| Limits | `255` | `MAX_RGB_VALUE` | +| HTTP | `404` | `HTTP_NOT_FOUND` | +| Time | `86400` | `SECONDS_PER_DAY` | +| Retry | `3` | `MAX_RETRY_ATTEMPTS` | +| Thresholds | `100` | `FREE_SHIPPING_THRESHOLD` | + +### When NOT to Replace + +- `0` and `1` in arithmetic are usually fine as literals +- Loop counters (`for i in range(10)`) are obvious from context +- Array index `[0]` for "first element" is idiomatic + +--- + +## Encapsulate Field + +Replace direct access to a public field with getter and setter methods. + +### Motivation + +A public field gives you no control over reads and writes. You can't add validation, logging, lazy initialization, or computed values later without changing every caller. Encapsulation creates a seam for future change. + +### Mechanics + +1. Create getter and setter methods for the field +2. Find all references to the field and replace reads with the getter, writes with the setter +3. Make the field private +4. Run tests + +### Example + +**Before:** +```python +class Person: + def __init__(self, name): + self.name = name # public field + +# Client: +person.name = " Bob " # no validation, no trimming +``` + +**After:** +```python +class Person: + def __init__(self, name): + self._name = None + self.name = name # uses the setter + + @property + def name(self): + return self._name + + @name.setter + def name(self, value): + if not value or not value.strip(): + raise ValueError("Name cannot be empty") + self._name = value.strip() +``` + +--- + +## Encapsulate Collection + +Don't return a raw mutable collection from a getter. Instead, return an unmodifiable view or a copy, and provide explicit add/remove methods. + +### Motivation + +When a getter returns a mutable list, callers can add, remove, or clear items without the owning object knowing. This breaks encapsulation -- the object can't enforce invariants, fire events, or validate changes. + +### Mechanics + +1. Add `addItem()` and `removeItem()` methods on the owning class +2. Change the getter to return an unmodifiable view (or a copy) +3. Find all callers that mutate the collection through the getter and change them to use the add/remove methods +4. Run tests + +### Example + +**Before:** +```javascript +class Course {} + +class Person { + get courses() { return this._courses; } + set courses(list) { this._courses = list; } +} + +// Client can mutate freely: +person.courses.push(newCourse); // bypasses Person +person.courses.splice(0, 1); // bypasses Person +person.courses = []; // replaces internal state +``` + +**After:** +```javascript +class Person { + get courses() { + return [...this._courses]; // return a copy + } + + addCourse(course) { + this._courses.push(course); + } + + removeCourse(course) { + const index = this._courses.indexOf(course); + if (index === -1) throw new RangeError('Course not found'); + this._courses.splice(index, 1); + } + + get numberOfCourses() { + return this._courses.length; + } +} +``` + +### Language-Specific Patterns + +| Language | Unmodifiable Return | +|----------|-------------------| +| Java | `Collections.unmodifiableList(list)` | +| JavaScript | `[...this._items]` or `Object.freeze([...this._items])` | +| Python | `tuple(self._items)` or `list(self._items)` (return a copy) | +| C# | `items.AsReadOnly()` | +| Go | Return a slice copy: `append([]T{}, items...)` | + +--- + +## Replace Type Code with Class + +Replace a type code (integer or string constant) that does not affect behavior with a proper class. Use when the type code is used for categorization but doesn't drive conditional logic. + +### When to Use Which + +| Situation | Refactoring | +|-----------|-------------| +| Type code is informational only (no behavior change) | Replace Type Code with Class | +| Type code drives behavior via conditionals | Replace Type Code with Subclasses | +| Type code can change at runtime | Replace Type Code with Strategy/State | +| Type code has few values and language supports it | Use an Enum | + +### Replace Type Code with Subclasses + +Used when the type code determines behavior through conditionals. + +**Before:** +```javascript +class Employee { + constructor(type) { + this._type = type; // 'engineer', 'manager', 'salesperson' + } + + calculatePay() { + switch (this._type) { + case 'engineer': return this.basePay; + case 'manager': return this.basePay + this.bonus; + case 'salesperson': return this.basePay + this.commission; + } + } + + canApproveExpenses() { + return this._type === 'manager'; + } +} +``` + +**After:** +```javascript +class Employee { + calculatePay() { throw new Error('abstract'); } + canApproveExpenses() { return false; } +} + +class Engineer extends Employee { + calculatePay() { return this.basePay; } +} + +class Manager extends Employee { + calculatePay() { return this.basePay + this.bonus; } + canApproveExpenses() { return true; } +} + +class Salesperson extends Employee { + calculatePay() { return this.basePay + this.commission; } +} +``` + +### Replace Type Code with Strategy/State + +Used when the type code can change at runtime (an employee can be promoted from engineer to manager), so subclassing the employee itself is not possible. + +**After (Strategy):** +```javascript +class Employee { + constructor(type) { + this._type = type; // EmployeeType strategy object + } + + calculatePay() { + return this._type.calculatePay(this); + } + + promoteToManager() { + this._type = new ManagerType(); + } +} + +class EngineerType { + calculatePay(employee) { return employee.basePay; } +} + +class ManagerType { + calculatePay(employee) { return employee.basePay + employee.bonus; } +} +``` + +--- + +## Decision Guide: Which Data Refactoring to Use + +| Situation | Refactoring | +|-----------|-------------| +| Primitive value has associated behavior | Replace Data Value with Object | +| Need one shared instance across the system | Change Value to Reference | +| Array positions have different meanings | Replace Array with Object | +| Literal number has domain meaning | Replace Magic Number with Symbolic Constant | +| Public field needs future flexibility | Encapsulate Field | +| Getter returns mutable collection | Encapsulate Collection | +| Type code is informational | Replace Type Code with Class / Enum | +| Type code drives behavior | Replace Type Code with Subclasses | +| Type code changes at runtime | Replace Type Code with Strategy | diff --git a/.claude/skills/refactoring-patterns/references/refactoring-workflow.md b/.claude/skills/refactoring-patterns/references/refactoring-workflow.md new file mode 100644 index 0000000..4af58ca --- /dev/null +++ b/.claude/skills/refactoring-patterns/references/refactoring-workflow.md @@ -0,0 +1,373 @@ +# Refactoring Workflow + +Detailed reference for when and how to refactor safely. The discipline of refactoring is as important as knowing the individual transformations. This reference covers the refactoring cycle, timing, safety techniques, and strategies for large-scale refactoring in production systems. + +## Table of Contents +1. [The Refactoring Cycle](#the-refactoring-cycle) +2. [When to Refactor](#when-to-refactor) +3. [When NOT to Refactor](#when-not-to-refactor) +4. [Testing and Refactoring](#testing-and-refactoring) +5. [Refactoring and Performance](#refactoring-and-performance) +6. [Branch by Abstraction](#branch-by-abstraction) +7. [Parallel Change (Expand-Migrate-Contract)](#parallel-change-expand-migrate-contract) +8. [Large-Scale Refactoring Strategies](#large-scale-refactoring-strategies) +9. [Refactoring Checklist](#refactoring-checklist) + +--- + +## The Refactoring Cycle + +Every refactoring follows the same four-step loop: + +``` +1. Run tests → GREEN +2. Apply one small structural change +3. Run tests → GREEN +4. Commit +``` + +**Then repeat.** + +### Why Small Steps Matter + +| Approach | Risk | Recovery Time | +|----------|------|---------------| +| One refactoring at a time | Minimal -- if tests fail, the cause is obvious | Seconds (revert one change) | +| Several refactorings between tests | Medium -- must debug to find which one broke | Minutes | +| Big-bang rewrite | Maximum -- structural and behavioral changes mixed | Hours to days (or never) | + +**Rule:** If a test fails after a refactoring step, **revert immediately**. Don't debug. The step was too big or wrong. Revert, think, try a smaller step. + +### The Two Hats + +Martin Fowler describes two distinct modes of work. You wear only one "hat" at a time: + +| Hat | What You Do | What You Don't Do | +|-----|-------------|-------------------| +| **Refactoring** | Change structure, keep behavior identical | Add features, fix bugs, change tests | +| **Adding Function** | Add new behavior, write new tests | Change existing code structure | + +**Switching hats:** You may alternate frequently, but never wear both at once. A typical sequence: + +1. Refactoring hat: restructure to make the new feature easy to add. Commit. +2. Adding-function hat: add the feature and its tests. Commit. +3. Refactoring hat: clean up any mess the new feature introduced. Commit. + +--- + +## When to Refactor + +### Preparatory Refactoring (Refactor to Make the Change Easy) + +**Trigger:** You're about to add a feature, and the code isn't structured to accommodate it easily. + +**Example:** You need to add a new payment method. The payment logic is in a long if/else chain. Before adding the new branch, refactor to Replace Conditional with Polymorphism. Now adding the new payment method means creating one new class. + +**Kent Beck's quote:** "Make the change easy (warning: this may be hard), then make the easy change." + +**The payoff:** The feature is faster to add, less likely to contain bugs, and the refactoring improves the code for all future changes, not just this one. + +### Comprehension Refactoring (Refactor to Understand) + +**Trigger:** You're reading code and struggling to understand it. Rename variables, extract methods, and reorganize to make the code express its intent. + +**Example:** You encounter a function called `calc` with variables named `a`, `b`, and `temp`. As you figure out what each does, rename them: `calculateMonthlyPayment`, `principal`, `interestRate`, `monthlyAmount`. The understanding you gain is encoded in the code itself. + +**Ward Cunningham's insight:** "By refactoring, I move the understanding from my head into the code itself." + +### Litter-Pickup Refactoring (Boy Scout Rule) + +**Trigger:** You touch a file for any reason and notice a small improvement you can make. Do it. + +**Examples:** +- Rename a misleading variable name +- Extract a method from a long function +- Remove dead code +- Add a missing guard clause + +**The rule:** Leave the code cleaner than you found it. Each small improvement compounds over time. A codebase that is consistently cleaned by every developer who touches it stays healthy. + +### Rule of Three + +**Trigger:** The third time you see duplicated code or a repeated pattern. + +**The progression:** +1. First time: Write it +2. Second time: Wince at the duplication but tolerate it +3. Third time: Refactor -- extract the common pattern + +**Why three, not two:** Premature abstraction is as dangerous as duplication. Two occurrences might be coincidental. Three confirms the pattern. + +### Long-Term Refactoring + +**Trigger:** A large structural problem that can't be fixed in one session. + +**Examples:** +- Replacing a library or framework +- Splitting a monolith into modules +- Changing a pervasive data representation + +**Approach:** The team agrees on a target architecture. Everyone makes small changes toward it during regular work. No one stops feature development for a "refactoring sprint." + +--- + +## When NOT to Refactor + +Not every piece of code deserves refactoring. Save your effort for code that justifies it. + +### Code You Should Leave Alone + +| Situation | Why | +|-----------|-----| +| The code works and nobody needs to modify it | If it's behind a clean interface, its internal messiness costs nothing | +| It's easier to rewrite from scratch | If the code is small and the rewrite is straightforward, don't polish what you'll replace | +| There are no tests and adding them is impractical | Refactoring without tests is too risky; consider characterization tests first | +| The code will be deleted soon | Don't beautify code with a known end-of-life | +| You're exploring or prototyping | Throwaway code benefits from speed, not structure | + +### The "Messy Middle" Trap + +Some teams swing between two extremes: +- **Never refactor:** Technical debt accumulates until development grinds to a halt +- **Always refactor:** Gold-plating code that doesn't need it, shipping features slowly + +The right balance: **Refactor code that you're about to change, or code that's actively hurting velocity.** Don't refactor code just because it's not beautiful. + +--- + +## Testing and Refactoring + +### The Safety Net + +Tests are not optional for refactoring. Without them, you cannot verify that behavior is preserved. + +| Test Type | Role in Refactoring | +|-----------|-------------------| +| Unit tests | Fast feedback on individual method behavior | +| Integration tests | Verify behavior across collaborating objects | +| Characterization tests | Capture existing behavior of legacy code (the starting point) | +| Regression tests | Ensure the entire system still works after changes | + +### Characterization Tests + +When you encounter code without tests that you need to refactor: + +1. Run the code with known inputs +2. Observe the actual outputs (even if you think they're "wrong") +3. Write tests that assert the actual current behavior +4. Now you have a safety net -- refactor freely + +**Example:** +```python +def test_weird_edge_case(): + # This behavior may be "wrong" but it's what exists. + # Capture it so refactoring doesn't accidentally change it. + result = calculate_shipping(weight=0, distance=100) + assert result == 5.99 # Captures existing behavior +``` + +### Test-Driven Refactoring Steps + +1. **Before starting:** Run all tests. If any fail, fix them first. +2. **After each refactoring step:** Run tests. All must pass. +3. **If a test fails:** Revert immediately. Don't debug. +4. **After completing a logical group of refactorings:** Commit. +5. **If you discover a bug during refactoring:** Stop refactoring. Fix the bug (adding-function hat). Then resume refactoring. + +--- + +## Refactoring and Performance + +### The Common Fear + +"Won't all these small methods and indirection make the code slower?" + +### The Reality + +1. Most performance concerns about refactored code are unfounded. Modern compilers and runtimes inline small methods. +2. Performance bottlenecks are almost never where you think they are. Profile first. +3. Well-structured code is **easier** to optimize because the hot path is isolated. + +### The Three-Step Performance Strategy + +1. **Write clear code first.** Don't optimize during refactoring. +2. **Profile the running system.** Find the actual bottleneck (usually 10% of the code causes 90% of the performance issue). +3. **Optimize only the measured hot path.** Well-refactored code makes this easy because the hot path is in a small, isolated method. + +### When Refactoring Genuinely Hurts Performance + +| Refactoring | Potential Cost | Mitigation | +|-------------|---------------|------------| +| Replace Temp with Query | Method called multiple times instead of cached once | Cache if profiling shows impact | +| Extract Method | Additional method call overhead | Usually inlined by the compiler/JIT | +| Replace Conditional with Polymorphism | Virtual dispatch instead of branch | Negligible in most cases; profile if in doubt | +| Introduce Parameter Object | Object allocation for each call | Often optimized away; pool if necessary | + +**Key insight:** Optimization and refactoring are separate concerns. Refactor first for clarity, then optimize the measured bottleneck. + +--- + +## Branch by Abstraction + +A technique for making large-scale changes to a widely-used component without creating a long-lived feature branch. + +### When to Use + +- Replacing a framework, library, or major internal component +- The replacement will take weeks or months +- You need to keep shipping features during the transition +- Feature branches would become stale and cause merge conflicts + +### How It Works + +``` +Step 1: Identify the component to replace (OldComponent) +Step 2: Create an abstraction layer (interface) that wraps OldComponent +Step 3: Change all callers to use the abstraction (deploy incrementally) +Step 4: Create NewComponent that implements the same abstraction +Step 5: Switch the abstraction to point to NewComponent (one change, deploy) +Step 6: Remove OldComponent and the abstraction layer (clean up) +``` + +### Example + +**Step 1-2:** Introduce the abstraction +```python +# Before: callers use OldPaymentGateway directly +class OldPaymentGateway: + def charge(self, amount, card): ... + +# After: introduce abstraction +class PaymentGateway(ABC): + @abstractmethod + def charge(self, amount, card): ... + +class OldPaymentGateway(PaymentGateway): + def charge(self, amount, card): ... # existing implementation +``` + +**Step 3:** Migrate callers to use `PaymentGateway` (the abstraction). Deploy. + +**Step 4:** Build `NewPaymentGateway(PaymentGateway)`. Test thoroughly. + +**Step 5:** Switch the wiring: +```python +# In configuration: +# gateway = OldPaymentGateway() # old +gateway = NewPaymentGateway() # new +``` + +**Step 6:** Delete `OldPaymentGateway`. Optionally inline the abstraction if only one implementation remains. + +--- + +## Parallel Change (Expand-Migrate-Contract) + +A technique for making breaking API changes safely by running old and new versions side by side. + +### When to Use + +- Renaming a widely-used method or changing its signature +- Changing a data format while consumers still read the old format +- Migrating from one API to another when you can't update all consumers at once + +### The Three Phases + +**1. Expand:** Add the new version alongside the old one. +```python +class User: + def get_full_name(self): # new name + return f"{self.first} {self.last}" + + def getFullName(self): # old name, still works + return self.get_full_name() # delegates to new +``` + +**2. Migrate:** Update all callers to use the new version. This can happen incrementally across multiple deployments. + +**3. Contract:** Remove the old version once all callers have migrated. +```python +class User: + def get_full_name(self): # only the new version remains + return f"{self.first} {self.last}" +``` + +### Parallel Change for Data + +``` +1. Expand: Write to both old and new columns/formats +2. Migrate: Update all readers to use the new format +3. Contract: Stop writing the old format, remove old column +``` + +--- + +## Large-Scale Refactoring Strategies + +### The Strangler Fig Pattern + +Gradually replace a legacy system by building new functionality around it, routing more and more traffic to the new system until the old one can be decommissioned. + +| Phase | Action | +|-------|--------| +| 1. Intercept | Place a routing layer in front of the legacy system | +| 2. Build new | Implement new components behind the router | +| 3. Redirect | Route requests to new components as they're ready | +| 4. Retire | Decommission old components once no traffic reaches them | + +### Mikado Method + +For complex refactorings with many interdependencies: + +1. Try the refactoring you want to make +2. If it breaks, note what needs to change first (the prerequisites) +3. Revert your change +4. Recursively fix the prerequisites (each may have its own prerequisites) +5. Build a dependency graph (the "Mikado Graph") +6. Solve the graph from the leaves (no-dependency tasks) toward the root + +### Feature Toggles During Refactoring + +Use feature flags to gradually roll out a refactored component: + +```python +if feature_flag('new_pricing_engine'): + return new_pricing_engine.calculate(order) +else: + return old_pricing_engine.calculate(order) +``` + +This allows: +- Incremental rollout (10% of traffic, then 50%, then 100%) +- Instant rollback by toggling the flag +- A/B comparison of old vs. new behavior + +--- + +## Refactoring Checklist + +Use this checklist before, during, and after refactoring sessions: + +### Before Starting + +- [ ] All existing tests pass (green) +- [ ] You've identified the specific smell or improvement target +- [ ] You can name the refactoring(s) you'll apply +- [ ] The code has test coverage for the area you'll change (add characterization tests if not) + +### During Refactoring + +- [ ] Each step is the smallest possible transformation +- [ ] Tests run after every step +- [ ] You revert immediately if tests fail (don't debug) +- [ ] You're wearing only the refactoring hat (no new features) +- [ ] You commit after each logical group of steps + +### After Completing + +- [ ] All tests still pass +- [ ] The code is easier to read than before +- [ ] Variable and method names reveal intent +- [ ] No unnecessary comments remain (the code explains itself) +- [ ] No new smells were introduced +- [ ] Changes are committed with a clear message describing the refactoring diff --git a/.claude/skills/refactoring-patterns/references/simplifying-conditionals.md b/.claude/skills/refactoring-patterns/references/simplifying-conditionals.md new file mode 100644 index 0000000..f31bca1 --- /dev/null +++ b/.claude/skills/refactoring-patterns/references/simplifying-conditionals.md @@ -0,0 +1,385 @@ +# Simplifying Conditional Logic + +Detailed reference for refactorings that tame complex conditional structures. Conditionals are the hardest code to read and the most likely to harbor bugs. These refactorings decompose, consolidate, and replace conditionals with clearer alternatives. + +## Table of Contents +1. [Decompose Conditional](#decompose-conditional) +2. [Consolidate Conditional Expression](#consolidate-conditional-expression) +3. [Replace Nested Conditional with Guard Clauses](#replace-nested-conditional-with-guard-clauses) +4. [Replace Conditional with Polymorphism](#replace-conditional-with-polymorphism) +5. [Introduce Special Case (Null Object)](#introduce-special-case-null-object) +6. [Introduce Assertion](#introduce-assertion) +7. [Decision Guide: Which Conditional Refactoring to Use](#decision-guide-which-conditional-refactoring-to-use) + +--- + +## Decompose Conditional + +Extract the condition, the then-branch, and the else-branch of a complex conditional into well-named methods. + +### Motivation + +A long `if` statement with a compound condition and multi-line branches forces the reader to simulate every path mentally. By naming each part, you turn the conditional into readable prose. + +### Mechanics + +1. Extract the condition into a method whose name describes the meaning (not the mechanics) +2. Extract the then-body into a method whose name describes what happens +3. Extract the else-body into a method whose name describes what happens +4. Run tests + +### Example + +**Before:** +```javascript +function calculateCharge(date, quantity, plan) { + let charge; + if (date.getMonth() >= 6 && date.getMonth() <= 8) { + charge = quantity * plan.summerRate; + } else { + charge = quantity * plan.regularRate + plan.regularServiceCharge; + } + return charge; +} +``` + +**After:** +```javascript +function calculateCharge(date, quantity, plan) { + if (isSummer(date)) { + return summerCharge(quantity, plan); + } else { + return regularCharge(quantity, plan); + } +} + +function isSummer(date) { + return date.getMonth() >= 6 && date.getMonth() <= 8; +} + +function summerCharge(quantity, plan) { + return quantity * plan.summerRate; +} + +function regularCharge(quantity, plan) { + return quantity * plan.regularRate + plan.regularServiceCharge; +} +``` + +### Naming the Condition + +| Condition Expression | Good Name | +|---------------------|-----------| +| `date.getMonth() >= 6 && date.getMonth() <= 8` | `isSummer(date)` | +| `user.age >= 18 && user.hasConsent` | `isEligible(user)` | +| `cart.total > 100 && !cart.hasPromo` | `qualifiesForDiscount(cart)` | +| `retries < MAX && !response.ok` | `shouldRetry(retries, response)` | +| `file.size > 0 && file.ext === '.csv'` | `isValidUpload(file)` | + +The condition name should answer a yes/no question using the domain vocabulary. + +--- + +## Consolidate Conditional Expression + +Combine a series of conditional checks that all lead to the same result into a single conditional with a descriptive name. + +### Motivation + +When multiple conditions return the same value, combining them into one named check makes the logic clearer: "All of these mean the same thing -- this situation is X." + +### Mechanics + +1. Verify that all the conditionals have no side effects +2. Combine using logical operators (`&&`, `||`) +3. Extract the combined condition into a named method +4. Run tests + +### Example + +**Before:** +```python +def disability_amount(employee): + if employee.seniority < 2: + return 0 + if employee.months_disabled > 12: + return 0 + if employee.is_part_time: + return 0 + # compute disability amount... + return base_amount * 1.5 +``` + +**After:** +```python +def disability_amount(employee): + if is_not_eligible_for_disability(employee): + return 0 + return base_amount * 1.5 + +def is_not_eligible_for_disability(employee): + return (employee.seniority < 2 + or employee.months_disabled > 12 + or employee.is_part_time) +``` + +### When to Consolidate vs. Keep Separate + +| Situation | Action | +|-----------|--------| +| All conditions mean the same business concept | Consolidate into one named check | +| Conditions are independent with different reasons | Keep separate (each deserves its own name) | +| Conditions should be evaluated in sequence for performance | Keep separate for short-circuit clarity | + +--- + +## Replace Nested Conditional with Guard Clauses + +Handle special cases and edge conditions at the top of the method and return early, leaving the main path of execution flat and unindented. + +### Motivation + +Deeply nested `if/else` structures obscure the normal path. Guard clauses make it clear: "These are the edge cases. Now here's the main logic." The main path runs at the lowest indentation level. + +### Mechanics + +1. Identify each edge case or special condition +2. Move it to the top of the method as an `if (condition) return earlyValue;` +3. Remove the corresponding `else` and reduce indentation +4. Run tests + +### Example + +**Before:** +```javascript +function payAmount(employee) { + let result; + if (employee.isSeparated) { + result = { amount: 0, reasonCode: 'SEP' }; + } else { + if (employee.isRetired) { + result = { amount: 0, reasonCode: 'RET' }; + } else { + // main calculation + result = { + amount: employee.salary * employee.rate, + reasonCode: 'REG' + }; + } + } + return result; +} +``` + +**After:** +```javascript +function payAmount(employee) { + if (employee.isSeparated) return { amount: 0, reasonCode: 'SEP' }; + if (employee.isRetired) return { amount: 0, reasonCode: 'RET' }; + + return { + amount: employee.salary * employee.rate, + reasonCode: 'REG' + }; +} +``` + +### Guard Clause Patterns + +| Pattern | Example | +|---------|---------| +| Null check | `if (input == null) return defaultValue;` | +| Empty check | `if (items.length === 0) return [];` | +| Permission check | `if (!user.canEdit) throw new ForbiddenError();` | +| Boundary check | `if (index < 0 \|\| index >= size) throw new RangeError();` | +| Status check | `if (order.isCancelled) return zeroPay();` | + +### "One return" vs. Guard Clauses + +Some coding standards mandate a single return statement per method. This leads to deeply nested conditionals and temporary result variables. Guard clauses with early returns produce clearer, flatter code. Fowler explicitly recommends guard clauses over single-return for methods with special cases. + +--- + +## Replace Conditional with Polymorphism + +Replace a conditional that checks a type, status, or category and branches to different behavior with polymorphic classes where each type provides its own implementation. + +### Motivation + +This is the gold standard for eliminating type-based conditionals. Instead of one function that knows about every type, each type knows about itself. Adding a new type means adding a new class -- not editing existing conditionals in multiple places (Open/Closed Principle). + +### Mechanics + +1. If the conditional is based on a type code, apply Replace Type Code with Subclasses first +2. Create a base method (possibly abstract) in the superclass +3. Copy each branch of the conditional into the corresponding subclass as an override +4. Remove the conditional from the superclass (or make it the default case) +5. Run tests + +### Example + +**Before:** +```python +class Bird: + def __init__(self, bird_type, voltage=0, coconut_count=0): + self.type = bird_type + self.voltage = voltage + self.coconut_count = coconut_count + + def speed(self): + if self.type == 'european': + return 35 - (self.voltage / 10) + elif self.type == 'african': + return 40 - (2 * self.coconut_count) + elif self.type == 'norwegian_blue': + return 0 if self.voltage > 100 else 10 + (self.voltage / 10) + else: + raise ValueError(f"Unknown bird type: {self.type}") +``` + +**After:** +```python +class Bird: + def speed(self): + raise NotImplementedError + +class EuropeanSwallow(Bird): + def speed(self): + return 35 - (self.voltage / 10) + +class AfricanSwallow(Bird): + def speed(self): + return 40 - (2 * self.coconut_count) + +class NorwegianBlueParrot(Bird): + def speed(self): + return 0 if self.voltage > 100 else 10 + (self.voltage / 10) +``` + +### When to Use Polymorphism vs. Keep the Conditional + +| Situation | Recommendation | +|-----------|---------------| +| Conditional appears in multiple methods | Polymorphism -- types know their own behavior | +| Only one method has the conditional | May be overkill -- Decompose Conditional may suffice | +| New types are added frequently | Polymorphism -- Open/Closed Principle | +| The set of types is fixed and small (e.g., 2-3) | Conditional may be simpler | +| Behavior varies by a code that changes at runtime | Use Strategy pattern instead of inheritance | + +--- + +## Introduce Special Case (Null Object) + +Instead of checking for a special case (usually null) in every caller, create a class that encapsulates the special-case behavior. + +### Motivation + +`if (customer == null)` checks scattered through the codebase add noise and are easy to forget. A `NullCustomer` or `UnknownCustomer` object responds to all the same methods with safe default behavior. + +### Mechanics + +1. Create a subclass or separate class for the special case +2. Add a method to the superclass or factory that creates the special case (e.g., `Customer.unknown()`) +3. Implement each method in the special case with the default behavior that callers currently use after their null checks +4. Change callers to use the special case object instead of null +5. Remove the null checks from callers +6. Run tests + +### Example + +**Before:** +```javascript +// Scattered throughout the codebase: +const customerName = (customer !== null) ? customer.name : 'Occupant'; +const billingPlan = (customer !== null) ? customer.billingPlan : BillingPlan.basic(); +const paymentHistory = (customer !== null) ? customer.paymentHistory : new NullPaymentHistory(); +``` + +**After:** +```javascript +class UnknownCustomer { + get name() { return 'Occupant'; } + get billingPlan() { return BillingPlan.basic(); } + get paymentHistory() { return new NullPaymentHistory(); } + get isUnknown() { return true; } +} + +class Customer { + get isUnknown() { return false; } + // ... normal implementation +} + +// Callers (no more null checks): +const customerName = customer.name; +const billingPlan = customer.billingPlan; +``` + +### Common Special Cases + +| Domain | Special Case Object | Default Behavior | +|--------|-------------------|------------------| +| Customer | `UnknownCustomer` | Returns "Occupant", basic plan | +| Currency | `NullMoney` | Zero amount, no currency | +| Logger | `NullLogger` | Silently discards all messages | +| Permission | `DeniedPermission` | Returns false for all checks | +| Config | `DefaultConfig` | Returns sensible defaults | +| User | `AnonymousUser` | Read-only, no privileges | + +--- + +## Introduce Assertion + +Make an assumption explicit by inserting an assertion that will fail fast if the assumption is violated. + +### Motivation + +Assertions document what the code expects to be true. They are executable documentation that catches bugs during development. Unlike comments, assertions are verified by the runtime. + +### Mechanics + +1. Identify an assumption in the code (a condition that should always be true) +2. Insert an assertion at the point where the assumption is made +3. Ensure the assertion does not have side effects +4. Run tests (they should still pass -- if an assertion fails, you found a bug) + +### Example + +**Before:** +```python +def apply_discount(product, discount_rate): + # discount should be between 0 and 1 + price = product.base_price * (1 - discount_rate) + return price +``` + +**After:** +```python +def apply_discount(product, discount_rate): + assert 0 <= discount_rate <= 1, f"Discount rate must be 0-1, got {discount_rate}" + price = product.base_price * (1 - discount_rate) + return price +``` + +### Assertion Guidelines + +| Guideline | Rationale | +|-----------|-----------| +| Never use assertions for input validation | Assertions can be disabled in production; use exceptions for untrusted input | +| Use assertions for programmer errors | Conditions that should never occur if the code is correct | +| Keep assertion messages descriptive | Include the actual value and the expected constraint | +| Don't put side effects in assertions | `assert items.remove(x)` breaks when assertions are disabled | + +--- + +## Decision Guide: Which Conditional Refactoring to Use + +| Situation | Refactoring | +|-----------|-------------| +| Long, complex condition expression | Decompose Conditional | +| Multiple conditions lead to same result | Consolidate Conditional Expression | +| Nested if/else with special cases | Replace Nested Conditional with Guard Clauses | +| Switch/if on type code in multiple places | Replace Conditional with Polymorphism | +| Null checks scattered everywhere | Introduce Special Case (Null Object) | +| Hidden assumption in code logic | Introduce Assertion | +| Condition appears once, set of types is small | Keep the conditional, but Decompose it | +| Condition varies at runtime | Use Strategy pattern | diff --git a/.claude/skills/refactoring-patterns/references/smell-catalog.md b/.claude/skills/refactoring-patterns/references/smell-catalog.md new file mode 100644 index 0000000..0c6db12 --- /dev/null +++ b/.claude/skills/refactoring-patterns/references/smell-catalog.md @@ -0,0 +1,347 @@ +# Code Smell Catalog + +A comprehensive catalog of code smells organized by family. Each smell includes a description, detection heuristics, and the named refactorings that fix it. + + +## Table of Contents +1. [What Is a Code Smell?](#what-is-a-code-smell) +2. [Family 1: Bloaters](#family-1-bloaters) +3. [Family 2: Object-Orientation Abusers](#family-2-object-orientation-abusers) +4. [Family 3: Change Preventers](#family-3-change-preventers) +5. [Family 4: Dispensables](#family-4-dispensables) +6. [Family 5: Couplers](#family-5-couplers) +7. [Smell-to-Refactoring Quick Reference](#smell-to-refactoring-quick-reference) + +--- + +## What Is a Code Smell? + +A code smell is a surface indication that usually corresponds to a deeper structural problem. Smells are not bugs -- the code works correctly -- but they make the code harder to understand, extend, and maintain. The term was coined by Kent Beck and popularized by Martin Fowler. + +**Key principles:** +- Smells are heuristics, not rules -- use judgment +- A smell that causes no real problem in context can be left alone +- Smells cluster: fixing one often reveals others nearby +- The "smell → refactoring" mapping is many-to-many; one smell may require several refactorings + +--- + +## Family 1: Bloaters + +Smells where code grows too large to work with effectively. + +### Long Method + +**Description:** A method that tries to do too much. The longer a method is, the harder it is to understand, test, and reuse. + +**Detection heuristics:** +- More than 10-15 lines of executable code +- Multiple levels of indentation +- Comments separating "sections" within the method +- Multiple responsibilities visible in one scan +- Difficulty naming the method because it does several things + +**Typical fixes:** +- Extract Method -- pull each logical section into a named method +- Replace Temp with Query -- eliminate temporaries that block extraction +- Replace Method with Method Object -- when extraction is blocked by tangled local variables +- Decompose Conditional -- when the length comes from complex branching + +**Example smell:** +``` +function processOrder(order) { + // validate order + if (!order.items || order.items.length === 0) { ... } + if (!order.customer) { ... } + // calculate totals + let subtotal = 0; + for (const item of order.items) { subtotal += item.price * item.qty; } + let tax = subtotal * 0.08; + let shipping = subtotal > 100 ? 0 : 9.99; + // apply discounts + if (order.customer.isPremium) { ... } + // save to database + db.save({ ...order, subtotal, tax, shipping }); + // send confirmation + emailService.send(order.customer.email, ...); +} +``` + +Each comment block should be its own method: `validateOrder()`, `calculateTotals()`, `applyDiscounts()`, `saveOrder()`, `sendConfirmation()`. + +### Large Class + +**Description:** A class that has too many fields, too many methods, or too many responsibilities. Often called a "God Class" or "Blob." + +**Detection heuristics:** +- More than 200-300 lines +- More than 10-15 fields +- Fields that cluster into subgroups (e.g., address fields, billing fields) +- Methods that only use a subset of the fields +- The class name is vague (`Manager`, `Handler`, `Processor`, `Utils`) + +**Typical fixes:** +- Extract Class -- split along the axis of change +- Extract Subclass -- when behavior varies by type +- Replace Data Value with Object -- when field clusters represent a concept + +### Long Parameter List + +**Description:** A method that takes more than three or four parameters, making calls confusing and error-prone. + +**Detection heuristics:** +- More than 3-4 parameters +- Boolean parameters that switch behavior +- Parameters that always travel together +- Callers passing `null` for unused parameters + +**Typical fixes:** +- Introduce Parameter Object -- group related params into `DateRange`, `Address`, `Options` +- Preserve Whole Object -- pass the object instead of extracting its fields +- Replace Parameter with Method -- have the method fetch data it needs + +### Data Clumps + +**Description:** Groups of variables that appear together in multiple places -- method parameters, field declarations, or local variables. + +**Detection heuristics:** +- Same three or more fields appear together in multiple classes +- Same group of parameters appears in multiple method signatures +- Deleting one member of the group would make no sense without the others + +**Typical fixes:** +- Extract Class -- create a new class for the clump (`Address`, `DateRange`, `Coordinates`) +- Introduce Parameter Object -- replace parameter groups with the new class +- Preserve Whole Object -- pass the object instead of its decomposed fields + +### Primitive Obsession + +**Description:** Using primitive types (strings, ints, arrays) to represent domain concepts instead of small objects. + +**Detection heuristics:** +- Constants or magic numbers used to represent types (`int ADMIN = 1`) +- Strings used for structured data (phone numbers, zip codes, currencies) +- Arrays or tuples used instead of named structures +- Validation logic for the same type scattered across multiple locations + +**Typical fixes:** +- Replace Data Value with Object -- `String email` becomes `EmailAddress` +- Replace Type Code with Subclasses -- when the type code drives behavior +- Replace Type Code with Strategy -- when subclassing is impractical +- Replace Magic Number with Symbolic Constant -- names instead of numbers + +--- + +## Family 2: Object-Orientation Abusers + +Smells where object-oriented features are used incorrectly or not at all. + +### Switch Statements + +**Description:** The same switch/case or if/else chain on a type code appears in multiple places. When a new type is added, every switch must be updated. + +**Detection heuristics:** +- `switch` on a type or status field that appears in more than one place +- `if/else if` chain checking `instanceof` or type strings +- Adding a new type requires editing multiple files + +**Typical fixes:** +- Replace Conditional with Polymorphism -- each type implements its own behavior +- Replace Type Code with Subclasses + Replace Conditional with Polymorphism +- Replace Type Code with Strategy when the type can change at runtime + +**Example:** +``` +// SMELL: same switch in calculatePay(), generateReport(), getPermissions() +switch (employee.type) { + case 'engineer': return basePay; + case 'manager': return basePay + bonus; + case 'salesperson': return basePay + commission; +} + +// FIX: polymorphism +class Engineer extends Employee { + calculatePay() { return this.basePay; } +} +class Manager extends Employee { + calculatePay() { return this.basePay + this.bonus; } +} +``` + +### Refused Bequest + +**Description:** A subclass inherits methods or data it does not want. It overrides parent methods to do nothing or throws "not supported" exceptions. + +**Detection heuristics:** +- Subclass overrides a method to do nothing or throw +- Subclass uses only a small fraction of inherited methods +- The "is-a" relationship feels forced + +**Typical fixes:** +- Push Down Method / Push Down Field -- move unwanted members to the sibling that actually uses them +- Replace Inheritance with Delegation -- the child holds a reference to the parent instead of extending it + +### Alternative Classes with Different Interfaces + +**Description:** Two classes do essentially the same job but have different method names and signatures, preventing interchangeability. + +**Detection heuristics:** +- Two classes with similar purpose but different method names +- Callers choose between them but can't treat them polymorphically +- Duplication of logic because no shared interface exists + +**Typical fixes:** +- Rename Method -- align names across both classes +- Extract Superclass or Extract Interface -- define a shared contract +- Move Method -- equalize what each class offers + +--- + +## Family 3: Change Preventers + +Smells that make changes expensive by scattering related logic. + +### Divergent Change + +**Description:** One class changes for multiple unrelated reasons. It is the opposite of the Single Responsibility Principle. + +**Detection heuristics:** +- You edit the same class for different kinds of changes (new database, new report format, new business rule) +- The class has methods that cluster into groups with no interaction between them +- Different team members edit the same file for different features + +**Typical fixes:** +- Extract Class -- split the class along its axes of change +- Each resulting class should change for exactly one reason + +### Shotgun Surgery + +**Description:** A single logical change requires edits in many different classes. It is the opposite of Divergent Change. + +**Detection heuristics:** +- A small functional change touches 5+ files +- A new field must be added to multiple classes +- A format change requires edits in scattered locations + +**Typical fixes:** +- Move Method / Move Field -- consolidate related logic into one class +- Inline Class -- if scattered pieces are too small, merge them into the class that should own the responsibility + +--- + +## Family 4: Dispensables + +Smells where something exists but shouldn't. + +### Lazy Class + +**Description:** A class that does too little to justify its existence. Each class costs complexity; if it doesn't carry its weight, merge it. + +**Typical fixes:** Inline Class, Collapse Hierarchy + +### Dead Code + +**Description:** Code that is never executed -- unreachable branches, unused variables, unneeded parameters, methods no one calls. + +**Typical fixes:** Delete it. Version control remembers. + +### Speculative Generality + +**Description:** Abstractions, parameters, hooks, or classes created "in case we need them someday." YAGNI -- You Aren't Gonna Need It. + +**Detection heuristics:** +- Abstract classes with only one subclass +- Parameters that are always passed the same value +- Methods that are only called by tests +- Framework infrastructure with no current use + +**Typical fixes:** +- Collapse Hierarchy -- remove unneeded abstract class +- Remove Parameter -- delete unused params +- Inline Class / Inline Method -- collapse unneeded indirection + +### Duplicate Code + +**Description:** The same or nearly identical code structure appears in more than one place. The most common and most expensive smell. + +**Detection heuristics:** +- Copy-pasted blocks with minor variations +- Methods in different classes that do the same thing +- Conditional branches with identical bodies + +**Typical fixes:** +- Extract Method -- share the common code +- Pull Up Method -- move shared method to a common base class +- Extract Superclass / Extract Class -- when duplication spans classes +- Form Template Method -- when method structure is identical but details differ + +--- + +## Family 5: Couplers + +Smells where classes are too tightly bound to each other. + +### Feature Envy + +**Description:** A method that uses more features (fields and methods) of another class than its own. It "envies" the other class's data. + +**Detection heuristics:** +- A method that calls 3+ getters on one foreign object +- A method that could be moved to the other class and would need fewer parameters + +**Typical fixes:** +- Move Method -- relocate the method to the class it envies +- Extract Method + Move Method -- extract the envious part, then move it + +### Inappropriate Intimacy + +**Description:** Two classes are overly entangled -- accessing each other's private details, forming a bidirectional dependency. + +**Typical fixes:** +- Move Method / Move Field to reduce the cross-boundary traffic +- Extract Class to put the shared concern in a neutral place +- Replace Inheritance with Delegation when subclass accesses too many parent internals + +### Message Chains + +**Description:** A client asks object A for B, then asks B for C, then asks C for D: `a.getB().getC().getD()`. The client is coupled to the entire navigation structure. + +**Typical fixes:** +- Hide Delegate -- have A provide the answer directly +- Extract Method + Move Method -- push the chain into the object that should know the answer + +### Middle Man + +**Description:** A class whose methods do nothing but delegate to another class. It adds indirection without value. + +**Detection heuristics:** +- More than half of a class's methods are one-line delegations +- The class has no logic of its own + +**Typical fixes:** +- Remove Middle Man -- let the client call the delegate directly +- Inline Method -- merge the trivial forwarding methods into the caller + +--- + +## Smell-to-Refactoring Quick Reference + +| Smell | Primary Refactoring | Secondary Refactoring | +|-------|--------------------|-----------------------| +| Long Method | Extract Method | Replace Temp with Query | +| Large Class | Extract Class | Extract Subclass | +| Long Parameter List | Introduce Parameter Object | Preserve Whole Object | +| Data Clumps | Extract Class | Introduce Parameter Object | +| Primitive Obsession | Replace Data Value with Object | Replace Type Code with Subclasses | +| Switch Statements | Replace Conditional with Polymorphism | Replace Type Code with Strategy | +| Refused Bequest | Replace Inheritance with Delegation | Push Down Method | +| Divergent Change | Extract Class | -- | +| Shotgun Surgery | Move Method / Move Field | Inline Class | +| Lazy Class | Inline Class | Collapse Hierarchy | +| Dead Code | Delete it | -- | +| Speculative Generality | Collapse Hierarchy | Inline Class | +| Duplicate Code | Extract Method | Pull Up Method | +| Feature Envy | Move Method | Extract Method + Move Method | +| Inappropriate Intimacy | Move Method / Move Field | Extract Class | +| Message Chains | Hide Delegate | Extract Method | +| Middle Man | Remove Middle Man | Inline Method | diff --git a/.claude/skills/systematic-debugging/SKILL.md b/.claude/skills/systematic-debugging/SKILL.md new file mode 100644 index 0000000..62fc752 --- /dev/null +++ b/.claude/skills/systematic-debugging/SKILL.md @@ -0,0 +1,283 @@ +--- +name: systematic-debugging +description: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes +--- + +# Systematic Debugging + +## Overview + +**Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure. + +**Violating the letter of this process is violating the spirit of debugging.** + +## The Iron Law + +``` +NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST +``` + +If you haven't completed Phase 1, you cannot propose fixes. + +## When to Use + +Use for ANY technical issue: +- Test failures +- Bugs in production +- Unexpected behavior +- Performance problems +- Build failures +- Integration issues + +**Use this ESPECIALLY when:** +- Under time pressure (emergencies make guessing tempting) +- "Just one quick fix" seems obvious +- You've already tried multiple fixes +- Previous fix didn't work +- You don't fully understand the issue + +**Don't skip when:** +- Issue seems simple (simple bugs have root causes too) +- You're in a hurry (rushing guarantees rework) +- Manager wants it fixed NOW (systematic is faster than thrashing) + +## The Four Phases + +You MUST complete each phase before proceeding to the next. + +### Phase 1: Root Cause Investigation + +**BEFORE attempting ANY fix:** + +1. **Read Error Messages Carefully** + - Don't skip past errors or warnings + - They often contain the exact solution + - Read stack traces completely + - Note line numbers, file paths, error codes + +2. **Reproduce Consistently** + - Can you trigger it reliably? + - What are the exact steps? + - Does it happen every time? + - If not reproducible → gather more data, don't guess + +3. **Check Recent Changes** + - What changed that could cause this? + - Git diff, recent commits + - New dependencies, config changes + - Environmental differences + +4. **Gather Evidence in Multi-Component Systems** + + **WHEN system has multiple components (CI → build → signing, API → service → database):** + + **BEFORE proposing fixes, add diagnostic instrumentation:** + ``` + For EACH component boundary: + - Log what data enters component + - Log what data exits component + - Verify environment/config propagation + - Check state at each layer + + Run once to gather evidence showing WHERE it breaks + THEN analyze evidence to identify failing component + THEN investigate that specific component + ``` + + **Example (multi-layer system):** + ```bash + # Layer 1: Workflow + echo "=== Secrets available in workflow: ===" + echo "IDENTITY: $([ -n "${IDENTITY:-}" ] && echo SET || echo UNSET)" + + # Layer 2: Build script + echo "=== Env vars in build script: ===" + printenv IDENTITY >/dev/null 2>&1 && echo "IDENTITY in environment" || echo "IDENTITY not in environment" + + # Layer 3: Signing script + echo "=== Keychain state: ===" + security list-keychains + security find-identity -v + + # Layer 4: Actual signing + codesign --sign "$IDENTITY" --verbose=4 "$APP" + ``` + + **This reveals:** Which layer fails (secrets → workflow ✓, workflow → build ✗) + +5. **Trace Data Flow** + + **WHEN error is deep in call stack:** + + See `root-cause-tracing.md` in this directory for the complete backward tracing technique. + + **Quick version:** + - Where does bad value originate? + - What called this with bad value? + - Keep tracing up until you find the source + - Fix at source, not at symptom + +### Phase 2: Pattern Analysis + +**Find the pattern before fixing:** + +1. **Find Working Examples** + - Locate similar working code in same codebase + - What works that's similar to what's broken? + +2. **Compare Against References** + - If implementing pattern, read reference implementation COMPLETELY + - Don't skim - read every line + - Understand the pattern fully before applying + +3. **Identify Differences** + - What's different between working and broken? + - List every difference, however small + - Don't assume "that can't matter" + +4. **Understand Dependencies** + - What other components does this need? + - What settings, config, environment? + - What assumptions does it make? + +### Phase 3: Hypothesis and Testing + +**Scientific method:** + +1. **Form Single Hypothesis** + - State clearly: "I think X is the root cause because Y" + - Write it down + - Be specific, not vague + +2. **Test Minimally** + - Make the SMALLEST possible change to test hypothesis + - One variable at a time + - Don't fix multiple things at once + +3. **Verify Before Continuing** + - Did it work? Yes → Phase 4 + - Didn't work? Form NEW hypothesis + - DON'T add more fixes on top + +4. **When You Don't Know** + - Say "I don't understand X" + - Don't pretend to know + - Ask for help + - Research more + +### Phase 4: Implementation + +**Fix the root cause, not the symptom:** + +1. **Create Failing Test Case** + - Simplest possible reproduction + - Automated test if possible + - One-off test script if no framework + - MUST have before fixing + - Use the `superpowers:test-driven-development` skill for writing proper failing tests + +2. **Implement Single Fix** + - Address the root cause identified + - ONE change at a time + - No "while I'm here" improvements + - No bundled refactoring + +3. **Verify Fix** + - Test passes now? + - No other tests broken? + - Issue actually resolved? + - Use the `superpowers:verification-before-completion` skill before claiming success + +4. **If Fix Doesn't Work** + - STOP + - Count: How many fixes have you tried? + - If < 3: Return to Phase 1, re-analyze with new information + - **If ≥ 3: STOP and question the architecture (step 5 below)** + - DON'T attempt Fix #4 without architectural discussion + +5. **If 3+ Fixes Failed: Question Architecture** + + **Pattern indicating architectural problem:** + - Each fix reveals new shared state/coupling/problem in different place + - Fixes require "massive refactoring" to implement + - Each fix creates new symptoms elsewhere + + **STOP and question fundamentals:** + - Is this pattern fundamentally sound? + - Are we "sticking with it through sheer inertia"? + - Should we refactor architecture vs. continue fixing symptoms? + + **Discuss with your human partner before attempting more fixes** + + This is NOT a failed hypothesis - this is a wrong architecture. + +## Red Flags - STOP and Follow Process + +If you catch yourself thinking: +- "Quick fix for now, investigate later" +- "Just try changing X and see if it works" +- "Add multiple changes, run tests" +- "Skip the test, I'll manually verify" +- "It's probably X, let me fix that" +- "I don't fully understand but this might work" +- "Pattern says X but I'll adapt it differently" +- "Here are the main problems: [lists fixes without investigation]" +- Proposing solutions before tracing data flow +- **"One more fix attempt" (when already tried 2+)** +- **Each fix reveals new problem in different place** + +**ALL of these mean: STOP. Return to Phase 1.** + +**If 3+ fixes failed:** Question the architecture (see Phase 4.5) + +## your human partner's Signals You're Doing It Wrong + +**Watch for these redirections:** +- "Is that not happening?" - You assumed without verifying +- "Will it show us...?" - You should have added evidence gathering +- "Stop guessing" - You're proposing fixes without understanding +- "Ultra-think this" - Question fundamentals, not just symptoms +- "We're stuck?" (frustrated) - Your approach isn't working + +**When you see these:** STOP. Return to Phase 1. + +## Common Rationalizations + +| Excuse | Reality | +|--------|---------| +| "Issue is simple, don't need process" | Simple issues have root causes too. Process is fast for simple bugs. | +| "Emergency, no time for process" | Systematic debugging is FASTER than guess-and-check thrashing. | +| "Just try this first, then investigate" | First fix sets the pattern. Do it right from the start. | +| "I'll write test after confirming fix works" | Untested fixes don't stick. Test first proves it. | +| "Multiple fixes at once saves time" | Can't isolate what worked. Causes new bugs. | +| "Reference too long, I'll adapt the pattern" | Partial understanding guarantees bugs. Read it completely. | +| "I see the problem, let me fix it" | Seeing symptoms ≠ understanding root cause. | +| "One more fix attempt" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. | + +## Quick Reference + +| Phase | Key Activities | Success Criteria | +|-------|---------------|------------------| +| **1. Root Cause** | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY | +| **2. Pattern** | Find working examples, compare | Identify differences | +| **3. Hypothesis** | Form theory, test minimally | Confirmed or new hypothesis | +| **4. Implementation** | Create test, fix, verify | Bug resolved, tests pass | + +## When Process Reveals "No Root Cause" + +If systematic investigation reveals issue is truly environmental, timing-dependent, or external: + +1. You've completed the process +2. Document what you investigated +3. Implement appropriate handling (retry, timeout, error message) +4. Add monitoring/logging for future investigation + +**But:** 95% of "no root cause" cases are incomplete investigation. + +## Supporting Techniques + +These techniques are part of systematic debugging and available in this directory: + +- **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger +- **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause +- **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling diff --git a/.claude/skills/systematic-debugging/condition-based-waiting-example.ts b/.claude/skills/systematic-debugging/condition-based-waiting-example.ts new file mode 100644 index 0000000..703a06b --- /dev/null +++ b/.claude/skills/systematic-debugging/condition-based-waiting-example.ts @@ -0,0 +1,158 @@ +// Complete implementation of condition-based waiting utilities +// From: Lace test infrastructure improvements (2025-10-03) +// Context: Fixed 15 flaky tests by replacing arbitrary timeouts + +import type { ThreadManager } from '~/threads/thread-manager'; +import type { LaceEvent, LaceEventType } from '~/threads/types'; + +/** + * Wait for a specific event type to appear in thread + * + * @param threadManager - The thread manager to query + * @param threadId - Thread to check for events + * @param eventType - Type of event to wait for + * @param timeoutMs - Maximum time to wait (default 5000ms) + * @returns Promise resolving to the first matching event + * + * Example: + * await waitForEvent(threadManager, agentThreadId, 'TOOL_RESULT'); + */ +export function waitForEvent( + threadManager: ThreadManager, + threadId: string, + eventType: LaceEventType, + timeoutMs = 5000 +): Promise { + return new Promise((resolve, reject) => { + const startTime = Date.now(); + + const check = () => { + const events = threadManager.getEvents(threadId); + const event = events.find((e) => e.type === eventType); + + if (event) { + resolve(event); + } else if (Date.now() - startTime > timeoutMs) { + reject(new Error(`Timeout waiting for ${eventType} event after ${timeoutMs}ms`)); + } else { + setTimeout(check, 10); // Poll every 10ms for efficiency + } + }; + + check(); + }); +} + +/** + * Wait for a specific number of events of a given type + * + * @param threadManager - The thread manager to query + * @param threadId - Thread to check for events + * @param eventType - Type of event to wait for + * @param count - Number of events to wait for + * @param timeoutMs - Maximum time to wait (default 5000ms) + * @returns Promise resolving to all matching events once count is reached + * + * Example: + * // Wait for 2 AGENT_MESSAGE events (initial response + continuation) + * await waitForEventCount(threadManager, agentThreadId, 'AGENT_MESSAGE', 2); + */ +export function waitForEventCount( + threadManager: ThreadManager, + threadId: string, + eventType: LaceEventType, + count: number, + timeoutMs = 5000 +): Promise { + return new Promise((resolve, reject) => { + const startTime = Date.now(); + + const check = () => { + const events = threadManager.getEvents(threadId); + const matchingEvents = events.filter((e) => e.type === eventType); + + if (matchingEvents.length >= count) { + resolve(matchingEvents); + } else if (Date.now() - startTime > timeoutMs) { + reject( + new Error( + `Timeout waiting for ${count} ${eventType} events after ${timeoutMs}ms (got ${matchingEvents.length})` + ) + ); + } else { + setTimeout(check, 10); + } + }; + + check(); + }); +} + +/** + * Wait for an event matching a custom predicate + * Useful when you need to check event data, not just type + * + * @param threadManager - The thread manager to query + * @param threadId - Thread to check for events + * @param predicate - Function that returns true when event matches + * @param description - Human-readable description for error messages + * @param timeoutMs - Maximum time to wait (default 5000ms) + * @returns Promise resolving to the first matching event + * + * Example: + * // Wait for TOOL_RESULT with specific ID + * await waitForEventMatch( + * threadManager, + * agentThreadId, + * (e) => e.type === 'TOOL_RESULT' && e.data.id === 'call_123', + * 'TOOL_RESULT with id=call_123' + * ); + */ +export function waitForEventMatch( + threadManager: ThreadManager, + threadId: string, + predicate: (event: LaceEvent) => boolean, + description: string, + timeoutMs = 5000 +): Promise { + return new Promise((resolve, reject) => { + const startTime = Date.now(); + + const check = () => { + const events = threadManager.getEvents(threadId); + const event = events.find(predicate); + + if (event) { + resolve(event); + } else if (Date.now() - startTime > timeoutMs) { + reject(new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`)); + } else { + setTimeout(check, 10); + } + }; + + check(); + }); +} + +// Usage example from actual debugging session: +// +// BEFORE (flaky): +// --------------- +// const messagePromise = agent.sendMessage('Execute tools'); +// await new Promise(r => setTimeout(r, 300)); // Hope tools start in 300ms +// agent.abort(); +// await messagePromise; +// await new Promise(r => setTimeout(r, 50)); // Hope results arrive in 50ms +// expect(toolResults.length).toBe(2); // Fails randomly +// +// AFTER (reliable): +// ---------------- +// const messagePromise = agent.sendMessage('Execute tools'); +// await waitForEventCount(threadManager, threadId, 'TOOL_CALL', 2); // Wait for tools to start +// agent.abort(); +// await messagePromise; +// await waitForEventCount(threadManager, threadId, 'TOOL_RESULT', 2); // Wait for results +// expect(toolResults.length).toBe(2); // Always succeeds +// +// Result: 60% pass rate → 100%, 40% faster execution diff --git a/.claude/skills/systematic-debugging/condition-based-waiting.md b/.claude/skills/systematic-debugging/condition-based-waiting.md new file mode 100644 index 0000000..70994f7 --- /dev/null +++ b/.claude/skills/systematic-debugging/condition-based-waiting.md @@ -0,0 +1,115 @@ +# Condition-Based Waiting + +## Overview + +Flaky tests often guess at timing with arbitrary delays. This creates race conditions where tests pass on fast machines but fail under load or in CI. + +**Core principle:** Wait for the actual condition you care about, not a guess about how long it takes. + +## When to Use + +```dot +digraph when_to_use { + "Test uses setTimeout/sleep?" [shape=diamond]; + "Testing timing behavior?" [shape=diamond]; + "Document WHY timeout needed" [shape=box]; + "Use condition-based waiting" [shape=box]; + + "Test uses setTimeout/sleep?" -> "Testing timing behavior?" [label="yes"]; + "Testing timing behavior?" -> "Document WHY timeout needed" [label="yes"]; + "Testing timing behavior?" -> "Use condition-based waiting" [label="no"]; +} +``` + +**Use when:** +- Tests have arbitrary delays (`setTimeout`, `sleep`, `time.sleep()`) +- Tests are flaky (pass sometimes, fail under load) +- Tests timeout when run in parallel +- Waiting for async operations to complete + +**Don't use when:** +- Testing actual timing behavior (debounce, throttle intervals) +- Always document WHY if using arbitrary timeout + +## Core Pattern + +```typescript +// ❌ BEFORE: Guessing at timing +await new Promise(r => setTimeout(r, 50)); +const result = getResult(); +expect(result).toBeDefined(); + +// ✅ AFTER: Waiting for condition +await waitFor(() => getResult() !== undefined); +const result = getResult(); +expect(result).toBeDefined(); +``` + +## Quick Patterns + +| Scenario | Pattern | +|----------|---------| +| Wait for event | `waitFor(() => events.find(e => e.type === 'DONE'))` | +| Wait for state | `waitFor(() => machine.state === 'ready')` | +| Wait for count | `waitFor(() => items.length >= 5)` | +| Wait for file | `waitFor(() => fs.existsSync(path))` | +| Complex condition | `waitFor(() => obj.ready && obj.value > 10)` | + +## Implementation + +Generic polling function: +```typescript +async function waitFor( + condition: () => T | undefined | null | false, + description: string, + timeoutMs = 5000 +): Promise { + const startTime = Date.now(); + + while (true) { + const result = condition(); + if (result) return result; + + if (Date.now() - startTime > timeoutMs) { + throw new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`); + } + + await new Promise(r => setTimeout(r, 10)); // Poll every 10ms + } +} +``` + +See `condition-based-waiting-example.ts` in this directory for complete implementation with domain-specific helpers (`waitForEvent`, `waitForEventCount`, `waitForEventMatch`) from actual debugging session. + +## Common Mistakes + +**❌ Polling too fast:** `setTimeout(check, 1)` - wastes CPU +**✅ Fix:** Poll every 10ms + +**❌ No timeout:** Loop forever if condition never met +**✅ Fix:** Always include timeout with clear error + +**❌ Stale data:** Cache state before loop +**✅ Fix:** Call getter inside loop for fresh data + +## When Arbitrary Timeout IS Correct + +```typescript +// Tool ticks every 100ms - need 2 ticks to verify partial output +await waitForEvent(manager, 'TOOL_STARTED'); // First: wait for condition +await new Promise(r => setTimeout(r, 200)); // Then: wait for timed behavior +// 200ms = 2 ticks at 100ms intervals - documented and justified +``` + +**Requirements:** +1. First wait for triggering condition +2. Based on known timing (not guessing) +3. Comment explaining WHY + +## Real-World Impact + +From debugging session (2025-10-03): +- Fixed 15 flaky tests across 3 files +- Pass rate: 60% → 100% +- Execution time: 40% faster +- No more race conditions diff --git a/.claude/skills/systematic-debugging/defense-in-depth.md b/.claude/skills/systematic-debugging/defense-in-depth.md new file mode 100644 index 0000000..e248335 --- /dev/null +++ b/.claude/skills/systematic-debugging/defense-in-depth.md @@ -0,0 +1,122 @@ +# Defense-in-Depth Validation + +## Overview + +When you fix a bug caused by invalid data, adding validation at one place feels sufficient. But that single check can be bypassed by different code paths, refactoring, or mocks. + +**Core principle:** Validate at EVERY layer data passes through. Make the bug structurally impossible. + +## Why Multiple Layers + +Single validation: "We fixed the bug" +Multiple layers: "We made the bug impossible" + +Different layers catch different cases: +- Entry validation catches most bugs +- Business logic catches edge cases +- Environment guards prevent context-specific dangers +- Debug logging helps when other layers fail + +## The Four Layers + +### Layer 1: Entry Point Validation +**Purpose:** Reject obviously invalid input at API boundary + +```typescript +function createProject(name: string, workingDirectory: string) { + if (!workingDirectory || workingDirectory.trim() === '') { + throw new Error('workingDirectory cannot be empty'); + } + if (!existsSync(workingDirectory)) { + throw new Error(`workingDirectory does not exist: ${workingDirectory}`); + } + if (!statSync(workingDirectory).isDirectory()) { + throw new Error(`workingDirectory is not a directory: ${workingDirectory}`); + } + // ... proceed +} +``` + +### Layer 2: Business Logic Validation +**Purpose:** Ensure data makes sense for this operation + +```typescript +function initializeWorkspace(projectDir: string, sessionId: string) { + if (!projectDir) { + throw new Error('projectDir required for workspace initialization'); + } + // ... proceed +} +``` + +### Layer 3: Environment Guards +**Purpose:** Prevent dangerous operations in specific contexts + +```typescript +async function gitInit(directory: string) { + // In tests, refuse git init outside temp directories + if (process.env.NODE_ENV === 'test') { + const normalized = normalize(resolve(directory)); + const tmpDir = normalize(resolve(tmpdir())); + + if (!normalized.startsWith(tmpDir)) { + throw new Error( + `Refusing git init outside temp dir during tests: ${directory}` + ); + } + } + // ... proceed +} +``` + +### Layer 4: Debug Instrumentation +**Purpose:** Capture context for forensics + +```typescript +async function gitInit(directory: string) { + const stack = new Error().stack; + logger.debug('About to git init', { + directory, + cwd: process.cwd(), + stack, + }); + // ... proceed +} +``` + +## Applying the Pattern + +When you find a bug: + +1. **Trace the data flow** - Where does bad value originate? Where used? +2. **Map all checkpoints** - List every point data passes through +3. **Add validation at each layer** - Entry, business, environment, debug +4. **Test each layer** - Try to bypass layer 1, verify layer 2 catches it + +## Example from Session + +Bug: Empty `projectDir` caused `git init` in source code + +**Data flow:** +1. Test setup → empty string +2. `Project.create(name, '')` +3. `WorkspaceManager.createWorkspace('')` +4. `git init` runs in `process.cwd()` + +**Four layers added:** +- Layer 1: `Project.create()` validates not empty/exists/writable +- Layer 2: `WorkspaceManager` validates projectDir not empty +- Layer 3: `WorktreeManager` refuses git init outside tmpdir in tests +- Layer 4: Stack trace logging before git init + +**Result:** All 1847 tests passed, bug impossible to reproduce + +## Key Insight + +All four layers were necessary. During testing, each layer caught bugs the others missed: +- Different code paths bypassed entry validation +- Mocks bypassed business logic checks +- Edge cases on different platforms needed environment guards +- Debug logging identified structural misuse + +**Don't stop at one validation point.** Add checks at every layer. diff --git a/.claude/skills/systematic-debugging/find-polluter.sh b/.claude/skills/systematic-debugging/find-polluter.sh new file mode 100755 index 0000000..985f5d0 --- /dev/null +++ b/.claude/skills/systematic-debugging/find-polluter.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# Bisection script to find which test creates unwanted files/state +# Usage: ./find-polluter.sh +# Example: ./find-polluter.sh '.git' 'src/**/*.test.ts' + +set -e + +if [ $# -ne 2 ]; then + echo "Usage: $0 " + echo "Example: $0 '.git' 'src/**/*.test.ts'" + exit 1 +fi + +POLLUTION_CHECK="$1" +TEST_PATTERN="$2" + +echo "🔍 Searching for test that creates: $POLLUTION_CHECK" +echo "Test pattern: $TEST_PATTERN" +echo "" + +# Get list of test files (find . emits ./-prefixed paths, so accept the +# pattern written with or without a leading ./) +TEST_PATTERN="${TEST_PATTERN#./}" +# find -path can't match '**/' against zero directory levels, so a pattern +# like src/**/*.test.ts would skip src/top.test.ts; also try the pattern +# with '**/' collapsed to cover files directly under the base directory. +TEST_FILES=$(find . \( -path "./$TEST_PATTERN" -o -path "./${TEST_PATTERN//\*\*\//}" \) | sort -u) +if [ -z "$TEST_FILES" ]; then + TOTAL=0 +else + TOTAL=$(printf '%s\n' "$TEST_FILES" | wc -l | tr -d ' ') +fi + +echo "Found $TOTAL test files" +echo "" + +COUNT=0 +for TEST_FILE in $TEST_FILES; do + COUNT=$((COUNT + 1)) + + # Skip if pollution already exists + if [ -e "$POLLUTION_CHECK" ]; then + echo "⚠️ Pollution already exists before test $COUNT/$TOTAL" + echo " Skipping: $TEST_FILE" + continue + fi + + echo "[$COUNT/$TOTAL] Testing: $TEST_FILE" + + # Run the test + npm test "$TEST_FILE" > /dev/null 2>&1 || true + + # Check if pollution appeared + if [ -e "$POLLUTION_CHECK" ]; then + echo "" + echo "🎯 FOUND POLLUTER!" + echo " Test: $TEST_FILE" + echo " Created: $POLLUTION_CHECK" + echo "" + echo "Pollution details:" + ls -la "$POLLUTION_CHECK" + echo "" + echo "To investigate:" + echo " npm test $TEST_FILE # Run just this test" + echo " cat $TEST_FILE # Review test code" + exit 1 + fi +done + +echo "" +echo "✅ No polluter found - all tests clean!" +exit 0 diff --git a/.claude/skills/systematic-debugging/root-cause-tracing.md b/.claude/skills/systematic-debugging/root-cause-tracing.md new file mode 100644 index 0000000..0e72e8f --- /dev/null +++ b/.claude/skills/systematic-debugging/root-cause-tracing.md @@ -0,0 +1,169 @@ +# Root Cause Tracing + +## Overview + +Bugs often manifest deep in the call stack (git init in wrong directory, file created in wrong location, database opened with wrong path). Your instinct is to fix where the error appears, but that's treating a symptom. + +**Core principle:** Trace backward through the call chain until you find the original trigger, then fix at the source. + +## When to Use + +```dot +digraph when_to_use { + "Bug appears deep in stack?" [shape=diamond]; + "Can trace backwards?" [shape=diamond]; + "Fix at symptom point" [shape=box]; + "Trace to original trigger" [shape=box]; + "BETTER: Also add defense-in-depth" [shape=box]; + + "Bug appears deep in stack?" -> "Can trace backwards?" [label="yes"]; + "Can trace backwards?" -> "Trace to original trigger" [label="yes"]; + "Can trace backwards?" -> "Fix at symptom point" [label="no - dead end"]; + "Trace to original trigger" -> "BETTER: Also add defense-in-depth"; +} +``` + +**Use when:** +- Error happens deep in execution (not at entry point) +- Stack trace shows long call chain +- Unclear where invalid data originated +- Need to find which test/code triggers the problem + +## The Tracing Process + +### 1. Observe the Symptom +``` +Error: git init failed in ~/project/packages/core +``` + +### 2. Find Immediate Cause +**What code directly causes this?** +```typescript +await execFileAsync('git', ['init'], { cwd: projectDir }); +``` + +### 3. Ask: What Called This? +```typescript +WorktreeManager.createSessionWorktree(projectDir, sessionId) + → called by Session.initializeWorkspace() + → called by Session.create() + → called by test at Project.create() +``` + +### 4. Keep Tracing Up +**What value was passed?** +- `projectDir = ''` (empty string!) +- Empty string as `cwd` resolves to `process.cwd()` +- That's the source code directory! + +### 5. Find Original Trigger +**Where did empty string come from?** +```typescript +const context = setupCoreTest(); // Returns { tempDir: '' } +Project.create('name', context.tempDir); // Accessed before beforeEach! +``` + +## Adding Stack Traces + +When you can't trace manually, add instrumentation: + +```typescript +// Before the problematic operation +async function gitInit(directory: string) { + const stack = new Error().stack; + console.error('DEBUG git init:', { + directory, + cwd: process.cwd(), + nodeEnv: process.env.NODE_ENV, + stack, + }); + + await execFileAsync('git', ['init'], { cwd: directory }); +} +``` + +**Critical:** Use `console.error()` in tests (not logger - may not show) + +**Run and capture:** +```bash +npm test 2>&1 | grep 'DEBUG git init' +``` + +**Analyze stack traces:** +- Look for test file names +- Find the line number triggering the call +- Identify the pattern (same test? same parameter?) + +## Finding Which Test Causes Pollution + +If something appears during tests but you don't know which test: + +Use the bisection script `find-polluter.sh` in this directory: + +```bash +bash ./find-polluter.sh '.git' 'src/**/*.test.ts' +``` + +Runs tests one-by-one, stops at first polluter. See script for usage. + +## Real Example: Empty projectDir + +**Symptom:** `.git` created in `packages/core/` (source code) + +**Trace chain:** +1. `git init` runs in `process.cwd()` ← empty cwd parameter +2. WorktreeManager called with empty projectDir +3. Session.create() passed empty string +4. Test accessed `context.tempDir` before beforeEach +5. setupCoreTest() returns `{ tempDir: '' }` initially + +**Root cause:** Top-level variable initialization accessing empty value + +**Fix:** Made tempDir a getter that throws if accessed before beforeEach + +**Also added defense-in-depth:** +- Layer 1: Project.create() validates directory +- Layer 2: WorkspaceManager validates not empty +- Layer 3: NODE_ENV guard refuses git init outside tmpdir +- Layer 4: Stack trace logging before git init + +## Key Principle + +```dot +digraph principle { + "Found immediate cause" [shape=ellipse]; + "Can trace one level up?" [shape=diamond]; + "Trace backwards" [shape=box]; + "Is this the source?" [shape=diamond]; + "Fix at source" [shape=box]; + "Add validation at each layer" [shape=box]; + "Bug impossible" [shape=doublecircle]; + "NEVER fix just the symptom" [shape=octagon, style=filled, fillcolor=red, fontcolor=white]; + + "Found immediate cause" -> "Can trace one level up?"; + "Can trace one level up?" -> "Trace backwards" [label="yes"]; + "Can trace one level up?" -> "NEVER fix just the symptom" [label="no"]; + "Trace backwards" -> "Is this the source?"; + "Is this the source?" -> "Trace backwards" [label="no - keeps going"]; + "Is this the source?" -> "Fix at source" [label="yes"]; + "Fix at source" -> "Add validation at each layer"; + "Add validation at each layer" -> "Bug impossible"; +} +``` + +**NEVER fix just where the error appears.** Trace back to find the original trigger. + +## Stack Trace Tips + +**In tests:** Use `console.error()` not logger - logger may be suppressed +**Before operation:** Log before the dangerous operation, not after it fails +**Include context:** Directory, cwd, environment variables, timestamps +**Capture stack:** `new Error().stack` shows complete call chain + +## Real-World Impact + +From debugging session (2025-10-03): +- Found root cause through 5-level trace +- Fixed at source (getter validation) +- Added 4 layers of defense +- 1847 tests passed, zero pollution diff --git a/.claude/skills/verification-before-completion/SKILL.md b/.claude/skills/verification-before-completion/SKILL.md new file mode 100644 index 0000000..7d45333 --- /dev/null +++ b/.claude/skills/verification-before-completion/SKILL.md @@ -0,0 +1,120 @@ +--- +name: verification-before-completion +description: Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always +--- + +# Verification Before Completion + +## Overview + +**Core principle:** Evidence before claims, always. + +**Violating the letter of this rule is violating the spirit of this rule.** + +## The Iron Law + +``` +NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE +``` + +If you haven't run the verification command in this message, you cannot claim it passes. + +## The Gate Function + +``` +BEFORE claiming any status or expressing satisfaction: + +1. IDENTIFY: What command proves this claim? +2. RUN: Execute the FULL command (fresh, complete) +3. READ: Full output, check exit code, count failures +4. VERIFY: Does output confirm the claim? + - If NO: State actual status with evidence + - If YES: State claim WITH evidence +5. ONLY THEN: Make the claim + +Skip any step = lying, not verifying +``` + +## Common Failures + +| Claim | Requires | Not Sufficient | +|-------|----------|----------------| +| Tests pass | Test command output: 0 failures | Previous run, "should pass" | +| Linter clean | Linter output: 0 errors | Partial check, extrapolation | +| Build succeeds | Build command: exit 0 | Linter passing, logs look good | +| Bug fixed | Test original symptom: passes | Code changed, assumed fixed | +| Regression test works | Red-green cycle verified | Test passes once | +| Agent completed | VCS diff shows changes | Agent reports "success" | +| Requirements met | Line-by-line checklist | Tests passing | + +## Red Flags - STOP + +- Using "should", "probably", "seems to" +- Expressing satisfaction before verification ("Great!", "Perfect!", "Done!", etc.) +- About to commit/push/PR without verification +- Trusting agent success reports +- Relying on partial verification +- Thinking "just this once" +- Tired and wanting work over +- **ANY wording implying success without having run verification** + +## Rationalization Prevention + +| Excuse | Reality | +|--------|---------| +| "Should work now" | RUN the verification | +| "I'm confident" | Confidence ≠ evidence | +| "Just this once" | No exceptions | +| "Linter passed" | Linter ≠ compiler | +| "Agent said success" | Verify independently | +| "I'm tired" | Exhaustion ≠ excuse | +| "Partial check is enough" | Partial proves nothing | +| "Different words so rule doesn't apply" | Spirit over letter | + +## Key Patterns + +**Tests:** +``` +✅ [Run test command] [See: 34/34 pass] "All tests pass" +❌ "Should pass now" / "Looks correct" +``` + +**Regression tests (TDD Red-Green):** +``` +✅ Write → Run (pass) → Revert fix → Run (MUST FAIL) → Restore → Run (pass) +❌ "I've written a regression test" (without red-green verification) +``` + +**Build:** +``` +✅ [Run build] [See: exit 0] "Build passes" +❌ "Linter passed" (linter doesn't check compilation) +``` + +**Requirements:** +``` +✅ Re-read plan → Create checklist → Verify each → Report gaps or completion +❌ "Tests pass, phase complete" +``` + +**Agent delegation:** +``` +✅ Agent reports success → Check VCS diff → Verify changes → Report actual state +❌ Trust agent report +``` + +## When To Apply + +**ALWAYS before:** +- ANY variation of success/completion claims +- ANY expression of satisfaction +- ANY positive statement about work state +- Committing, PR creation, task completion +- Moving to next task +- Delegating to agents + +**Rule applies to:** +- Exact phrases +- Paraphrases and synonyms +- Implications of success +- ANY communication suggesting completion/correctness diff --git a/.claude/skills/writing-for-agents/SKILL-MECHANICS.md b/.claude/skills/writing-for-agents/SKILL-MECHANICS.md new file mode 100644 index 0000000..9cdbdb2 --- /dev/null +++ b/.claude/skills/writing-for-agents/SKILL-MECHANICS.md @@ -0,0 +1,22 @@ +# Skill mechanics + +The skill-specific branch of [`writing-for-agents`](SKILL.md): what changes when the document is a skill (frontmatter, the invocation choice, and router skills). Everything else about writing it is the universal reference in `SKILL.md`. + +## Invocation + +Two choices, trading the two loads: + +- A **model-invoked** skill keeps a `description`, so the agent can fire it autonomously, and other skills can reach it. You can still type its name: model-invocation always _includes_ user reach; a description only ever adds agent discovery, never removes the human's. The description is the skill's top-level context pointer, forced to stay loaded at all times: permanent context load in exchange for discoverability. A model-invoked skill whose content is all reference is also one home for shared reference: another skill can invoke it, so reference needed by several skills lives in one place. Mechanics: omit `disable-model-invocation`, and write a model-facing description carrying the trigger branches (the pointer-writing rules in `SKILL.md` apply in full). +- A **user-invoked** skill strips the description from the agent's reach: only the human typing its name can invoke it, and no other skill can. Zero context load, but it spends cognitive load: you are the index that must remember it exists. Mechanics: set `disable-model-invocation: true`; the `description` becomes human-facing: a one-line summary, trigger lists stripped. + +Pick model-invocation only when the agent must reach the skill on its own, or another skill must. If it only ever fires by hand, make it user-invoked and pay no context load. + +Shared reference that two user-invoked skills both need can live in neither: with no descriptions, neither can fire the other. Push it to a plain file outside the skill system: external reference any skill can point at. + +## Splitting by invocation + +The invocation cut of splitting (the sequence cut lives in `SKILL.md`): split off a model-invoked skill when you have a distinct leading word that should trigger it on its own (a trigger word you actually use in your prompts), or another skill must reach it. You pay context load for the new always-loaded description, so that independent reach has to be worth it. + +## Router skills + +When user-invoked skills multiply past what you can remember, that piled-up cognitive load is cured by a **router skill**: one user-invoked skill that names the others and when to reach for each, so the human has one skill to remember instead of many. It can only hint, never fire them: user-invoked skills have no description, so nothing but the human can reach them. diff --git a/.claude/skills/writing-for-agents/SKILL.md b/.claude/skills/writing-for-agents/SKILL.md new file mode 100644 index 0000000..a37608d --- /dev/null +++ b/.claude/skills/writing-for-agents/SKILL.md @@ -0,0 +1,81 @@ +--- +name: writing-for-agents +description: Writing documents for agents. Use when creating or editing skills, or modifying AGENTS.md or CLAUDE.md. +--- + +Reference for writing any document an agent consumes: a skill, an `AGENTS.md` / `CLAUDE.md`, a doc reached by a pointer. The packaging differs; the writing does not: the same levers make each one predictable, since the agent takes the same _process_ every run rather than producing the same output. + +When the document you're writing is a skill, read [`SKILL-MECHANICS.md`](SKILL-MECHANICS.md) for frontmatter, invocation choice, and router skills. + +## Context pointers + +A **context pointer** is a reference held in the agent's context that names some out-of-context material and encodes the condition for reaching it. A skill's description is one; a line in `AGENTS.md` naming a doc is the same object. The pointer's _wording_, not its target, decides when the agent reaches the material, and how reliably. A must-have target behind a weakly worded pointer is a variance bug: sharpen the wording first, and inline the material only if sharpening fails. + +A pointer does two jobs: state what the material is, and list the **branches** that should trigger reaching it (a branch is a distinct case the document handles, so different runs take different paths through it). Every word of an always-loaded pointer costs on every turn, so it earns even harder pruning than the body: + +- **Front-load the leading word**: the pointer is where it does its triggering work. +- **One trigger per branch.** Synonyms that rename a single branch are one branch written twice; collapse them and keep only genuinely distinct branches. +- **Cut identity the body already carries.** + +## The two loads + +Every document and pointer you add spends one of two budgets: + +- **Context load** is the cost of always-loaded material on the agent's window: an `AGENTS.md` line, a skill description, anything sitting in context every turn, spending tokens and attention whether or not it fires. +- **Cognitive load** is the cost on the human: which documents exist and when to reach for each. The human is the index. Not a cost to minimise: it is the price of human agency; spend it where human judgement matters, remove it where it does not. + +Material reached only through a pointer escapes context load at the price of the pointer's own line; material with no pointer at all rides entirely on cognitive load. + +## Information hierarchy + +A document is built from two content types: **steps** (the ordered actions the agent performs) and **reference** (definitions, rules, facts consulted on demand). The two mix freely: all steps (a recipe), all reference (a review's rules, this skill), or both. The core decision is where each piece sits on the **information hierarchy**, a ladder ranked by how immediately the agent needs the material: + +1. **In-file step** is the primary tier: what the agent does, in order. +2. **In-file reference** is consulted on demand. Often a legitimately flat peer-set (every rule of a review on one rung), which is a fine arrangement, not a smell. +3. **Disclosed reference** is pushed out into a separate file, reached by a context pointer, loaded only when the pointer fires. Spans a sibling file in the same folder through fully external reference that lives anywhere and any document can point at. + +Push too little down and the top bloats; push too much and you hide material the agent actually needs. That tension is the whole decision. + +**Progressive disclosure** is the move down the ladder (out of the main file and behind a pointer) so the top stays legible. Not primarily a token optimisation: it is how the hierarchy is protected. Branching is the cleanest disclosure test: inline what every branch needs, and push behind a pointer what only some branches reach. When a document has steps, in-file reference that should be disclosed buries them and turns attending to them into a coin-flip: a variance lever, not just a legibility one. + +**Co-location** is the within-file companion: where the ladder decides _how far down_ a piece sits, co-location decides _what sits beside it_ once there. Keep a concept's definition, rules, and caveats under one heading rather than scattered, so reading one part brings its neighbours with it. The test: the document should read like documentation written for the agent. Grouped material reads that way; scattered material does not. (Distinct from duplication: that repeats one meaning in two places; scattering fragments one meaning across many.) + +**Sprawl** is the failure mode here: a document simply too long, even when every line is live and unique. Attention thins across the excess, and every extra line is one more to keep relevant. The cure is the ladder: disclose reference behind pointers, and split by branch or sequence so each path carries only what it needs. + +## Steps and completion criteria + +Every step ends on a **completion criterion**, the condition that tells the agent the work is done. Two properties make it a lever: + +- **Clarity**: can the agent tell done from not-done? A vague bound ("understanding reached") invites **premature completion**: ending the step before it is genuinely done, attention slipping to _being done_. The visible steps still ahead (the **post-completion steps**) supply the pull; the criterion's clarity is the resistance. Defend in order: **sharpen the bound first** (local and cheap); only if it is irreducibly fuzzy _and_ you observe the rush, hide the later steps by splitting the sequence. Hiding only works across a real context boundary (a hand-off or a subagent dispatch; an inline call leaves the later steps in context and clears nothing). +- **Demand**: how much it requires. "Every modified model accounted for" forces thorough work where "produce a change list" does not. Demand drives **legwork** (the digging the agent does within the work, latent in the wording rather than written as its own step), and it is not step-bound: "every rule applied" binds a body of flat reference just as "every step done" binds a sequence, which is how an all-reference document still carries an exhaustiveness bar. + +The strongest criteria are both checkable and exhaustive. + +## When to split + +Splitting one document into two spends one of the two loads, so split only when the cut earns it: + +- **By sequence**: split a run of steps where the post-completion steps tempt the agent to rush the one in front of it. Keeping them out of view drives more legwork on the current task. Beware the reverse: merging sequences exposes each step's later steps to what follows, inviting premature completion. +- **By invocation**, skill-specific: see [`SKILL-MECHANICS.md`](SKILL-MECHANICS.md). + +## Leading words + +A **leading word** is a compact concept already living in the model's pretraining that the agent thinks with while running the document (_lesson_, _fog of war_, _tracer bullets_). Repeated as a token, never as a sentence, it accumulates a distributed definition and anchors a whole region of behaviour in the fewest tokens, by recruiting priors the model already holds. Coining your own works if you define it clearly, but a made-up word recruits no priors: you pay in definition tokens what a pretrained word gives free; reach for an existing word first. + +It anchors twice. In the body, _execution_: the agent reaches for the same behaviour every time the word appears, and inside flat reference it focuses attention on a class of thing to look for. In a pointer, _invocation_: when the same word lives in your prompts, your docs, and your codebase, the agent links that shared language to the material and reaches it more reliably. + +Hunt for opportunities to refactor with leading words. A triad spelled out at three sites, a pointer spending a sentence to gesture at one idea. Each is a passage begging to collapse into a single token: + +- "fast, deterministic, low-overhead" → _tight_ (a _tight_ loop). +- "a loop you believe in" → _red_, turning a fuzzy gate into a binary observable state (the loop goes _red_ on the bug, or it doesn't). + +You win twice: fewer tokens, and a sharper hook for the agent to hang its thinking on. Assume every document is carrying restatements that leading words retire. Go find them. + +**Negation** is the failure mode beside this lever: steering by prohibition drags the forbidden behaviour into context and makes it _more_ available, not less. _Don't think of an elephant_, and the elephant is all there is; the negation is a weak modifier the strongly-activated concept overruns, so the ban half-reads as an instruction to do the thing. Prompt the **positive**: state the target behaviour ("write one-line comments") so the banned one is never spoken. A prohibition earns its place only as a hard guardrail you cannot phrase positively; even then, pair it with the positive target so attention lands on what to do. + +## Pruning + +- Keep each meaning in a **single source of truth**: one authoritative place, so changing the behaviour is a one-place edit. **Duplication** (the same meaning in more than one place) costs maintenance and tokens, and inflates a meaning's prominence on the ladder past its real rank. (The accidental inverse of a leading word, which repeats a token on purpose, never the meaning.) +- The **environment** is a source of truth too (`package.json` scripts, config files, the directory layout, `--help` output), and a document that restates it is a **cache**: a copy of a lookup, earning its load only when the lookup is expensive. Cache what the agent cannot find by looking: the unwritten convention, the reason behind a choice, the gotcha no config confesses. Leave the one-file, one-command lookups to the environment, where they cannot go stale. +- Check every line for **relevance**: does it still bear on what the document does? A line loses relevance by never bearing on the task (mere exposition, or a branch that should be disclosed) or by going stale as the behaviour or world it describes changes. Shorter documents are easier to keep relevant. Without a pruning discipline the default fate is **sediment**: stale layers that settle because adding feels safe and removing feels risky, until you must core down through them to find what is still live. +- Hunt **no-ops** sentence by sentence: an instruction the model already obeys by default pays load to say nothing. The test (does it change behaviour versus the default?) is model-relative, not reader-relative: two people disagreeing about a no-op disagree about the default, and settle it by running the document, not by debate. When a sentence fails, delete the whole sentence rather than trim words from it. The test also grades leading words: a word too weak to beat the default (_be thorough_ when the agent is already thorough-ish) is a no-op, and the fix is a stronger word (_relentless_), not a different technique. diff --git a/.claude/skills/writing-for-agents/agents/openai.yaml b/.claude/skills/writing-for-agents/agents/openai.yaml new file mode 100644 index 0000000..079c933 --- /dev/null +++ b/.claude/skills/writing-for-agents/agents/openai.yaml @@ -0,0 +1,3 @@ +interface: + display_name: "Writing for Agents" + short_description: "Write documents agents consume" diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 84d1fdd..d2e68e7 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -39,6 +39,7 @@ jobs: - name: Install test deps run: | pip install -r tests/requirements.txt + ansible-galaxy collection install -r ansible/requirements.yml - name: Reject committed host-only Git settings run: python3 -m machine_cli.local_overrides --check - name: Unit tests and CLI smoke @@ -48,9 +49,42 @@ jobs: pytest tests/unit -q - name: Ansible syntax run: | - ansible-galaxy collection install -r ansible/requirements.yml ansible-playbook --syntax-check -i ansible/inventory/local.yml ansible/workstation.yml + code-health: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # delta and the component check compare against the merge base + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Install uv + run: pip install uv==0.13.5 + - name: Cache ai-health and its tree-sitter grammars + uses: actions/cache@v4 + with: + path: | + ~/.cache/uv + ~/.cache/tree-sitter-language-pack + key: aihealth-${{ hashFiles('scripts/aihealth') }} + - name: Merge base with main + id: base + run: | + base="$(git merge-base origin/main HEAD)" || { echo "no merge base with origin/main" >&2; exit 1; } + echo "rev=$base" >> "$GITHUB_OUTPUT" + - name: Changed files must not get worse (docs/code-health.md) + run: | + scripts/aihealth delta --base "${{ steps.base.outputs.rev }}" --head HEAD --config .aihealth.toml + scripts/aihealth delta --base "${{ steps.base.outputs.rev }}" --head HEAD --config .aihealth-tests.toml tests + - name: Component scores must not fall + run: scripts/aihealth_components.py --compare "${{ steps.base.outputs.rev }}" HEAD + - name: Report per component + run: | + scripts/aihealth scan . --config .aihealth.toml + scripts/aihealth scan tests --config .aihealth-tests.toml + ansible-lint: needs: changes if: needs.changes.outputs.ansible == 'true' || needs.changes.outputs.hosts == 'true' @@ -90,6 +124,8 @@ jobs: with: python-version: "3.12" - name: Run all hooks + env: + SKIP: aihealth-delta,aihealth-delta-tests # the code-health job gates the delta against the merge base run: | pip install pre-commit pre-commit run --all-files --show-diff-on-failure --verbose @@ -167,11 +203,12 @@ jobs: with: python-version: "3.12" - name: Install test deps - run: pip install -r tests/requirements.txt + run: | + pip install -r tests/requirements.txt + ansible-galaxy collection install -r ansible/requirements.yml - name: Unit tests and Ansible syntax on ARM run: | python3 -m py_compile machine_cli/machine python3 -m compileall -q machine_cli pytest tests/unit -q - ansible-galaxy collection install -r ansible/requirements.yml ansible-playbook --syntax-check -i ansible/inventory/local.yml ansible/workstation.yml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 24899ed..fd8090e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,5 +1,8 @@ --- default_stages: [pre-commit] +# Skills installed with `npx skills add` stay byte-identical to their pinned source; skills-lock.json +# holds commit hashes that detect-secrets mistakes for secrets. +exclude: ^(\.claude/skills/(refactoring-patterns|python-testing-patterns|systematic-debugging|verification-before-completion|receiving-code-review|writing-for-agents|github-actions-hardening)/|skills-lock\.json$) repos: - repo: https://github.com/pre-commit/pre-commit-hooks.git rev: v5.0.0 @@ -57,11 +60,11 @@ repos: - --simplify - --diff files: ^home/core/\.bashrc$ - - repo: https://github.com/psf/black - rev: 24.10.0 + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.17.6 hooks: - - id: black - language_version: python3 + - id: ruff-format + - id: ruff-check - repo: https://github.com/google/yamlfmt rev: v0.14.0 hooks: @@ -103,14 +106,28 @@ repos: additional_dependencies: ['@fission-ai/openspec@1.14.3'] files: ^openspec/specs/ pass_filenames: false + - id: aihealth-delta + name: ai-health - staged files must not get worse (docs/code-health.md) + entry: scripts/aihealth delta --staged --config .aihealth.toml + language: system + types_or: [python, shell] + pass_filenames: false + require_serial: true + - id: aihealth-delta-tests + name: ai-health - staged tests must not get worse (docs/code-health.md) + entry: scripts/aihealth delta --staged --config .aihealth-tests.toml tests + language: system + files: ^tests/ + types: [python] + pass_filenames: false + require_serial: true + - id: aihealth-suppression-reason + name: 'ai-health suppressions need a reason (# aihealth: disable= -- )' + entry: 'aihealth:[ \t]*disable=(?![\w, \t]+-- .{10})' + language: pygrep + types_or: [python, shell] - id: no-co-authored-by name: forbid Co-authored-by trailers in commit messages entry: '(?i)^co-authored-by:' language: pygrep stages: [commit-msg] - - repo: https://github.com/pycqa/flake8 - rev: '7.1.1' - hooks: - - id: flake8 - args: - - --max-line-length=120 diff --git a/AGENTS.md b/AGENTS.md index 3814541..4e962d5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,6 +21,13 @@ Dotfiles + machine setup (mise dotfile groups, `machine` CLI, Ansible). Start wi - Run affected integration tests when behavior crosses deployment or system boundaries; for Ansible changes also run `ansible-lint ansible/*.yml`. See Readme "Tests" for Docker/APT tests. - Record commands, results and why the selection covers the change. Rerun after relevant edits, not merely because another workflow step started. +## Code health + +- Before every commit run `scripts/aihealth delta --config .aihealth.toml` and, for changed tests, `scripts/aihealth delta --config .aihealth-tests.toml tests` (add `--format json` for machine-readable output): no changed file may get worse and a new file must have no finding. The target is score 10 (no finding) per file; details in [docs/code-health.md](docs/code-health.md). +- Fix findings instead of suppressing them. Never remove or weaken type hints and never add type aliases only to silence a smell; the real fix is a parameter object or dataclass where it improves the code. Otherwise leave the finding or suppress it file-wide with `# aihealth: disable= -- `. +- Refactor without changing behaviour: run the tests of the touched code before and after each small step, and keep refactoring and behaviour changes in separate commits. +- Always call ai-health through `scripts/aihealth` (it holds the pin) and always pass `--config`. + ## Design decisions - Before changing an area, read its spec in `openspec/specs/` and the rationale in the archived `design.md` under `openspec/changes/archive/`. If a change would contradict a requirement or a recorded decision, ask the owner. diff --git a/Readme.md b/Readme.md index 8d8033f..73903c4 100644 --- a/Readme.md +++ b/Readme.md @@ -183,6 +183,7 @@ tests/ # unit + Docker/CI | Project containers (`sde`, `sdx`) | [docs/project-containers.md](docs/project-containers.md) | | `machine` CLI internals, layers, Galaxy vs. local roles | [docs/architecture.md](docs/architecture.md) | | Tests, CI, `machine testenv` | [docs/testing.md](docs/testing.md) | +| Code health with ai-health: components, gate, suppressions (`scripts/aihealth`) | [docs/code-health.md](docs/code-health.md) | | ThinkPad L13 Yoga Gen 2 | [docs/thinkpad-l13-yoga-gen2.md](docs/thinkpad-l13-yoga-gen2.md) | | Fingerprint login (manual) | [docs/fingerprint.md](docs/fingerprint.md) | diff --git a/ansible/roles/stylus_touch_guard/files/stylus_touch_guard.py b/ansible/roles/stylus_touch_guard/files/stylus_touch_guard.py index 33b2cd4..fb5cca3 100755 --- a/ansible/roles/stylus_touch_guard/files/stylus_touch_guard.py +++ b/ansible/roles/stylus_touch_guard/files/stylus_touch_guard.py @@ -4,6 +4,7 @@ Ported from ditschi/helpers-and-automation (Yoga L13 Thinkpad). Device nodes are resolved by name so /dev/input/eventN renumbering is fine. """ + from __future__ import annotations import argparse diff --git a/docs/code-health.md b/docs/code-health.md new file mode 100644 index 0000000..9d33982 --- /dev/null +++ b/docs/code-health.md @@ -0,0 +1,89 @@ +# Code health + +Code health is measured with [ai-health](https://github.com/epatel/ai-health) (MIT, deterministic, no AI needed), modelled on [CodeScene Code Health](https://codescene.io/docs/guides/technical/code-health.html). Score 1-10 per file and per component; the target is 10 (no finding), 9.5 is the minimum on the way there. Agents develop against it; pre-commit and CI keep it from getting worse. + +## Commands + +```bash +scripts/aihealth delta --config .aihealth.toml # changed files (incl. untracked) vs HEAD; exit 1 if worse +scripts/aihealth delta --config .aihealth-tests.toml tests # the same for the tests component +scripts/aihealth delta --config .aihealth.toml --format json # JSON, for agents +scripts/aihealth scan . --config .aihealth.toml # report: python-cli and shell +scripts/aihealth scan tests --config .aihealth-tests.toml # report: python-tests +scripts/aihealth scan machine_cli/updates.py --config .aihealth.toml -v # one file, every finding +uvx nox -s code-health # both scans plus the score of each component +scripts/aihealth_components.py --compare "$(git merge-base origin/main HEAD)" HEAD # what CI checks +``` + +`scripts/aihealth` only pins ai-health to a commit (so `uvx` serves it from the cache, also offline after the first run) and passes every argument through. Always give `--config`: `aihealth scan ` otherwise reads `/.aihealth.toml` and silently falls back to the defaults. `scripts/aihealth_components.py` exists because ai-health has no comparison of component scores between two revisions; it exports both with `git archive`, scans them with the checkout's profiles and splits the JSON by language. A full scan takes about 3 s. + +## Components + +| Component | Files | Config | +| --- | --- | --- | +| `python-cli` | Python outside `tests/`, `openspec/` and `.claude/skills/` | `.aihealth.toml` | +| `shell` | sh, bash and zsh files outside the same directories, including `home/**/.local/bin` and `home/**/.shell` | `.aihealth.toml` | +| `python-tests` | Python under `tests/` | `.aihealth-tests.toml` | + +Not scored: +- Ansible: ansible-lint is its gate (owner decision). +- Python scripts without a file extension (`machine_cli/machine`, `home/core/.local/bin/ssh-route`, `home/ssh-tunnel/.local/bin/ssh-tunnel`, `home/work/.local/bin/work-net`, `ansible/roles/homelab_node/files/homelab-ci`): ai-health does not detect them yet ([epatel/ai-health#3](https://github.com/epatel/ai-health/issues/3)). +- Test-specific smells (large and duplicated assertion blocks): ai-health has none yet. +- `.claude/skills/`: third-party agent skills, pinned in `skills-lock.json`. + +## Profile "strict" + +`.aihealth.toml` (owner decision 2026-11-23): CodeScene thresholds - cyclomatic complexity > 9, function > 70 lines, > 4 arguments, nesting 4, bumpy road 2 bumps, complex conditional 2 `and`/`or`, file > 600 lines, primitive obsession > 30 % of typed parameters (ai-health counts `str`, numbers, `bool` and the plain containers `dict`/`list`/`tuple`/`set` as primitive) - plus `decay = 8`, `symbol_cap = 4`, `density_loc = 100000` and `delta.tolerance = 0`. File score `10 - 9 x (1 - e^(-P/8))`, P the sum of the weighted findings; component score = mean of the file scores weighted by lines of code. + +`.aihealth-tests.toml` repeats the profile and sets the weights of `excess_arguments` (pytest fixtures arrive as arguments), `primitive_obsession` and `low_cohesion` (test classes group cases) to 0. `tests/unit/test_aihealth_config.py` keeps the shared sections of both files equal: change the profile in `.aihealth.toml` and copy it. The duplication goes away once ai-health supports overrides per path ([epatel/ai-health#4](https://github.com/epatel/ai-health/issues/4)); then both files merge into one. Test code gets no primitive-obsession suppressions; the smell is off there by config. + +## Gate + +- pre-commit `aihealth-delta` and `aihealth-delta-tests`: `delta --staged` per component; fails when a staged file gets worse or a new file has a finding. +- CI job `code-health`: `delta` against the merge base with `origin/main`, not its tip, so a branch behind `main` is not charged with newer changes there, the component comparison of merge base and head over the files that exist in both (a component may drop at most 0.01; deleted and new files are left out, new and changed files are judged by `delta`), and the full scan as a report (`delta` does not see duplication across files). The uv cache and `~/.cache/tree-sitter-language-pack` (about 30 MB of grammars) are cached. +- Suppressions are file-wide only: `# aihealth: disable=[, ] -- `. Without ` -- ` ai-health takes the reason as part of the smell name and silently ignores the suppression; the pygrep hook `aihealth-suppression-reason` rejects suppressions without ` -- ` and a reason of at least ten characters. +- Linting is separate: ruff (format and pycodestyle/pyflakes rules), shellcheck, shfmt, ansible-lint. Their structure rules stay off; each smell has one source, ai-health. + +## Steckbrief Code Health + +Profile for comparing this approach with the other repositories; the headings are fixed. + +### 1. Messumfang + +Three components with their own score and the target 10 (minimum 9.5): `python-cli` (all Python outside `tests/`, `openspec/` and `.claude/skills/`), `python-tests` (`tests/`) and `shell` (sh, bash, zsh, including dotfiles in hidden directories, which ai-health lists through `git ls-files`). Not scored: Ansible (ansible-lint only, owner decision), Python scripts without an extension (documented gap, epatel/ai-health#3); third-party skills in `.claude/skills/`. An overall score is not used for the gate; a large Python share would hide the shell component. + +### 2. Tools und Versionen, je Sprache + +- Python and shell: ai-health v0.4.0, pinned to commit `033d1867fe514867d944d9387ee72db0188eed47` in `scripts/aihealth`, run with `uvx` (tree-sitter-language-pack for parsing). +- Lint: ruff 0.17.6 (replaces black and flake8), shellcheck 0.11, shfmt 3.10, ansible-lint. +- Before ai-health, this change built an own checker on the Python standard library (`code_health/`, `ast`/`tokenize`, a line-based shell parser, PyYAML for Ansible), cross-checked with radon 6.0.1 (cyclomatic complexity equal for 533 of 537 functions) and complexipy 9.0.0 (cognitive complexity equal for 526 of 537). It found the same hotspots and was removed once ai-health was in place, following the owner's rule of no own logic where a tool exists. Checked and not used: lizard (no shell), ruff's structure rules (pass/fail without values), jscpd (Node). + +### 3. Abgebildete Smells + +ai-health covers complex method, large method, brain method, excess arguments, primitive obsession, code duplication (also across files in `scan`), deep nesting, bumpy road, complex conditional, cognitive complexity, large file and low cohesion (LCOM4). Not covered: brain class/god class and many functions per module as separate smells, large and duplicated assertion blocks (no test smells for Python yet), constructor over-injection (constructors count like any function). Switched off for `python-tests`: excess arguments, primitive obsession, low cohesion. + +### 4. Schwellen, Gewichte und Score-Formel + +See [Profile "strict"](#profile-strict). ai-health's default weights (brain method 2.0, large file 1.5, complex method 0.75, ...); severity = value / threshold, at most 3; per symbol the penalties are capped at 4; file score `10 - 9 x (1 - e^(-P/8))`, no density relief for large files. + +### 5. Bedienung + +`scripts/aihealth delta --config ` (text or `--format json`), `scripts/aihealth scan --config `, `uvx nox -s code-health` (the repository's task runner is nox). `delta` checks changed files only (working tree, `--staged`, or `--base`/`--head`). About 3 s for a full scan, well under a second for a small delta after the first run. + +### 6. Gate + +pre-commit hooks `aihealth-delta` and `aihealth-delta-tests` (`delta --staged` per component, tolerance 0, new files without findings) and the CI job `code-health` (delta against the merge base, component comparison with tolerance 0.01, report). No stored baseline: the base revision is the ratchet. Suppressions file-wide with a reason, enforced by a pygrep hook. + +### 7. Ergebnis + +Before (ai-health with the final strict profile on `main` 0a3d695, measured 2026-11-24 with `scripts/aihealth_components.py 0a3d695`): `python-cli` 3.97, `python-tests` 6.30, `shell` 8.89. Worst files: `tests/unit/test_update_and_env.py` 1.28, `machine_cli/ssh_client.py` 1.49, `machine_cli/netrc_sync.py` 1.52, `tests/unit/test_host_profiles.py` 1.62, `machine_cli/env_push.py` 1.94. The own checker measured the same hotspots (`python-cli` 3.76, `python-tests` 6.49, `shell` 8.10, `ansible` 8.65). + +After: added once the refactorings are done. + +### 8. Skills + +Searched with `npx skills find` (python, refactoring, testing, tdd, debugging, git, code review, documentation, shell, ansible, ci, and more); every adopted SKILL.md was read before. Adopted, project-local under `.claude/skills/` and pinned in `skills-lock.json` (pre-commit leaves them untouched): `wondelai/skills@refactoring-patterns`, `wshobson/agents@python-testing-patterns`, `obra/superpowers@systematic-debugging`, `obra/superpowers@verification-before-completion`, `obra/superpowers@receiving-code-review`, `mattpocock/skills@writing-for-agents`, `github/awesome-copilot@github-actions-hardening`. Rejected, among others: `codehealth-mcp` (paid CodeScene token), `obra/superpowers@brainstorming`, `writing-plans` and `mattpocock@to-spec` (compete with OpenSpec), `obra/superpowers@using-git-worktrees` (ignores this repository's worktree rule), `getsentry@agents-md` (prescribes `Co-Authored-By`), `test-driven-development` and `mattpocock@tdd` (dogmatic or blocking autonomous work), `wshobson@bash-defensive-patterns` (a blanket `set -Eeuo pipefail` changes behaviour). + +### 9. Erfahrungen + +Added once the refactorings are done. diff --git a/docs/testing.md b/docs/testing.md index 3315235..13b2140 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -15,6 +15,8 @@ pytest tests/integration -n auto -m apt # Pi Zero APT + tests/hosts/ci-rpi-zero. pytest tests/integration -m apt_gnome # private desktop APT + ci-home-laptop.yml (slow on a cold cache) ansible-lint ansible/*.yml # locally / in CI on changes under ansible/ or machine/hosts/ ansible-galaxy collection install -r ansible/requirements.yml +scripts/aihealth delta --config .aihealth.toml # code health of the changed files (docs/code-health.md) +uvx nox -s code-health # ai-health scan and score per component ``` Locally the APT tests download through a caching apt proxy (`dotfiles-test-apt-cache`, apt-cacher-ng on the Docker network `dotfiles-test`), so later runs fetch almost nothing. It is started on first use and kept running; `docker rm -f dotfiles-test-apt-cache` stops it (after a change to `tests/docker/apt-cache/` as well), `docker volume rm dotfiles-test-apt-cache` drops the cache. It is off in CI; `DOTFILES_TEST_APT_CACHE=0|1` overrides. The test image installs no recommended packages. @@ -22,6 +24,7 @@ Locally the APT tests download through a caching apt proxy (`dotfiles-test-apt-c CI (`.github/workflows/verify.yml`): - Unit + Ansible syntax (amd64 + arm) +- Code health with ai-health: delta against the merge base, component scores, report ([code-health.md](code-health.md)) - Docker matrix of context/device combinations (without APT) - Clean install from `tests/hosts/ci-container.yml` - APT + Ansible from `tests/hosts/ci-rpi-zero.yml` and `ci-home-laptop.yml` (CI host configs, read through `MACHINE_HOSTS_DIR=tests/hosts`) diff --git a/machine_cli/updates.py b/machine_cli/updates.py index 244be30..14e42c6 100644 --- a/machine_cli/updates.py +++ b/machine_cli/updates.py @@ -689,8 +689,7 @@ def block_update(self, plan: dict) -> None: def stash_conflicts(self, plan: dict) -> str: sha = self.stash_push( - f"conflicting with {plan['upstream']} " - f"{self._rev(plan['upstream'])[:8]}", + f"conflicting with {plan['upstream']} {self._rev(plan['upstream'])[:8]}", plan["conflicts"], ) if not sha: diff --git a/noxfile.py b/noxfile.py index 92a9a33..595535e 100644 --- a/noxfile.py +++ b/noxfile.py @@ -41,6 +41,23 @@ def tests(session: nox.Session) -> None: session.run("pytest", "tests/unit", "-q", *session.posargs) +@nox.session(name="code-health", python=False) +def code_health(session: nox.Session) -> None: + """ai-health scan of each component and their scores (docs/code-health.md).""" + session.run( + "scripts/aihealth", "scan", ".", "--config", ".aihealth.toml", external=True + ) + session.run( + "scripts/aihealth", + "scan", + "tests", + "--config", + ".aihealth-tests.toml", + external=True, + ) + session.run("scripts/aihealth_components.py", external=True) + + @nox.session(python=PYTHON) def ansible(session: nox.Session) -> None: """Ansible syntax check and lint.""" @@ -72,7 +89,7 @@ def docker(session: nox.Session) -> None: "docker and not apt and not apt_gnome", "-n", "auto", - *session.posargs + *session.posargs, ) session.log("Full apt profile: pytest tests/integration -m apt") session.log( diff --git a/openspec/changes/code-health/.openspec.yaml b/openspec/changes/code-health/.openspec.yaml new file mode 100644 index 0000000..aa249d5 --- /dev/null +++ b/openspec/changes/code-health/.openspec.yaml @@ -0,0 +1,3 @@ +--- +schema: spec-driven +created: 2026-11-23 diff --git a/openspec/changes/code-health/design.md b/openspec/changes/code-health/design.md new file mode 100644 index 0000000..8649cd3 --- /dev/null +++ b/openspec/changes/code-health/design.md @@ -0,0 +1,72 @@ +# Design + +## Context + +See proposal.md - Why. + +Inventory before this change: +- Linters in pre-commit: `black`, `flake8` (max line length 120, no complexity plugin), `shellcheck` (bash and sh, zsh excluded), `shfmt` (4 spaces), `yamlfmt`, `codespell`, `detect-secrets`, hygiene hooks, local hooks (`gitconfig-no-host-settings`, `bashrc-no-managed-blocks`, `mise-tools-declared-once`, `openspec-specs-strict`, `no-co-authored-by`). No complexity or size limits anywhere; no `pyproject.toml`, no ruff, no isort. +- Task runner: `noxfile.py` with uv venvs (`compile`, `tests`, `ansible`, `docker`). CI: `.github/workflows/verify.yml` (unit tests amd64/arm, pre-commit `--all-files`, ansible-lint on relevant changes, Docker and APT jobs). +- Code: 118 Python files (29 000 lines of code without blank lines, comments and docstrings; `machine_cli/` 9 700, `tests/` 17 000), 42 shell files (2 100 lines), 14 Ansible roles (1 774 lines of task files). The host setup is untouched: the check runs only in the repository. + +Measurements on 2026-11-23: +- Own checker (first step of this change, CodeScene thresholds, own deductions): `python-cli` 3.76, `python-tests` 6.49, `shell` 8.10, `ansible` 8.65; 85 files below 9.5. +- ai-health with the strict profile on `main` (0a3d695): `python-cli` 3.97, `python-tests` 6.30, `shell` 8.89. While the first refactorings were in progress the branch measured `python-cli` 4.76 (62 files, 41 with findings), `python-tests` 6.43, `shell` 9.56. A full scan takes about 3 s. The hotspots match the own checker: `tests/unit/test_update_and_env.py` (46 changes in 12 months, 1.28), `tests/unit/test_host_profiles.py` (44, 1.62), `machine_cli/updates.py` (30, 1.04), `tests/unit/test_bw_and_answers.py` (24, 7.0), `tests/unit/test_machine_cli.py` (22, 5.26), `machine_cli/tools.py` (17, 2.82), `machine_cli/dotfiles.py` (17, 3.79), `tests/unit/test_zsh_handoff.py` (15, 2.77); largest gaps to 10 also in `machine_cli/ssh_client.py`, `env_pull.py`, `netrc_sync.py`, `bw_client.py`. +- ai-health does not detect Python scripts without an extension (`machine_cli/machine`, `home/core/.local/bin/ssh-route`, `home/ssh-tunnel/.local/bin/ssh-tunnel`, `home/work/.local/bin/work-net`, `ansible/roles/homelab_node/files/homelab-ci`); epatel/ai-health#3 asks for shebang detection. In git repositories it lists files through `git ls-files`, so hidden directories such as `home/core/.local/bin` and `home/core/.shell` are scored. +- ai-health has no test detection for Python and supports suppressions only per file (`# aihealth: disable= -- `; without ` -- ` the reason becomes part of the smell name and the suppression silently does nothing). + +## Goals / Non-Goals + +**Goals:** +- One shared tool and profile for Python across the owner's repositories (owner decision Q2), with score 10 as the target. +- One command with machine-readable output and a mode for changed files, which agents develop against. +- An agent-proof gate: per file against the base revision and per component in CI. +- A section "Steckbrief Code Health" in `docs/code-health.md` with the nine headings requested by the owner, for the comparison with the other repositories. + +**Non-Goals:** +- A score for Ansible (owner decision Q3); ansible-lint stays its only gate. +- Test-specific smells (large and duplicated assertion blocks): ai-health has none; they are a documented gap until upstream adds them (owner decision Q4). +- Keeping the own checker as a cross-check; it is removed. + +## Decisions + +**ai-health as the tool, pinned to a commit.** ai-health (MIT) is deterministic, covers Python and shell with CodeScene-like smells, has `scan`, `delta` with exit codes and JSON, and Claude Code hooks (owner decision Q1). It is pinned to commit `033d1867fe514867d944d9387ee72db0188eed47` (the commit behind v0.4.0) rather than the tag: with the tag `uvx` resolves over the network on every call (about 1.6 s), with the commit everything comes from the cache (about 0.24 s, also offline). The pin lives only in `scripts/aihealth`, a three-line script that runs ai-health through `uvx` and passes every argument through; hook, CI and nox call it with an explicit `--config` per component, so there is no second copy of the pin in a lock file or in pre-commit's `additional_dependencies`. The pre-commit hooks therefore use `language: system`; a `language: python` hook would need a second pin. An earlier version of the wrapper also split paths per component and merged the JSON of both; it was cut back because ai-health does all of that per call (owner rule, 2026-11-24: no own logic where the tool can do it). + +**Components.** `python-cli` (everything outside `tests/`, `openspec/` and the third-party skills in `.claude/skills/`), `python-tests` (`tests/`) and `shell`. The main scan with `.aihealth.toml` covers Python and shell together; the component scores are computed from its JSON per language (shell = bash, zsh, sh), as the LOC-weighted mean ai-health also uses for its project score. Tests are scanned separately with `.aihealth-tests.toml`. + +**Profile strict in two files.** `.aihealth.toml` holds the profile (owner decision Q15): CodeScene thresholds (ai-health's defaults for complex method 9, large method 70, nesting 4, bumpy road 2, complex conditional 2 and arguments 4 already match), `large_file = 600`, `primitive_obsession = 0.3`, `decay = 8` (stricter than the default 15; matches the own prototypes), `symbol_cap = 4`, `density_loc = 100000` (large files are not relieved through their smell density), `delta.tolerance = 0`. ai-health reads exactly one file per call, so `.aihealth-tests.toml` repeats the profile and only adds `[weights]` 0 for `excess_arguments` (pytest fixtures arrive as arguments), `primitive_obsession` and `low_cohesion` (test classes group cases). A unit test keeps `[thresholds]`, `[score]` and `[delta]` of both files equal, so the profile is changed in one place and the test points at the other. Two configs is the owner's decision for all repositories (Q18.1, 2026-11-26) until ai-health supports overrides per path (epatel/ai-health#4); then they merge into one. Test code gets no primitive-obsession suppressions. Every call passes `--config` explicitly, because `aihealth scan ` otherwise reads `/.aihealth.toml` and silently falls back to the defaults. + +For the own checker the owner had first chosen 50 % for primitive obsession; the strict profile for ai-health sets 30 % for production code and switches the smell off in test code (owner decisions Q15 and Q18). + +**Gate.** Locally the pre-commit hook runs `delta --staged` for both configurations (exit 1 on any degradation; a new file with a finding counts as degraded). In CI, `delta --base "$(git merge-base origin/main HEAD)" --head HEAD` runs per configuration with full fetch depth; against `origin/main` a branch behind `main` would be charged with `main`'s newer changes. CI also compares the component scores of merge base and head (owner decision Q6): `scripts/aihealth_components.py` exports the merge base with `git archive`, scans both trees and fails when a component drops by more than 0.01, counted only over the files that exist in both revisions (owner decision Q6, 2026-11-26): over all files, deleting a healthy file lowered the LoC-weighted mean and failed the check, which would block removing dead code; new and changed files are judged per file by `delta` anyway. Dropping the comparison was rejected. `delta` does not see cross-file duplication, so the CI also prints the full scan of each component as a report. The tree-sitter grammars (`~/.cache/tree-sitter-language-pack`, about 30 MB) are cached in CI. + +**Suppressions.** ai-health supports only file-wide suppressions. The pygrep hook `aihealth-suppression-reason` rejects `aihealth: disable=` unless it is followed by smell names, ` -- ` and a reason of at least ten characters (regex `aihealth:[ \t]*disable=(?![\w, \t]+-- .{10})`), the same as in homelab; no own code is needed. + +**ruff replaces black and flake8.** One linter and formatter for Python in all repositories (owner decision Q8), in its own commit so the reformatting can be reviewed separately. `ruff format` (black-compatible) and `ruff check` with the rules flake8 enforced today (`E`, `F`, `W`, maximum line length 120); `C90` and other structure rules stay off, because ai-health is the only source for each smell (owner decision Q9). isort is not used in this repository, so import sorting is not added. + +**Own checker removed.** The checker built first (`code_health/`, standard library plus PyYAML, own deductions) measured the same hotspots as ai-health and was removed with its config, baseline and tests once ai-health was in place (owner rule, 2026-11-24: no own logic where a tool exists, it does not stay as a cross-check). Its measurements are kept in Context and in the docs' Steckbrief. + +**Component comparison is the only own logic.** `scripts/aihealth_components.py` (about 95 lines of code) exists because ai-health cannot compare component scores between two revisions (owner decision Q6); everything else is plain ai-health calls. + +**Commands.** The task runner is nox: `uvx nox -s code-health` prints the scan of each component and their scores; agents and humans check changed files with `scripts/aihealth delta --config ` (`--format json`). + +**Two skills from skills.sh, project-local.** `wondelai/skills@refactoring-patterns`, `wshobson/agents@python-testing-patterns`, `obra/superpowers@systematic-debugging`, `obra/superpowers@verification-before-completion`, `obra/superpowers@receiving-code-review`, `mattpocock/skills@writing-for-agents` and `github/awesome-copilot@github-actions-hardening` are installed under `.claude/skills/` and pinned in `skills-lock.json` (owner decisions, 2026-11-23 and 2026-11-24). Their SKILL.md files were read before; pre-commit excludes them so they stay byte-identical to the pinned source. Skills from `codehealth-mcp` were excluded because they need the paid CodeScene token. + +**Two pull requests.** The first carries the ai-health gate, the profiles, ruff, the docs and the skills; the second the refactorings toward 10, after the owner approved the ai-health hotspots (owner decision, 2026-11-24). Each gets an independent review, green CI and the owner's go before it is merged. + +**Type hints stay.** Type hints are never removed or weakened and no type aliases are added only to silence a smell; a finding is fixed with a parameter object or dataclass where that improves the code, otherwise it stays or gets a file-wide suppression with a reason (owner rule, 2026-11-24). Primitive obsession is off in test code and stays at 30 % in production code (owner decision Q18, 2026-11-24). + +**Refactorings.** Behaviour-preserving, in small steps with the tests of the touched code green before and after, one file or one topic per commit, ordered by change frequency. The first four (updates, commands, shell scripts, Ansible task files) started against the own checker and fix findings ai-health reports as well; further refactorings toward 10 start after the owner approved the ai-health hotspots. + +## Risks / Trade-offs + +- [Upstream changes or disappears] → Pinned commit; `scripts/aihealth` is the only place to change. +- [No network in CI or on a host] → Grammar cache in CI; locally the first run downloads, later runs work offline from the uv and grammar caches. +- [Scripts without extension are not scored] → Documented gap until epatel/ai-health#3 is solved; their size and complexity are known from the own checker's measurement. +- [Two profile files drift apart] → Unit test compares them. +- [Strict gate blocks unrelated small edits in unhealthy files] → `delta` only fails when a file gets worse, not because it is already unhealthy. +- [Refactoring breaks behaviour] → Small steps, each with the unit tests green; tests for the touched code first where coverage is thin. + +## Migration Plan + +No host changes. Order: ai-health wrapper, profiles, nox session, hooks and CI, docs; ruff migration as its own commit after the running refactorings landed; then, after the owner's approval of the hotspots, refactorings toward 10; the own checker is removed in the first pull request. Rollback: remove the ai-health hooks and CI steps. diff --git a/openspec/changes/code-health/proposal.md b/openspec/changes/code-health/proposal.md new file mode 100644 index 0000000..63e9053 --- /dev/null +++ b/openspec/changes/code-health/proposal.md @@ -0,0 +1,40 @@ +# Proposal + +## Why + +Agents change this repository often. According to CodeScene's whitepaper "AI-Ready Code" (A. Tornhill, 2026), AI changes in unhealthy code have at least 60 % more defects; the underlying study only covered code with a health of 7 or more. Healthy code is therefore a precondition for agents to work reliably, next to tests, coverage and review. The owner decided not to use the proprietary CodeScene score (paid token) and to measure code health with free tools instead, modelled on CodeScene Code Health, with the target score 10 (no finding) and 9.5 as the minimum on the way there. Agents shall be able to develop against the check. + +After comparing approaches across six repositories, the owner decided on 2026-11-23 to use ai-health for Python in all repositories and for shell where it occurs, with one shared strict profile. The own checker built first in this change was removed once ai-health was in place, following the owner's rule of no own logic where a tool exists (2026-11-24). + +## What Changes + +- ai-health (github.com/epatel/ai-health, MIT, deterministic, no AI needed) pinned to commit `033d1867fe514867d944d9387ee72db0188eed47` (v0.4.0) in one place, `scripts/aihealth`, which only runs it through `uvx` and passes the arguments through. +- Components with their own score: `python-cli` (all Python outside `tests/`, `openspec/` and the third-party skills), `python-tests` (`tests/`), `shell` (sh, bash and zsh files ai-health detects). Ansible has no score; ansible-lint stays its gate (owner decision Q3). Python scripts without a file extension (`machine_cli/machine`, `ssh-route`, `ssh-tunnel`, `work-net`, `homelab-ci`) are a documented gap while epatel/ai-health#3 is open (owner decision Q16). +- Profile "strict" in `.aihealth.toml` (CodeScene thresholds, `decay = 8`, `density_loc = 100000`, `delta.tolerance = 0`; owner decision Q15); `.aihealth-tests.toml` repeats it and switches off the argument, primitive and cohesion smells for tests. +- Commands: `uvx nox -s code-health` (scan report per component) and `scripts/aihealth delta --config ` for the changed files, with `--format json` for agents. +- Gate: pre-commit hook `aihealth delta --staged` per component (exit 1 on any degradation; new files must have no smell); CI `delta` against the merge base with `main` per component and a comparison of the component scores of merge base and head (owner decision Q6); the tree-sitter grammars are cached in CI. +- Suppressions only file-wide as `# aihealth: disable= -- `; a pygrep hook rejects them without a reason. +- ruff replaces black and flake8 as the Python linter and formatter, in its own commit; its structure rules (`C90`) stay off, ai-health is the only source for each smell (owner decisions Q8, Q9). +- The own checker (`code_health/`, `code-health.toml`, `code-health-baseline.json`, its tests) is removed; its measurements are recorded in design.md and the Steckbrief (owner rule, 2026-11-24: no own logic where a tool exists). +- `AGENTS.md` and `docs/code-health.md` describe the ai-health workflow; the docs carry the "Steckbrief Code Health" for the comparison across repositories. +- Refactorings without behaviour change toward score 10, in small tested steps, ordered by change frequency; refactorings beyond those already running need the owner's approval of the ai-health hotspots. +- Agent skills from skills.sh, installed project-locally: `wondelai/skills@refactoring-patterns`, `wshobson/agents@python-testing-patterns`, `obra/superpowers@systematic-debugging`, `verification-before-completion` and `receiving-code-review`, `mattpocock/skills@writing-for-agents`, `github/awesome-copilot@github-actions-hardening` (owner decisions, 2026-11-23 and 2026-11-24). +- Two pull requests: first the gate, tooling, docs and skills; then the refactorings (owner decision, 2026-11-24). + +## Capabilities + +### New Capabilities +- `code-health`: the code health check with ai-health: components, profile, commands, gate, suppressions and documented gaps. + +### Modified Capabilities +- `pre-commit-checks`: the hook list names ruff instead of black and flake8, plus the ai-health hooks. + +Affected profiles: none. The check runs only in the repository (development, pre-commit, CI); nothing is installed or linked on hosts. + +## Impact + +- New: `scripts/aihealth`, `scripts/aihealth_components.py`, `.aihealth.toml`, `.aihealth-tests.toml`, `ruff.toml`, `docs/code-health.md`, the seven skills under `.claude/skills/` with `skills-lock.json`, unit tests for the configuration consistency. +- Changed: `AGENTS.md`, `noxfile.py`, `.pre-commit-config.yaml`, `.github/workflows/verify.yml`, `Readme.md`, `docs/testing.md`; the ruff migration reformats Python files without changing behaviour. Refactorings touch `machine_cli/`, scripts under `home/`, `ansible/` and `tests/` without changing behaviour. +- Dependencies: ai-health and tree-sitter-language-pack (about 30 MB of grammars, cached) via `uvx`, only for development and CI; ruff via pre-commit. + +Where: this checkout `/home/ditschi/dotfiles/.claude/worktrees/xenodochial-ellis-c9a21e` on branch `code-health`. It is a git worktree that is not the live checkout, and AGENTS.md says to stay in a non-live checkout instead of creating another worktree. The refactorings touch `machine_cli` and shell scripts that run on the live host, so the work must not happen in the live checkout. diff --git a/openspec/changes/code-health/specs/code-health/spec.md b/openspec/changes/code-health/specs/code-health/spec.md new file mode 100644 index 0000000..be4be93 --- /dev/null +++ b/openspec/changes/code-health/specs/code-health/spec.md @@ -0,0 +1,89 @@ +# Spec Delta + +## Purpose + +Measures the health of the repository's Python and shell code on a scale from 1 to 10 per component with ai-health, modelled on CodeScene Code Health, and keeps it from getting worse through a gate in pre-commit and CI. + +## ADDED Requirements + +### Requirement: Pinned tool +Code health SHALL be measured with ai-health, pinned to one commit in exactly one place, `scripts/aihealth`, which passes its arguments to ai-health unchanged. Every hook, CI step and nox session SHALL call ai-health through it. + +#### Scenario: Updating ai-health +- **WHEN** the pinned commit is changed in `scripts/aihealth` +- **THEN** the hook, CI and nox use the new version without further edits + +### Requirement: Components +The code SHALL be scored in three components: `python-cli` (Python files outside `tests/`, `openspec/` and `.claude/skills/`), `python-tests` (Python files under `tests/`) and `shell` (shell files ai-health detects outside the same directories). Each component score SHALL be the mean of its file scores weighted by lines of code. + +#### Scenario: Report per component +- **WHEN** a user runs `uvx nox -s code-health` +- **THEN** the output shows one score for each of `python-cli`, `python-tests` and `shell` + +### Requirement: Not scored +Ansible files SHALL NOT get a score; ansible-lint SHALL remain their gate. Python scripts without a file extension SHALL be listed in `docs/code-health.md` as not scored while ai-health cannot detect them. + +#### Scenario: Script without extension +- **WHEN** ai-health scans the repository +- **THEN** `machine_cli/machine` is not scored and the docs name this gap + +### Requirement: Strict profile +The thresholds, score parameters and delta tolerance SHALL be set in `.aihealth.toml` (profile "strict": CodeScene thresholds, file size 600 lines, primitive obsession 30 %, decay 8, density 100 000 lines, tolerance 0). `.aihealth-tests.toml` SHALL repeat these values unchanged and set the weights of excess arguments, primitive obsession and low cohesion to 0. + +#### Scenario: Diverging test profile +- **WHEN** `.aihealth-tests.toml` sets a threshold that differs from `.aihealth.toml` +- **THEN** the unit tests fail + +#### Scenario: Fixture arguments +- **WHEN** a test function takes six pytest fixtures +- **THEN** no excess-arguments finding is reported for it + +### Requirement: Explicit configuration +Every ai-health call SHALL pass the configuration of its component with `--config`, so that no call falls back to the defaults. + +#### Scenario: Scanning the tests directory +- **WHEN** the tests component is scanned +- **THEN** ai-health reads `.aihealth-tests.toml` from the repository root + +### Requirement: Changed files for agents +`scripts/aihealth delta --config ` SHALL compare the changed files of the working tree with `HEAD` and exit with 1 when a file got worse or a new file has a finding; `--format json` SHALL give the same result as JSON. + +#### Scenario: Agent checks its change +- **WHEN** an agent runs `scripts/aihealth delta --config .aihealth.toml --format json` after editing a module +- **THEN** it gets the new and worsened findings of the changed files + +### Requirement: Pre-commit gate +A pre-commit hook SHALL run `delta --staged` for each component and fail when a staged file got worse or a new file has a finding. + +#### Scenario: Commit that adds a finding +- **WHEN** a commit adds a complex function to a file without findings +- **THEN** the hook fails and names the file and the finding + +### Requirement: CI gate +The CI SHALL run `delta` per component between the merge base with `main` and `HEAD`, and SHALL fail when the score of a component at `HEAD`, counted over the files that exist in both revisions, is lower than at the merge base by more than 0.01. The CI SHALL cache the tree-sitter grammars. + +#### Scenario: Branch behind main +- **WHEN** a branch is behind `main` and changes one file without making it worse +- **THEN** the gate passes, because it compares against the merge base + +#### Scenario: Deleting a healthy file +- **WHEN** a pull request deletes a file without findings +- **THEN** the component comparison passes + +#### Scenario: Component gets worse +- **WHEN** a pull request lowers the `shell` component score +- **THEN** the CI gate fails and names the component + +### Requirement: Suppressions with reason +A finding SHALL be suppressed only file-wide with `# aihealth: disable=[, ] -- `; a pre-commit hook SHALL reject a suppression without ` -- ` and a reason of at least ten characters. + +#### Scenario: Suppression without reason +- **WHEN** a file contains `# aihealth: disable=complex_method` +- **THEN** the hook fails + +### Requirement: Target score +The target for every file and component SHALL be 10 (no finding); 9.5 SHALL be the minimum on the way there. + +#### Scenario: Reviewing a component +- **WHEN** a component scores 9.6 +- **THEN** it meets the minimum, and its remaining findings are still to be fixed diff --git a/openspec/changes/code-health/specs/pre-commit-checks/spec.md b/openspec/changes/code-health/specs/pre-commit-checks/spec.md new file mode 100644 index 0000000..ae12471 --- /dev/null +++ b/openspec/changes/code-health/specs/pre-commit-checks/spec.md @@ -0,0 +1,14 @@ +# Spec Delta + +## MODIFIED Requirements + +### Requirement: Pre-commit hooks +`pre-commit` SHALL run the hygiene hooks, `detect-private-key`, `detect-secrets`, `shellcheck`, `shfmt` (4 spaces), `ruff format` and `ruff check` (maximum line length 120, structure rules off), `yamlfmt`, `codespell` and the local hooks `gitconfig-no-host-settings`, `bashrc-no-managed-blocks`, `aihealth-delta`, `aihealth-delta-tests` and `aihealth-suppression-reason`. + +#### Scenario: Running all hooks +- **WHEN** a user runs `pre-commit run --all-files` +- **THEN** all of these hooks run + +#### Scenario: Delta hooks in CI +- **WHEN** the CI `pre-commit` job runs all hooks +- **THEN** it skips `aihealth-delta` and `aihealth-delta-tests`, because the `code-health` job checks the delta against the merge base diff --git a/openspec/changes/code-health/tasks.md b/openspec/changes/code-health/tasks.md new file mode 100644 index 0000000..acdb183 --- /dev/null +++ b/openspec/changes/code-health/tasks.md @@ -0,0 +1,64 @@ +# Tasks + +## 1. Own checker (history; removed in 6.1) + +- [x] 1.1 Apply the decisions (complex conditional from 2 operators, primitive obsession over annotated arguments) to `code-health.toml` and the rules; verify with `python3 -m code_health` that the run completes and the config comments state each value's origin +- [x] 1.2 Parts `python-cli`, `python-tests`, `shell` with their own rule sets in `code-health.toml` (table, JSON, baseline and gate per part, overall score for information) and the `ansible` part (tasks per file, complex `when`, `block` nesting, Jinja control tags, duplicated tasks); verify with `python3 -m code_health` that each part score is shown and that `excess-arguments` is not reported for tests +- [x] 1.3 Unit tests for the Python metrics (cyclomatic and cognitive complexity, nesting with `elif`, bumps, conditionals, arguments, primitive arguments, LCOM4, assertion blocks, nested functions excluded from duplication) in `tests/unit/test_code_health_python.py`; verify with `pytest tests/unit/test_code_health_python.py -q` +- [x] 1.4 Unit tests for the shell parser (functions in all three definition styles, nesting, `case` items, heredocs, keywords inside strings and comments, files without logic) in `tests/unit/test_code_health_shell.py`; verify with `pytest tests/unit/test_code_health_shell.py -q` +- [x] 1.5 Unit tests for rules, scoring, suppressions, `--json`, `--changed` and the gate and baseline on a temporary git repository in `tests/unit/test_code_health.py`; verify with `pytest tests/unit/test_code_health.py -q` +- [x] 1.6 Refactor `code_health/` until every file scores 10.0; verify with `python3 -m code_health code_health/*.py --all` +- [x] 1.7 Write `docs/code-health.md` (rules, thresholds with origin, formula, gate, baseline, suppressions, commands) with the section "Steckbrief Code Health" and its nine headings (Messumfang, Tools und Versionen, Abgebildete Smells, Schwellen/Gewichte/Formel, Bedienung, Gate, Ergebnis, Skills, Erfahrungen) and link it from `Readme.md` and `docs/testing.md`; verify the documented commands run as written + +## 2. Gate with the own checker (history; replaced in group 3, removed in 6.1) + +- [x] 2.1 Add the nox session `code-health` (passes arguments through); verify `uvx nox -s code-health -- --changed` prints the table +- [x] 2.2 Generate `code-health-baseline.json` with `python3 -m code_health --update-baseline`; verify `python3 -m code_health --gate --changed` passes on the branch +- [x] 2.3 Add the local pre-commit hook `code-health` (`--gate --base HEAD` on the staged files, serial); verify it fails on a scratch commit that adds a complex function and passes after reverting +- [x] 2.4 Add the gate step to the `unit` job in `verify.yml` (`--gate --changed origin/main`, full fetch depth); verify the workflow YAML with `pre-commit run check-yaml --files .github/workflows/verify.yml` +- [x] 2.5 Add the section "Code health" to `AGENTS.md`: run `python3 -m code_health --changed` before every commit, fix smells instead of suppressing them, suppress only with a reason, tighten the baseline after improvements; add a rule for behaviour-preserving refactoring +- [x] 2.6 Install `wondelai/skills@refactoring-patterns` and `wshobson/agents@python-testing-patterns` project-locally with `npx skills add`; verify they appear under `.claude/skills/` and their SKILL.md matches the reviewed version + +## 3. ai-health + +- [x] 3.1 Add `scripts/aihealth` with the pinned commit `033d1867fe514867d944d9387ee72db0188eed47` as the only pin; subcommands pass `--config` per component (`scan`, `delta` for `python-cli`/`shell` with `.aihealth.toml` and for `python-tests` with `.aihealth-tests.toml`); verify `scripts/aihealth scan` and `scripts/aihealth delta --format json` run and the wrapper itself has no findings +- [x] 3.2 Add `.aihealth.toml` and `.aihealth-tests.toml` (profile strict) and `tests/unit/test_aihealth_config.py`, which checks that `[thresholds]`, `[score]` and `[delta]` are equal and the three test weights are 0; verify with `pytest tests/unit/test_aihealth_config.py -q` +- [x] 3.3 Add `scripts/aihealth_components.py` (component scores of a revision from the scan JSON; compare merge base and head, tolerance 0.01) with unit tests for the comparison; verify with its tests and a run against `HEAD~1` +- [x] 3.4 Change the nox session `code-health` to print the ai-health scan per component; verify `uvx nox -s code-health` +- [x] 3.5 Add the pre-commit hooks `aihealth-delta` (`scripts/aihealth delta --staged`, `language: system`) and `aihealth-suppression-reason` (pygrep); verify the delta hook fails on a scratch change that adds a complex function and passes after reverting, and the pygrep hook fails on a suppression without ` -- ` +- [x] 3.6 Add the CI steps: grammar cache, `delta` against the merge base per component, component comparison, scan report; verify with `pre-commit run check-yaml --files .github/workflows/verify.yml` and a local run of the same commands +- [x] 3.7 Rewrite `docs/code-health.md` for ai-health (components, profile, commands, gate, suppressions, gaps: scripts without extension, Ansible, test smells), update the Steckbrief, `AGENTS.md`, `Readme.md` and `docs/testing.md`; verify the documented commands run as written + +- [x] 3.8 Cut `scripts/aihealth` back to the pin (hooks, CI and nox pass `--config` per component themselves) and drop the cosmetic type aliases in `scripts/aihealth_components.py`; verify the hooks fail and pass on scratch changes and `scripts/aihealth scan scripts/aihealth_components.py --config .aihealth.toml` shows no finding +- [x] 3.9 Install `obra/superpowers@systematic-debugging`, `verification-before-completion`, `receiving-code-review`, `mattpocock/skills@writing-for-agents` and `github/awesome-copilot@github-actions-hardening` project-locally; verify their SKILL.md match the reviewed copies + +## 4. ruff + +- [x] 4.1 Add `ruff.toml` (format line length 88 as black, lint line length 120 as flake8, rules `E`, `F`, `W`, no `C90`) and replace the `black` and `flake8` hooks with `ruff-format` and `ruff` (check); verify `pre-commit run ruff --all-files` and `pre-commit run ruff-format --all-files` pass after 4.2 +- [x] 4.2 Reformat with `ruff format` and fix `ruff check` findings in one separate commit without behaviour change, after the running refactorings landed; verify `pytest tests/unit -q` + +## 4b. Pull request 1 + +- [ ] 4b.1 Open PR 1 (gate, profiles, ruff, docs, skills) without the refactorings; run an independent review (`/code-review` high or a fresh reviewer subagent with only the diff, the repo and AGENTS.md), fix or justify findings, wait for green CI (`gh pr checks`), and merge only after the owner's go in this session + +## 5. Refactoring toward 10 (pull request 2) + +- [ ] 5.1 Land the running refactorings (`machine_cli/updates.py`, `machine_cli/commands.py`, shell scripts, Ansible task files), each reviewed and committed per file with its tests green; verify per file with its tests and `scripts/aihealth delta` +- [ ] 5.2 Present the ai-health hotspots (strict) to the owner and get approval for the further refactorings +- [ ] 5.3 Refactor the approved files toward 10, ordered by change frequency, one file or topic per commit; verify per file with its tests and `scripts/aihealth delta`, until every component scores at least 9.5 + +## 6. Removal of the own checker + +- [x] 6.1 Remove (owner rule 2026-11-24, in PR 1) `code_health/`, `code-health.toml`, `code-health-baseline.json`, its tests and nox session; verify `pytest tests/unit -q` and that no reference is left + +## 7. Validation + +- [ ] 7.1 `pytest tests/unit -q` (shared test and validation config and `machine_cli` core change) +- [ ] 7.2 `pre-commit run --files ` including the new untracked files, then `pre-commit run --all-files` because the hook configuration changes +- [ ] 7.3 `openspec validate code-health --strict` +- [ ] 7.4 Review the branch diff against main with a fresh reviewer (`/code-review` or a review subagent) and fix the findings + +## Workflow follow-up + +- Fill in "7. Ergebnis" and "9. Erfahrungen" of the Steckbrief, report scores before and after per component, remaining findings and the Steckbrief path, and open the PR. +- Archive the change after review (`/opsx:archive`). diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..8c24f1e --- /dev/null +++ b/ruff.toml @@ -0,0 +1,13 @@ +# ruff replaces black and flake8 (owner decision 2026-11-23). Formatting as black did +# (line length 88); linting the pycodestyle/pyflakes rules flake8 checked, with its line +# length 120. Structure rules (C90, PLR09xx) stay off: ai-health is the only source for +# complexity and size findings (docs/code-health.md). +line-length = 88 +target-version = "py311" +extend-exclude = ["openspec/changes/*/spike"] + +[lint] +select = ["E", "F", "W"] + +[lint.pycodestyle] +max-line-length = 120 diff --git a/scripts/aihealth b/scripts/aihealth new file mode 100755 index 0000000..6af5604 --- /dev/null +++ b/scripts/aihealth @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# ai-health pinned to one commit, the only place that holds the pin (docs/code-health.md). +# Arguments go to ai-health unchanged; always pass --config (.aihealth.toml, or +# .aihealth-tests.toml for tests/). +set -euo pipefail +exec uvx --quiet --from "git+https://github.com/epatel/ai-health@033d1867fe514867d944d9387ee72db0188eed47" aihealth "$@" diff --git a/scripts/aihealth_components.py b/scripts/aihealth_components.py new file mode 100755 index 0000000..d7d364c --- /dev/null +++ b/scripts/aihealth_components.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +# aihealth: disable=primitive_obsession -- ai-health scan JSON arrives as plain dicts; wrapping it adds no value +"""Component scores of a revision, and the CI check that no component got worse. + + scripts/aihealth_components.py scores of the working tree + scripts/aihealth_components.py REV scores of REV + scripts/aihealth_components.py --compare BASE [HEAD] + exit 1 when a component of HEAD scores + more than 0.01 below BASE, counted over + the files that exist in both + +Both revisions are exported with `git archive` and scanned with the profiles of the +current checkout, so a change of the profile does not count as a change of the code. +""" + +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +WRAPPER = ROOT / "scripts" / "aihealth" +TOLERANCE = 0.01 +SHELL_LANGUAGES = {"bash", "zsh", "sh", "shell"} + + +def code_component(entry: dict) -> str | None: + """Component of a file from the code scan: python-cli or shell.""" + if entry["language"] == "python": + return "python-cli" + return "shell" if entry["language"] in SHELL_LANGUAGES else None + + +def tests_component(entry: dict) -> str | None: + """The tests scan holds the python-tests component only.""" + return "python-tests" if entry["language"] == "python" else None + + +def component_files(scans: dict[str, dict]) -> dict[str, tuple[str, float, int]]: + """Component, score and lines of code per repository path, from ai-health scan JSON.""" + files = {e["path"]: (code_component(e), e) for e in scans["code"]["files"]} + files |= { + f"tests/{e['path']}": (tests_component(e), e) for e in scans["tests"]["files"] + } + return { + path: (name, entry["score"], entry["loc"]) + for path, (name, entry) in files.items() + if name + } + + +def component_scores(files: dict[str, tuple[str, float, int]]) -> dict[str, float]: + """LoC-weighted mean of the file scores per component.""" + totals: dict[str, list[float]] = {} + for name, score, loc in files.values(): + total = totals.setdefault(name, [0.0, 0.0]) + total[0] += score * loc + total[1] += loc + return { + name: round(weighted / loc, 2) + for name, (weighted, loc) in sorted(totals.items()) + if loc + } + + +def common(files: dict, other: dict) -> dict: + """The entries of `files` whose path also exists in `other`.""" + return {path: entry for path, entry in files.items() if path in other} + + +def regressions(base: dict[str, float], head: dict[str, float]) -> list[str]: + return [ + f"{name}: {base[name]:.2f} -> {score:.2f}" + for name, score in head.items() + if name in base and round(base[name] - score, 2) > TOLERANCE + ] + + +def export(revision: str, target: Path) -> None: + """The revision's files in `target`, as a git repository so ai-health lists them like in the checkout.""" + archive = subprocess.run( + ["git", "-C", str(ROOT), "archive", revision], check=True, capture_output=True + ) + subprocess.run(["tar", "-x", "-C", str(target)], input=archive.stdout, check=True) + subprocess.run(["git", "-C", str(target), "init", "-q"], check=True) + subprocess.run(["git", "-C", str(target), "add", "-A"], check=True) + + +def scan(tree: Path) -> dict[str, dict]: + configs = { + "code": (tree, ".aihealth.toml"), + "tests": (tree / "tests", ".aihealth-tests.toml"), + } + return { + name: _scan_json(path, ROOT / config) + for name, (path, config) in configs.items() + } + + +def _scan_json(path: Path, config: Path) -> dict: + command = [ + str(WRAPPER), + "scan", + str(path), + "--config", + str(config), + "--format", + "json", + ] + return json.loads( + subprocess.run(command, check=True, capture_output=True, text=True).stdout + ) + + +def files_of(revision: str) -> dict[str, tuple[str, float, int]]: + with tempfile.TemporaryDirectory() as directory: + export(revision, Path(directory)) + return component_files(scan(Path(directory))) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("revisions", nargs="*") + parser.add_argument("--compare", action="store_true", help="compare BASE [HEAD]") + args = parser.parse_args(argv) + if not args.compare: + files = ( + files_of(args.revisions[0]) + if args.revisions + else component_files(scan(ROOT)) + ) + scores = component_scores(files) + print(json.dumps(scores, indent=2)) + return 0 + base, head = (args.revisions + ["HEAD"])[:2] + base_files, head_files = files_of(base), files_of(head) + # Only files in both revisions: deleting a healthy file must not count as a drop, + # and new or changed files are judged per file by `aihealth delta`. + before = component_scores(common(base_files, head_files)) + after = component_scores(common(head_files, base_files)) + print(json.dumps({"base": before, "head": after}, indent=2)) + failed = regressions(before, after) + for line in failed: + print(f"component got worse: {line}", file=sys.stderr) + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills-lock.json b/skills-lock.json new file mode 100644 index 0000000..bf57b5b --- /dev/null +++ b/skills-lock.json @@ -0,0 +1,61 @@ +{ + "version": 2, + "skills": { + "github-actions-hardening": { + "source": "github/awesome-copilot", + "commit": "f10fdb8b2660ce85c98f220b2f1ca24653768a5c", + "sourceType": "github", + "skillPath": "skills/github-actions-hardening/SKILL.md", + "computedHash": "ce7df8e90622480a41ffae4a81c78dbf4de3a6965cc21a91693efdf15fb3284c", + "installMode": "copy" + }, + "python-testing-patterns": { + "source": "wshobson/agents", + "commit": "1eecf4b58eb380ff7ddc258a11c6586381d67b95", + "sourceType": "github", + "skillPath": "plugins/python-development/skills/python-testing-patterns/SKILL.md", + "computedHash": "8113c05a831d4872c9294b0df26a335c09af423ee2e23d8b9b6817b300d96796", + "installMode": "copy" + }, + "receiving-code-review": { + "source": "obra/superpowers", + "commit": "22f0b463e7a5e579904dd6211a520321035526f7", + "sourceType": "github", + "skillPath": "skills/receiving-code-review/SKILL.md", + "computedHash": "528d336858d6f7d22cfcb887a249409ce682cb7d37a939cb15a82f2576a35876", + "installMode": "copy" + }, + "refactoring-patterns": { + "source": "wondelai/skills", + "commit": "c37678106e63ef1c5472d848fb3d8b8c5b33fafe", + "sourceType": "github", + "skillPath": "refactoring-patterns/SKILL.md", + "computedHash": "d6b31d50feaf66929da92cb5f8da61af60daf76b6f1e30860d46810a674bdf98", + "installMode": "copy" + }, + "systematic-debugging": { + "source": "obra/superpowers", + "commit": "22f0b463e7a5e579904dd6211a520321035526f7", + "sourceType": "github", + "skillPath": "skills/systematic-debugging/SKILL.md", + "computedHash": "79ff0583175346e39431b0dc713b223edd1bd7a7ea2b6c8b78b2fb9a3fed6782", + "installMode": "copy" + }, + "verification-before-completion": { + "source": "obra/superpowers", + "commit": "22f0b463e7a5e579904dd6211a520321035526f7", + "sourceType": "github", + "skillPath": "skills/verification-before-completion/SKILL.md", + "computedHash": "09b0e3a4689c1c38a3b8fc6ef57a1d4165aa33c0013d546dbde9dd348941a319", + "installMode": "copy" + }, + "writing-for-agents": { + "source": "mattpocock/skills", + "commit": "abeeaf95660ba9e8b7c753eb38f441ca707a8823", + "sourceType": "github", + "skillPath": "skills/productivity/writing-for-agents/SKILL.md", + "computedHash": "e79a2476b2417b228922453478d9505a6b9af19f3a412e560728ce62ed3555ca", + "installMode": "copy" + } + } +} diff --git a/tests/unit/test_aihealth_components.py b/tests/unit/test_aihealth_components.py new file mode 100644 index 0000000..6b722f8 --- /dev/null +++ b/tests/unit/test_aihealth_components.py @@ -0,0 +1,105 @@ +"""Component scores and the component check of scripts/aihealth_components.py.""" + +import importlib.util +from pathlib import Path + +import pytest + +SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "aihealth_components.py" +spec = importlib.util.spec_from_file_location("aihealth_components", SCRIPT) +components = importlib.util.module_from_spec(spec) +spec.loader.exec_module(components) + + +def scan(*files: tuple[str, str, int, float]) -> dict: + return { + "files": [ + {"path": path, "language": lang, "loc": loc, "score": score} + for path, lang, loc, score in files + ] + } + + +SCANS = { + "code": scan( + ("a.py", "python", 100, 10.0), + ("b.py", "python", 300, 6.0), + ("c.sh", "bash", 50, 9.0), + ("Makefile", "make", 10, 1.0), + ), + "tests": scan(("unit/test_a.py", "python", 200, 8.0), ("run.sh", "bash", 20, 1.0)), +} + + +def test_component_scores_weight_by_lines(): + files = components.component_files(SCANS) + assert sorted(files) == ["a.py", "b.py", "c.sh", "tests/unit/test_a.py"] + assert components.component_scores(files) == { + "python-cli": 7.0, + "python-tests": 8.0, + "shell": 9.0, + } + + +def test_deleting_a_healthy_file_is_not_a_drop(): + base = components.component_files(SCANS) + head = {path: entry for path, entry in base.items() if path != "a.py"} + before = components.component_scores(components.common(base, head)) + after = components.component_scores(components.common(head, base)) + assert components.regressions(before, after) == [] + + +@pytest.mark.parametrize( + "head, expected", + [ + ({"shell": 8.995, "python-cli": 7.0}, []), + ({"shell": 8.99, "python-cli": 6.99}, []), + ({"shell": 8.9, "python-cli": 7.5}, ["shell: 9.00 -> 8.90"]), + ({"shell": 9.0, "python-cli": 7.0, "python-tests": 1.0}, []), + ], +) +def test_regressions_allow_a_small_tolerance_and_new_components(head, expected): + assert components.regressions({"shell": 9.0, "python-cli": 7.0}, head) == expected + + +def test_a_drop_of_exactly_the_tolerance_passes_for_every_score(): + hundredths = [value / 100 for value in range(101, 1001)] + assert not [ + s + for s in hundredths + if components.regressions({"x": s}, {"x": round(s - 0.01, 2)}) + ] + + +def test_scan_calls_the_pinned_ai_health_with_the_component_configs( + monkeypatch, tmp_path +): + calls = [] + + def fake_run(command, **kwargs): + calls.append(command) + return type("Result", (), {"stdout": '{"files": []}'})() + + monkeypatch.setattr(components.subprocess, "run", fake_run) + components.scan(tmp_path) + root = components.ROOT + assert calls == [ + [ + str(components.WRAPPER), + "scan", + str(tmp_path), + "--config", + str(root / ".aihealth.toml"), + "--format", + "json", + ], + [ + str(components.WRAPPER), + "scan", + str(tmp_path / "tests"), + "--config", + str(root / ".aihealth-tests.toml"), + "--format", + "json", + ], + ] diff --git a/tests/unit/test_aihealth_config.py b/tests/unit/test_aihealth_config.py new file mode 100644 index 0000000..74ec613 --- /dev/null +++ b/tests/unit/test_aihealth_config.py @@ -0,0 +1,36 @@ +"""The two ai-health profiles must stay the same profile (docs/code-health.md).""" + +import tomllib +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +SHARED_SECTIONS = ("thresholds", "score", "delta") + + +def profile(name: str) -> dict: + return tomllib.loads((ROOT / name).read_text()) + + +@pytest.mark.parametrize("section", SHARED_SECTIONS) +def test_tests_profile_repeats_the_shared_section(section): + assert ( + profile(".aihealth-tests.toml")[section] == profile(".aihealth.toml")[section] + ) + + +def test_tests_profile_switches_off_fixture_and_class_smells(): + weights = profile(".aihealth-tests.toml")["weights"] + assert weights == { + "excess_arguments": 0, + "primitive_obsession": 0, + "low_cohesion": 0, + } + + +def test_strict_profile_values(): + strict = profile(".aihealth.toml") + assert strict["score"] == {"decay": 8, "symbol_cap": 4, "density_loc": 100000} + assert strict["delta"] == {"tolerance": 0.0} + assert strict["thresholds"] == {"large_file": 600, "primitive_obsession": 0.3} diff --git a/tests/unit/test_techuser_ssh.py b/tests/unit/test_techuser_ssh.py index a40912e..3bf9779 100644 --- a/tests/unit/test_techuser_ssh.py +++ b/tests/unit/test_techuser_ssh.py @@ -15,8 +15,7 @@ HELPER = REPO / "home/work/.local/bin/ssh-askpass-azkv" USER_A, USER_B = "ci-user-a", "ci-user-b" TECHUSERS = ( - f"{USER_A}=vault-a/technical-user-password " - f"{USER_B}=vault-b/technical-user-password" + f"{USER_A}=vault-a/technical-user-password {USER_B}=vault-b/technical-user-password" ) SECRET = "s3cret-from-vault" # pragma: allowlist secret diff --git a/tests/unit/test_work_net.py b/tests/unit/test_work_net.py index c58a538..147fdf0 100644 --- a/tests/unit/test_work_net.py +++ b/tests/unit/test_work_net.py @@ -41,9 +41,7 @@ def _keyring(tmp_path: Path, locked: bool | None, secret: str = "") -> Path: _stub( bin_dir, "secret-tool", - f'echo "$@" >>"{calls}"\n' - f'[ "$1" = lookup ] && printf %s "{secret}"\n' - "exit 0\n", + f'echo "$@" >>"{calls}"\n[ "$1" = lookup ] && printf %s "{secret}"\nexit 0\n', ) return calls