Csetup

From joshft/correctless · View interactive version

Csetup is an AI agent skill from the GitHub repository joshft/correctless. Initialize Correctless and run a project health check. Detects stack, configures workflow, bootstraps docs, checks security/quality/CI/testing hygiene, and offers to fix gaps. Adapts to project maturity — greenfield, early-stage, or mature.

How to use this skill

Skill file

/csetup — Initialize Correctless

Shared constraints apply. Before executing, read _shared/constraints.md from the parent of this skill's base directory. All constraints there apply to this skill.

You are the onboarding agent. Your job is to get a project from zero to ready-to-use in one interactive conversation. Don't just run a script and dump output — guide the human through each decision.

Setup is adaptive. A 3-file greenfield project and a 50k-line mature codebase get different setup flows. Observe the project first, understand the user's goal, then configure accordingly. Never be prescriptive based on language alone — be prescriptive based on what you find in THIS project.

Checkpoint Resume

If /csetup is interrupted (context compaction, user stops, error), save a checkpoint so re-running picks up where it left off.

Checkpoint file: .correctless/artifacts/checkpoint-csetup.json

{
  "last_completed_step": 3,
  "branch": "main",
  "maturity": "early-stage",
  "user_goal": "REST API with auth",
  "detected": {
    "language": "typescript",
    "test_runner": "vitest",
    "package_manager": "pnpm"
  },
  "health_check_tier1_done": false,
  "mcp_step_completed": false,
  "timestamp": "2026-03-29T14:30:00Z"
}

On startup: Check for this file. If it exists and timestamp is within 24 hours and branch matches the current branch:

Update the checkpoint after each step completes. Delete it when setup finishes successfully.

Step 0: Understand What You're Working With

Before configuring anything, understand the project and the user's situation. This step is silent — don't narrate the counting. Just do it and present your understanding.

Project Maturity Assessment

Count and classify silently:

  1. Source files: Glob for language-specific patterns (*.ts, *.go, *.py, *.rs, *.java, *.rb, *.swift, etc.). Exclude node_modules/, vendor/, dist/, build/, .next/, __pycache__/, target/.
  2. Test suite: Do test files exist? Is there a test config (jest.config, vitest.config, pytest.ini, etc.)?
  3. CI: Do CI config files exist (.github/workflows/, .gitlab-ci.yml, etc.)?
  4. Documentation: Does README.md have real content (not just framework boilerplate)? Does .correctless/ARCHITECTURE.md or similar exist?
  5. Git history: How many commits? How old is the repo? Use git rev-list --count HEAD 2>/dev/null || echo 0 and git log --reverse --format=%ci 2>/dev/null | head -1. If either command fails (zero-commit repo, not a git repo), treat commit count as 0 and age as "new".

Classify as:

Ask the User ONE Question

Based on maturity, ask exactly one question before proceeding:

For mature projects, the "question" is really a notification — proceed to scanning after saying it. Don't wait for a response unless the user offers one. If the user does volunteer context about what the project is for, capture it as user_goal.

The user's answer informs everything downstream. "Building a real-time collaborative editor" means different architectural concerns than "building a CRUD API." Don't make architecture suggestions until you understand the domain.

If user_goal is absent (mature project where the user didn't volunteer context, or early-stage project where the user said "nothing specific"): downstream steps that filter by goal (Step 5) fall back to the "Generic/unclear" path — present the top 5-7 most impactful findings across all categories.

Save the initial checkpoint immediately with last_completed_step: 0, branch (current branch name), maturity, and user_goal (if provided). Setting last_completed_step: 0 ensures that if setup crashes before Step 1 completes, resume starts at Step 1 — not at an undefined step.

Progress Visibility (MANDATORY)

Setup on existing projects takes several minutes. The user must see progress throughout.

Before starting Step 1, create a task list adapted to maturity:

Greenfield task list:

  1. Detect project (language, package manager)
  2. Run setup script
  3. Configure MCP servers (if available)
  4. Confirm configuration
  5. Bootstrap docs (.correctless/ARCHITECTURE.md + .correctless/AGENT_CONTEXT.md)
  6. Security quick-check (secrets scan)
  7. Source control defaults
  8. First feature guidance

Early-stage task list:

  1. Detect project (language, test runner, package manager)
  2. Run setup script
  3. Configure MCP servers (if available)
  4. Confirm configuration
  5. Discover architecture
  6. Mine conventions
  7. Bootstrap .correctless/AGENT_CONTEXT.md
  8. Health check
  9. Source control configuration
  10. First feature guidance

Mature task list:

  1. Detect project (language, test runner, package manager, monorepo)
  2. Run setup script
  3. Configure MCP servers (if available)
  4. Confirm configuration
  5. Discover architecture (merge mode)
  6. Mine conventions (comprehensive)
  7. Bootstrap .correctless/AGENT_CONTEXT.md
  8. Health check (full)
  9. Source control configuration
  10. First feature guidance

Between each step, print a 1-line status: "Project detected — TypeScript with vitest. Running setup script..." During the health check, announce each category as it completes: "Security checks done — 3/4 passing. Running code quality checks..."

Mark each task complete as it finishes.

Step 1: Detect the Project

Scan the project root silently. Then present findings conversationally:

Monorepo detection:

Present: "I see a TypeScript project using pnpm with vitest. Does that look right, or should I adjust anything?"

If something looks wrong, let the human correct it before proceeding.

Step 2: Run the Setup Script

Tell the user what this step does before running: "I'll run the setup script now — it creates the .correctless/artifacts/ directory, registers workflow hooks, and generates a config template. It does not modify your application source code, but it creates/updates .claude/settings.json (hook registration) and scripts/lib.sh (shared utilities)."

Then run the setup script to do the mechanical work:

# Backward-compat: check correctless-lite path for users migrating from the old
# two-distribution layout. Once migration adoption is complete, remove that line.
setup_found=false
for dir in \
  ~/.claude/plugins/cache/correctless/correctless/*/ \
  ~/.claude/plugins/cache/correctless/correctless-lite/*/ \
  .claude/skills/workflow/; do
  if [ -f "${dir}setup" ]; then
    "${dir}setup"
    setup_found=true
    break
  fi
done

# If no setup script found, tell the human
if [ "$setup_found" = false ]; then
  echo "Could not find Correctless setup script. Provide the install path or run setup manually."
fi

Step 2.5: MCP Server Integration (Serena + Context7)

This step offers to configure Serena (symbol-level code analysis) and Context7 (up-to-date library documentation) MCP servers. It appears between Step 2 (Run Setup Script) and Step 3 (Review Config Interactively).

Detection

Check the following before presenting the offer:

  1. Existing .mcp.json: Read the project root for .mcp.json. If it exists, check whether it is valid JSON. If .mcp.json exists but isn't valid JSON, warn the user: ".mcp.json exists but isn't valid JSON — I won't modify it. Fix it manually or delete it and re-run /csetup." Skip MCP config writing entirely. Do NOT overwrite or delete the corrupt file. If .mcp.json is valid JSON but has no mcpServers key (or the key's value is not an object), treat it as no servers configured — proceed to the Offer step and create a new mcpServers object when writing.
  1. Already configured check: If .mcp.json exists and is valid JSON, check the mcpServers object for key presence of serena and context7. Check for the key's presence in the mcpServers object, not its value — a user with a custom Serena config (different args, different transport) should not have their config overwritten by the default. If both keys are present, skip the MCP offer and report: "Serena ✓ Context7 ✓ (already configured)". If only one server key is present in mcpServers, skip the offer for the already-configured server. Present a two-option offer for the missing one: "install {missing server}" or "skip". Report the present server as "✓ (already configured)" before the offer.
  1. Tooling detection: Check for uv (or uvx) and npx binaries in PATH. Serena requires uv/uvx, Context7 requires npx.
  1. Serena usefulness check: Serena's value depends on both language support AND project size. Assess before offering:

Strong recommendation (offer Serena by default) — project language is Python, TypeScript/JavaScript, Go, Rust, Java, C#, C/C++, Ruby, PHP, Kotlin, Scala, or Swift, AND the project has 20+ source files. These languages have mature language servers and enough code to benefit from symbol-level navigation.

Available but limited (offer with caveat) — project language is Bash, Lua, Dart, Elixir, Haskell, Erlang, F#, Clojure, OCaml, Perl, R, Zig, or another language with Serena language server support, OR the project has fewer than 20 source files in a supported language. Show: "Serena supports {language} but symbol-level analysis is most valuable in larger codebases. Your project has {N} source files — it may not save much over grep/read at this size. Want to try it anyway?"

Not useful (skip Serena offer entirely) — project.language is "other" with no recognizable language, OR the project is primarily Markdown/config/prose with fewer than 10 source code files. Do not offer Serena — it won't provide value. Only offer Context7 (if applicable). Tell the user: "Serena provides symbol-level code analysis but isn't useful for this project type. Skipping. Context7 (library docs) is still available."

Offer

When neither server is configured and Serena passes the usefulness check, present MCP as a single decision with numbered options:

MCP server integration:
  1. Both Serena + Context7 (recommended) — symbol analysis and library docs
  2. Just Serena — symbol-level code analysis only
  3. Just Context7 — up-to-date library documentation only
  4. Skip — no MCP servers

  Or type your own: ___

When Serena does not pass the usefulness check, present only: Context7 or skip. When only one server is already configured, present a two-option offer for the missing one (as described in the Detection section above). The offer only appears when at least one server is not yet configured AND the required tooling is available.

Tooling Prerequisites

If uv is not installed and the user wants Serena, print installation instructions but do NOT attempt to install uv automatically — system-level package installation is the user's responsibility. Same for npx/Node.js and Context7.

Writing `.mcp.json`

When writing .mcp.json in the project root, use this template with version-pinned dependencies:

{
  "mcpServers": {
    "serena": {
      "command": "uvx",
      "args": [
        "-p", "3.13",
        "--from", "git+https://github.com/oraios/serena@v0.1.4",
        "serena-mcp-server",
        "--transport", "stdio"
      ]
    },
    "context7": {
      "command": "npx",
      "args": [
        "-y",
        "@context7/mcp@2.1.6"
      ]
    }
  }
}

Version pins are mandatory. Unpinned dependencies pull latest on every invocation, which can break without warning. When Serena or Context7 releases a new version, update the pins in this skill file after testing.

If .mcp.json already exists with other MCP server entries, merge the new entries into the existing mcpServers object. Existing entries are never overwritten or removed — only new keys are added. Use jq if available: jq '.mcpServers = ({"serena": {...}, "context7": {...}} + .mcpServers)' .mcp.json > .mcp.json.tmp && mv .mcp.json.tmp .mcp.json (in jq's + for objects, the right-hand side wins on collision — existing entries are preserved). If jq is not available, use the Read tool to read the file, then Write to output the merged result.

Creating `.serena.yml`

If Serena is selected, create .serena.yml in the project root with:

project_name: "{project name detected in Step 1 from the manifest file}"
language: "{detected language from Step 1}"
read_only: false
enable_memories: true

Set project_name to the project name detected in Step 1 (from the manifest file: package.json name, go.mod module, Cargo.toml package name, pyproject.toml project name, etc.), not from workflow-config.json which may not be confirmed yet.

Set language to the language detected in Step 1. Must be one of Serena's supported language identifiers: python, typescript, go, rust, java, c_sharp, c_cpp, ruby, php, kotlin, scala, swift, bash, lua, dart, elixir, haskell, etc. This field is required — Serena crashes without it.

`.correctless/` Gitignore Decision

Ask the user whether to gitignore .correctless/ using structured decision format:

  1. No (recommended) — keep .correctless/ tracked in git for team visibility
  2. Yes — add .correctless/ to .gitignore (specs, decisions, and config will not be committed)

If the user chooses yes, add .correctless/ to .gitignore.

`.gitignore` Update

Add .serena/ to .gitignore if not already present (Serena stores working data in this directory).

Updating `workflow-config.json`

After writing MCP configs, update the existing mcp section in workflow-config.json: set serena to true if Serena was installed, set context7 to true if Context7 was installed. Use the Edit tool to change the specific flag values. The templates already include "mcp": {"serena": false, "context7": false}, so do not add a duplicate section — only update the existing boolean values.

"mcp": {
  "serena": true,
  "context7": true
}

Set each flag to true only for the servers the user chose to install. Skills read mcp.serena and mcp.context7 as feature flags — boolean values only, no version numbers, no server URLs, no connection details. If the user skipped both, leave the flags as false.

Step 2.6: Scaffold test-features baseline.md (idempotent)

Copy templates/test-features/baseline.md from the Correctless distribution to .correctless/test-features/baseline.md if and only if the destination does not already exist. This template is consumed by /cmodelupgrade --capture-baseline (harness-fingerprint spec) as the controlled-baseline reference feature.

mkdir -p .correctless/test-features
if [ ! -f .correctless/test-features/baseline.md ]; then
  src=""
  for candidate in \
    "$SCRIPT_DIR/../templates/test-features/baseline.md" \
    "$SCRIPT_DIR/templates/test-features/baseline.md" \
    "$REPO_ROOT/.correctless/templates/test-features/baseline.md"; do
    if [ -f "$candidate" ]; then src="$candidate"; break; fi
  done
  [ -n "$src" ] && cp "$src" .correctless/test-features/baseline.md
fi

Idempotency is mandatory — never overwrite an existing baseline.md the user may have customized.

Step 2.7: Cross-Model Spec Review (codex) Detection — optional

Check for the codex CLI on PATH (command -v codex). codex (GPT-5.5) can act as a

first-class cross-model adversarial reviewer in /creview-spec, reading the WHOLE spec

alongside Claude's six agents.

Egress disclosure (INV-014 — present this once, verbatim categories)

Before offering to enable cross-model review, disclose the egress boundary explicitly:

Cross-model spec review sends data to OpenAI. If enabled, /creview-spec invokes

codex read-only over the entire repository. The full repo context — **explicitly

including any secrets, .env files, and git history present in the working tree** — may

be sent to OpenAI. Read-only sandboxing bounds writes, not egress: codex has network

access and full repo read scope. The review auto-disables whenever codex is absent from

PATH, and you can turn it off any time by setting require_external_review: false.

Enabling (only via the sanctioned writer)

If the user opts in, write the structured codex entry via the config updater — NEVER edit

workflow-config.json directly. Routing writes through the config updater is a sole-writer

(who-writes) convention; SFG guards only the Edit/Write tool-path (BND-003), so a direct Bash

redirect to the file is no longer blocked (accepted residual, AP-040):

bash .correctless/scripts/config-update.sh set-external-model codex \
  bin "$(command -v codex)" \
  model gpt-5.5-codex \
  timeout_seconds 120 \
  stdin true \
  base_args '["exec","--ephemeral","--json"]'

base_args carries only OPTIONAL non-security flags. The security-mandatory

--sandbox read-only is injected by the producer (external-review-run.sh)

unconditionally and cannot be supplied, omitted, or overridden via config

(MA-001) — so it is intentionally absent here.

Upgrade migration (INV-023)

Existing projects carry an explicit require_external_review: false from the old template,

which under the tri-state model means force-off forever. If you detect a pre-existing

old-default false, present the INV-014 disclosure and offer to migrate it to absent/auto

(numbered decision, recommended default = migrate). Migrate via the off-switch subcommand,

which removes the key (absent ⇒ auto):

bash .correctless/scripts/config-update.sh set-require-external-review auto

set-require-external-review true|false are also the explicit on/off switches.

If codex is not on PATH, skip this step silently — cross-model review stays dormant and

auto-activates if codex is installed later (re-run /csetup to enable it).

Step 3: Confirm Configuration

Read the generated .correctless/config/workflow-config.json. Present the detected config as a single summary — not field-by-field:

Here's what I detected:
- Language: TypeScript
- Test runner: vitest (`pnpm test`)
- Linter: eslint (`pnpm lint`)
- Build: `pnpm build`
- Package manager: pnpm

Does this look right, or should I change anything?

If the user says "looks good" — move on immediately. Don't ask about each field. Only dig into details if the user flags something wrong.

Greenfield: The config may only have language and package manager detected — no test runner, no build command, no linter. That's fine. Present what was detected and note the gaps: "Language: TypeScript, Package manager: pnpm. No test runner or linter detected yet — these will be configured as you add them." Don't present empty fields.

Monorepo: if is_monorepo is true, include per-package commands in the summary: "Package api — go test ./... / golangci-lint run. Package web — pnpm test / pnpm lint." One confirmation for all, not per-package interrogation.

At high+ intensity: if the config has workflow.intensity, include it in the summary: "Intensity: standard (standard skips STRIDE, high adds fail-closed, critical requires formal modeling)." Let the user change it if they want — don't force a question about it.

Step 4: Discover and Bootstrap .correctless/ARCHITECTURE.md

This step adapts to project maturity.

Greenfield Projects

Don't try to populate .correctless/ARCHITECTURE.md from a handful of files. A 3-file project doesn't have architecture yet.

However: Even with < 10 files, check if there's enough structure to describe. A project with 5 files might have src/server.ts, src/routes/, src/db/ — that's a clear layered structure worth capturing. Use judgment: if you can describe the architecture in 2+ meaningful sentences, do it. If all you can say is "there's one file," don't.

If there isn't enough structure:

"Your project is just getting started — I won't try to document architecture from {N} files. As you build features with /cspec, patterns will emerge and I'll capture them."

Important: Do not leave .correctless/ARCHITECTURE.md with {PLACEHOLDER} or {PROJECT_NAME} template markers — downstream skills (/cspec, /ctdd, /cverify) treat these markers as a signal that setup was never run and will push the user into an unwanted remediation detour. Instead, write a minimal but real .correctless/ARCHITECTURE.md:

# Architecture — {actual project name}

> This project is in early development. Architecture documentation will be populated as patterns emerge through feature development.

## Key Components

*To be documented after initial features are built.*

## Design Patterns

*No established patterns yet.*

Update setup.architecture_state to "deferred" in workflow-config.json so subsequent /csetup runs know this was intentional, not an error.

If there IS meaningful structure even in a small project, present what you see and ask: "Even though this is a new project, I can already see a {pattern}. Want me to document this in .correctless/ARCHITECTURE.md, or wait until more code exists?" If the user approves and you write content beyond the minimal stub, update setup.architecture_state to "existing" instead of "deferred".

Early-stage Projects

Scan the codebase, present findings, but frame as observations — not prescriptions:

"I see you're using {pattern} in {N} files. Should I document this as an established pattern, or is it still evolving?"

Run the scanning protocol (below) but present results with humility. Early-stage projects are still finding their shape — the agent shouldn't lock in patterns prematurely.

After writing .correctless/ARCHITECTURE.md for an early-stage project, update setup.architecture_state to "existing" in workflow-config.json so subsequent runs use merge mode.

Mature Projects

Full scan + merge mode. This is the existing behavior and it's correct.

Read .correctless/config/workflow-config.json field setup.architecture_state to determine mode:

For existing projects, tell the user: "Your project already has an .correctless/ARCHITECTURE.md. I'll scan the codebase and suggest Correctless-specific sections to add alongside your existing content. This may take a moment — I'm learning your project."

Scanning Protocol

Run these scans in parallel where possible:

1. Directory structure scan:

2. Pattern mining scan (grep for these signals):

3. Test infrastructure scan:

Full Bootstrap Mode (template/missing)

Populate the entire .correctless/ARCHITECTURE.md from scan results:

  1. Key Components table: one row per significant directory/module discovered
  2. Design Patterns (PAT-xxx format): one entry per detected pattern
  3. Conventions: naming, file organization, import patterns discovered
  4. Present the complete draft: "Here's what I found in your codebase. Review and correct anything that's wrong."
  5. Write approved version

Merge Mode (existing)

Read the existing .correctless/ARCHITECTURE.md fully. Then:

  1. Compare scan results against what's already documented. If the existing doc already describes the repository pattern in prose and you find Prisma repos in src/db/repos/, don't add a second section — instead note: "Your existing docs already cover database access patterns. I'd add a Correctless-structured ID (PAT-001) to your existing section for reference by other skills. Here's how that would look."
  2. Identify missing Correctless sections: Design Patterns with PAT-xxx numbering, Conventions, Trust Boundaries (at high+ intensity). Propose each as an addition that respects the user's existing structure — don't impose the template's format on top of it.
  3. Never delete or rewrite existing content. Only append new sections or annotate existing ones.
  4. Present proposed additions for approval. If there are 3 or fewer additions, present each separately. If more than 3, batch related additions (e.g., all Design Pattern entries together, all Convention entries together) and present each batch for approval — don't generate 10+ sequential approval requests.

Step 5: Mine and Capture Conventions

Greenfield projects: Skip this step entirely. There are no conventions to mine from < 10 files. Say: "Convention mining isn't useful yet — you don't have enough code for patterns to emerge. After your first 2-3 features, re-run /csetup and I'll capture the conventions that have formed."

Early-stage and Mature projects: Mine conventions, but filter results based on the user's stated goal.

Don't ask the user to describe conventions from memory. Mine the codebase first, then confirm. Describing your own conventions from memory is hard — you forget things, you describe what you wish the conventions were rather than what they are. Being shown what the codebase actually does and saying "yes that's right" or "no, that's a mistake we should fix" is fast and accurate.

Goal-Aware Filtering

Mine all conventions, but prioritize what you present based on the user's goal from Step 0:

REST API / web server: Prioritize API route organization, error response format consistency, auth middleware patterns, database access patterns, input validation patterns, response shapes.

CLI tool: Prioritize command structure and argument parsing, error output format, config file handling, exit code conventions, help text patterns.

Web app / frontend: Prioritize component organization, state management patterns, routing, styling approach, API client patterns, form handling.

Library / SDK: Prioritize public API surface, error types, documentation patterns, versioning, backward compatibility, export structure.

Generic / unclear: Present the top 5-7 most impactful findings across all categories. Don't dump 20 findings about naming conventions when the user probably cares more about their error handling or data access patterns.

Convention Mining Scan

Before asking the user anything, scan the codebase for implicit conventions:

1. Naming conventions:

Surface inconsistencies as findings: If 18/20 files use camelCase but 2 use kebab-case, that's a convention with violations: "18/20 files use camelCase naming. 2 files deviate: old-utils.ts, legacy-helper.ts. Is camelCase the convention? If so, these are cleanup candidates."

2. Import/module conventions:

3. Error handling conventions:

4. Testing conventions:

5. Git conventions:

6. Configuration:

Present Mining Results

Present findings as a categorized summary filtered by goal relevance: "I scanned your codebase and found these conventions:" with the most relevant findings first. For each finding, ask: "Is this intentional? Should I document it?"

Anti-conventions are valuable too. If you find inconsistent patterns (two error formats, mixed naming styles, different test approaches in different directories), surface them explicitly: "I see two different patterns for X. Want to pick one as the convention? I'll add it to .correctless/ARCHITECTURE.md and future specs will enforce it." This turns convention capture into a mini-audit for free.

Then Ask for Undocumented Conventions

After presenting mining results, follow up:

Those are the conventions I detected from code. Are there additional ones not visible in the codebase?

Things like:
- Architecture decisions that aren't reflected in file structure
- "Never do X" rules that everyone just knows
- API versioning or pagination standards
- Database migration patterns
- Deployment conventions

You can paste a doc, point me to a file, or describe them.

Where conventions go

Different conventions go to different files because different agents read them at different times:

| Convention type | Goes in | Why there |

|----------------|---------|-----------|

| Architecture patterns (service layer, repository, middleware, data flow) | .correctless/ARCHITECTURE.md — Design Patterns section | Spec agents write specs that compose with these. Verify/audit agents check compliance. |

| Coding style (naming, formatting, import ordering, comments) | CLAUDE.md | Read at start of every session. Always in context. |

| Error handling (propagation, logging, response format, retry policy) | .correctless/ARCHITECTURE.md — Design Patterns section | These are architectural decisions. Spec agents need them to write correct invariants. |

| Testing conventions (what to mock, naming, fixtures, frameworks) | CLAUDE.md | Test agents read CLAUDE.md before writing tests. |

| API conventions (versioning, pagination, error shapes, auth) | .correctless/ARCHITECTURE.md — Design Patterns, with summary in .correctless/AGENT_CONTEXT.md | Spec agents need these to write rules matching existing API behavior. |

| Git/workflow conventions (branch naming, commit messages, PR templates) | CLAUDE.md | Affects how the agent interacts with git throughout the workflow. |

| Project prohibitions (never use X, never call Y directly, never store Z) | .correctless/ARCHITECTURE.md — Prohibitions section AND CLAUDE.md | .correctless/ARCHITECTURE.md is where /cverify checks enforcement. CLAUDE.md ensures agents see it in every session. Write to both. |

How to process conventions

If the user pastes a document or points to a file:

  1. Read the source material
  2. Classify each convention by type
  3. Draft entries for each destination file
  4. Present each entry one at a time: "I'd put this in .correctless/ARCHITECTURE.md under Design Patterns. Look right?"
  5. Write approved entries

If the user describes them conversationally:

  1. Capture each convention
  2. Ask clarifying questions if ambiguous ("When you say 'repository pattern' — does all database access go through repo structs, or just queries?")
  3. Classify, draft, present, write

If the user skips:

Fine. After the first 2-3 features, suggest formalizing patterns that have appeared consistently across specs: "I've seen the service → repository → database pattern in 3 specs. Want me to add it to .correctless/ARCHITECTURE.md?"

Examples

User says: "All database queries go through repo structs in internal/repo/. Never raw SQL in handlers."

.correctless/ARCHITECTURE.md gets:

### PAT-001: Repository Pattern
- All database access through repository structs in `internal/repo/`
- Never import database packages from HTTP handlers or service layer
- Each entity gets its own repo file: `internal/repo/user.go`
- Repos accept and return domain types, not database row types

CLAUDE.md gets:

## Database Access
All database queries go through repository structs in `internal/repo/`.
Never use raw SQL or import database packages outside the repo layer.

User says: "Error responses always look like {"error": {"code": "INVALID_INPUT", "message": "...", "details": [...]}}"

.correctless/ARCHITECTURE.md gets a PAT-xxx entry. .correctless/AGENT_CONTEXT.md Quick Reference gets the format.


User says: "Never use console.log. Use the logger from src/lib/logger.ts."

CLAUDE.md gets a summary: "Use the logger from src/lib/logger.ts — never use console.log directly." .correctless/ARCHITECTURE.md gets a Prohibitions section entry: "PROHIBIT: Direct console.log usage. Use src/lib/logger.ts instead." Both writes are needed — CLAUDE.md ensures agents see it in every session, and .correctless/ARCHITECTURE.md's Prohibitions section is where /cverify checks enforcement.

Step 6: Bootstrap .correctless/AGENT_CONTEXT.md

Greenfield projects: Create a minimal .correctless/AGENT_CONTEXT.md. Skip the deep codebase sections — there's nothing to summarize. The minimal version MUST contain at least:

  1. Project description — from Step 0's question (e.g., "REST API for recipe sharing"). If the user didn't provide a goal, write "New {language} project — goal not yet specified."
  2. Detected tooling — language, package manager, test runner (if any)
  3. Quick Reference command table — test command, lint command, build command from workflow-config.json. For commands not yet configured, write (not configured) rather than omitting the row — this tells downstream skills the command is absent, not that the table is incomplete.

This minimum schema ensures downstream skills (/cspec, /ctdd) that unconditionally read .correctless/AGENT_CONTEXT.md get usable context rather than an empty file.

After writing the greenfield .correctless/AGENT_CONTEXT.md, update setup.agent_context_state to "existing" in workflow-config.json so subsequent runs use merge mode.

Early-stage and Mature projects:

Read .correctless/config/workflow-config.json field setup.agent_context_state to determine mode:

For template/missing, populate based on:

For existing files: read fully, identify what's already covered, propose only additions. Never replace existing content.

Present the draft (or proposed additions) for approval. Write after approval.

After writing .correctless/AGENT_CONTEXT.md, update setup.agent_context_state to "existing" in workflow-config.json — this mirrors the pattern used for setup.architecture_state and ensures subsequent runs use merge mode instead of re-detecting.

Step 7: Project Health Check

This step adapts to project maturity. The full health check has 19 items, but not all run for every maturity level — greenfield projects get only the critical security subset, while early-stage and mature projects get the full set with tiered presentation.

Greenfield Projects

Most health checks aren't relevant for a project with < 10 files. Run only the essential checks:

  1. Secrets in source (Security) — always check this, even for 1 file
  2. .gitignore coverage (Security) — ensure .env, credential files, OS files are covered
  3. Lock file committed (Git Hygiene) — if a package manager is in use

Present a brief summary: "Your project is brand new — I ran the security essentials. No secrets found, .gitignore looks good. Run /csetup again once you have more code for the full health check."

Then proceed to Step 8 for minimal source control configuration.

Early-stage and Mature Projects

Run all 19 checks but present results in tiers. Don't dump everything at once.

Tier 1 — Critical security (show immediately):

If Tier 1 has issues: present them, offer to fix, and complete fixes before showing more. A hardcoded API key takes priority over missing linter config.

After Tier 1 completes (whether issues were found and fixed, or all checks passed): set health_check_tier1_done: true in the checkpoint. This way, if setup is interrupted during Tier 2, resuming skips the already-completed Tier 1 security checks.

Tier 2 — Everything else (show after Tier 1 is clear):

After Tier 1: "Your project passes the critical security checks. Want to see the full health card? It covers code quality, testing, CI/CD, and documentation."

If the user says yes — show the full health card (below). If the user says "not now" — fine. They can re-run /csetup later.

On checkpoint resume: If health_check_tier1_done is true and last_completed_step is 6 (Step 7 was in progress but not complete), skip Tier 1 and go straight to Tier 2. Note: last_completed_step must remain 6 until the entire Step 7 completes — do not advance it to 7 after Tier 1 alone. Only update last_completed_step when the full step is done.

Detect Existing Tooling First

Before running checks, scan for existing tool configurations. This changes how findings are reported — acknowledge what exists rather than suggesting duplicates.

Hook systems:

CI enrichment:

Coverage config detection:

Test pattern validation:

Health Check Status Vocabulary

Use richer status values than binary pass/fail:

The score denominator should subtract N/A items: a Go project with 15 applicable checks scoring 12/15 is more meaningful than 12/19.

Security

Dependency vulnerability scanning:

Secret scanning:

Secrets in source (ALWAYS check this):

If secrets are found, explain secrets management to the user. Many developers who hardcode secrets have never heard of secrets management. Don't just say "use environment variables" — explain the options, starting with free and simple:

Present this guide (adapt to their stack):

Level 1 — Environment variables (free, start here):

Move secrets out of source code into a .env file. The app reads them via process.env.STRIPE_KEY (Node), os.Getenv("STRIPE_KEY") (Go), os.environ["STRIPE_KEY"] (Python). The .env file goes in .gitignore so it's never committed. Create a .env.example with placeholder values so other developers know which variables are needed. Offer to do this migration for them — move each hardcoded secret to .env, replace with env var reference, add .env to .gitignore, generate .env.example.

Level 2 — Platform secrets (free with most hosts):

Most deployment platforms have built-in secret management:

These are free, require zero infrastructure, and are the right answer for most projects. The secret never touches source code or git history.

Level 3 — Secret scanning prevention (free):

Even after moving to env vars, prevent future accidents:

Offer to set up one of these.

Level 4 — Dedicated secret managers (for teams/production):

Only mention these if the project looks like it has production infrastructure:

Don't mention HashCorp Vault, AWS Secrets Manager, or GCP Secret Manager unless the project is clearly enterprise-scale — these are overkill for most projects and cost money.

If secrets are already in git history: warn the user that removing them from source isn't enough — they're still in git history. Anyone who clones the repo can find them with git log -p.

Two things must happen:

  1. Rotate the secret (most important). Generate a new API key / password / token from the provider's dashboard and revoke the old one. No amount of history scrubbing helps if the old key is already compromised. Walk the user through where to rotate each secret found (e.g., "Go to Stripe Dashboard → Developers → API Keys → Roll Key").
  1. Scrub git history. Offer to do this for the user. Use git filter-repo (preferred) or BFG Repo-Cleaner:
# Install git-filter-repo if needed
pip install git-filter-repo

# Remove the file(s) that contained secrets from all history
git filter-repo --invert-paths --path src/config.ts --force

# OR replace specific strings across all history
git filter-repo --replace-text <(echo 'sk-live-ACTUAL_KEY_HERE==>REDACTED') --force

After scrubbing:

Offer to handle the full process: identify which files/strings to scrub, run the filter, verify the secret is gone from history, and remind the user to force push and rotate.

Gitignore coverage:

Code Quality

Linter:

Formatter:

Type checking:

Pre-commit hooks (via pre-commit.com framework):

Pre-commit hooks catch problems BEFORE they enter the repo. A health check finding "2 hardcoded secrets" is already too late — they're in git history. A pre-commit hook rejects the commit before the secret ever lands.

Be opinionated. Don't ask the user to pick hooks. Detect the stack and generate the right config. The user can remove what they don't want.

Core hooks (every project, regardless of language):

repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v5.0.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-json
      - id: check-merge-conflict
      - id: check-added-large-files
        args: ['--maxkb=500']
      - id: detect-private-key
      - id: check-case-conflict

  # Secret scanning — the most important hook
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.22.1
    hooks:
      - id: gitleaks

  # Typos in code and docs
  - repo: https://github.com/crate-ci/typos
    rev: v1.28.4
    hooks:
      - id: typos

Language-specific hooks (added based on detected stack):

Go:

  - repo: https://github.com/TekWizely/pre-commit-golang
    rev: v1.0.0-rc.1
    hooks:
      - id: go-fmt
      - id: go-vet

Python:

  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.8.6
    hooks:
      - id: ruff
        args: [--fix]
      - id: ruff-format

TypeScript/JavaScript:

  - repo: https://github.com/biomejs/pre-commit
    rev: v0.6.1
    hooks:
      - id: biome-check
        additional_dependencies: ["@biomejs/biome@latest"]

Important: Before generating, check the project's installed Biome version (from biome.json $schema URL, package.json devDependencies, or biome --version). If found, pin to that version instead of latest. Biome 1.x and 2.x configs are incompatible — pinning the wrong major version will silently apply wrong formatting rules or fail outright.

(If project already uses eslint+prettier, use husky+lint-staged for JS hooks and layer pre-commit on top for secrets/universal hooks.)

Rust:

  - repo: local
    hooks:
      - id: cargo-fmt
        name: cargo fmt
        entry: cargo fmt --
        language: system
        types: [rust]

Shell scripts:

  - repo: https://github.com/shellcheck-py/shellcheck-py
    rev: v0.10.0.1
    hooks:
      - id: shellcheck

Conventional commits (if detected/configured):

  - repo: https://github.com/commitizen-tools/commitizen
    rev: v4.1.1
    hooks:
      - id: commitizen

After generating the config:

  1. Write .pre-commit-config.yaml
  2. Run pre-commit install to activate hooks
  3. Run pre-commit run --all-files once — this surfaces existing issues (trailing whitespace, formatting, maybe a private key in a fixture). Fixing these in one commit establishes a clean baseline.

Relationship to CI: Add pre-commit run --all-files as the first step in the generated CI workflow. This catches any commits that bypassed local hooks via git commit --no-verify.

Testing

Test runner:

Coverage:

Race detector (Go only — reported inline under Test runner):

CI/CD

CI pipeline:

CI on PRs:

Branch protection:

Documentation

README:

.env.example:

LICENSE:

Git Hygiene

.gitignore completeness:

Committed artifacts:

Lock file:

Large files:

Present the Health Card

Format the results as a health card using the status vocabulary above:

Project Health Check — {project-name} ({language}/{framework})

Security:
  {✓/✗/—} Dependency scanning: {Found|Found (via CI)|Missing|N/A}
  {✓/✗/—} Secret scanning: {Found|Found (equivalent: husky+gitleaks)|Missing}
  {✓/✗/—} No secrets in source: {Found: clean|FOUND: N secrets — fix now}
  {✓/✗/—} .gitignore covers sensitive files: {Found|Partial|Missing}

Code Quality:
  {✓/✗/—} Linter: {Found: eslint|Found (via CI)|Missing}
  {✓/✗/—} Formatter: {Found: prettier|Missing}
  {✓/✗/—} Type checking: {Found: strict|Partial: not strict|N/A}
  {✓/✗/—} Pre-commit hooks: {Found: pre-commit|Found (equivalent: husky)|Missing}

Testing:
  {✓/✗/—} Test runner: {Found: jest (47 tests)|Missing: zero tests}
  {✓/✗/—} Coverage reporting: {Found (via CI)|Partial: no threshold|Missing}

CI/CD:
  {✓/✗/—} CI pipeline: {Found: GitHub Actions (runs tests, lint)|Missing}
  {✓/✗/—} Branch protection: {Found|Missing}

Documentation:
  {✓/✗/—} README: {Found|Partial: boilerplate|Missing}
  {✓/✗/—} .env.example: {Found|Missing|N/A: no .env}
  {✓/✗/—} LICENSE: {Found|Missing}

Git Hygiene:
  {✓/✗/—} .gitignore complete: {Found|Partial}
  {✓/✗/—} No committed build artifacts: {Found: clean|FOUND: node_modules/ tracked}
  {✓/✗/—} Lock file committed: {Found|Missing}
  {✓/✗/—} No large files (>5MB): {Found: clean|FOUND: N files — consider git-lfs}

Score: X/Y checks passing (Y = applicable checks, excluding N/A)

Prioritize and Offer Fixes

Group issues by urgency:

  1. Fix now (security): hardcoded secrets, missing .gitignore for .env, committed credentials
  2. Fix soon (quality): no linter, no CI, no tests, committed build artifacts
  3. Recommended (hygiene): no pre-commit hooks, no coverage, no .env.example, no LICENSE

For each issue: explain what it is (one sentence), why it matters (one sentence), and offer to generate the fix. The human picks which fixes to apply.

What to generate when asked:

| Fix | Generated file | Tailored to |

|-----|---------------|-------------|

| Dependabot config | .github/dependabot.yml | Package ecosystems detected |

| CI workflow | .github/workflows/ci.yml | Language, test runner, linter, build command, pre-commit run --all-files as first step |

| Pre-commit config | .pre-commit-config.yaml | Core hooks (gitleaks, typos, file hygiene) + language-specific hooks |

| Coverage config | Updated test script + CI step | Test runner detected |

| .env.example | .env.example with redacted values | Current .env file |

| .gitignore additions | Updated .gitignore | Stack-specific entries |

| Linter config | .eslintrc.* or equivalent | Framework detected |

| Formatter config | .prettierrc or equivalent | Language detected |

Every generated file includes: # Generated by Correctless /csetup — review and customize as needed

After applying fixes, re-run the health card to show progress.

Step 8: Source Control Configuration

Greenfield projects: Keep this light. Confirm the default branch name and write sensible defaults to workflow-config.json under the workflow key: workflow.branching_strategy: "feature-branches", workflow.merge_strategy: "squash". These defaults are read by workflow-advance.sh init and /caudit — if left absent, those tools fail silently. Tell the user: "I've set feature branches with squash merge as defaults. You can change these later by re-running /csetup." Skip PR template, commit convention detection, and branch protection — there's no commit history to analyze yet. Mention: "Once you have your first PR, re-run /csetup to set up PR templates and branch protection."

Early-stage and Mature projects:

Statusline

If the Correctless statusline hook exists at .correctless/hooks/statusline.sh, check whether it's already registered in .claude/settings.json:

Source Control

Detect and configure source control preferences. Check what's already configured before asking.

Auto-detect first:

Present detected values, then ask what's missing:

Source Control — detected:
  ✓ Remote: GitHub
  ✓ Default branch: main
  ✓ gh CLI: installed
  ✓ Commit style: conventional commits (detected from history)
  ✗ PR template: none found → I can generate one
  ✗ Branch protection: not configured → recommend enabling

Branching strategy:
  1. Feature branches (recommended) — branch per feature, merge via PR
  2. Trunk-based — short-lived branches, commit to main frequently

  Or type your own: ___

Merge strategy:
  1. Squash (recommended) — clean history, one commit per feature
  2. Merge commit — preserves branch history
  3. Rebase — linear history, no merge commits

  Or type your own: ___

Where answers go:

| Setting | Stored in | Read by |

|---------|-----------|---------|

| Branching strategy | workflow-config.json | workflow-advance.sh init, /caudit |

| Merge strategy | workflow-config.json (workflow.merge_strategy) | /ctdd done, /caudit |

| PR CLI tool | CLAUDE.md | Every session |

| Commit format | CLAUDE.md | Every session |

| PR template | .github/pull_request_template.md | Agent pre-fills on PR creation |

If no PR template exists, offer to generate one with Correctless sections:

## Description
<!-- What does this change do? -->

## Spec
<!-- Link: .correctless/specs/xxx.md -->

## Testing
<!-- Coverage? All rules covered? -->

## Checklist
- [ ] Tests pass
- [ ] Spec rules covered
- [ ] /cverify passed
- [ ] Documentation updated

PR CLI tool goes to CLAUDE.md. If gh is detected: write Use \gh\ for GitHub operations (PRs, issues, checks). If glab is detected: write Use \glab\ for GitLab operations (MRs, issues, pipelines). This ensures every downstream skill that creates PRs knows which tool to use.

Commit format goes to CLAUDE.md. If conventional commits:

## Commit Messages
Use conventional commits: feat:, fix:, test:, docs:, refactor:, chore:
During TDD: test(feature): ..., feat(feature): ..., fix(feature): per QA finding
During audit: fix(audit-qa-r2): finding-id — description

Step 9: First Feature Guidance

End with clear, maturity-appropriate next steps.

Greenfield:

"You're set up. Your project is new, so setup was minimal — Correctless will learn your patterns as you build.

Start your first feature:

  1. git checkout -b feature/my-feature
  2. Run /cspec — I'll walk you through writing your first spec

The workflow guides you from there: spec → review → tests → implementation → QA → verify → docs."

Early-stage:

"You're set up. Your existing code is untouched — Correctless only activates on feature branches. The conventions I found will inform specs and reviews going forward.

Start a feature:

  1. git checkout -b feature/my-feature
  2. Run /cspec

Check workflow state anytime: .correctless/hooks/workflow-advance.sh status"

Mature:

"You're set up. I've learned your project's conventions and they'll inform every spec, review, and verification.

Start a feature: git checkout -b feature/my-feature then /cspec.

Or review a PR: /cpr-review {number}.

Current commands: /csetup, /cspec, /creview, /creview-spec, /cmodel, /ctdd, /cverify, /caudit, /cupdate-arch, /cdocs, /cpostmortem, /cdevadv, /credteam, /crefactor, /cpr-review, /ccontribute, /cmaintain, /cstatus, /csummary, /cmetrics, /cdebug, /chelp, /cwtf, /cquick, /crelease, /cexplain, /cauto, /carchitect, /cmodelupgrade, /cdashboard, /ctriage, /cprune

Check workflow state: .correctless/hooks/workflow-advance.sh status"

If the human says they want to start a feature, ask what they want to build and suggest they run /cspec. Do not auto-invoke /cspec.

Delete the checkpoint file — setup is complete.

Subsequent Runs

When /csetup is run on a project that's already configured:

  1. Re-assess maturity (the project may have grown since last setup)
  2. Handle maturity transitions — if maturity has increased, run the steps that were previously skipped:
  1. Re-run health checks appropriate to the current maturity level
  2. Show what improved since last run, what's new, what's still missing
  3. Only offer to fix new or unresolved issues — don't re-prompt for things already declined
  4. Re-detect tools (mutation testing, Alloy, external model CLIs) and offer to enable newly found ones
  5. Re-mine conventions if the project has grown significantly within the same maturity tier — "You had 30 source files last time, now you have 120. Want me to rescan for new patterns?"

Claude Code Feature Integration

Task Lists

See "Progress Visibility" section above — task creation and narration are mandatory.

If Something Goes Wrong

Constraints

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.