---
name: guidelines-init
description: >
  Scaffolds a PROJECT_GUIDELINES.md file for a codebase by auto-detecting project
  conventions and interviewing the user. Use this skill when the user wants to set up
  coding standards, initialize project guidelines, create a style guide, establish
  code conventions, or says things like "set up guidelines", "init standards",
  "create a style guide", or "what conventions should we follow". Also use when
  a project has no PROJECT_GUIDELINES.md and the user asks for a code review.
---

# Guidelines Init

Generate a `PROJECT_GUIDELINES.md` file that becomes the single source of truth
for project conventions. This file is later consumed by `/guidelines-review`.

## Arguments

`$ARGUMENTS` determines the mode:

| Argument | Mode |
|---|---|
| *(empty)* | **Simple** — flat list of rules, minimal interview |
| `--simple` | **Simple** — same as empty |
| `--full` | **Full** — categorized guidelines with severity tags, comprehensive interview |
| `--upgrade` | **Upgrade** — converts an existing simple-mode file to full mode |

---

## CONVENTIONS.md Integration

Before generating `PROJECT_GUIDELINES.md`, check for an existing `.context/CONVENTIONS.md` (also check the project root if not found in `.context/`).

### If CONVENTIONS.md exists with code quality rules

Code quality rules include: naming conventions, file organization / directory structure rules, error handling patterns, testing conventions (naming, coverage targets — not the framework or run command), git conventions (commit format, branch naming), import ordering rules (not the tool that enforces them).

If any of these are found:

1. **Extract and migrate** those rules into the `PROJECT_GUIDELINES.md` generation process:
   - In simple mode: include them in the flat rules list
   - In full mode: place them in the appropriate category sections (Naming → Code Style, file organization → Architecture, etc.)
   - Present the migration to the user before generating: "I found these code quality rules in your CONVENTIONS.md that belong in PROJECT_GUIDELINES.md: [list]. I will include them in the generated guidelines."

2. **After generating PROJECT_GUIDELINES.md**, update `CONVENTIONS.md`:
   - Remove the migrated code quality sections
   - Keep only: Language and Runtime, Tooling (formatter/linter/type checker), Testing (framework + run command only), Build and Run
   - Ensure the `## Project Guidelines Reference` section exists and points to `PROJECT_GUIDELINES.md`
   - Show the user what was removed and confirm before writing

### If CONVENTIONS.md exists but has only tooling/environment content

No migration needed. After generating `PROJECT_GUIDELINES.md`, add the `## Project Guidelines Reference` section to `CONVENTIONS.md` if it is missing.

### If CONVENTIONS.md does not exist

No migration needed. Mention to the user that `/context-init` can create `CONVENTIONS.md` for tooling and environment setup, and it will automatically reference the generated guidelines file.

---

## Simple Mode Workflow

Default when no flag is provided. Optimized for getting rules on paper fast.

### Phase 1 — Quick scan

Identify the project's tech stack and shape. This is for context only — not an
exhaustive convention analysis.

- Read `package.json`, `go.mod`, `Cargo.toml`, or `pyproject.toml` (whichever exists)
  to identify the primary language and framework.
- Use `Glob("src/*/")` or `Glob("*/")` to understand directory structure.
- Note the test framework if obvious from config files.
- Check for monorepo signals: `Glob("packages/*/package.json")`, `Glob("apps/*/")`,
  `lerna.json`, `pnpm-workspace.yaml`, `turbo.json`.
- Check for `.context/CONVENTIONS.md` to detect existing code quality rules to migrate (see CONVENTIONS.md Integration above).

Do NOT run the full signal file table or pattern detection. Keep this under 30 seconds.

### Phase 2 — Ask for rules

Present a 2-3 sentence summary of what you detected:

> "This looks like a TypeScript/React project using Jest for testing, organized
> by feature under `src/features/`."

Then ask a single open-ended question:

> "What rules matter to you? List whatever comes to mind — coding conventions,
> architectural boundaries, things that annoy you in code review. I'll turn them
> into a guidelines file."

Accept the user's response as-is. Do NOT:
- Force answers into categories
- Ask follow-up questions for each category
- Suggest rules the user didn't mention
- Run a structured 8-category interview

If the user's list is very short (< 3 rules), it's fine to ask: "Anything else,
or is that the full list?" — but only once.

### Phase 3 — Generate

Write `PROJECT_GUIDELINES.md` with this format:

```markdown
# Project Guidelines

<!-- mode: simple -->
<!-- Generated by guidelines-init | Last updated: YYYY-MM-DD -->

## Overview
[One paragraph: project description and tech stack]

## Rules

- [Rule 1 — clean up the user's wording to be actionable, but preserve their intent]
- [Rule 2]
- [Rule 3]
- ...
```

**Rules for the generated file:**

- Include the `<!-- mode: simple -->` marker on the line after the heading. This tells
  `/guidelines-review` which mode to use.
- Put all rules under a single `## Rules` heading as a flat bullet list.
- Clean up grammar and make each bullet actionable, but do not change the meaning.
- Do NOT add rules the user did not mention.
- Do NOT add severity tags. A rule is a rule — if it's in the file, it matters.
- Do NOT add category headings (Code Style, Architecture, etc.).
- If `.context/CONVENTIONS.md` exists, end the Overview paragraph with: "Tooling and
  environment setup (formatter, linter, test runner, build commands) are documented in
  `.context/CONVENTIONS.md`."

After writing, if a CONVENTIONS.md migration was performed (see CONVENTIONS.md Integration above), update `.context/CONVENTIONS.md` now — remove the migrated sections and ensure the `## Project Guidelines Reference` section is present.

Tell the user the file is ready and offer: "Want to add, remove, or reword anything?" — but skip the summary table. The file is short enough to read.

Recommend committing `PROJECT_GUIDELINES.md` (and the updated `CONVENTIONS.md` if modified) to the repo.

---

## Full Mode Workflow

Used when `--full` is provided. Comprehensive auto-detection, structured interview,
categorized output with severity tags.

### Phase 1 — Auto-detect

Scan the project to infer as much as possible before asking the user anything.
Read files, don't just check existence.

**Signal files to scan:**

| Signal file | What to infer |
|---|---|
| `package.json` | Language (TS/JS), framework, test runner, linter, formatter |
| `tsconfig.json` / `jsconfig.json` | Strict mode, module system, path aliases |
| `.eslintrc*` / `eslint.config.*` | Lint rules already codified |
| `.prettierrc*` | Formatting conventions |
| `pyproject.toml` / `setup.cfg` / `requirements.txt` | Python tooling, linter config |
| `ruff.toml` / `.flake8` | Python linting conventions |
| `go.mod` | Go module conventions, Go version |
| `Cargo.toml` | Rust edition, features, dependencies |
| `Dockerfile` / `docker-compose.yml` | Containerization conventions |
| `.github/workflows/*.yml` | CI/CD patterns, checks, test commands |
| `.editorconfig` | Indentation, line endings, charset |
| `CLAUDE.md` / `.github/copilot-instructions.md` | Prior AI-assistant conventions |
| `.context/CONVENTIONS.md` | Existing naming, error handling, testing, git conventions to migrate |
| `.gitignore` | What the project considers generated/private |

**Pattern detection (use Glob and Grep, not shell commands):**

- Use `Glob("**/*.test.*")` and `Glob("**/*.spec.*")` to detect test file naming
- Use `Glob("**/*_test.go")` or `Glob("**/test_*.py")` for language-specific test patterns
- Use `Grep` on a sample of source files (first 10 found) to detect:
  - Import style (named vs default exports, absolute vs relative paths)
  - Indentation (tabs vs spaces, width)
  - Quote style (single vs double)
  - Semicolon usage
- Use `Glob("*/")` and `Glob("src/*/")` to detect directory structure organization
- Check for monorepo signals: `Glob("packages/*/package.json")`, `Glob("apps/*/")`,
  presence of `lerna.json`, `pnpm-workspace.yaml`, or `turbo.json`

### Phase 2 — Interview

Present auto-detected findings as a summary, then ask targeted questions to fill gaps.
Organize questions by category. **Skip categories already fully answered by auto-detection.**

If code quality rules were found in `.context/CONVENTIONS.md`, pre-populate the interview with those rules. Present them as "detected from your existing CONVENTIONS.md" and ask if the user wants to keep, modify, or discard each before proceeding.

Ask these in order:

1. **Code Style** — Naming conventions, max line length, import ordering, quote style
2. **Architecture** — Preferred patterns, directory structure rules, module boundaries
3. **Error Handling** — Strategy (exceptions, Result types), logging conventions
4. **Testing** — Coverage areas, naming conventions, organization, mocking strategy
5. **Git Workflow** — Branch naming, commit message format, PR size expectations
6. **Documentation** — Docstrings/JSDoc policy, README standards, inline comments
7. **Security** — Secret management, input validation, dependency update policy
8. **Performance** — Caching strategy, N+1 awareness, bundle size, lazy loading

Don't ask about categories that clearly don't apply (e.g., skip "bundle size" for a
CLI tool, skip "N+1 queries" for a project without a database).

If `references/guideline-categories.md` is available in the plugin directory, read
the sections relevant to the detected tech stack for example rules to reference during
generation. Do not copy examples verbatim — adapt them to the project's own code.

### Phase 3 — Generate

Create `PROJECT_GUIDELINES.md` in the repo root.

**Critical: every section or subsection must have a severity comment on the line
immediately after the heading.** Format: `<!-- severity: error|warning|info -->`

Default severity mapping:

| Category | Default Severity |
|---|---|
| Security | `error` |
| Error Handling | `error` |
| Architecture | `error` |
| Code Style | `warning` |
| Testing | `warning` |
| Git Workflow | `warning` |
| Documentation | `warning` |
| Performance | `info` |

Template:

```markdown
# Project Guidelines

<!-- mode: full -->
<!-- Generated by guidelines-init | Last updated: YYYY-MM-DD -->

## Overview
<!-- One paragraph describing the project and its primary tech stack -->

## Code Style

### Naming
<!-- severity: warning -->
- ...

### Formatting
<!-- severity: warning -->
- ...

### Imports
<!-- severity: warning -->
- ...

## Architecture

### Directory Structure
<!-- severity: error -->
- ...

### Module Boundaries
<!-- severity: error -->
- ...

## Error Handling
<!-- severity: error -->
- ...

## Testing

### Requirements
<!-- severity: warning -->
- ...

### Conventions
<!-- severity: warning -->
- ...

## Git Workflow
<!-- severity: warning -->
- ...

## Documentation
<!-- severity: warning -->
- ...

## Security
<!-- severity: error -->
- ...

## Performance
<!-- severity: info -->
- ...
```

**Formatting rules for the generated file:**

- The `<!-- severity: ... -->` comment is the contract that `/guidelines-review` depends
  on. It must appear on the line directly after the section heading, before any content.
- Use concrete examples with code blocks. Don't say "use descriptive names" — say
  `use descriptive names like fetchUserById, not getData`.
- Each bullet should be independently actionable.
- Use the project's own code as examples wherever possible.
- Omit sections that don't apply to the project entirely, don't leave them blank.
- If `.context/CONVENTIONS.md` exists, end the Overview paragraph with: "Tooling and
  environment setup (formatter, linter, test runner, build commands) are documented in
  `.context/CONVENTIONS.md`."

### Phase 4 — Confirm

Show the user a summary table:

```
| Category       | Rules | Severity |
|----------------|-------|----------|
| Code Style     | 8     | warning  |
| Architecture   | 4     | error    |
| Error Handling | 3     | error    |
| Testing        | 5     | warning  |
| ...            | ...   | ...      |
```

Ask if they want to:
- Adjust severity levels for any category
- Add, remove, or modify any specific rules
- Change the location of the file

Once confirmed, if a CONVENTIONS.md migration was performed (see CONVENTIONS.md Integration above), update `.context/CONVENTIONS.md` now — remove the migrated sections and ensure the `## Project Guidelines Reference` section is present.

Recommend committing `PROJECT_GUIDELINES.md` (and the updated `CONVENTIONS.md` if modified) to the repo.

---

## Upgrade Workflow

Used when `--upgrade` is provided. Converts a simple-mode file to full mode.

1. Verify `PROJECT_GUIDELINES.md` exists. If not, tell the user to run
   `/guidelines-init` first and stop.
2. Check for `<!-- mode: simple -->`. If the file is already full mode, tell the user
   it's already in full mode and stop.
3. Read the existing simple rules into memory.
4. Run full-mode **Phase 1** (auto-detect) to gather project context.
5. Run full-mode **Phase 2** (interview), but pre-populate with the existing simple
   rules. Present a proposed mapping of existing rules to categories:
   > "Here's how I'd categorize your existing rules:
   > - 'Don't add code to handler.ts' → Architecture > Module Boundaries
   > - 'Everything needs test cases' → Testing > Requirements
   > Agree with this mapping, or want to move anything?"
6. Run full-mode **Phase 3** (generate) with the `<!-- mode: full -->` marker.
   Incorporate the existing simple rules into the appropriate category sections.
7. Run full-mode **Phase 4** (confirm).

---

## Edge Cases

**Monorepo:** If you detect a monorepo (multiple `package.json` files, `packages/`
or `apps/` directory, or `lerna.json` / `pnpm-workspace.yaml` / `turbo.json`), ask
whether guidelines should be global or per-package. In both modes, generate a
root-level file. In simple mode, keep it as a flat list. In full mode, note where
per-package overrides would go.

**CONVENTIONS.md with only tooling content:** If `.context/CONVENTIONS.md` exists but
contains only tooling and environment information (no naming, error handling, testing
conventions, git workflow, or architecture rules), skip migration. Just add the
`## Project Guidelines Reference` section if missing.

**CONVENTIONS.md at project root instead of .context/:** If `CONVENTIONS.md` is found
at the project root rather than `.context/`, treat it the same way — scan for code
quality rules, migrate them, and update the file.

**Existing guidelines with mode mismatch:**
- Running with no flag or `--simple` when a full-mode file exists: warn the user that
  replacing it will lose severity tags and category structure. Suggest using the
  existing full-mode file or running `/guidelines-review` against it instead.
- Running with `--full` when a simple-mode file exists: suggest `--upgrade` instead
  of replacing, since upgrade preserves existing rules.

**Existing guidelines, same mode:** Ask whether to update (merge new detections) or
replace entirely. Default to merging.

**Empty project:** In simple mode, generate a starter with 3-5 universal rules
marked as `<!-- TODO: add your project-specific rules -->`. In full mode, generate
a starter template with sensible defaults and `<!-- TODO: customize -->` markers.

## Rules

- Do NOT invent conventions that aren't supported by evidence from the scan or user input.
  If something is unknown and the user declines to specify, mark it as "Not specified"
  rather than guessing.
- Keep the output actionable and scannable — bullet points over paragraphs.
- In full mode, the severity comment format must be exactly `<!-- severity: error -->`,
  `<!-- severity: warning -->`, or `<!-- severity: info -->`.
- In simple mode, do NOT add severity tags or category structure.
- The mode marker (`<!-- mode: simple -->` or `<!-- mode: full -->`) must always be
  present in generated files.
