<metadata>
purpose: Define AI Developer Workflows structure and implementation
type: workflow-framework
domain: agentic-development
concepts: [adw, workflow-composition, reusability]
prerequisites: [agent-architecture]
last-updated: 2025-09-30
</metadata>

<overview>
AI Developer Workflows (ADWs) are the fundamental building blocks of agentic engineering. An ADW combines agentic prompts with deterministic code to create repeatable, reliable automation patterns. This document defines ADW structure, composition rules, and library-building practices.
</overview>

# ADW FUNDAMENTALS

## WHAT IS AN AI DEVELOPER WORKFLOW?

**Definition**: An AI Developer Workflow (ADW) is a structured, reusable pattern that combines:
1. **Agentic Prompts**: Natural language instructions that guide AI behavior
2. **Deterministic Code**: Validation, error handling, and control flow logic
3. **Checkpoints**: Verification points that ensure quality and correctness
4. **Metadata**: Context that enables discovery and composition

**Formula**:
```
ADW = Agentic Prompts + Deterministic Code + Checkpoints + Metadata

Where:
- Agentic Prompts define WHAT to do
- Deterministic Code defines HOW to validate and control
- Checkpoints define WHEN to verify
- Metadata defines WHY and WHERE to use this workflow
```

## WHY ADWs EXIST

**Problem**: Raw agent interactions are non-repeatable, hard to debug, and don't scale.

**Without ADWs**:
```
Developer: "Fix the authentication bug"
Agent: [Does something different each time]
Result: Non-deterministic, hard to improve, can't scale
```

**With ADWs**:
```
Developer: "Run bug-fix workflow on authentication issue"
Agent: [Follows defined workflow with checkpoints]
Result: Repeatable, measurable, improvable, scalable
```

## ADW ANATOMY

### Core Structure
```xml
<adw>
  <metadata>
    <name>workflow-name</name>
    <version>1.0.0</version>
    <category>bug-fix|feature|refactor|test|docs</category>
    <complexity>low|medium|high</complexity>
    <estimated-duration>5-30 minutes</estimated-duration>
    <requires-human>approval|never|on-failure</requires-human>
    <agents-required>[bugsy, gitty]</agents-required>
  </metadata>

  <inputs>
    <input name="description" type="string" required="true">
      <validation>Must be non-empty and describe the issue</validation>
    </input>
    <input name="affected-files" type="array" required="false">
      <validation>Files must exist in repository</validation>
    </input>
  </inputs>

  <phases>
    <phase name="discovery" agent="assigned" checkpoint="automatic">
      <agentic-prompt>
        Your task is to identify the root cause of: {{description}}

        Steps:
        1. Read the relevant files
        2. Search for related patterns
        3. Identify the specific issue
        4. Propose a solution approach

        Output format:
        - Root cause: [description]
        - Affected components: [list]
        - Solution approach: [description]
      </agentic-prompt>

      <deterministic-validation>
        - Verify all mentioned files exist
        - Check that root cause is specific, not vague
        - Ensure solution approach addresses root cause
        - Validate no breaking changes proposed
      </deterministic-validation>

      <on-failure action="escalate">
        Request human clarification if root cause unclear
      </on-failure>
    </phase>

    <phase name="implementation" agent="assigned" checkpoint="automatic">
      <agentic-prompt>
        Implement the solution: {{solution-approach}}

        Requirements:
        1. Modify only necessary files
        2. Add tests for the fix
        3. Update relevant documentation
        4. Follow existing code style

        Output: Changed files and test results
      </agentic-prompt>

      <deterministic-validation>
        - Run linter on changed files
        - Execute test suite
        - Verify coverage not decreased
        - Check for new security issues
      </deterministic-validation>

      <on-failure action="self-heal">
        Attempt to fix validation failures automatically
        Escalate if self-heal fails after 3 attempts
      </on-failure>
    </phase>

    <phase name="verification" agent="assigned" checkpoint="manual">
      <agentic-prompt>
        Generate summary of changes for human review:

        1. What was the bug?
        2. What was the root cause?
        3. What did you change?
        4. What tests did you add?
        5. Any potential side effects?
      </agentic-prompt>

      <deterministic-validation>
        - All tests passing
        - No lint errors
        - Coverage >= baseline
        - Security scan clean
      </deterministic-validation>

      <on-approval action="complete">
        Mark workflow as successful
      </on-approval>
    </phase>
  </phases>

  <outputs>
    <output name="changed-files" type="array" />
    <output name="test-results" type="object" />
    <output name="summary" type="string" />
  </outputs>

  <metrics>
    <metric name="execution-time" unit="seconds" />
    <metric name="files-changed" unit="count" />
    <metric name="tests-added" unit="count" />
    <metric name="self-heal-attempts" unit="count" />
  </metrics>
</adw>
```

## THE AGENTIC + DETERMINISTIC BALANCE

**Key Insight**: ADWs are neither purely agentic nor purely deterministic. They combine both.

### When to Use Agentic Prompts
```
USE AGENTIC FOR:
✓ Understanding natural language requirements
✓ Analyzing code patterns
✓ Generating creative solutions
✓ Writing code that matches context
✓ Explaining changes in natural language

EXAMPLES:
- "Analyze this error and identify the root cause"
- "Generate test cases that cover edge cases"
- "Refactor this function to improve readability"
- "Write documentation for this API"
```

### When to Use Deterministic Code
```
USE DETERMINISTIC FOR:
✓ Validation (schema, syntax, security)
✓ Test execution
✓ Metric collection
✓ Error handling
✓ Control flow decisions
✓ Resource management

EXAMPLES:
- Run linter and parse output
- Execute test suite and check exit code
- Validate file exists before reading
- Measure code coverage percentage
- Enforce timeout on operations
```

### The Balance Pattern
```
PHASE STRUCTURE:
1. Agentic: Understand and generate solution
2. Deterministic: Validate solution correctness
3. Agentic: Fix issues if deterministic validation fails
4. Deterministic: Re-validate
5. Decision: Continue or escalate

EXAMPLE:
[Agentic] Generate code to fix bug
    ↓
[Deterministic] Run tests - FAIL
    ↓
[Agentic] Analyze test failure and fix code
    ↓
[Deterministic] Run tests - PASS
    ↓
[Decision] Proceed to next phase
```

## ADW COMPOSITION PATTERNS

### Pattern 1: Sequential Composition
**Use Case**: Workflow A must complete before B starts.

```xml
<composed-adw name="feature-with-docs">
  <workflow id="feature" type="feature-implementation">
    <phase>requirements</phase>
    <phase>implementation</phase>
    <phase>testing</phase>
  </workflow>

  <workflow id="docs" type="documentation" depends-on="feature">
    <input>feature.outputs.changed-files</input>
    <phase>generate-docs</phase>
    <phase>review</phase>
  </workflow>

  <success-condition>
    All workflows complete successfully
  </success-condition>
</composed-adw>
```

### Pattern 2: Parallel Composition
**Use Case**: Multiple independent workflows can run simultaneously.

```xml
<composed-adw name="comprehensive-fix">
  <parallel>
    <workflow id="backend-fix" type="bug-fix">
      <target>server/auth.js</target>
    </workflow>

    <workflow id="frontend-fix" type="bug-fix">
      <target>client/login.tsx</target>
    </workflow>

    <workflow id="test-update" type="test-generation">
      <target>tests/auth.test.js</target>
    </workflow>
  </parallel>

  <sync-point name="integration-test">
    <wait-for>All parallel workflows complete</wait-for>
    <action>Run integration tests</action>
  </sync-point>
</composed-adw>
```

### Pattern 3: Conditional Composition
**Use Case**: Execute different workflows based on runtime conditions.

```xml
<composed-adw name="adaptive-fix">
  <decision-point>
    <condition>bug.severity == "critical"</condition>
    <if-true>
      <workflow type="hotfix-immediate" />
    </if-true>
    <if-false>
      <workflow type="bug-fix-standard" />
    </if-false>
  </decision-point>
</composed-adw>
```

### Pattern 4: Loop Composition
**Use Case**: Repeat workflow until condition met.

```xml
<composed-adw name="coverage-improvement">
  <loop max-iterations="5">
    <workflow type="test-generation" />

    <deterministic-check>
      coverage = measure_coverage()
      return coverage >= target_coverage
    </deterministic-check>

    <continue-if>coverage < target_coverage</continue-if>
    <escalate-if>iterations >= max_iterations</escalate-if>
  </loop>
</composed-adw>
```

## BUILDING ADW LIBRARIES

### Library Structure
```
adw-library/
├── metadata.json
├── categories/
│   ├── bug-fix/
│   │   ├── simple-bug-fix.yaml
│   │   ├── integration-bug-fix.yaml
│   │   └── security-bug-fix.yaml
│   ├── feature/
│   │   ├── api-endpoint.yaml
│   │   ├── ui-component.yaml
│   │   └── database-migration.yaml
│   ├── refactor/
│   │   ├── extract-function.yaml
│   │   ├── rename-variable.yaml
│   │   └── optimize-performance.yaml
│   ├── test/
│   │   ├── unit-test-gen.yaml
│   │   ├── integration-test-gen.yaml
│   │   └── e2e-test-gen.yaml
│   └── docs/
│       ├── api-docs.yaml
│       ├── readme-update.yaml
│       └── inline-comments.yaml
├── compositions/
│   ├── full-feature-workflow.yaml
│   ├── comprehensive-refactor.yaml
│   └── release-preparation.yaml
└── shared/
    ├── validation-rules.yaml
    ├── checkpoint-templates.yaml
    └── error-handlers.yaml
```

### Discovery Mechanism
```xml
<metadata name="adw-library-index">
  <workflows>
    <workflow id="simple-bug-fix">
      <category>bug-fix</category>
      <tags>[quick, low-risk, automated]</tags>
      <complexity>low</complexity>
      <success-rate>0.92</success-rate>
      <avg-duration>8 minutes</avg-duration>
      <use-when>
        - Clear bug description
        - Single file affected
        - No breaking changes
      </use-when>
    </workflow>

    <workflow id="feature-with-tests">
      <category>feature</category>
      <tags>[medium-risk, requires-tests]</tags>
      <complexity>medium</complexity>
      <success-rate>0.78</success-rate>
      <avg-duration>25 minutes</avg-duration>
      <use-when>
        - New functionality required
        - API changes acceptable
        - Test coverage required
      </use-when>
    </workflow>
  </workflows>

  <search-criteria>
    <by-category>Filter by workflow category</by-category>
    <by-complexity>Match to task complexity</by-complexity>
    <by-success-rate>Prefer proven workflows</by-success-rate>
    <by-tags>Semantic search by characteristics</by-tags>
  </search-criteria>
</metadata>
```

### Versioning Strategy
```
WORKFLOW VERSION FORMAT: major.minor.patch

MAJOR: Breaking changes to inputs/outputs
- Changed input schema
- Changed output format
- Removed phases
- Changed agent requirements

MINOR: Backward-compatible improvements
- Added optional inputs
- Enhanced validation
- Improved error messages
- Added new phases (optional)

PATCH: Bug fixes and optimizations
- Fixed validation logic
- Improved prompts
- Performance optimizations
- Documentation updates
```

## ADW BEST PRACTICES

### 1. Single Responsibility
**Each ADW should do ONE thing well.**

❌ Bad: "fix-bugs-and-add-features-and-refactor.yaml"
✓ Good: "simple-bug-fix.yaml" + "add-feature.yaml" + "refactor-component.yaml"

### 2. Clear Inputs/Outputs
**Define explicit schemas.**

```yaml
inputs:
  description:
    type: string
    required: true
    validation: "Must be 10-500 characters"
    example: "Login button doesn't submit when Enter pressed"

  priority:
    type: enum
    values: [low, medium, high, critical]
    default: medium

outputs:
  changed-files:
    type: array<string>
    description: "List of file paths modified"

  test-coverage:
    type: float
    description: "Code coverage percentage after changes"
```

### 3. Comprehensive Validation
**Never trust agentic output without verification.**

```yaml
validation:
  syntax:
    - Run linter on all changed files
    - Parse for syntax errors

  semantic:
    - Check imports resolve
    - Verify function signatures match usage
    - Validate types (if TypeScript)

  behavioral:
    - Run unit tests
    - Run integration tests
    - Check no regressions

  security:
    - Scan for vulnerabilities
    - Check for exposed secrets
    - Validate input sanitization
```

### 4. Graceful Degradation
**Handle failures elegantly.**

```yaml
failure-handling:
  self-heal:
    max-attempts: 3
    strategies:
      - Retry with corrected prompt
      - Use alternative approach
      - Simplify solution

  escalation:
    trigger: "After 3 failed self-heal attempts"
    action: "Request human intervention"
    provide:
      - Failure history
      - Attempted solutions
      - Current state
      - Suggested next steps
```

### 5. Comprehensive Metrics
**Measure everything that matters.**

```yaml
metrics:
  performance:
    - execution-time
    - agent-tokens-used
    - files-read
    - files-written

  quality:
    - tests-passing
    - coverage-delta
    - lint-errors
    - security-issues

  reliability:
    - success-rate
    - self-heal-success-rate
    - escalation-rate
    - false-positive-rate
```

## ADW ANTI-PATTERNS

### Anti-Pattern 1: Vague Prompts
❌ "Fix the code to make it better"
✓ "Refactor this function to reduce complexity. Target: cyclomatic complexity < 10, preserve existing behavior, add unit tests"

### Anti-Pattern 2: Missing Validation
❌ Accept agent output without verification
✓ Run deterministic checks on all outputs before proceeding

### Anti-Pattern 3: No Rollback
❌ Leave system in broken state on failure
✓ Automatic rollback with saved checkpoints

### Anti-Pattern 4: Monolithic Workflows
❌ Single 50-step workflow that does everything
✓ Composable 3-5 step workflows that chain together

### Anti-Pattern 5: Silent Failures
❌ Workflow fails without clear explanation
✓ Detailed error messages with context and next steps

## WORKFLOW EXAMPLE: Complete Bug Fix ADW

```yaml
name: simple-bug-fix
version: 1.2.0
category: bug-fix
complexity: low
estimated-duration: 5-15 minutes

inputs:
  description:
    type: string
    required: true
    validation: "10-500 characters describing the bug"

  affected-files:
    type: array<string>
    required: false
    validation: "Files must exist in repository"

phases:
  - name: discovery
    agent: bugsy
    checkpoint: automatic

    agentic-prompt: |
      Analyze the bug: {{description}}

      1. Read affected files (or search if not provided)
      2. Identify the root cause
      3. Verify the bug can be reproduced
      4. Propose minimal fix

      Output JSON:
      {
        "root_cause": "specific description",
        "affected_files": ["file1.js", "file2.js"],
        "solution_approach": "description",
        "estimated_risk": "low|medium|high"
      }

    validation:
      - Parse JSON output
      - Verify all files exist
      - Check risk level is specified
      - Ensure solution addresses root cause

    on-failure:
      action: escalate
      message: "Cannot identify root cause. Need human analysis."

  - name: implementation
    agent: bugsy
    checkpoint: automatic

    agentic-prompt: |
      Implement this fix: {{solution_approach}}

      Requirements:
      - Change only necessary code
      - Add test case for this bug
      - Maintain existing code style
      - Add inline comment explaining fix

      Output: List of changed files

    validation:
      - Run linter on changed files
      - Execute test suite
      - Verify new test exists and passes
      - Check coverage not decreased

    on-failure:
      action: self-heal
      max-attempts: 3
      strategy: |
        1. Analyze validation failure
        2. Correct the issue
        3. Re-run validation

    escalate-if:
      - self-heal attempts >= 3
      - breaking change detected
      - security issue introduced

  - name: verification
    agent: validation
    checkpoint: semi-automatic

    agentic-prompt: |
      Verify the bug fix is complete:

      1. Confirm bug no longer reproduces
      2. Check no regressions introduced
      3. Verify test coverage adequate
      4. Generate summary for human review

      Output summary with:
      - What was fixed
      - How it was fixed
      - Test coverage added
      - Any potential side effects

    validation:
      - All tests passing
      - Coverage >= baseline
      - No new security issues
      - No new lint errors

    on-success:
      action: request-approval
      provide:
        - Summary
        - Changed files diff
        - Test results

    on-approval:
      action: complete
      next-steps:
        - Mark task as coding_done
        - Notify gitty agent for commit

outputs:
  changed-files:
    type: array<string>

  test-coverage:
    type: object
    schema:
      before: float
      after: float
      delta: float

  summary:
    type: string

metrics:
  - execution-time
  - files-changed
  - tests-added
  - self-heal-attempts
  - escalation-occurred

rollback:
  enabled: true
  trigger: "Validation failure or human rejection"
  action: "Revert all file changes, restore from checkpoint"
```

## CONCLUSION

**ADWs are the core abstraction that makes agentic engineering scalable and reliable.** They transform ad-hoc agent interactions into structured, repeatable, measurable workflows.

**Key Takeaways**:
1. ADWs = Agentic Prompts + Deterministic Code
2. Balance creativity with validation
3. Compose simple workflows into complex ones
4. Build libraries of proven patterns
5. Measure and improve continuously

<next-steps>
<step>Study common-adws.md for proven workflow examples</step>
<step>Implement lesson-07-zte.md for full automation</step>
<step>Review 08-KPI-METRICS/ to measure ADW effectiveness</step>
</next-steps>