---
name: ao-intent-drift
description: "Detect when implementation work drifts away from the original issue intent, plan, or specification"
category: analysis
version: 1.0.0
tier: 3
invokes: [ao-state, ao-git]
invoked_by: [ao-implementation, ao-validation, ao-critical-review]
state_files:
  read: [constitution.md, focus.json, issues/*.md, issues/references/*.md, specs/*.md]
  write: [focus.json]
---

# ao-intent-drift

Detect when implementation work **drifts away** from the original issue intent, plan, or specification.

## Purpose

Agents are good at solving *a* problem, not always *the* problem. This skill catches:
- **Scope creep** — touching files not in the plan
- **Over-engineering** — complexity exceeding requirements
- **Under-delivery** — acceptance criteria not addressed
- **Architectural deviation** — new abstractions without discussion
- **Gold plating** — features added without request

## When to Use

- After implementation, before validation
- When reviewing changes that seem larger than expected
- Continuous monitoring during multi-file changes
- When confidence drops mid-iteration

## CRITICAL: No Assumptions

> **NEVER assume. NEVER guess. ALWAYS ask.**

**Before analyzing drift, confirm sources:**

| If unclear about... | ASK |
|---------------------|-----|
| Original intent | "Which issue/plan defines the expected scope?" |
| Plan approval | "Was this plan validated before implementation?" |
| Acceptance criteria | "Where are the acceptance criteria defined?" |

## Workflow Overview

```mermaid
flowchart LR
    A[1. Gather Intent] --> B[2. Collect Actuals]
    B --> C[3. Analyze Drift]
    C --> D[4. Score & Recommend]
    D --> E[5. Report]
```

## Phase 1: Gather Intent Sources

**Collect all sources that define what should be built:**

### 1.1 Issue Description

```bash
# Read the active issue from focus.json
cat .agent/ops/focus.json | grep "issues_in_iteration"
# Extract issue content
cat .agent/ops/issues/*.md | grep -A 50 "ISSUE-ID"
```

Key extraction targets:
- **Problem statement** — What problem does this solve?
- **Acceptance criteria** — What must be true when done?
- **Scope boundaries** — What's explicitly out of scope?

### 1.2 Approved Plan (if exists)

```bash
# Look for plan reference in focus.json or issue
cat .agent/ops/focus.json | grep "plan:"
# Check plan file
cat .agent/ops/plans/*.md 2>/dev/null || echo "No explicit plan file"
```

From plan, extract:
- **Files to modify** (explicit list)
- **Approach** (strategy description)
- **Non-goals** (what NOT to do)

### 1.3 Specification Reference (if exists)

```bash
# Check for linked spec
cat .agent/ops/issues/references/ISSUE-ID.md 2>/dev/null
cat .agent/ops/specs/*.md | grep -l "ISSUE-ID"
```

## Phase 2: Collect Actuals

**Gather what was actually done:**

### 2.1 Git Diff Analysis

```bash
# Get list of changed files
git diff --name-only HEAD~1..HEAD

# Get full diff for analysis
git diff HEAD~1..HEAD --stat

# For unstaged changes
git diff --name-only
```

### 2.2 Change Summary

Build a structured summary:

```
Files Added:    [list]
Files Modified: [list]
Files Deleted:  [list]
Lines Added:    N
Lines Removed:  N
```

### 2.3 Semantic Analysis

For each changed file, identify:
- **New exports** (functions, classes, types)
- **New dependencies** (imports added)
- **New patterns** (abstractions introduced)

## Phase 3: Drift Detection

**Compare intent vs actuals using drift patterns:**

### 3.1 Drift Pattern Matrix

| Pattern | Detection Rule | Severity |
|---------|----------------|----------|
| **Scope Creep** | Files touched not mentioned in plan | Medium |
| **Architectural Deviation** | New abstractions/patterns not discussed | High |
| **Over-Engineering** | Complexity ratio exceeds 2:1 vs requirements | Medium |
| **Under-Delivery** | Acceptance criteria without evidence | Critical |
| **Gold Plating** | Features without traceability to requirements | Low |
| **Dependency Drift** | New dependencies not justified | Medium |

### 3.2 Scope Creep Detection

```
FOR each file in git_diff:
    IF file NOT in plan.files_to_modify:
        IF file is test file AND plan allows new tests:
            SKIP  # Tests are usually OK
        ELSE:
            FLAG as scope_creep
            RECORD: {file, reason: "not in plan"}
```

### 3.3 Under-Delivery Detection

```
FOR each criterion in acceptance_criteria:
    evidence = SEARCH(git_diff, criterion.keywords)
    IF evidence.confidence < 0.5:
        FLAG as under_delivery
        RECORD: {criterion, missing_evidence}
```

### 3.4 Complexity Analysis

```
planned_files = len(plan.files_to_modify)
actual_files = len(git_diff.files)
complexity_ratio = actual_files / planned_files

IF complexity_ratio > 2.0:
    FLAG as over_engineering
    RECORD: {ratio, detail: "2x more files than planned"}
```

## Phase 4: Scoring & Recommendations

### 4.1 Drift Score Calculation

```
drift_score = 0

# Weighted contributions
drift_score += scope_creep_count * 10
drift_score += under_delivery_count * 25  # Most serious
drift_score += over_engineering_penalty * 15
drift_score += architectural_deviation_count * 20
drift_score += gold_plating_count * 5

# Cap at 100
drift_score = min(drift_score, 100)
```

### 4.2 Threshold Actions

| Drift Score | Status | Action |
|-------------|--------|--------|
| 0-20 | ✅ Aligned | Continue normally |
| 21-50 | ⚠️ Minor Drift | Log warning, optional human checkpoint |
| 51-75 | 🟠 Significant Drift | Auto-lower confidence, require review |
| 76-100 | 🔴 Critical Drift | HARD STOP, require human approval |

### 4.3 Recommendation Output

```markdown
## Intent Drift Analysis

**Issue**: {ISSUE-ID}
**Drift Score**: {score}/100
**Status**: {aligned|minor_drift|significant_drift|critical_drift}

### Deviations Found

| # | Type | Severity | Detail |
|---|------|----------|--------|
| 1 | Scope Creep | Medium | `utils/helpers.py` not in plan |
| 2 | Under-Delivery | Critical | AC#3 "API validation" not evidenced |

### Recommendation

{continue|checkpoint|replan|hard_stop}

### Suggested Actions

1. {action_1}
2. {action_2}
```

## Phase 5: Integration

### 5.1 When to Run

**Automatic triggers:**
- End of implementation phase (before validation)
- After significant batch of changes (5+ files)
- When confidence-sensitive issue

**Manual triggers:**
- User requests drift check
- Review reveals unexpected changes

### 5.2 Confidence Impact

```
IF drift_score > 50:
    current_confidence = issue.confidence
    new_confidence = lower_confidence(current_confidence)
    RECORD: "Confidence lowered {current} → {new} due to drift score {score}"
```

### 5.3 Constitution Configuration

```yaml
# In .agent/ops/constitution.md
intent_drift:
  enabled: true
  threshold: 50           # Score above this triggers checkpoint
  auto_lower_confidence: true
  hard_stop_threshold: 75
  exempt_patterns:
    - "*.test.*"          # Test files don't count as scope creep
    - "*.md"              # Documentation changes exempt
    - "__snapshots__/*"   # Snapshot updates exempt
```

## Templates

### Drift Report Template

```markdown
# Intent Drift Report

**Generated**: {timestamp}
**Issue**: {issue_id} — {issue_title}
**Plan**: {plan_ref|"No explicit plan"}

## Summary

| Metric | Value |
|--------|-------|
| Drift Score | {score}/100 |
| Files Planned | {N} |
| Files Changed | {M} |
| Acceptance Criteria | {passed}/{total} |

## Deviation Details

### Scope Analysis

**Planned files:**
- {file_1}
- {file_2}

**Actual files changed:**
- {file_1} ✅
- {file_2} ✅
- {file_3} ⚠️ NOT IN PLAN

### Acceptance Criteria Coverage

- [x] AC#1: {description} — Evidence: {file:line}
- [ ] AC#2: {description} — NO EVIDENCE FOUND
- [x] AC#3: {description} — Evidence: {file:line}

### Architectural Changes

{List any new abstractions, patterns, or structures introduced}

## Recommendation

**Action**: {continue|checkpoint|replan|hard_stop}

**Rationale**: {explanation}

**Next Steps**:
1. {step}
```

## Edge Cases

### No Explicit Plan

If no plan document exists:
1. Use issue description as sole intent source
2. Extract implied scope from acceptance criteria
3. Be more lenient on file count (no explicit comparison)
4. Focus on under-delivery detection

### Incremental Implementation

For multi-iteration issues:
1. Track cumulative drift across iterations
2. Reset scope comparison per iteration if plan allows
3. Maintain running drift score

### Emergency Fixes

For hotfix/critical issues:
1. Reduce drift threshold sensitivity
2. Focus only on under-delivery (did it fix the issue?)
3. Skip over-engineering checks

## Troubleshooting

### "All files flagged as scope creep"

**Cause**: Plan doesn't list expected files explicitly.
**Fix**: Ask user to clarify planned scope, or exempt all if plan was informal.

### "Under-delivery false positive"

**Cause**: Keyword matching too strict.
**Fix**: Review acceptance criteria wording; flag may indicate need for explicit test.

### "Drift score seems too high/low"

**Cause**: Weight calibration.
**Fix**: Adjust weights in constitution, or report for skill improvement.

## Integration with Other Skills

| Skill | Integration |
|-------|-------------|
| `ao-implementation` | Run drift check after major changes |
| `ao-validation` | Include drift score in validation report |
| `ao-critical-review` | Use drift findings to focus review |
| `ao-retrospective` | Record drift patterns for learning |
| `ao-planning` | Reference past drift to improve plans |
