---
name: refine
description: "Take triaged issues, gather codebase and provider context, draft acceptance criteria, propose spec outline in comments, mark handoff-ai-eng when ready"
type: intake
cadence: daily
---


# Refine

## Objetivo

Take issues labeled `needs-refinement`, gather codebase and provider context, draft
acceptance criteria, propose a spec outline as a comment, and mark `handoff-ai-eng`
when the issue is ready for local execution.

## Precondiciones

- Authenticated CLI session: `gh auth status` (GitHub) or `az account show` (Azure DevOps).
- Repository cloned locally with at least 30 days of git history (required for Step 2b codebase search).
- Issues have been processed by the triage runbook (carrying `needs-refinement` label).
- `CONSTITUTION.md` exists for boundary constraint extraction. If only `.ai-engineering/CONSTITUTION.md` exists, treat it as a legacy compatibility input.

## Procedimiento

### Step 1 -- Fetch refinement candidates

Fetch all open issues, then filter out those already processed by this runbook (i.e., already carrying `handoff-ai-eng` or `needs-clarification`).

```bash
# GitHub — fetch all open issues and filter client-side
gh issue list --state open --json number,title,body,labels,milestone,assignees --limit 100 \
  | jq '[.[] | select(
      (.labels | map(.name) | contains(["handoff-ai-eng"]) | not) and
      (.labels | map(.name) | contains(["needs-clarification"]) | not)
    )]'

# Azure DevOps
az boards query --wiql "SELECT [System.Id],[System.Title],[System.Description],[System.State],[System.Tags] FROM workitems WHERE [System.State] <> 'Closed' AND [System.Tags] NOT CONTAINS 'handoff-ai-eng' AND [System.Tags] NOT CONTAINS 'needs-clarification'" -o json
```

If no candidates are found, output a summary report in the chat (do not save locally) explaining why: total open issues, how many were skipped and by which label (handoff-ai-eng vs needs-clarification), and confirm no action was taken.

### Step 2 -- Gather context for each issue

For each candidate, collect four layers of evidence.

**2a. Read issue metadata** -- title, body, comments, linked PRs.

```bash
# GitHub
gh issue view <NUMBER> --json title,body,comments,labels,milestone,projectItems
gh issue view <NUMBER> --json timelineItems   # linked PRs, cross-references

# Azure DevOps
az boards work-item show --id <ID> --expand all -o json
az boards work-item relation list --id <ID> -o json
```

**2b. Search codebase for related files** -- use issue title and key terms.

```bash
git grep -l "<keyword>" -- "src/" "tests/"
git log --oneline --since="30 days ago" --all --grep="<keyword>" -- "src/"
```

**2c. Check spec history** -- identify overlap with completed or rejected specs.

```bash
git grep -l "<keyword>" -- ".ai-engineering/specs/_history.md"
git log --oneline --all -- ".ai-engineering/specs/" | head -20
```

**2d. Read project boundaries** -- extract constraints that apply to the issue scope.

```bash
cat CONSTITUTION.md || cat .ai-engineering/CONSTITUTION.md
```

### Step 3 -- Draft acceptance criteria

Synthesize gathered context into testable acceptance criteria per issue.

- Each criterion must be verifiable (test, command output, or observable behavior).
- Reference specific files or modules from Step 2b.
- Respect boundary constraints from Step 2d.
- Note continuity or conflict with prior specs from Step 2c.
- Maximum 8 criteria per issue. If more are needed, the issue should be split.

### Step 4 -- Propose spec outline as a comment

Post a structured comment on the issue:

```bash
gh issue comment <NUMBER> --body "$(cat <<'COMMENT'
## Proposed Spec Outline

**Summary**: <1-2 sentence problem statement from issue body and codebase context>

**Goals** (verifiable):
- <goal tied to an acceptance criterion>

**Suggested Approach**: <2-4 sentences based on codebase analysis>

**Affected Files/Areas**:
- `<path/to/file>` -- <what changes>

**Acceptance Criteria**:
- [ ] AC-1: <verifiable statement referencing specific code area>
- [ ] AC-2: <verifiable statement with measurable outcome>

**Risks**: <overlaps with spec-NNN, boundary constraint X, missing tests>

**Spec History**: <related spec reference or "No prior specs for this area">

---
_Generated by runbook:refine. Review and adjust before execution._
COMMENT
)"

# Azure DevOps: use az boards work-item update --id <ID> --discussion "<body>" -o json
```


### Step 5 -- Mark well-scoped issues as ready

An issue qualifies for handoff when ALL conditions are met:
- Has 3-8 clear, verifiable acceptance criteria.
- Affected files/areas are identified (not "TBD" or generic).
- No unresolved questions remain.
- Does not conflict with an active spec (check `.ai-engineering/specs/spec.md`).

```bash
# GitHub
gh issue edit <NUMBER> --add-label "handoff-ai-eng" --remove-label "needs-refinement"

# Azure DevOps
az boards work-item update --id <ID> --fields "System.Tags=handoff-ai-eng" -o json
```


### Step 6 -- Escalate issues needing clarification

If the issue cannot be fully refined (ambiguous scope, missing context, conflicting
requirements), post a comment with specific questions and re-label.

```bash
gh issue comment <NUMBER> --body "$(cat <<'COMMENT'
## Refinement Blocked -- Clarification Needed

1. <specific question about scope, behavior, or priority>
2. <specific question about affected area or constraint>

**Context gathered**: Related files: `<paths>`. Related specs: <refs>. Boundary constraints: <constraints>.

---
_Generated by runbook:refine. Respond to unblock refinement._
COMMENT
)"

gh issue edit <NUMBER> --add-label "needs-clarification" --remove-label "needs-refinement"

# Azure DevOps: use --discussion for comment, --fields "System.Tags=needs-clarification"
```

## Output

No local files. Always output a summary report in the chat at the end of the run, including:
- Total open issues found
- Issues skipped by label (handoff-ai-eng count, needs-clarification count)
- Issues processed: commented + labeled in this run
- Which issues were marked handoff-ai-eng vs escalated needs-clarification
- If no candidates: brief explanation and label breakdown

## Guardrails

- Never writes to `spec.md` or `plan.md` locally. Spec outlines are proposed as issue comments only.
- Never modifies source code, configuration files, or framework artifacts.
- Never creates pull requests or branches.
- Never closes or resolves issues. Only adds labels and comments.
- Never removes protected labels (`p1-critical`, `pinned`, `security`).
- Never mutates issues in `closed` or `resolved` state.
- Enforces a maximum of 30 mutations per run. Remaining candidates are skipped.
- Mutations are enabled by default. All qualifying issues are labeled and commented.
- Does not generate reports. Does not save output locally.
