# AutoWorkflow

> Automated workflow enforcement via hooks + system prompts.
> **All automation is hook-driven → Claude executes the actual work**

## How It Works

```
┌─────────────────────────────────────────────────────────────┐
│  USER MESSAGE                                               │
│       ↓                                                     │
│  HOOK TRIGGERS (shell scripts)                              │
│       ↓                                                     │
│  HOOK OUTPUT (instructions/prompts for Claude)              │
│       ↓                                                     │
│  CLAUDE READS OUTPUT + ACTS                                 │
│       ↓                                                     │
│  RESPONSE TO USER                                           │
└─────────────────────────────────────────────────────────────┘
```

**Key:** Hooks OUTPUT instructions → Claude READS them → Claude DOES the work

---

## Architecture

```
.claude/hooks/           →  AUTO-TRIGGERS (output prompts to Claude)
.claude/settings.json    →  HOOK CONFIG + SYSTEM INSTRUCTIONS
.claude/.autoworkflow/   →  STATE FILES (phase, iterations, etc.)
CLAUDE.md (this file)    →  WORKFLOW SUMMARY
instructions/            →  AI_RULES.md + user's documentation
system/                  →  DETAILED REFERENCE (gates, loops, triggers, router)
```

**Priority:** Hooks → settings.json → This file → system/*.md

---

## Auto-Triggers (Hooks)

| Event | Hook | Output to Claude |
|-------|------|------------------|
| User message | `session-check.sh` | "Provide your project documentation" |
| After Write/Edit | `post-edit.sh` | Runs `npm run verify`, shows errors |
| Before git commit | `pre-tool-router.sh` | Runs all 7 gate checks, BLOCKS if fail |

**Hooks don't do the work - they tell Claude what to do!**

---

## Workflow

```
ANALYZE → PLAN → CONFIRM → IMPLEMENT → VERIFY → AUDIT → COMMIT → UPDATE
```

| Phase | What Claude Does |
|-------|------------------|
| ANALYZE | Read relevant files, check user's documentation |
| PLAN | Design approach, show suggestions |
| CONFIRM | **Wait for user approval** |
| IMPLEMENT | Make changes (after approval only) |
| VERIFY | Run `npm run verify` - **AUTO-TRIGGERED** |
| AUDIT | Run `npm run audit:ui` + `audit:cycles` |
| COMMIT | Conventional commit format - **BLOCKED if checks fail** |
| UPDATE | Note changes in session context |

---

## Auto-Verification Loop

After EVERY code edit, `post-edit.sh` automatically:
1. Runs `npm run verify`
2. Shows errors to Claude
3. Claude fixes them
4. Repeats until passing (max 10 iterations)

```
EDIT → HOOK RUNS VERIFY → ERRORS? → CLAUDE FIXES → VERIFY AGAIN → ...
```

---

## Pre-Commit Gate (7 Checks)

Before `git commit`, `pre-commit-check.sh` runs:

| Check | Pass Condition |
|-------|----------------|
| TypeScript | 0 errors |
| ESLint | 0 warnings |
| TODO/FIXME | None in staged files |
| console.log | None in staged files |
| UI Enforcement | No orphan features |
| Circular Deps | No import cycles |
| Commit Format | `type(scope): description` |

**If ANY check fails → Commit is BLOCKED (exit 1)**

---

## Task Types

| Type | Workflow | Audit? |
|------|----------|--------|
| feature | Full (all phases) | Yes |
| fix | Standard (no audit) | No |
| refactor | With audit | Yes |
| docs | Simple | No |
| query | Analyze → Respond | No |

---

## State Tracking

All state stored in `.claude/.autoworkflow/`:
- `phase` - Current workflow phase
- `task-type` - Classified task type
- `verify-iteration` - Loop count (max 10)
- `verify-status` - PASSED/FAILED
- `plan-approved` - User approval status

---

## Logging System

Real-time visibility into hook execution, gates, and workflow events.

**Log Location:** `.claude/.autoworkflow/logs/aw.log`

**CLI Commands:**
```bash
npx autoworkflow logs          # Watch logs in real-time
npx autoworkflow logs --recent # Show last 50 entries
npx autoworkflow logs --all    # Show all logs
npx autoworkflow logs --clear  # Clear logs
npx autoworkflow logs --stats  # Show statistics
```

**Or use tail directly:**
```bash
tail -f .claude/.autoworkflow/logs/aw.log
```

**Log Categories:**
| Category | Events |
|----------|--------|
| HOOK | Hook start/complete |
| PHASE | Phase transitions |
| GATE | Gate checks (pass/block) |
| VERIFY | Verification iterations |
| MEMORY | Memory update prompts |
| COMMIT | Commit events |
| ERROR | Errors and failures |

**Debug Mode:** Set `AUTOWORKFLOW_DEBUG=1` to see logs in terminal.

---

## Memory System (Serena-inspired)

Persistent context that survives across sessions. **Claude edits files directly** + hooks prompt at key moments.

**Memory Files:** `.claude/.autoworkflow/memories/`
| File | Purpose | When to Update |
|------|---------|----------------|
| `decisions.md` | Architectural/implementation choices | After PLAN phase |
| `patterns.md` | Discovered codebase patterns | After IMPLEMENT |
| `blockers.md` | Known issues and workarounds | When hitting errors |
| `context.md` | Session continuity | Before COMMIT |

**How it works:**
1. **Session Start** → Memories summary displayed automatically
2. **Phase Transitions** → Hooks prompt to update relevant memory
3. **Claude Edits Directly** → Use Edit tool on memory files
4. **No Shell Commands** → Just read and edit the markdown files

**Memory Format:**
```markdown
## [Entry Title]
*[Date]*

[Content - decisions made, patterns found, blockers hit]

---
```

**Automated Prompts:**
| Trigger | Memory Prompt |
|---------|---------------|
| After PLAN | "Record any decisions made" |
| After IMPLEMENT | "Record any patterns discovered" |
| Before COMMIT | "Update context for next session" |
| Error encountered | "Consider recording this blocker" |

---

## Reflection Prompts (Serena-inspired)

Before each phase transition, Claude receives reflection prompts to self-assess:

| Phase | Reflection |
|-------|------------|
| PLAN | Have you read all relevant files? Understood existing patterns? |
| IMPLEMENT | Does this match the request? Considered all affected files? |
| VERIFY | Is implementation complete? Edge cases handled? |
| COMMIT | Would you be confident shipping this? |

**Manual reflection:**
```bash
.claude/hooks/phase-transition.sh reflect PLAN
```

---

## Mode Restrictions (Serena-inspired)

Task types have different allowed operations:

| Mode | Restrictions |
|------|--------------|
| `docs` | Warn on non-.md file creation |
| `fix` | Warn on new file creation, dependency changes |
| `refactor` | Warn on behavior-changing operations (migrations) |
| `query` | Warn on any modifications (read-only) |

Phase restrictions:
- `ANALYZE`/`PLAN` phases warn on file creation/dependency changes
- Must reach `IMPLEMENT` phase before making modifications

---

## Blocking Rules

- **No orphan features** - Backend must have UI
- **No TODO/FIXME** - Complete the work
- **No console.log** - No debug logs
- **No circular deps** - Clean imports
- **Conventional commits** - `type(scope): description`

---

## Slash Commands

| Command | Purpose |
|---------|---------|
| `/analyze [topic]` | Analyze codebase for a task |
| `/plan [task]` | Create implementation plan |
| `/verify` | Run TypeScript + ESLint |
| `/audit` | Run UI + cycle audits |
| `/audit project` | Full project scan → technical context |
| `/commit [msg]` | Pre-commit gate + commit |
| `/init` | Set up AutoWorkflow files |
| `/fix` | Fix verification errors |
| `/suggest` | Show suggestions for current task |
| `/build` | Build a feature end-to-end |

---

## NPM Commands

```bash
npm run verify        # TypeScript + ESLint
npm run audit:ui      # Check orphan features
npm run audit:cycles  # Check circular deps
npm run format        # Prettier
```

---

## Hook Files

| Hook | Trigger Event | Purpose |
|------|---------------|---------|
| `session-check.sh` | UserPromptSubmit | Init, blueprint check, task classify |
| `post-edit.sh` | PostToolUse (Write\|Edit) | Auto-verify with loop tracking |
| `pre-tool-router.sh` | PreToolUse (Bash) | Route to appropriate check |
| `pre-commit-check.sh` | Before git commit | All 7 gate checks, BLOCKS |
| `phase-transition.sh` | Manual call | State management |
| `audit-runner.sh` | Manual call | Run UI + cycle audits |
| `blueprint-generator.sh` | Manual call | Enhanced project discovery (8 scans) |
| `logger.sh` | Sourced by hooks | Centralized logging system |

---

## Documentation Workflow

Your project documentation is the single source of truth:

```
┌─────────────────────────────────────────────────────────────┐
│  Session Start                                              │
│       ↓                                                     │
│  USER PROVIDES: PRD / Spec / Userflow / Implementation      │
│       ↓                                                     │
│  THAT DOCUMENT = SOURCE OF TRUTH                            │
│       ↓                                                     │
│  Referenced for ALL tasks                                   │
└─────────────────────────────────────────────────────────────┘
```

**How it works:**
1. Provide your documentation (PRD, spec, userflow, implementation guide)
2. That document is used directly - no transformation or format conversion
3. All tasks reference your document as the single source of truth

**No BLUEPRINT.md generation.** Your document IS the blueprint.

---

## Project Discovery (Serena-inspired)

`/audit project` runs 8 scans for technical context:

| Scan | What It Detects |
|------|-----------------|
| Architecture | Monorepo, microservices, modular, feature-based, layered |
| Essential Commands | npm scripts, Makefile targets, tool configs |
| Tech Stack | Framework, styling, database, state, testing |
| Structure | Source directories, organization |
| Routes | App Router, Pages Router, SPA routes |
| Components | React/Vue/Svelte components |
| API | REST endpoints, GraphQL |
| Environment | .env files, required variables, configs |

**Note:** Scans provide technical context. BLUEPRINT.md content comes from your documentation.

---

## Required Reading

| File | Purpose |
|------|---------|
| `instructions/AI_RULES.md` | Your coding standards |
| User's documentation | Single source of truth (PRD/spec/userflow) |

If no documentation provided → Hook prompts user to provide it

---

## Detailed Reference

| File | Contains |
|------|----------|
| `system/triggers.md` | Event → Hook → Claude action mappings |
| `system/gates.md` | Blocking checkpoint definitions |
| `system/loops.md` | Verify/fix cycle definitions |
| `system/router.md` | Task type classification |

---

## Quick Reference

**New feature:**
```
Analyze → Plan+Suggest → [approval] → Implement → VERIFY(auto) → Audit → Commit(blocked) → Update
```

**Bug fix:**
```
Analyze → Plan → [approval] → Implement → VERIFY(auto) → Commit(blocked)
```

**Question:**
```
Analyze → Respond
```
