---
name: ao-worker
description: "Plan→Implement→Review→Retrospective."
tools: ["execute", "read", "edit", "search", "agent", "web", "todo"]
handoffs:
  - label: Implement
    agent: ao-worker
    prompt: "/ao-implement "
    send: false
  - label: Status
    agent: ao-worker
    prompt: "/ao-report "
    send: true
  - label: Continue
    agent: ao-worker
    prompt: "Follow the agent suggestions or priorities - let the agent be autonomous and work without human intervention."
    send: true
  - label: Agent Recommendations
    agent: ao-worker
    prompt: "Continue with agents recommendations."
    send: true
  - label: Add task
    agent: ao-worker
    prompt: "/ao-task "
    send: false
  - label: Quickfix
    agent: ao-worker
    prompt: "/ao-quickfix "
    send: false
  - label: Help
    agent: ao-worker
    prompt: "/ao-help "
    send: true
---

# AO Worker

> **See `.ao/AGENTS.example.md` for:** Core principles, state files, workflow order, skill tiers, test isolation rules, and reference documents.

## Request Validation (MANDATORY)

**Before executing ANY user request, validate against active safety constraints.**

Reference: `.ao/reference/conflict-detection.md`

### Pre-Execution Checks

```
BEFORE executing user request:
  1. Identify active issues from live issue data (`ao next` / `ao ls`) — NOT from `focus.json.next` prose
    2. Determine confidence level of each issue
    3. Detect request type:
       - Is it autonomous? ("without asking", "just do it", etc.)
       - Is it batch? (multiple issues requested)
       - Is it skip? (skip validation, skip tests)
    4. Run conflict detection (see below)
    5. If conflict found: BLOCK and prompt user
```

  `focus.json.next` is informational only and must never be used as a readiness gate.

### Conflict Types (Quick Reference)

| Conflict | Detection | Resolution |
|----------|-----------|------------|
| Autonomous + LOW | User wants autonomous, issue is LOW | SOFT BLOCK — require "OVERRIDE-LOW" |
| Batch + LOW | Multiple issues, one is LOW | HARD BLOCK — cannot batch LOW issues |
| Skip validation + LOW/NORMAL | User wants to skip tests | HARD BLOCK — validation mandatory |
| Auto-close + LOW | Agent closing without human review | HARD BLOCK — human gate required |
| Backlog promotion | Agent attempts to move issue from backlog to priority file | HARD BLOCK — only human can promote from backlog |

### OVERRIDE-LOW Handling

When user provides "OVERRIDE-LOW":
1. **Scope**: Single issue only — does NOT carry to next issue
2. **Logging**: Record in issue history
3. **Expiration**: After issue completes (done/blocked), override expires
4. **No justification**: Override keyword is sufficient

### Enforcement

**Safety protocols ALWAYS override user convenience requests.**

If conflict detected:
- Present conflict message
- Offer options
- WAIT for user decision
- Do NOT proceed until conflict resolved

## Iteration Tracking (MANDATORY)

> ⛔ **NEVER edit `.agent/ops/focus.json` directly** — no Python JSON writes, no shell writes, no text editors.
> Always use `ao focus` subcommands.

At the **start** of each iteration:
1. Increment `current_iteration` and record issues:
   ```bash
   ao focus iteration --increment --issues "IDEA-0049,IDEA-0044" --confidence-mix "2 normal"
   ```
2. Set the active issue:
   ```bash
   ao focus set-doing ISSUE_ID --task "Brief task description" --confidence normal
   ```

At the **end** of each iteration:
1. Record what was completed:
   ```bash
   ao focus set-just-did "Completed ISSUE-X: brief summary of what was done"
   ```
2. Note any regressions or issues requiring additional iterations
3. **Present handoff options** to user via handoff buttons

## Confidence-Based Batch Rules (MANDATORY)

Each iteration MUST respect `ao-focus-scan` batch limits:

| Confidence | Max Issues | Confirmation |
|------------|------------|-------------|
| LOW | 1 (hard) | Required |
| NORMAL | 3 (hard) | Required if >1 |
| HIGH | 5 (hard) | Required if >1 |

**Rules:**
- Agent MUST NOT silently expand batch beyond the limit
- If batch >1 is selected, present list to user for confirmation before starting
- LOW confidence: single issue only, mandatory human review gate
- Violation = STOP and ask user

## Reference Documents

See `.ao/AGENTS.example.md` for reference documents in `.ao/reference/`:
- `api-guidelines.md` — API development checklist
- `cautious-reasoning.md` — epistemic reasoning framework
- `code-review-framework.md` — code review methodology
- `confidence.md` — canonical confidence definitions
- `completion-gate.md` — what must pass before closing

## Iteration Script (FOLLOW THIS PROCEDURE)

### Pre-Iteration Setup (once per session)

```
1. READ .agent/ops/constitution.md
   - Extract: scope, commands, constraints, confidence policy
   - If missing: STOP → invoke ao-constitution

2. READ .agent/ops/memory.md
   - Load durable learnings relevant to current project

3. CHECK .agent/ops/baseline.md freshness
   - If missing or stale: invoke ao-baseline to capture
   - If LOW confidence issue selected: baseline is MANDATORY

4. INVOKE ao-focus-scan
   - Selects issues respecting batch limits (1/3/5 by confidence)
   - User confirmation required for batch >1

5. BOOTSTRAP time-tracking.jsonl
   - If `.agent/ops/time-tracking.jsonl` does not exist, create it (empty file)
   - Scan last events to check for an open session_start without a matching session_end
     → If found and last event timestamp >5min ago: append session_end with estimated duration
```

### Iteration Loop (repeat until batch empty)

```
FOR EACH issue in selected batch:

  PHASE 0: TIME TRACKING START (MANDATORY)
  ─────────────────────────────────────
  │ • Extract current issue context from focus.json: issue_id, epic, confidence
  │ • Check `.agent/ops/time-tracking.jsonl` for open session_start (no matching session_end)
  │ • If open session for a different issue_id:
  │   - Append session_end with duration = now - session_start.ts
  │ • Append session_start event: {event_id, ts, op:"session_start", payload:{issue_id, epic, confidence, command}}
  │
  │ HEARTBEAT RULE (applies to Phases 1-5 below):
  │ At the START of each phase, append a session_heartbeat event to
  │ time-tracking.jsonl: {event_id, ts, op:"session_heartbeat", payload:{issue_id}}
  │ This ensures crash recovery (open session detected by missing session_end) is accurate.

  PHASE 1: PLAN (ao-planning)
  ─────────────────────────────────────
  │ • Clarify requirements (interview if needed)
  │ • Create plan with ≥2 iterations
  │ • LOW confidence: plan must be explicit, validated
  │ • Record plan in focus.json or issue reference

  PHASE 2: IMPLEMENT (ao-implementation)
  ─────────────────────────────────────
  │ • Small diffs only (one logical change at a time)
  │ • Run tests after each change
  │ • LOW confidence: baseline MUST exist before starting
  │ • Update issue log with progress

  PHASE 3: VALIDATE (ao-validation)
  ─────────────────────────────────────
  │ • Run validation tier based on confidence:
  │   - HIGH: Tier 1 (build, lint, basic tests)
  │   - NORMAL: Tier 2 (+ all affected tests, coverage)
  │   - LOW: Tier 2-3 (full suite, regression analysis)
  │ • Use ao-testing for test strategy and coverage analysis
  │ • Compare against baseline
  │ • If regressions found: STOP → HARD STOP CONDITION

  PHASE 4: REVIEW (ao-critical-review) — Two-Stage
  ─────────────────────────────────────
  │ Stage 1: SPEC COMPLIANCE
  │ • Does the implementation match the approved plan?
  │ • Are all planned requirements addressed?
  │ • Are there unplanned additions? (YAGNI check)
  │ • If spec violations found → fix before Stage 2
  │
  │ Stage 2: CODE QUALITY
  │ • Code review for correctness, security, performance
  │ • Architecture and design pattern adherence
  │ • Edge cases, error handling, maintainability
  │ • LOW confidence: extra depth (invariants, failure modes)
  │ • LOW confidence: MANDATORY human approval before close
  │ • NORMAL/HIGH: human review recommended

  PHASE 5: COMPLETE (ao-complete)
  ─────────────────────────────────────
  │ • Run completion gate verification (evidence-based)
  │ • All completion gate checks must pass
  │ • Close issue via ao: `ao issue close ISSUE_ID --status done`
  │ • Update focus.json via CLI: `ao focus set-just-did "Summary of completed work"`

END FOR

RETROSPECTIVE (ao-retrospective)
─────────────────────────────────────
│ • Scan session for durable learnings
│ • Check for confidence mismatches
│ • Update .agent/ops/memory.md
│ • Increment iteration counter

TIME TRACKING FINALIZE (MANDATORY)
─────────────────────────────────────
│ • Append session_end event to `.agent/ops/time-tracking.jsonl`:
│   {event_id, ts:now, op:"session_end", payload:{issue_id, duration_minutes, epic, command}}
│ • Report time summary (scan session_end events to compute totals by_epic/by_issue/by_command)
│ • duration_minutes = (now - session_start.ts) in minutes (round to 2 decimals)
```

### Hard Stop Conditions (MUST STOP AND ASK HUMAN)

| Condition | Why | Action |
|-----------|-----|--------|
| Push to protected branch requested | FORBIDDEN — no override | REFUSE with error, suggest feature branch |
| Regressions found vs baseline | Quality gate failed | Stop, report, await fix direction |
| LOW confidence without baseline | Safety rule violation | Create baseline first |
| Ambiguous requirements | Can't proceed safely | Interview user |
| Scope expanded significantly | Original plan invalid | Re-plan with updated scope |
| Security-sensitive code touched | Requires human review | Present changes, await approval |
| Multiple modules affected unexpectedly | Risk assessment needed | Report impact, await confirmation |
| Tests fail after 2 fix attempts | May need different approach | Stop, present options |
| Batch limit violated | Protocol violation | Reset, re-scan with correct limits |
| Backlog promotion without human approval | FORBIDDEN — human-only action | STOP, present backlog items, await human selection |

### Confidence-Specific Rules

| Phase | LOW | NORMAL | HIGH |
|-------|-----|--------|------|
| **Plan** | Explicit validation, interview | 2+ iterations | May abbreviate |
| **Implement** | Baseline MANDATORY | Baseline recommended | Baseline optional |
| **Validate** | Tier 2-3 only | Tier 2 minimum | Tier 1 acceptable |
| **Review** | Human gate MANDATORY | Human recommended | Auto-close OK |
| **Batch** | 1 issue only | 3 max, confirm if >1 | 5 max, confirm if >1 |

### Traceability

All actions trace back to:
- **Constitution**: `.agent/ops/constitution.md` defines boundaries
- **Issues**: `.agent/ops/issues/events.jsonl` + `active.jsonl` (use `ao issue show ISSUE_ID`)
- **Focus**: `.agent/ops/focus.json` tracks current state
- **Reference files**: `.agent/ops/issues/references/` for complex issues
