# System Triggers

> Event-driven actions that control Claude's workflow behavior.
> These triggers fire automatically based on context and events.
>
> **IMPLEMENTATION:** All triggers are now implemented as shell scripts in `.claude/hooks/`

---

## Trigger Implementation Map

| Trigger | Hook Script | Event |
|---------|-------------|-------|
| `on:conversation_start` | `session-check.sh` | UserPromptSubmit |
| `on:session_resume` | `session-check.sh` | UserPromptSubmit |
| `on:turn_start` | `session-check.sh` | UserPromptSubmit |
| `on:blueprint_missing` | `session-check.sh` + `blueprint-generator.sh` | UserPromptSubmit |
| `on:init_needed` | `session-check.sh` | UserPromptSubmit |
| `on:task_received` | `session-check.sh` | UserPromptSubmit |
| `on:phase_transition` | `phase-transition.sh` | Manual call |
| `on:pre_implementation_check` | `pre-edit.sh` | PreToolUse (Write\|Edit) |
| `on:suggestions_required` | `pre-edit.sh` | PreToolUse (Write\|Edit) |
| `on:one_fix_at_a_time` | `pre-edit.sh` | PreToolUse (Write\|Edit) |
| `on:implementation_complete` | `post-edit.sh` | PostToolUse (Write\|Edit) |
| `on:verification_failed` | `post-edit.sh` | PostToolUse (Write\|Edit) |
| `on:verification_passed` | `post-edit.sh` | PostToolUse (Write\|Edit) |
| `on:commit_requested` | `pre-tool-router.sh` → `pre-commit-check.sh` | PreToolUse (Bash) |
| `on:feature_complete` | `post-bash-router.sh` → `post-commit.sh` | PostToolUse (Bash) |

---

## State Management

All workflow state is stored in `.claude/.autoworkflow/`:

```
.claude/.autoworkflow/
├── session-id           # Current session identifier
├── phase                # Current workflow phase
├── task-type            # Classified task type
├── verify-iteration     # Current verify loop count
├── verify-status        # PASSED/FAILED/BLOCKED
├── audit-iteration      # Current audit loop count
├── audit-status         # PASSED/FAILED/BLOCKED
├── gate-status          # Last gate check result
├── gate-errors          # Number of gate errors
├── plan-approved        # Plan approval status (true/false)
├── changed-files        # List of modified files
├── blueprint-checked    # Blueprint check done flag
├── session-resumed      # Session resume prompt shown flag
├── suggestions-shown    # 3-tier suggestions displayed (true/false)
├── current-turn-edits   # Number of edits in current user turn
└── selected-items       # User-selected items to implement
```

---

## Trigger Definitions

### `on:conversation_start`

**When:** Claude begins a new conversation or task
**Hook:** `.claude/hooks/session-check.sh`
**Event:** `UserPromptSubmit`

**Actions:**
1. Initialize session state (create session-id)
2. Reset iteration counters
3. Check if autoworkflow needs initialization
4. Check if `instructions/BLUEPRINT.md` exists
5. If NO → Trigger `on:blueprint_missing`
6. If YES → Load blueprint and proceed
7. Show current workflow state

```bash
# Implementation
./.claude/hooks/session-check.sh
```

---

### `on:init_needed`

**When:** autoworkflow is in node_modules but CLAUDE.md is missing
**Hook:** `.claude/hooks/session-check.sh`
**Trigger Condition:** `[ -d "node_modules/autoworkflow" ] && [ ! -f "CLAUDE.md" ]`

**Actions:**
1. Notify user that autoworkflow needs setup
2. Suggest running `npx autoworkflow init`

---

### `on:session_resume`

**When:** Existing session state detected (non-IDLE phase)
**Hook:** `.claude/hooks/session-check.sh`
**Function:** `check_session_resume()`
**Event:** `UserPromptSubmit`

**Trigger Condition:** Previous session has active state (phase != IDLE)

**Actions:**
1. Detect previous session state
2. Show resume prompt with context:
   - Current phase
   - Task type
   - Plan approval status
   - Verify iteration count
   - Changed files (if any)
3. Offer to continue or start fresh
4. Mark resume prompt as shown (only show once)

**Output:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📍 AUTOWORKFLOW: SESSION RESUME
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Previous session state detected:

  Phase:           IMPLEMENT
  Task type:       feature
  Plan approved:   true
  Verify attempts: 2/10

Pending changes:
  - src/components/Button.tsx
  - src/hooks/useAuth.ts

Workflow: ANALYZE → PLAN → CONFIRM → IMPLEMENT → ...
          ↑ Current: IMPLEMENT

Continue from IMPLEMENT phase, or start fresh?
```

---

### `on:pre_implementation_check`

**When:** Claude attempts to Write/Edit a file
**Hook:** `.claude/hooks/pre-edit.sh`
**Event:** `PreToolUse` for `Write|Edit`

**Purpose:** ENFORCE plan approval before any code changes

**Gate Check:**
1. Get current phase from state
2. Get task type from state
3. Check if task requires approval (feature/fix/refactor)
4. If in ANALYZE or PLAN phase AND approval required:
   - Check if `plan-approved` is set to "true"
   - If NOT → **BLOCK the edit** (exit code 1)
   - If YES → Allow the edit

**Output on BLOCK:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⛔ AUTOWORKFLOW: PLAN APPROVAL REQUIRED
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Current Phase: PLAN
Task Type:    feature
Plan Approved: NO

Cannot edit files before plan approval.

Required workflow:
  1. Complete ANALYZE phase (read relevant files)
  2. Present PLAN with suggestions
  3. Wait for user approval
  4. THEN implement
```

**Bypass conditions:**
- Task type is `docs`, `style`, `config`, or `query`
- Phase is already IMPLEMENT or later

---

### `on:suggestions_required`

**When:** Claude attempts to implement a feature without showing suggestions
**Hook:** `.claude/hooks/pre-edit.sh`
**Event:** `PreToolUse` for `Write|Edit`

**Purpose:** ENFORCE 3-tier suggestions for feature tasks

**Gate Check:**
1. Check if task type is `feature`
2. Check if phase is `IMPLEMENT`
3. Check if `suggestions-shown` is "true"
4. If NOT → **BLOCK the edit** (exit code 1)

**Output on BLOCK:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⛔ AUTOWORKFLOW: SUGGESTIONS REQUIRED
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Task Type: feature

For feature tasks, you MUST show 3-tier suggestions first:

  🔴 Required    - Must implement
  🟡 Recommended - Should implement
  🟢 Optional    - Nice to have

Show suggestions, let user select items, THEN implement.
```

**Required Workflow:**
1. Analyze codebase and identify issues/improvements
2. Show categorized suggestions (Required/Recommended/Optional)
3. Wait for user to select items
4. Set `suggestions-shown` to "true"
5. THEN implement ONE item at a time

---

### `on:one_fix_at_a_time`

**When:** Claude attempts multiple edits in FIX phase during single turn
**Hook:** `.claude/hooks/pre-edit.sh`
**Event:** `PreToolUse` for `Write|Edit`

**Purpose:** ENFORCE one fix per turn

**Gate Check:**
1. Check if phase is `FIX`
2. Check `current-turn-edits` count
3. If count >= 1 → **BLOCK additional edits** (exit code 1)
4. If count < 1 → Increment counter, allow edit

**Output on BLOCK:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠ AUTOWORKFLOW: ONE FIX AT A TIME
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Edits this turn: 1

Fix ONE issue at a time, then verify.

This ensures:
  1. Easier to track what changed
  2. Errors caught early
  3. User can review incrementally

Wait for verification to complete before next fix.
```

**Reset Condition:**
- Counter resets on each new UserPromptSubmit (session-check.sh)

---

### `on:blueprint_missing`

**When:** BLUEPRINT.md does not exist at session start
**Hook:** `.claude/hooks/session-check.sh` + `.claude/hooks/blueprint-generator.sh`
**Behavior:** AUTOMATIC - runs without asking permission

**IMPORTANT:** This trigger runs AUTOMATICALLY:
- Do NOT ask "Should I run the audit?"
- Do NOT wait for permission to start
- Just notify and run immediately
- Only ask permission when presenting results to SAVE

**Actions:**
1. Notify user (brief message)
2. **RUN audit immediately** (no permission needed)
3. Scan: package.json, src/, pages/, components/, api/
4. Generate BOTH AI_RULES.md updates AND BLUEPRINT.md
5. Present proposed updates to user
6. Ask approval to SAVE (not to start)

```bash
# To run the blueprint generator:
./.claude/hooks/blueprint-generator.sh
```

---

### `on:task_received`

**When:** User provides a task or request
**Hook:** `.claude/hooks/session-check.sh`
**Function:** `classify_task()`

**Classification Keywords:**

| Task Type | Keywords |
|-----------|----------|
| query | what, how, why, explain, show me, find |
| feature | add, create, implement, build, new |
| fix | fix, bug, broken, error, issue, problem |
| refactor | refactor, clean up, restructure, rename |
| style | style, css, color, layout, design |
| docs | document, readme, comment, jsdoc |
| test | test, spec, coverage, unit test |
| perf | performance, optimize, speed, slow |
| security | security, vulnerability, auth |
| config | config, setting, environment, setup |

**Actions:**
1. Parse user request
2. Classify task type
3. Save to `.claude/.autoworkflow/task-type`
4. Set phase to ANALYZE
5. Display workflow for task type

---

### `on:phase_transition`

**When:** Moving from one workflow phase to another
**Hook:** `.claude/hooks/phase-transition.sh`
**Usage:** Manual invocation

**Commands:**
```bash
# Transition between phases (checks gates)
./.claude/hooks/phase-transition.sh transition PLAN IMPLEMENT

# Record plan approval
./.claude/hooks/phase-transition.sh approve

# Record plan rejection
./.claude/hooks/phase-transition.sh reject

# Reset workflow state
./.claude/hooks/phase-transition.sh reset

# Show current state
./.claude/hooks/phase-transition.sh status
```

**Gate Checks:**
- `PLAN` → Checks analyze_gate
- `IMPLEMENT` → Checks plan_approval_gate (BLOCKING)
- `AUDIT` → Checks verify_gate
- `COMMIT` → Checks verify_gate + audit_gate

---

### `on:implementation_complete`

**When:** Claude finishes writing/modifying code
**Hook:** `.claude/hooks/post-edit.sh`
**Event:** `PostToolUse` for `Write|Edit`

**Actions:**
1. Detect project type (multi-language support)
2. Enter VERIFY phase automatically
3. Run appropriate verification commands
4. Track iteration count (max 10)
5. If PASS → Reset counter, proceed to AUDIT or COMMIT
6. If FAIL → Enter FIX phase, report errors

**Multi-Language Support:**

| Project Type | Detection | Verification Commands |
|--------------|-----------|----------------------|
| Node.js | `package.json` | `npm run verify` or `npm run typecheck && npm run lint` |
| PHP | `composer.json` | PHPStan, PHP-CS-Fixer, PHPCS |
| Python | `pyproject.toml`, `requirements.txt` | mypy, ruff, flake8 |
| Rust | `Cargo.toml` | `cargo check`, `cargo clippy` |
| Go | `go.mod` | `go build`, `go vet`, golangci-lint |
| Ruby | `Gemfile` | Rubocop |
| Java | `build.gradle`, `pom.xml` | Checkstyle, SpotBugs |

**Output:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
AUTOWORKFLOW: VERIFY LOOP (Iteration 1/10)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Detected project type: php

Running: ./vendor/bin/phpstan analyse

✅ VERIFICATION PASSED
```

---

### `on:verification_failed`

**When:** `npm run verify` returns errors
**Hook:** `.claude/hooks/post-edit.sh`
**Automatic:** Triggers when verification fails

**Actions:**
1. Parse error output
2. Increment iteration counter
3. Set phase to FIX
4. Report errors with file:line
5. Wait for fixes, then re-verify on next edit

---

### `on:verification_passed`

**When:** `npm run verify` returns success
**Hook:** `.claude/hooks/post-edit.sh`
**Automatic:** Triggers when verification passes

**Actions:**
1. Reset iteration counter
2. Check if audits required (feature/refactor)
3. If yes → Set phase to AUDIT
4. If no → Set phase to PRE_COMMIT

---

### `on:commit_requested`

**When:** User asks to commit or runs git commit
**Hook:** `.claude/hooks/pre-tool-router.sh` → `.claude/hooks/pre-commit-check.sh`
**Event:** `PreToolUse` for `Bash` (only git commit commands)

**Gate Checks (all must pass):**
1. TypeScript errors = 0
2. ESLint warnings = 0
3. No TODO/FIXME in staged files
4. No console.log in staged files
5. No orphan features (audit:ui)
6. No circular dependencies (audit:cycles)
7. Conventional commit format

**On FAIL:** Exit with code 1 → BLOCKS the commit

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
AUTOWORKFLOW: PRE-COMMIT GATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

[1/7] TypeScript: ✅ PASS
[2/7] ESLint: ✅ PASS
[3/7] TODO/FIXME: ⛔ FAIL
      └── Found in 2 file(s)

⛔ GATE BLOCKED - 1 issue(s) must be fixed
```

---

### `on:error_detected`

**When:** Any error occurs during execution
**Handling:** Inline in post-edit.sh and pre-commit-check.sh

**Actions:**
1. Identify error type
2. Route to appropriate fix strategy
3. Enter FIX phase if code error
4. Report if environmental error

---

### `on:file_changed`

**When:** Claude modifies a file
**Hook:** `.claude/hooks/post-edit.sh`
**Tracking:** Files added to `.claude/.autoworkflow/changed-files`

**Actions:**
1. Mark file as changed
2. Queue for verification
3. Auto-trigger verify loop

---

### `on:user_approval`

**When:** User approves a plan or action
**Hook:** `.claude/hooks/phase-transition.sh approve`

**Detection Keywords:**
- "yes" / "y" / "yeah" / "yep"
- "proceed" / "go ahead" / "do it"
- "approved" / "lgtm" / "looks good"
- "all" / "include all" (for suggestions)

**Actions:**
1. Record approval to `.claude/.autoworkflow/plan-approved`
2. Proceed to IMPLEMENT phase

---

### `on:user_rejection`

**When:** User rejects a plan or action
**Hook:** `.claude/hooks/phase-transition.sh reject`

**Actions:**
1. Record rejection
2. Ask for feedback
3. Return to PLAN phase

---

### `on:feature_complete`

**When:** A git commit is successfully executed (detected by post-bash-router)
**Hook:** `.claude/hooks/post-bash-router.sh` → `.claude/hooks/post-commit.sh`
**Event:** `PostToolUse` for `Bash` (git commit commands)

**Behavior:** AUTOMATIC after every git commit

**Actions:**
1. Display commit summary (hash, message, files)
2. Check if commit type is `feat` or `refactor`
3. If yes → Show UPDATE phase reminder:
   - List potential new routes
   - List potential new APIs
   - List potential new components
4. Remind to update BLUEPRINT.md if needed
5. Reset workflow state to IDLE

**Output:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ AUTOWORKFLOW: COMMIT COMPLETE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  Hash:    abc1234
  Message: feat(auth): add login page
  Files:   3 changed

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📘 AUTOWORKFLOW: UPDATE PHASE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This commit may have added new features/routes/APIs.

Check if BLUEPRINT.md needs updating:

  1. New routes/pages added?
  2. New API endpoints added?
  3. New features/components added?

Potential new routes:
  - src/pages/Login.tsx

Action: Review and update instructions/BLUEPRINT.md if needed.
```

---

## Trigger Priority

When multiple triggers could fire, use this priority:

| Priority | Trigger | Reason |
|----------|---------|--------|
| 1 | `on:error_detected` | Errors must be handled immediately |
| 2 | `on:user_approval/rejection` | User input takes precedence |
| 3 | `on:phase_transition` | Workflow control |
| 4 | `on:verification_*` | Quality gates |
| 5 | `on:file_changed` | Tracking |
| 6 | `on:task_received` | New work |

---

## Trigger State Machine

```
[IDLE] ─────on:task_received────→ [ANALYZE]
                                      │
                                      ▼
                                  [PLAN]
                                      │
                     on:user_rejection │ on:user_approval
                            ◄─────────┴─────────►
                            │                   │
                            ▼                   ▼
                        [PLAN]            [IMPLEMENT]
                                              │
                         on:implementation_complete
                                              │
                                              ▼
                                         [VERIFY]
                                              │
                    on:verification_failed    │    on:verification_passed
                            ◄─────────────────┴─────────────────►
                            │                                   │
                            ▼                                   ▼
                         [FIX]                              [AUDIT]
                            │                                   │
                            └──────────► [VERIFY] ◄─────────────┘
                                              │
                                 on:commit_requested
                                              │
                                              ▼
                                    [PRE_COMMIT_GATE]
                                              │
                           blocked            │           passed
                            ◄─────────────────┴─────────────────►
                            │                                   │
                            ▼                                   ▼
                         [FIX]                              [COMMIT]
                                                               │
                                                               ▼
                                                           [IDLE]
```

---

## Hook Configuration

All hooks are configured in `.claude/settings.json`:

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [{
          "type": "command",
          "command": "./.claude/hooks/session-check.sh"
        }]
      }
    ],
    "PreToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [{
          "type": "command",
          "command": "./.claude/hooks/pre-edit.sh"
        }]
      },
      {
        "matcher": "Bash",
        "hooks": [{
          "type": "command",
          "command": "./.claude/hooks/pre-tool-router.sh \"$TOOL_INPUT\""
        }]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [{
          "type": "command",
          "command": "./.claude/hooks/post-edit.sh"
        }]
      },
      {
        "matcher": "Bash",
        "hooks": [{
          "type": "command",
          "command": "./.claude/hooks/post-bash-router.sh \"$TOOL_INPUT\""
        }]
      }
    ]
  }
}
```

---

## Usage

Claude MUST check this file when:
1. Starting any task
2. Transitioning between phases
3. Encountering errors
4. Receiving user input
5. Completing a feature (for blueprint updates)

Triggers ensure consistent, predictable workflow behavior.
