---
name: ao-focus-scan
description: "Analyze issues to update focus.json with three sections: in_progress, next_queue (up to 10 ready issues), and recent_work (latest 5). Enforces issue-first workflow and confidence-based batch limits."
category: core
invokes: [ao-state, ao-task, ao-usage]
invoked_by: []
state_files:
  read: [issues/events.jsonl, issues/active.jsonl, focus.json, constitution.md]
  write: [focus.json]
references: [.ao/reference/confidence.md]
---

# Focus Scan

> **Confidence Reference**: This skill uses canonical confidence definitions from [.ao/reference/confidence.md](.ao/reference/confidence.md). Batch limits are HARD limits determined by confidence level.

## Purpose
Update focus.json with comprehensive work status across three keys:
1. **`in_progress`** - Issues with in_progress status
2. **`next_queue`** - Up to 10 issues ready for implementation
3. **`recent_work`** - Latest 5 completed issues

**Enforces that all work is tracked as issues and respects confidence-based batch limits.**

## Three-Section JSON Structure

The ao-focus-scan generates focus.json. Preserve all existing keys; update only:
- `in_progress` — list of issue IDs (strings) for in-progress issues
- `next_queue` — up to 10 issue IDs (strings), sorted priority→confidence
- `recent_work` — latest 5 issue IDs (strings)
- `session_info.last_updated` — today's date

> **Why IDs only?** `ao focus` fetches full issue details (title, priority, confidence, status) live from active.jsonl. Storing only IDs avoids duplicating data.

## Context Optimization

**Use `ao ls` for all issue queries.** See `ao-usage` skill for command reference.

`focus.json.next` is informational prose only. Never use it to decide whether work is available.

```
1. `ao ls --ready --sort priority --limit 20` — quick overview of actionable issues
2. Identify issues by priority and confidence
3. `ao issue show ISSUE_ID` for full details on selected issue
```

## CLI Commands

### ao Priority Scan

```
1. `ao ls --ready --sort priority` — list actionable issues
2. Identify target issue: highest priority, normal/high confidence, no blockers
3. `ao issue show ISSUE_ID --yes --format json --progress none` — load full details
4. Filter for status: todo or in_progress
5. Select first actionable issue (respecting depends_on)
```

### Focus Update (CLI — MANDATORY)

> ⛔ **NEVER update `focus.json` by reading and writing JSON directly.**
> Always use `ao focus` subcommands — these are the ONLY permitted write path.

#### `in_progress` (Currently Working On)
- Issues with status `in_progress`
- **IDs only**: `["FEAT-0012@a3f2c1", ...]` (no title/priority/confidence)

#### `next_queue` (What We Should Work On Next — up to 10)
- Issues ready for implementation (status `todo`, fully specified)
- Sorted: priority (high → medium → low) → confidence (high → normal → low)
- **IDs only**: `["FEAT-0012@a3f2c1", ...]`

#### `recent_work` (Recent Work — latest 5)
- Latest 5 closed issues
- **IDs only**: `["FEAT-0012@a3f2c1", ...]`

To update:
1. Query `ao ls` for each status/priority combination
2. Build three ID lists: in_progress, next_queue, recent_work
3. Use `ao focus sync` to rebuild all three arrays from the live issue store
4. Use `ao focus` to verify the output (resolves IDs live from active.jsonl)
## Confidence-Based Batch Limits (MANDATORY — HARD LIMITS)

| Confidence | Max Issues | Limit Type | User Confirmation | Rationale |
|------------|------------|------------|-------------------|-----------|
| LOW | 1 | **HARD** (no exceptions) | Required before start | High uncertainty requires focused human oversight |
| NORMAL | 3 | **HARD** (cannot exceed) | Required for batch >1 | Standard workflow with reasonable batching |
| HIGH | 5 | **HARD** (cannot exceed) | Required for batch >1 | Well-understood work can be batched |

**Enforcement (NON-OPTIONAL):**

1. **Read confidence** from these sources (in order of precedence):
   - Issue's `confidence:` field (if present) — preferred
   - Constitution's default confidence level
   - Default to `normal` if neither specifies

2. **LOW confidence enforcement (strictest):**
   - Select EXACTLY 1 issue — **no batching allowed**
   - Agent MUST NOT silently expand to multiple issues
   - Requires explicit user confirmation before starting work

3. **NORMAL/HIGH confidence enforcement:**
   - Cannot exceed the hard limit (3 for normal, 5 for high)
   - If batch size >1, MUST present list to user for confirmation
   - User can approve, modify selection, or switch to single-issue mode

4. **Violation handling:**
   - If any skill or agent attempts to work on more issues than allowed: STOP
   - Log violation and ask user how to proceed

## Issue-First Enforcement

Before starting any work:

1. **Check for existing issue**: Is there an issue for the requested work?
   - Yes → proceed to priority scan
   - No → prompt to create issue first

2. **If user requests work without an issue**:
   ```
   ⚠️ No issue found for this work.
   
   All work should be tracked for auditability.
   
   Create an issue first?
   [Y]es, create and start / [N]o, work without tracking
   
   Suggested: {TYPE}-{next}@{hash} — "{inferred title}"
   ```

3. **Even simple chores need issues**:
   - "Fix typo" → `CHORE` issue
   - "Update dependency" → `CHORE` issue  
   - "Add comment" → `DOCS` issue
   - "Quick refactor" → `REFAC` issue (needs permission anyway)

## Baseline Freshness Check (MANDATORY)

**Before selecting any issue, verify baseline is current:**

1. Check if `.agent/ops/baseline.md` exists
2. If it exists, check the timestamp/date in header (look for "Captured:" or date pattern)
3. Determine freshness:
   - **Fresh**: Baseline captured within last 24 hours AND no commits since capture
   - **Stale**: Baseline > 24 hours old OR commits made since capture
   - **Missing**: No baseline.md file

4. **If baseline is STALE or MISSING:**
   ```
   ⚠️ BASELINE STALE OR MISSING
   
   Baseline must be current before selecting issues.
   Current state: {MISSING | STALE (captured: {date})}
   
   Options:
   1. Run baseline capture now (RECOMMENDED)
   2. Skip baseline check (NOT RECOMMENDED — risks regressions)
   ```

5. **If baseline is fresh**: Proceed to issue selection

**Rationale:** Baseline comparison is required after implementation. Working without a fresh baseline means you cannot validate changes against known-good state.

## Autonomous Mode Validation (MANDATORY)

**Before selecting issues, validate user request against active constraints.**

### Conflict Detection

When user requests autonomous/batch work, check for conflicts:

```
function validate_autonomous_request(user_request, candidate_issues):
    
    // Check for autonomous keywords
    autonomous_keywords = ["autonomous", "without asking", "just do it", 
                          "don't ask", "work independently", "no interruptions"]
    is_autonomous = any(kw in user_request.lower() for kw in autonomous_keywords)
    
    // Check for LOW confidence issues
    low_confidence_issues = [i for i in candidate_issues if i.confidence == "low"]
    
    // CONFLICT: Autonomous + LOW
    IF is_autonomous AND low_confidence_issues:
        SOFT_BLOCK:
        ```
        ⚠️ AUTONOMOUS MODE BLOCKED — LOW Confidence Detected
        
        LOW confidence issues require human oversight at each step.
        
        LOW confidence issues in scope:
        - {list issues}
        
        Options:
        1. Respond with "OVERRIDE-LOW" to proceed with single issue only
        2. Exclude LOW confidence issues from this session
        3. Work with standard human checkpoints
        ```
        
        IF user_response == "OVERRIDE-LOW":
            LOG: "OVERRIDE-LOW used for {issue_id}"
            CONTINUE with single LOW issue only
            RESET override after issue completes
        ELSE:
            WAIT for user decision
    
    // CONFLICT: Batch + LOW
    IF len(candidate_issues) > 1 AND low_confidence_issues:
        HARD_BLOCK:
        ```
        ⛔ BATCH MODE BLOCKED — LOW Confidence Issues
        
        Cannot batch LOW confidence issues.
        
        LOW confidence = max 1 issue per iteration with:
        - Mandatory human review hard stop
        - Explicit approval before next issue
        
        Options:
        1. Work on single LOW issue: {first_low_issue}
        2. Work on only NORMAL/HIGH issues: {list}
        3. Use OVERRIDE-LOW for each LOW issue individually
        ```
        
        // Cannot proceed until user makes selection
        WAIT for user decision
```

### Override Scope

**OVERRIDE-LOW applies to SINGLE ISSUE ONLY:**

1. When user provides "OVERRIDE-LOW":
   - Log the override in issue history
   - Proceed with that ONE issue
   - After issue completes (done or blocked), override expires

2. For the next LOW confidence issue:
   - Must prompt again
   - Previous override does NOT carry forward
   - This prevents accidentally bypassing review for multiple issues

### Integration with Procedure

Add as Step 0.5 in procedure (after baseline check, before issue scan):

```
0.5) **Validate autonomous request** (MANDATORY if autonomous keywords detected):
     - Run conflict detection on user request
     - If SOFT_BLOCK: prompt for OVERRIDE-LOW
     - If HARD_BLOCK: refuse and present options
     - Log any overrides applied
```

## Procedure

1. **Verify baseline freshness** (see above — MANDATORY)
   - If baseline not fresh, resolve before proceeding

2. **Read confidence level** (MANDATORY — determines batch limits):
   - **First**: Check if the issue has a `confidence:` field → use that value
   - **Second**: If no issue confidence, read constitution's default confidence
   - **Third**: If neither exists, default to `normal`
   - **Record** the confidence source in focus.json for auditability
   - Note: LOW confidence triggers special handling (single-issue only)

3. **Scan issues in priority order** (stop when actionable issues found):
   ```bash
   # Query ready issues, sorted by priority
   ao ls --ready --sort priority --yes --format json --progress none
   ```
   - **SKIP** `priority:backlog` items — backlog items need triage first
   - Filter for: status is `todo` and all `depends_on` are satisfied

4. **Apply batch limit** based on confidence:

   *For LOW confidence:*
   ```
   🎯 LOW CONFIDENCE MODE — Single Issue Focus
   
   Selected: {ISSUE-ID} — {title}
   
   Batch size: 1 (hard limit for low confidence)
   
   This issue will receive:
   - Mandatory interview before planning
   - Extensive implementation details
   - Hard stop after implementation for human review
   - ≥90% test coverage requirement
   
   Proceed with this issue? [Y]es / [N]o, select different
   ```

   *For NORMAL confidence:*
   ```
   📋 Selected {N} issues for this iteration (max 3):
   
   1. {ISSUE-ID-1} — {title}
   2. {ISSUE-ID-2} — {title}
   
   Proceed? [Y]es / [M]odify selection / [S]ingle issue only
   ```

   *For HIGH confidence:*
   - Proceed with selection (up to 5), report only

5. **Action based on findings**:

   *If an actionable issue is found:*
   - Update `doing_now` via CLI (MANDATORY — NEVER edit focus.json directly):
     ```bash
     ao focus set-doing FEAT-0012@a3f2c1 --task "Add user authentication" --confidence normal
     ao focus set-next "Review existing auth patterns in codebase, then create implementation plan"
     ```

   *If all issues are blocked:*
   - Identify the specific blockers
   - Update focus to indicate blockers need resolution
   - Suggest resolving dependencies or creating new issues

   *If no prioritized issues exist but backlog has items:*
   - Prompt user:
     ```
     📋 No prioritized issues, but {N} items in backlog.
     
     1. Triage backlog (/ao-task triage)
     2. Create new issue (/ao-task)
     3. Run discovery (/ao-baseline, /ao-review)
     ```

   *If no issues exist at all:*
   - Update focus to indicate planning/discovery needed
   - Prompt user:
     ```
     📋 No issues anywhere. What would you like to do?
     
     1. Create new issues (/ao-task)
     2. Run discovery to find work (/ao-baseline, /ao-review)
      3. Describe what you want to work on (I'll create an issue)
      ```

6. **Update focus.json via `ao focus` CLI (MANDATORY — NEVER edit directly)**:
    - Rebuild all three queue arrays from the live issue store:
      ```bash
      ao focus sync
      ```
    - Update iteration tracking when starting a new batch:
      ```bash
      ao focus iteration --increment --issues "ID1,ID2,ID3" --confidence-mix "3 normal"
      ```
    - Verify with `ao focus` to confirm live resolution works

