# AI Agent Guidelines

**Version:** 4.9

---

## Critical Rules

| Rule | Description |
|------|-------------|
| **CLI First** | Use `civyk-hatch` CLI for all workflow operations |
| **CLI Flags** | Use named flags (`--flag value`), NOT positional args |
| **OS Shell** | Bash (Linux/macOS), PowerShell (Windows) |
| **ASCII-Only** | No Unicode. Use `->`, `[ok]`, `[x]`, `[!]` |
| **Mermaid Diagrams** | Mermaid syntax only. No ASCII art |
| **State Auto-Detection** | After stage 2, CLI auto-detects stage from state.json |

---

## Quick Reference

**Priority:** Constitution > Spec > Plan > Corporate Guidelines > Supporting Docs

**Task States:** `[ ]` pending, `[x]` complete, `[F]` failed, `[B]` blocked

**RFC 2119:** MUST = mandatory. NEVER = prohibited. SHOULD = follow unless justified. MAY = use judgment.

| DO | DON'T |
|----|-------|
| STOP + `CLARIFICATION NEEDED` when unclear | Commit secrets/credentials |
| Follow Constitution at all times | Modify `memory/` during implementation |
| Pre-commit: formatters -> linters -> type checkers -> build | Add requirements not in specs |

| Problem | Action |
|---------|--------|
| Spec unclear | STOP, mark [B], WAIT |
| Test fail (syntax) | Auto-fix max 2x |
| Test fail (logic) | Mark [F], WAIT |
| Constitution conflict | STOP, FLAG, WAIT |
| Missing file | SEARCH, then CLARIFICATION NEEDED |

**Markers:**

| Marker | Action |
|--------|--------|
| `[!]` | Treat as MUST, never skip |
| `[ok]`/`[x]` | Verify before proceeding |
| `[STOP: USER_INPUT_REQUIRED]` | WAIT for user |
| `[STOP: USER_CONFIRMATION_REQUIRED]` | WAIT for user |
| `[STOP: *]` (all others) | Execute and AUTO-CONTINUE |
| `[AUTO-CONTINUE]` / no marker | Proceed immediately |
| `[STAGE TRANSITION]` | Auto-continue to next stage |
| `[WAIT-FOR-INPUT]` | Stop and wait |
| `[GATE-CHECK]` | Pass: continue. Fail: wait |
| `[WORKFLOW COMPLETE]` | Stop, report completion |

**Default:** No marker = `[AUTO-CONTINUE]`. Do NOT ask "should I continue?" between stages.

---

## CLI Commands

| Command | Description |
|---------|-------------|
| `analyze-project` | Analyze existing project (git branch workflow) |
| `constitution` | Create project constitution |
| `specify` | Create baseline specification |
| `clarify` | Ask structured questions |
| `plan` | Create implementation plan |
| `tasks` | Generate actionable tasks |
| `implement` | Execute implementation |
| `checklist` | Generate quality checklist |
| `analyze` | Cross-artifact consistency check |
| `tests` | Iterative test implementation (`--target-coverage=N`) |
| `review` | Iterative code review (`--commits=N` or `--since="date"`) |
| `orchestrate` | Orchestrate complete workflow |
| `resume` | Resume workflow from saved state |
| `generate-guidelines` | Generate coding guidelines |
| `deepwiki` | Generate AI-powered wiki (requires civyk-repoix) |
| `deepwiki-update-state` | Update deepwiki workflow state |
| `sync-docs` | Sync documentation with codebase (iterative) |
| `understand` | Build hierarchical codebase understanding |

**Interfaces:**

- `/civyk-hatch.xxx` (slash commands) -> Human users in IDE
- `civyk-hatch xxx` (CLI) -> AI agents programmatically
- `civyk_hatch_*` (MCP tools) -> AI agents via JSON-RPC

**MCP Tools (v4.0+):**

| Tool | Purpose |
|------|---------|
| `civyk_hatch_list_workflows` | List available workflows |
| `civyk_hatch_get_stage` | Get stage prompt (skill, stage, feature_dir?, scope?, chunk?) |
| `civyk_hatch_execute_stage` | Execute stage (skill, stage, feature_dir?, user_input?, dry_run?) |

**Workflow-Specific Parameters (execute_stage):**

| Parameter | Workflows | Description |
|-----------|-----------|-------------|
| `mode` | understand | `quick`, `standard`, or `deep` |
| `target_coverage` | tests | Target coverage % (0-100) |
| `iterations` | tests, review | Max iterations |
| `include`/`exclude` | understand | File patterns |
| `max_agents` | understand, review | Max parallel agents (default 10/5) |
| `docstrings` | understand | Enable docstring updates (default false) |

**State Locations:**

| Command | State Location |
|---------|----------------|
| `analyze-project` | `.analysis/{project}-{timestamp}/state.json` |
| `deepwiki` | `wiki/state.json` (via `deepwiki-update-state` CLI) |
| `constitution` | `memory/constitution.md` (file-existence check) |
| `generate-guidelines` | No state (requires `--stage`) |
| Others | `specs/{feature}/.state/state.json` |

**Stage Auto-Detection:**

| Command Type | Stages 1-2 | Stage 3+ |
|--------------|------------|----------|
| Feature-scoped (specify, plan, etc.) | Needs `--stage` | Auto-detected |
| analyze-project | Auto-detected | Auto-detected |
| constitution, generate-guidelines | Needs `--stage` | Needs `--stage` |

**[!] Do NOT duplicate next steps in prompts** -- CLI handles via `emit_stage()` and `emit_complete()`.

---

## File Write Rules

**analyze-project/deepwiki:** Use `write-report`/`write-data` CLI commands. Never `Out-File`, `echo >`, `cat <<`.

**Feature workflows (specify, plan, implement, etc.):** Use Edit/Write tools as directed by prompts.

| Rule | Requirement |
|------|-------------|
| **--append First** | Place `--append` before `--content` to prevent truncation |
| **Stdin for Large** | Content >2000 chars MUST use `--stdin` mode |
| **Full Quality** | Chunking = multiple writes, NOT reduced content |

**Stdin mode:**

```bash
# Linux/macOS
cat << 'EOF' | civyk-hatch write-report <file.md> --stage=<id> --append --stdin
<content>
EOF

# Windows PowerShell
@"
<content>
"@ | civyk-hatch write-report <file.md> --stage=<id> --append --stdin
```

**Temp File Fallback:** If stdin fails, use system temp folder (`$env:TEMP` or `/tmp`). Never create temp files in analysis directory.

---

## Template Handling

| Directive | Purpose | Example |
|-----------|---------|---------|
| `{{copy-template:src:dest}}` | Copy template to feature_dir | `{{copy-template:spec-template.md:spec.md}}` |
| `{{include:path}}` | Include template inline | `{{include:checklist-template.md}}` |

**[!] Replace ALL `[...]` placeholders** -- prompts verify none remain.

**Prohibited in output:** `TODO`, `TBD`, `TKTK`, `???`, `<placeholder>`, "will be analyzed", "coming soon"

**Variable syntax:** `{variable}` = CLI-substituted. `{{variable}}` = literal `{variable}` for display.

**Context variables:** `feature_dir`, `spec_path`, `analysis_dir`, `stage`, `total_stages`, `command`

**Append:** Markdown supports `--append`. JSON does not (creates invalid JSON).

**CLI `--chunk` vs Prompt "Part":** `--chunk=N` = separate CLI invocations. "Parts" = sections within ONE invocation. Do NOT use `--chunk=N` for internal Parts.

---

## Chunking (>1500 lines)

**[!] MANDATORY when file exceeds 1500 lines or context limits apply.**

| Principle | Description |
|-----------|-------------|
| **Completion-based** | Each chunk is a complete logical section (NOT size-based) |
| **Full quality** | Multiple writes, NOT reduced content |
| **No placeholders** | Never TODO, TBD, "will be analyzed" |
| **Resume support** | Check existing content before starting |

**Pattern:** `[STOP: GENERATE_CHUNK_N]` -> Generate -> `write-report --append` -> Verify -> `[ok] Chunk N/Total`

**Resume:** Check file exists -> scan last completed section -> skip completed chunks.

---

## CLI Utility Commands

### Stage Tracking

```bash
# Feature workflows
civyk-hatch update-stage <stage> --status=completed --prompt=<workflow> --feature-dir=<dir> --artifacts=<files>

# Tests/review iterations
civyk-hatch update-stage <stage> --prompt=tests --feature-dir=<dir> --status=in_progress --iterations=<N> --current-coverage=<N> --target-coverage=<N>
civyk-hatch update-stage <stage> --prompt=review --feature-dir=<dir> --status=in_progress --iterations=<N>

# analyze-project
civyk-hatch update-stage <id> --status=completed --analysis-dir=<dir>
```

### Deepwiki State Commands

| Command | Purpose |
|---------|---------|
| `deepwiki-update-state init --files=N --symbols=N --components="a,b"` | Initialize state |
| `deepwiki-update-state stage --stage=ID --status=completed [--artifacts=files]` | Update stage |
| `deepwiki-update-state verify-stage --stage=ID [--wiki-dir=<path>]` | Verify prerequisites |
| `deepwiki-update-state enumerate-index [--wiki-dir=<path>]` | Discover file/component patterns |
| `deepwiki-update-state business-context --context-file=path` | Save business context |
| `deepwiki-update-state project-size --category=<small\|medium\|large\|very_large> [--files=N] [--symbols=N]` | Save project size |
| `deepwiki-update-state file-patterns --extensions=".py,.ts" [--test-patterns=...] [--language=...]` | Save file patterns |
| `deepwiki-update-state stats [--files=N] [--symbols=N] [--components="a,b"]` | Update generation stats |
| `deepwiki-update-state discovery-cache --key=K --value='json'` | Save cross-stage context |
| `deepwiki-update-state show [--key=KEY]` | Show state (or specific key) |
| `deepwiki-update-state complete` | Mark workflow complete |

### Other Commands

| Command | Purpose |
|---------|---------|
| `init <project> --ai <agent>` | Initialize new project |
| `check` | Check installed tools and feature paths |
| `get-context --field scope` | Get render context |
| `file-stats <file> --pattern "^##"` | File info and pattern counts |
| `list-files --pattern "**/*.cs"` | Find files by pattern |
| `search-lib <library>` | Search configured Artifactory |
| `check-artifactory <url> <library>` | Check library availability |
| `show-fragment <command> <fragment>` | Show prompt fragment (debug) |

**Artifactory:** Configure in `memory/config.json` (`artifactory.enabled`, `url`, `repos`, `apiKeyEnv`). When enabled, agents auto-validate dependencies during plan, implement, and analyze-project workflows.

---

## analyze-project Reference

| Stage | ID | Description | Command |
|-------|-----|-------------|---------|
| 1 | 01a-initialization | Setup & Scope | `--stage=1` |
| 2 | 01b-input-collection | Input Collection | `--stage=2` |
| 3 | 01c-script-execution | Script Execution | `--stage=3` |
| 4-8 | 02a-02e | Scan, Deep Dive, Config, Tests, Quality Gates | `--stage=4..8` |
| 9 | 03a-full-app | Scope A (4 chunks) | `--stage=9 --chunk=1..4` |
| 10 | 03b-cross-cutting | Scope B (3 chunks) | `--stage=10 --chunk=1..3` |
| 11-13 | 04a-04c | Report Chunks 1-9 | `--stage=11..13` |
| 14 | 04d-report-verification | Report Verification | `--stage=14` |
| 15 | 05a-executive-summary | Executive Summary | `--stage=15` |
| 16 | 06-artifacts | Final Artifacts | `--stage=16 --chunk=1` |

**Normal flow:** After stage 1, run `civyk-hatch analyze-project` on the analysis branch -- CLI auto-detects.

**Resuming:** `git checkout analysis/{project}-{timestamp}` then `civyk-hatch analyze-project`.

**Stage 16 Chunks:** Scope A (13): func-legacy (1-3), func-target (4-6), tech-legacy (7-9), tech-target (10-12), stage-prompts (13). Scope B: cross-cutting-artifacts (1).

**Preference Keys:** `q1_language`, `q2_database`, `q3_message_bus`, `q4_package_manager`, `q5_deployment`, `q6_iac`, `q7_containerization`, `q8_observability`, `q9_security`, `q10_testing`

---

## Corporate Guidelines

**Loading:** Detect tech stack -> Detect profile -> Load base -> Load override.

| Stack | Markers |
|-------|---------|
| React | `package.json` with `react`, `next.config.js` |
| Node.js | `package.json` with `express`/`fastify`/`koa` |
| Python | `requirements.txt`, `pyproject.toml`, `manage.py` |
| Java | `pom.xml`, `build.gradle` |
| .NET | `*.csproj`, `*.sln` |

**Paths:** Base: `.guidelines/base/{stack}-base.md`. Override: `.guidelines/profiles/{profile}/{stack}-overrides.md`

**Profiles:** `corporate` or `personal` (from `memory/config.json` -> `.guidelines-profile` -> default `personal`)

**Priority:** Constitution > Profile Override > Base Guideline > Defaults

---

## civyk-repoix Integration

### Mode Detection

DeepWiki Stage 01 tries MCP first, falls back to CLI. Mode persisted in `state.json`.

### CLI Fallback

```bash
civyk-repoix query <tool-name> [--param value]
```

**Name conversion:** MCP and CLI use the same tool names. Action parameter dispatches to specific operations. Arrays use commas (`--kinds "class,function"`). Booleans become flags (`--include-private`).

**Exit codes:** `0` = success (JSON stdout), `1` = error.

### Pattern Syntax (Critical)

| Tool | Syntax | NOT Supported |
|------|--------|---------------|
| `search(action="symbols")` | SQL LIKE (`%` wildcard, `_` single char) | Regex, OR patterns (`A\|B` silently returns empty) |
| `search(action="code")` | Regex (with `is_regex=true`) | SQL LIKE |
| `files` | fnmatch glob (`*`, `**`, `?`, `[abc]`, `[!abc]`) | Brace expansion (`{a,b}`) |

**search(action="symbols"):** `"struct"` is NOT a valid kind -- Go/Rust/C# structs map to `"class"`.

### Pagination

All list tools return `has_more`. **MUST paginate when `has_more=true`** using `limit`/`offset`.

`symbol(action="hierarchy")` uses `ancestors_has_more`/`descendants_has_more` instead.

### MCP Tools (14 Consolidated)

| Tier | Tool | Actions | Purpose |
|------|------|---------|---------|
| **Core** | `status` | `check`, `reindex`, `perf_stats` | Index health, re-indexing, performance stats |
| **Core** | `search` | `symbols`, `code`, `definition` | Find symbols, text patterns, definitions |
| **Core** | `symbol` | `detail`, `references`, `callers`, `hierarchy`, `similar` | Symbol details, usage, call graph, type hierarchy |
| **Core** | `file` | `symbols`, `imports`, `related` | Per-file symbols, imports, related files |
| **Core** | `files` | -- | List/filter repository files |
| **Core** | `git` | `changes`, `hotspots`, `diff` | Recent changes, churn hotspots, branch diffs |
| **Core** | `understand` | `store`, `recall`, `stats`, `invalidate` | AI cache: persist/retrieve understanding |
| **Core** | `explore` | -- | Multi-strategy deep-dive in one call |
| **Core** | `remember` | -- | Cross-session key-value memory |
| **Extended** | `architecture` | `components`, `dependencies`, `endpoints` | Module graph, dependency analysis, API endpoints |
| **Extended** | `quality` | `dead_code`, `duplicates`, `circular_deps`, `impact` | Code health and impact analysis |
| **Extended** | `context` | `task`, `delta`, `docs`, `trace` | Token-budgeted context packs |
| **Extended** | `tests` | `recommended`, `for_file`, `code_for_test` | Test discovery and mapping |
| **Specialist** | `conversation` | `list`, `history`, `search`, `context`, `log`, `finalize` | Conversation history across sessions |

### DeepWiki Stages

| Priority | Stages | Content |
|----------|--------|---------|
| P1 | 1-7 | check-repoix, business-context, quickstart, overview, diagrams, flows, components |
| P2 | 8-12 | api, models, config, dependencies, decisions |
| P3 | 13-16 | errors, examples, enrichment, summary |

---

## AI Context Cache

**[!] Check cached understanding BEFORE reading source files.**

**Protocol:**
1. `understand(action="recall", target="path")` before reading any file
2. If `found=true` AND `fresh=true` -> use cached, skip file read
3. If `found=false` or `fresh=false` -> read file, then `understand(action="store")`

**understand(action="store") fields:** `scope` (file/class/module/project), `target` (path), `purpose` (1-2 sentences), `importance` (critical/high/medium/low). Optional: `key_points`, `gotchas`, `analysis`.

**understand(action="stats") params:** `limit` (1-200), `offset`, `filter` (path contains), `scope`, `sort_by` (importance/access_count/target), `include_fresh` (bool), `case_insensitive` (bool).

**Session start:** Call `understand(action="stats", limit=50)` to see what's cached. Recall relevant entries before working.

---

## Code Generation

- Small commits (1 scenario, 1-5 files, <300 lines)
- Default to latest LTS versions; state version + reasoning in plan.md

---

## Ethics & Safety

**MUST NOT:** Commit secrets/keys, share PII, make undisclosed network calls

**Licensing:** Prefer permissive (MIT, Apache, BSD). STOP for license conflicts.
