# UluOps Pipeline Definition Language (PDL) Specification

**Version:** 1.6.0
**Status:** Draft
**Created:** 2026-01-14
**Updated:** 2026-10-26

---

## Table of Contents

- [Overview](#overview)
- [Design Principles](#design-principles)
- [Relationship to Other Definition Languages](#relationship-to-other-definition-languages)
- [Schema Structure](#schema-structure)
  - [CI/CD Pipeline](#cicd-pipeline)
  - [Multi-Workflow Orchestration](#multi-workflow-orchestration)
  - [Hybrid Pipeline (Workflows + Commands)](#hybrid-pipeline-workflows--commands)
- [Detailed Field Reference](#detailed-field-reference)
  - [Interface Block](#interface-block)
  - [Triggers Block](#triggers-block)
  - [Environment Block](#environment-block)
  - [Stages Block](#stages-block)
  - [Convergence Block](#convergence-block)
  - [Approvals Block](#approvals-block)
  - [Rollback Block](#rollback-block)
  - [Notifications Block](#notifications-block)
  - [Artifacts Block](#artifacts-block)
  - [State Block](#state-block)
  - [Postflight Block](#postflight-block)
  - [Scoring Block](#scoring-block)
- [Stage Dependency Graph](#stage-dependency-graph)
- [Execution Semantics (normative)](#execution-semantics-normative)
- [Convergence Loops](#convergence-loops)
- [Trigger Event Types](#trigger-event-types)
- [Approval Workflows](#approval-workflows)
- [Rollback Strategies](#rollback-strategies)
- [Data Flow Between Stages](#data-flow-between-stages)
- [Composition Rules](#composition-rules)
- [Runtime Behavior](#runtime-behavior)
- [Examples](#examples)
- [JSON Schema Reference](#json-schema-reference)
- [Revision History](#revision-history)
- [Appendix: Type Definitions](#appendix-type-definitions)

---

## Overview

The **Pipeline Definition Language (PDL)** is a YAML-based specification for defining multi-workflow orchestrations in the UluOps validation framework. Pipelines compose workflows, commands and agents into **stages** with explicit dependencies, gates, triggers, approvals, rollback strategies, and external notifications.

### Key Characteristics

| Aspect | Description |
|--------|-------------|
| **Format** | YAML with JSON Schema validation |
| **File Extension** | `.pipeline.yaml` |
| **Schema URL** | `https://uluops.ai/schemas/pdl/v1.6.0/pipeline.json` |
| **Scope** | Multi-workflow, command and agent orchestration with CI/CD integration |

### What Pipelines Do

Pipelines serve as the **top-level orchestration layer**:

1. **Organize workflows, commands and agents into stages** with explicit dependencies and gates
2. **Trigger execution** based on events (git push, PR, schedule, webhook, manual)
3. **Enforce approval gates** requiring human authorization before critical stages
4. **Manage environment** (variables, secrets) scoped to pipeline or stage
5. **Handle failures** with automatic rollback strategies
6. **Notify external systems** (Slack, email, GitHub status)
7. **Preserve artifacts** with configurable retention policies
8. **Maintain state** across pipeline runs

### What Pipelines Do NOT Do

Pipelines delegate to lower layers:

- **No validation/execution logic** — that belongs in agents (ADL)
- **No single-agent invocation context** — that belongs in commands (CDL)
- **No multi-command phase orchestration** — that belongs in workflows (WDL)
- **No scoring rubrics or criteria** — that belongs in agents (ADL); `pipeline.scoring` only combines agent scores into a headline score

### Pipeline vs Workflow

| Aspect | Workflow (WDL) | Pipeline (PDL) |
|--------|----------------|----------------|
| **Contains** | Commands in phases | Workflows, commands and agents in stages |
| **Triggers** | None (invoked by caller) | Git events, webhooks, schedules, manual |
| **Approvals** | None | Human gates before stages |
| **Rollback** | None | Automatic failure recovery |
| **Notifications** | None | External system integration |
| **Artifacts** | Output files | Preserved files with retention |
| **State** | Per-run only | Persisted across runs |
| **Environment** | Inherited from caller | Own variables and secrets |

---

## Design Principles

### 1. Stages Orchestrate Workflows, Commands and Agents

A stage references workflows, commands, agents, or inline steps. Workflows and commands are referenced by `name@version`; agents by their `subagent_type` identifier, with no CDL wrapper.

```yaml
stages:
  - id: validate
    name: Validate
    workflows:
      - ref: ship@1.0.0

  - id: quick-check
    name: Quick Check
    commands:
      - ref: validate@1.0.0

  - id: review
    name: Review
    agents:
      - ref: code-validator
```

> **Withdrawn in 1.6.0:** this principle used to read "Workflow/Command Orchestration, Not Agent Orchestration" and marked a stage's `agents:` list as wrong. PDL 1.2.0 (2026-03-07) added `agents` as an execution primitive, and the principle, the composition rules and the "What Pipelines Can Reference" table were never updated, so from 1.2.0 to 1.5.0 this document forbade a construct its own schema declared and 290 of the corpus's 324 stages used (census 2026-10-25). 1.6.0's gate rules are written about agents, so the rule is withdrawn rather than left to contradict them.

### 2. Event-Driven Execution

Pipelines define when they should run via triggers. Unlike workflows which are invoked programmatically, pipelines respond to external events.

```yaml
triggers:
  - type: git_push
    branches: [main, master]
    
  - type: schedule
    cron: "0 2 * * *"
```

### 3. Human-in-the-Loop Approvals

Critical stages can require human approval before execution. This enables safe deployment workflows with mandatory review checkpoints.

```yaml
stages:
  - id: deploy-prod
    approval:
      required: true
      approvers: ["@release-team", "@security-team"]
      timeout_hours: 24
```

### 4. Fail-Safe with Rollback

Pipelines can define automatic rollback strategies to recover from failures. This ensures production stability even when deployments fail.

```yaml
rollback:
  enabled: true
  strategy: revert_to_last_success
  triggers:
    - condition: "stages.deploy.failed"
      action: rollback_deploy
```

### 5. Declarative Stage Dependencies

Stages declare explicit dependencies. The runtime builds a DAG (Directed Acyclic Graph) and determines execution order. Independent stages may run in parallel (the `pdl-executor` skill does; core runs them in array order), with the same statuses either way.

```yaml
stages:
  - id: build
    # No depends_on = root stage
    
  - id: test
    depends_on: [build]
    
  - id: deploy
    depends_on: [test]
```

### 6. Consistent Interface Pattern

Pipelines use the same `interface` block structure as Agents (ADL), Commands (CDL), and Workflows (WDL) for consistency across the definition language family.

```yaml
pipeline:
  interface:
    name: release-pipeline
    version: 1.0.0
    displayName: Release Pipeline
    description: Complete CI/CD pipeline from validation to production deployment
    domain: software
```

---

## Relationship to Other Definition Languages

```
                    ADL (Agent Definition)
                           │
                           │ wrapped by
                           ▼
                    CDL (Command Definition)
                           │
                           │ orchestrated by
                           ▼
                    WDL (Workflow Definition)
                           │
                           │ staged by
                           ▼
                    PDL (Pipeline Definition)  ◄── YOU ARE HERE
```

### Composition Hierarchy

| Level | Definition | Contains | Example |
|-------|------------|----------|---------|
| Agent (ADL) | Atomic validation/execution unit | Scoring, criteria, tasks | `code-validator.agent.yaml` |
| Command (CDL) | Single agent + execution context | Preflight, overrides, output | `validate.command.yaml` |
| Workflow (WDL) | Multiple commands + phases | Gates, aggregation, context | `ship.workflow.yaml` |
| **Pipeline (PDL)** | **Workflows, commands and agents in stages** | **Triggers, gates, approvals, rollback** | **`release.pipeline.yaml`** |

### Composition Rules

```
Pipeline (PDL)
    ├── Can reference: Workflows (WDL), Commands (CDL), Agents (ADL, by subagent_type)
    └── Can contain: Inline shell commands (steps)

Workflow (WDL)
    ├── Can reference: Commands (CDL)
    └── Cannot reference: Agents, Pipelines

Command (CDL)
    ├── Can reference: Agents (ADL)
    └── Cannot reference: Commands, Workflows, Pipelines

Agent (ADL)
    └── Cannot reference: anything (atomic unit)
```

### Why Pipelines Exist

Pipelines solve the **CI/CD integration problem**:

- **Workflows** define *which commands* to run and *in what order*
- **Pipelines** define *when workflows run*, *who approves them*, *what happens on failure*

Without pipelines, CI/CD systems would need custom scripts to handle triggers, approvals, rollbacks, and notifications.

---

## Schema Structure

### CI/CD Pipeline

A complete CI/CD pipeline with validation, testing, and deployment:

```yaml
pipeline:
  interface:
    name: release-pipeline
    version: 1.0.0
    displayName: Release Pipeline
    description: Complete CI/CD pipeline from development validation to production deployment
    domain: software
    subdomain: ci-cd
    tags: [release, ci-cd, deployment]

  # ───────────────────────────────────────────────────────────────────
  # TRIGGERS
  # ───────────────────────────────────────────────────────────────────
  triggers:
    - type: git_push
      branches: [main, master]
      paths:
        include: ["src/**", "package.json"]
        exclude: ["**/*.md", "docs/**"]
        
    - type: pull_request
      actions: [opened, synchronize, reopened]
      branches: [main, master]
      
    - type: schedule
      cron: "0 2 * * 1"  # Weekly Monday 2 AM
      timezone: "UTC"
      
    - type: manual
      allowed: true
      parameters:
        - name: skip_tests
          type: boolean
          default: false
        - name: environment
          type: string
          options: [staging, production]
          default: staging

  # ───────────────────────────────────────────────────────────────────
  # ENVIRONMENT
  # ───────────────────────────────────────────────────────────────────
  environment:
    variables:
      - name: NODE_ENV
        value: "production"
        
      - name: CI
        value: "true"
        
      - name: VALIDATION_THRESHOLD
        value: "{{ params.strict ? 85 : 70 }}"
        
    secrets:
      - name: NPM_TOKEN
        required: true
        stages: [build, publish]
        
      - name: DEPLOY_KEY
        required: true
        stages: [deploy-staging, deploy-prod]
        
      - name: SLACK_WEBHOOK
        required: false
        stages: [notify]

  # ───────────────────────────────────────────────────────────────────
  # STAGES
  # ───────────────────────────────────────────────────────────────────
  stages:
    # Stage 1: Pre-flight checks
    - id: preflight
      name: Pre-Flight Checks
      parallel: true
      
      steps:
        - name: Install dependencies
          command: npm ci
          
        - name: Verify clean git state
          command: git status --porcelain
          expect_empty: true
          
        - name: Check Node version
          command: node --version
          expect_match: "^v2[02]\\."

        - name: Detect integration tests
          command: test -d test/integration && echo "DETECTED" || echo "NOT_DETECTED"
          continue_on_error: true

      gate:
        on_failure: abort
        
    # Stage 2: Core validation (workflow)
    - id: validate
      name: Core Validation
      depends_on: [preflight]
      
      workflows:
        - ref: ship@>=1.0.0
          args:
            target: "."
            strict: "{{ params.strict || false }}"
            
      gate:
        threshold: 70
        on_failure: abort
        
    # Stage 3: Security audit (workflow + steps)
    - id: security
      name: Security Review
      depends_on: [validate]
      parallel: false
      
      workflows:
        - ref: security-audit@>=1.0.0
          args:
            target: "."
            
      steps:
        - name: Dependency audit
          command: npm audit --audit-level=high
          continue_on_error: false
          
        - name: License check
          command: npx license-checker --onlyAllow "MIT;Apache-2.0;BSD-3-Clause;ISC"
          
      gate:
        threshold: 85
        on_failure: abort
        
    # Stage 4: Integration tests (conditional)
    - id: integration
      name: Integration Testing
      depends_on: [security]
      # preflight is an ancestor (security -> validate -> preflight), so its steps are readable
      condition: "!params.skip_tests && stages.preflight.steps['Detect integration tests'].output == 'DETECTED'"
      timeout: 900000  # 15 minutes
      
      steps:
        - name: Start test database
          command: docker-compose up -d test-db
          
        - name: Run integration tests
          command: npm run test:integration
          env:
            DATABASE_URL: "postgres://localhost:5432/test"
            
        - name: Stop test database
          command: docker-compose down
          always_run: true
          
      gate:
        on_failure: warn
        
    # Stage 5: Build
    - id: build
      name: Build
      depends_on: [security]  # Can run parallel to integration
      
      steps:
        - name: Build production bundle
          command: npm run build
          
        - name: Generate types
          command: npm run build:types
          
      artifacts:
        - name: dist
          path: "./dist/**/*"
          
    # Stage 6: Deploy to staging
    - id: deploy-staging
      name: Deploy to Staging
      depends_on: [build, integration]   # a SKIPPED integration stage still satisfies this
      condition: "params.environment == 'staging'"   # trigger.* is not a condition root
      
      steps:
        - name: Deploy to staging
          command: npm run deploy:staging
          env:
            DEPLOY_KEY: "{{ secrets.DEPLOY_KEY }}"
            
        - name: Smoke test
          command: npm run test:smoke -- --env=staging
          
      gate:
        on_failure: abort
        
    # Stage 7: Deploy to production (requires approval)
    - id: deploy-prod
      name: Deploy to Production
      depends_on: [deploy-staging]   # SKIPPED when environment is production; still satisfies
      condition: "params.environment == 'production'"
      
      approval:
        required: true
        approvers: ["@release-team"]
        min_approvals: 1
        timeout_hours: 24
        auto_reject_on_change: true
        
      steps:
        - name: Deploy to production
          command: npm run deploy:prod
          env:
            DEPLOY_KEY: "{{ secrets.DEPLOY_KEY }}"
            
        - name: Verify deployment
          command: npm run test:smoke -- --env=production
          retries: 3
          retry_delay: 30000
          
      gate:
        on_failure: abort

  # ───────────────────────────────────────────────────────────────────
  # ROLLBACK
  # ───────────────────────────────────────────────────────────────────
  rollback:
    enabled: true
    strategy: revert_to_last_success
    
    triggers:
      - condition: "stages.deploy-prod.failed"
        action: rollback_production
        
      - condition: "stages.deploy-staging.failed && stages.deploy-prod.started"
        action: rollback_all
        
    actions:
      rollback_production:
        steps:
          - name: Revert production deployment
            command: npm run deploy:prod:rollback
          - name: Verify rollback
            command: npm run test:smoke -- --env=production
            
      rollback_all:
        steps:
          - name: Revert staging
            command: npm run deploy:staging:rollback
          - name: Revert production
            command: npm run deploy:prod:rollback
            
    notify_on_rollback: true

  # ───────────────────────────────────────────────────────────────────
  # NOTIFICATIONS
  # ───────────────────────────────────────────────────────────────────
  notifications:
    channels:
      - type: slack
        webhook: "{{ secrets.SLACK_WEBHOOK }}"
        events: [started, stage_complete, success, failure, rollback]
        channel: "#deployments"
        
      - type: email
        recipients: ["team@example.com"]
        events: [failure, rollback]
        
      - type: github_status
        events: [success, failure]
        enabled: true
        context: "uluops/release-pipeline"
        
    templates:
      started: |
        🚀 Pipeline started: {{ pipeline.name }} v{{ pipeline.version }}
        Trigger: {{ trigger.type }} ({{ trigger.ref || trigger.branch }})
        
      success: |
        ✅ Pipeline completed successfully
        Duration: {{ pipeline.duration | duration }}
        Stages: {{ stages | length }} completed
        
      failure: |
        ❌ Pipeline failed at stage: {{ failed_stage.name }}
        Error: {{ failed_stage.error }}
        Duration: {{ pipeline.duration | duration }}
        
      rollback: |
        ⚠️ Rollback triggered
        Stage: {{ failed_stage.name }}
        Action: {{ rollback.action }}

  # ───────────────────────────────────────────────────────────────────
  # ARTIFACTS
  # ───────────────────────────────────────────────────────────────────
  artifacts:
    - name: build_output
      path: "./dist/**/*"
      retention_days: 30
      compression: gzip
      
    - name: test_results
      path: "./coverage/**/*"
      retention_days: 7
      
    - name: validation_reports
      path: "./**/*-features-list.md"
      retention_days: 90
      
    - name: logs
      path: "./.uluops/logs/**/*"
      retention_days: 14

  # ───────────────────────────────────────────────────────────────────
  # STATE
  # ───────────────────────────────────────────────────────────────────
  state:
    persistence: true
    ttl: "30d"
    
    tracked:
      - last_successful_deploy
      - last_rollback
      - deployment_count
      - failure_count
```

### Multi-Workflow Orchestration

A simpler pipeline that orchestrates multiple validation workflows:

```yaml
pipeline:
  interface:
    name: full-validation
    version: 1.0.0
    displayName: Full Validation Pipeline
    description: Comprehensive validation pipeline running multiple specialized workflows
    domain: software

  triggers:
    - type: pull_request
      actions: [opened, synchronize]
      
    - type: manual
      allowed: true

  stages:
    - id: pre-implementation
      name: Pre-Implementation Review
      workflows:
        - ref: pre-implementation@>=1.0.0
          args:
            target: "."
      gate:
        threshold: 70
        on_failure: warn
        
    - id: post-implementation
      name: Post-Implementation Validation
      depends_on: [pre-implementation]
      workflows:
        - ref: post-implementation@>=1.0.0
          args:
            target: "."
      gate:
        threshold: 75
        on_failure: abort
        
    - id: ship-gate
      name: Ship Readiness Gate
      depends_on: [post-implementation]
      workflows:
        - ref: ship@>=1.0.0
          args:
            target: "."
            strict: true
      gate:
        threshold: 80
        on_failure: abort

  notifications:
    channels:
      - type: github_status
        events: [success, failure]
        enabled: true
        context: "uluops/validation"
```

### Hybrid Pipeline (Workflows + Commands)

A pipeline that mixes workflows with direct command invocations:

```yaml
pipeline:
  interface:
    name: audit-and-fix
    version: 1.0.0
    displayName: Audit and Fix Pipeline
    description: Run validation audit then attempt automatic fixes
    domain: software

  triggers:
    - type: schedule
      cron: "0 3 * * *"  # Daily at 3 AM
      
    - type: manual
      allowed: true
      parameters:
        - name: auto_fix
          type: boolean
          default: true

  stages:
    # Stage 1: Run full audit workflow
    - id: audit
      name: Full Audit
      workflows:
        - ref: ship@>=1.0.0
          args:
            target: "."
      gate:
        threshold: 90  # warn: the run continues; stages.audit.passed is false below 90
        on_failure: warn

    # Stage 2: Run individual fix commands (conditional)
    - id: auto-fix
      name: Automatic Fixes
      depends_on: [audit]
      condition: "params.auto_fix && !stages.audit.passed"
      
      commands:
        - ref: lint-fix@>=1.0.0
          args:
            target: "."
          timeout: 300000
          
        - ref: type-fix@>=1.0.0
          args:
            target: "."
          condition: "context.typescript_detected"   # a commandRef condition: a free string, outside the 1.6.0 language

      sequential: true  # Run commands in order
      
    # Stage 3: Re-validate after fixes
    - id: verify
      name: Verify Fixes
      depends_on: [auto-fix]
      condition: "stages.auto-fix.passed"
      
      workflows:
        - ref: ship@>=1.0.0
          args:
            target: "."
            
      gate:
        threshold: 80
        on_failure: warn

  artifacts:
    - name: audit_before
      path: "./.uluops/audit-before.json"
      source: "stages.audit.output"
      
    - name: audit_after
      path: "./.uluops/audit-after.json"
      source: "stages.verify.output"
      condition: "stages.verify.completed"
```

---

## Detailed Field Reference

### Interface Block

The interface block identifies the pipeline and is consistent with ADL, CDL, and WDL.

```yaml
interface:
  name: release-pipeline          # Required: kebab-case identifier
  version: 1.0.0                  # Required: semantic version
  displayName: Release Pipeline   # Required: human-readable (3-50 chars)
  description: Full CI/CD...      # Required: purpose description (20-500 chars)
  domain: software                # Required: primary domain
  subdomain: ci-cd                # Optional: domain refinement
  tags: [release, deploy]         # Optional: searchable tags
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | Yes | Kebab-case identifier (`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`) |
| `version` | string | Yes | Semantic version (`^\d+\.\d+\.\d+$`) |
| `displayName` | string | Yes | Human-readable name (3-50 characters) |
| `description` | string | Yes | Pipeline purpose and scope (20-500 characters) |
| `domain` | Domain | Yes | Primary domain classification |
| `subdomain` | string | No | Domain refinement (kebab-case) |
| `tags` | string[] | No | Searchable discovery tags |

### Triggers Block

Triggers define when the pipeline executes.

```yaml
triggers:
  - type: git_push
    branches: [main, master]
    paths:
      include: ["src/**"]
      exclude: ["**/*.md"]
      
  - type: pull_request
    actions: [opened, synchronize, reopened]
    branches: [main]
    
  - type: schedule
    cron: "0 2 * * *"
    timezone: "UTC"
    
  - type: webhook
    event: custom_event
    secret: "{{ secrets.WEBHOOK_SECRET }}"
    
  - type: manual
    allowed: true
    parameters:
      - name: environment
        type: string
        options: [staging, production]
        default: staging
```

#### Trigger Types

| Type | Description | Key Fields |
|------|-------------|------------|
| `git_push` | Triggered on push to branch | `branches`, `tags`, `paths` |
| `pull_request` | Triggered on PR events | `actions`, `branches`, `paths` |
| `schedule` | Cron-based scheduling | `cron`, `timezone` |
| `webhook` | External HTTP webhook | `event`, `secret`, `payload_filter` |
| `manual` | Manual invocation | `allowed`, `parameters` |
| `pipeline` | Triggered by another pipeline | `pipeline`, `condition` |

#### git_push Trigger

```yaml
- type: git_push
  branches: [main, master]        # Branch patterns (glob supported)
  tags: ["v*"]                    # Tag patterns
  paths:
    include: ["src/**", "*.json"] # Files that trigger (glob)
    exclude: ["**/*.md"]          # Files that don't trigger
```

#### pull_request Trigger

```yaml
- type: pull_request
  actions:                        # PR actions that trigger
    - opened                      # PR opened
    - synchronize                 # New commits pushed
    - reopened                    # PR reopened
    - closed                      # PR closed (merged or not)
    - labeled                     # Label added
  branches: [main]                # Target branch filter
  paths:
    include: ["src/**"]
    exclude: ["docs/**"]
```

#### schedule Trigger

```yaml
- type: schedule
  cron: "0 2 * * 1-5"            # Cron expression (required)
  timezone: "America/New_York"    # Timezone (default: UTC)
  skip_if_running: true           # Don't start if previous still running
```

#### webhook Trigger

```yaml
- type: webhook
  event: deployment_requested     # Event name to match
  secret: "{{ secrets.HOOK }}"    # HMAC verification secret
  payload_filter: "$.env == 'production'"  # JSONPath filter
```

#### manual Trigger

```yaml
- type: manual
  allowed: true                   # Enable manual triggering
  parameters:                     # Input parameters
    - name: environment
      type: string
      options: [dev, staging, prod]
      default: staging
      required: true
    - name: skip_tests
      type: boolean
      default: false
    - name: version
      type: string
      pattern: "^v\\d+\\.\\d+\\.\\d+$"
```

### Environment Block

Environment variables and secrets for the pipeline.

```yaml
environment:
  variables:
    - name: NODE_ENV
      value: "production"
      
    - name: LOG_LEVEL
      value: "{{ trigger.type == 'manual' ? 'debug' : 'info' }}"
      
    - name: DEPLOY_TARGET
      value: "{{ params.environment || 'staging' }}"
      
  secrets:
    - name: NPM_TOKEN
      required: true
      stages: [build, publish]    # Stages that can access
      
    - name: DEPLOY_KEY
      required: true
      stages: [deploy-staging, deploy-prod]
      provider: vault             # Optional: secret provider
      path: "secret/deploy/key"   # Provider-specific path
```

| Field | Type | Description |
|-------|------|-------------|
| `variables` | Variable[] | Environment variables |
| `secrets` | Secret[] | Secret references |

#### Variable Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | Yes | Variable name (uppercase recommended) |
| `value` | string | Yes | Value or template expression |
| `stages` | string[] | No | Limit to specific stages |

#### Secret Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | Yes | Secret name |
| `required` | boolean | No | Fail if not available (default: false) |
| `stages` | string[] | No | Stages that can access |
| `provider` | string | No | Secret provider (vault, aws, etc.) |
| `path` | string | No | Provider-specific path |

### Stages Block

Stages are the primary execution units in a pipeline.

```yaml
stages:
  - id: preflight
    name: Pre-Flight
    steps:
      - name: Install dependencies
        command: npm ci

  - id: build
    name: Build
    description: Builds and validates the bundle; blocks on either agent's verdict
    depends_on: [preflight]       # Must name stages declared earlier
    # condition omitted: the stage always runs (a bare "true" is a syntax error in 1.6.0)
    timeout: 600000               # 10 minutes
    parallel: true                # Run steps in parallel
    forward: auto                 # What dependents receive: auto | none | full
    
    # Workflow references
    workflows:
      - ref: build-workflow@1.0.0
        args:
          target: "."
          
    # Command references
    commands:
      - ref: validate@1.0.0
        args:
          strict: true

    # Direct agent references
    agents:
      - ref: code-validator
        model: sonnet
        threshold: 75             # Per-agent threshold: the gate is in per-agent mode
      - ref: security-analyst
        model: opus
        threshold: 85
        condition: "stages.preflight.passed"

    # Inline steps
    steps:
      - name: Install dependencies
        command: npm ci
        
      - name: Build
        command: npm run build
        
    # Gate configuration
    gate:
      threshold: 70               # Fallback for an agent without its own threshold
      decision: not_negative      # Default on a blocking gate
      on_failure: fail            # FAILED; the run continues
      
    # Stage-level artifacts
    artifacts:
      - name: dist
        path: "./dist/**/*"
        
    # Approval (if required)
    approval:
      required: false
```

#### Stage Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | string | Yes | Unique stage identifier (kebab-case) |
| `name` | string | Yes | Human-readable stage name |
| `description` | string | No | What the stage does and what its gate decides |
| `depends_on` | string[] | No | Stages that must reach a terminal status first; each must be declared earlier (empty = root). See [Dependencies and ordering](#dependencies-and-ordering) |
| `condition` | string | No | Run condition in the [condition language](#the-condition-language), at most 512 code points; false skips the stage |
| `forward` | `auto` \| `none` \| `full` | No | What the stage's results forward to its dependents (default `auto`). See [Output forwarding](#output-forwarding) |
| `receives` | `auto` \| `none` | No | Whether the stage's agents receive forwarded results (default `auto`) |
| `timeout` | number | No | Timeout in milliseconds |
| `parallel` | boolean | No | Run items in parallel (default: false) |
| `workflows` | WorkflowRef[] | No | Workflow references |
| `commands` | CommandRef[] | No | Command references |
| `agents` | AgentRef[] | No | Direct agent references (subagent_type identifiers) |
| `steps` | Step[] | No | Inline shell steps |
| `sequential` | boolean | No | Force sequential execution |
| `gate` | Gate | No | Pass/fail gate |
| `artifacts` | Artifact[] | No | Stage-specific artifacts |
| `approval` | Approval | No | Human approval requirement |
| `env` | Record | No | Stage-specific environment |
| `inputs` | Record | No | Input parameters from dependencies |
| `outputs` | Output[] | No | Stage outputs |
| `artifacts_from` | string[] | No | Import declared file artifacts from named stages; does not govern result forwarding |

`stage` is closed in 1.6.0: any key not in this table is a load error (`unknown_key`). `skip_if` is not a stage key; write a `condition`.

#### Workflow Reference

```yaml
workflows:
  - ref: ship@>=1.0.0             # Version requirement
    args:                         # Arguments to pass
      target: "."
      strict: true
    condition: "context.has_src"  # Conditional execution (a free string; see below)
    timeout: 300000               # Override timeout
```

A `condition` on a workflow or command ref is a free string in 1.6.0. The condition language governs stage and `agentRef` conditions only.

#### Command Reference

```yaml
commands:
  - ref: validate@latest
    args:
      target: "."
    condition: "true"
    timeout: 120000
```

#### Agent Reference

Direct agent references invoke agents by their `subagent_type` identifier without CDL indirection. Unlike commands and workflows which use `name@version` format, agent refs use bare kebab-case identifiers since agents are resolved by type, not version.

```yaml
agents:
  - ref: dx-validator               # subagent_type identifier (no version)
    model: sonnet                   # Optional: model alias override
    args:                           # Optional: arguments to pass
      target: "."
    threshold: 80                   # Optional: per-agent score threshold
    condition: "params.dx == 'on'"  # Optional: run condition (condition language)
    timeout: 300000                 # Optional: timeout in milliseconds
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `ref` | string | Yes | Agent subagent_type identifier (kebab-case, no version) |
| `model` | string | No | Model alias override: `sonnet`, `opus`, or `haiku` |
| `args` | object | No | Arguments to pass to the agent |
| `threshold` | integer (0-100) | No | Per-agent score threshold. Any agent declaring one puts the stage gate in per-agent mode ([Score](#score)) |
| `condition` | string | No | Run condition in the [condition language](#the-condition-language), at most 512 code points; false skips the agent |
| `timeout` | number | No | Agent timeout in milliseconds (minimum 1000). An agent that does not return in time is unjudgeable and its stage ends ERRORED |

`agentRef` is closed in 1.6.0: any other key is a load error (`unknown_key`).

**Resolution chain:** `agents.ref` maps directly to the Agent tool's `subagent_type` parameter. No CDL lookup is needed — the executor passes the ref value straight through.

**When to use `agents` vs `commands`:**
- Use `agents` when you want direct, lightweight agent invocation without CDL indirection
- Use `commands` when you need the CDL layer's pre-flight checks, argument validation, or output formatting
- Both produce the same result (an agent execution), but `agents` is more direct

#### Inline Step

```yaml
steps:
  - name: Install dependencies    # Required: step name
    command: npm ci               # Required: shell command
    working_dir: "./packages/core"  # Optional: working directory
    env:                          # Optional: additional env vars
      NODE_ENV: "development"
    timeout: 60000                # Optional: step timeout
    continue_on_error: false      # Optional: don't fail stage
    always_run: false             # Optional: run even if prior failed
    retries: 0                    # Optional: retry count
    retry_delay: 5000             # Optional: delay between retries
    expect_empty: false           # Optional: expect no output
    expect_match: ""              # Optional: regex output match
```

#### Gate Configuration

```yaml
gate:
  threshold: 70                   # Score threshold (aggregate mode), or per-agent fallback
  aggregate: min                  # min, max, average (aggregate mode only)
  decision: not_negative          # not_negative, positive, ignore
  on_failure: abort               # abort, fail, warn, skip (deprecated alias of fail)
  on_success: continue            # continue, skip_remaining (unspecified; see below)
```

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `threshold` | integer (0-100) | — | Aggregate mode: `aggregate(scores)` must reach it. Per-agent mode: the fallback for agents without their own threshold. Absent in aggregate mode: the gate is decision-only |
| `aggregate` | `min` \| `max` \| `average` | `min` | How scores combine in aggregate mode. A load error in per-agent mode |
| `decision` | `not_negative` \| `positive` \| `ignore` | `not_negative` on blocking gates, `ignore` on `warn` | How each agent's decision class is compared ([Decision](#decision)) |
| `on_failure` | `abort` \| `fail` \| `warn` \| `skip` | `abort` | What a failure does ([Failure modes](#failure-modes)) |
| `on_success` | `continue` \| `skip_remaining` | `continue` | `skip_remaining` is not specified by the execution semantics (zero corpus uses) |

`gate` is closed in 1.6.0: any other key is a load error (`unknown_key`). The rules a gate applies are normative in [Gates](#gates).

### Convergence Block

Iterative convergence loop over a subset of stages, gated on agent scores **or** an executor-stage decision. Pipeline-level, optional. When present, the listed `loop_stages` are re-executed until the convergence gate passes or `max_iterations` is reached; stages not listed run exactly once after the loop exits.

The gate is one of two kinds, exactly one per gate (schema-enforced as mutually exclusive):

- **Score gate** — `threshold` (+ optional `aggregate`). The loop exits when the aggregated raw agent score meets the threshold. Use for assess→fix loops where quality is measured numerically.
- **Decision gate** — `satisfied_by` (a set of decision tokens). The loop exits when the gate stage's completion **Decision** is in that set. Use for queue-drain / task-completion loops whose gate stage is an executor-type agent that emits a Decision, not a score (e.g. `issue-remediation`, gated on the `issue-batcher` reporting `DRAINED`).

```yaml
# Score-gated (assess → investigate → execute until quality converges)
convergence:
  loop_stages: [assess, investigate, execute]   # Re-run each iteration, in dependency order

  gate:
    stages: [assess]              # Stage IDs whose agent scores feed the convergence score
    aggregate: average            # min, max, average (default: average)
    threshold: 95                 # Exit the loop when aggregated score >= threshold

  max_iterations: 5               # Hard cap (1-20)
  min_iterations: 1               # Iterations required before the gate may exit (default: 1)
  on_max_iterations: warn         # warn (proceed as UNCONVERGED), abort (default: warn)
  stall_iterations: 2             # Exit after N consecutive fixless iterations (default: 2)
  on_stall: warn                  # warn (proceed as UNCONVERGED), abort (default: warn)
  carry_context: true             # Pass prior-iteration findings into next iteration (default: true)

  tracker:
    suppress_agent_saves: true          # Loop-stage agents must not save_run/create_issue (default: true)
    allow_executor_issue_updates: true  # Executor may update pre-existing issues its fixes resolve (default: true)
```

```yaml
# Decision-gated (queue-drain loop; gate stage is a decision-only executor)
convergence:
  loop_stages: [pull, investigate, execute]

  gate:
    stages: [pull]                # Single executor-type stage that emits a Decision
    satisfied_by: [DRAINED]       # Converge when the gate stage's Decision is DRAINED
                                  # (no threshold/aggregate — decision gates carry no score)

  max_iterations: 5
```

| Field | Type | Description |
|-------|------|-------------|
| `loop_stages` | string[] | Stage IDs re-executed each iteration, in dependency order. Required. |
| `gate.stages` | string[] | Stage IDs whose gate signal (score or decision) feeds convergence. Must be a subset of `loop_stages`. Required. |
| `gate.aggregate` | enum | **Score gates only.** How agent scores across the gate stages combine: `min`, `max`, `average`. Default `average`. Not permitted with `satisfied_by`. |
| `gate.threshold` | integer | **Score gate.** Convergence score threshold (0-100). Mutually exclusive with `satisfied_by` — exactly one of the two is required. |
| `gate.satisfied_by` | string[] | **Decision gate.** Completion Decision tokens that converge the loop (uppercase, e.g. `[DRAINED]`). The gate stage must be a single executor-type agent emitting a Decision, not a score. Mutually exclusive with `threshold`/`aggregate` — exactly one of `threshold`/`satisfied_by` is required. |
| `max_iterations` | integer | Hard iteration cap (1-20). Required. |
| `min_iterations` | integer | Iterations that must complete before the gate can exit the loop. Default 1. |
| `on_max_iterations` | enum | `warn`: proceed to post-loop stages with decision `UNCONVERGED`; `abort`: fail the pipeline. Default `warn`. |
| `stall_iterations` | integer | Exit the loop early after this many **consecutive** iterations that applied zero mechanical fixes (1-10). Default `2`. See [Stall Exit](#stall-exit). |
| `on_stall` | enum | `warn`: proceed to post-loop stages with decision `UNCONVERGED`, `exit_reason: stalled`; `abort`: fail the pipeline. Default `warn`. |
| `tracker.suppress_agent_saves` | boolean | Loop-stage agents must not call `save_run`/`create_issue` — postflight owns run persistence. Default `true`. See [Tracker Persistence](#tracker-persistence). |
| `tracker.allow_executor_issue_updates` | boolean | Executor exception: issue-level updates (`update_status`, `add_issue_note`) on **pre-existing** tracker issues its fixes resolve remain allowed. Default `true`. |
| `carry_context` | boolean | Pass prior-iteration findings and fix summaries into the next iteration's agent prompts. Default `true`. |

See [Convergence Loops](#convergence-loops) for execution semantics.

### Approvals Block

Human approval requirements for stages.

```yaml
approval:
  required: true
  approvers:                      # Who can approve
    - "@release-team"             # Team mention
    - "user@example.com"          # Individual email
    - "github:octocat"            # Platform-specific
  min_approvals: 2                # Minimum required
  timeout_hours: 24               # Auto-reject after
  auto_reject_on_change: true     # Reject if source changes
  allow_self_approval: false      # Triggerer can't approve
  
  notification:
    channels: [slack, email]
    message: "Deployment to {{ params.environment }} requires approval"
```

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `required` | boolean \| string | false | Whether approval is required (boolean or expression) |
| `approvers` | string[] | [] | List of approvers |
| `min_approvals` | number | 1 | Minimum approvals needed |
| `timeout_hours` | number | 72 | Hours before auto-reject |
| `auto_reject_on_change` | boolean | true | Reject if code changes |
| `allow_self_approval` | boolean | false | Allow triggerer to approve |
| `notification` | Notification | - | Approval request notification |

### Rollback Block

Automatic failure recovery configuration.

```yaml
rollback:
  enabled: true
  strategy: revert_to_last_success  # Strategy type
  
  triggers:
    - condition: "stages.deploy-prod.failed"
      action: rollback_production
      
    - condition: "stages.verify.score < 50"
      action: rollback_and_notify
      
  actions:
    rollback_production:
      steps:
        - name: Revert deployment
          command: kubectl rollout undo deployment/app
        - name: Verify
          command: npm run test:smoke
      timeout: 300000
      
    rollback_and_notify:
      steps:
        - name: Revert
          command: npm run deploy:rollback
      notify: true
      
  preserve_logs: true
  notify_on_rollback: true
  max_rollback_attempts: 3
```

#### Rollback Strategies

| Strategy | Description |
|----------|-------------|
| `revert_to_last_success` | Restore last successful deployment |
| `revert_to_previous` | Restore immediate previous state |
| `custom` | Execute custom rollback actions |
| `none` | No automatic rollback |

### Notifications Block

External system notification configuration.

```yaml
notifications:
  channels:
    - type: slack
      webhook: "{{ secrets.SLACK_WEBHOOK }}"
      channel: "#deployments"
      events: [started, success, failure, rollback]
      
    - type: email
      recipients:
        - "team@example.com"
        - "{{ trigger.author_email }}"
      events: [failure]
      
    - type: github_status
      enabled: true
      context: "uluops/ci"
      
    - type: webhook
      url: "https://api.example.com/notify"
      method: POST
      headers:
        Authorization: "Bearer {{ secrets.API_TOKEN }}"
      events: [success, failure]
      
  templates:
    started: "🚀 {{ pipeline.name }} started by {{ trigger.author }}"
    success: "✅ {{ pipeline.name }} completed in {{ pipeline.duration | duration }}"
    failure: "❌ {{ pipeline.name }} failed at {{ failed_stage.name }}"
    rollback: "⚠️ Rollback triggered for {{ pipeline.name }}"
    
  rate_limit:
    max_per_hour: 10
    deduplicate: true
```

#### Notification Channel Types

| Type | Description | Key Fields |
|------|-------------|------------|
| `slack` | Slack webhook | `webhook`, `channel` |
| `email` | Email notification | `recipients`, `subject` |
| `github_status` | GitHub commit status | `context`, `target_url` |
| `webhook` | Generic HTTP webhook | `url`, `method`, `headers` |
| `pagerduty` | PagerDuty incident | `routing_key`, `severity` |
| `teams` | Microsoft Teams | `webhook` |

#### Notification Events

| Event | Description |
|-------|-------------|
| `started` | Pipeline started |
| `stage_started` | Stage started |
| `stage_complete` | Stage completed (success or failure) |
| `approval_required` | Approval requested |
| `approved` | Approval granted |
| `rejected` | Approval rejected |
| `success` | Pipeline completed successfully |
| `failure` | Pipeline failed |
| `rollback` | Rollback triggered |
| `timeout` | Pipeline or stage timed out |

### Artifacts Block

File preservation configuration.

```yaml
artifacts:
  - name: build_output
    path: "./dist/**/*"
    retention_days: 30
    compression: gzip
    
  - name: test_results
    path: "./coverage/**/*"
    retention_days: 7
    required: true                # Fail if not found
    
  - name: logs
    path: "./.uluops/logs/**/*"
    retention_days: 14
    condition: "pipeline.status == 'failed'"
    
  - name: validation_report
    source: "stages.validate.output"
    format: json
    retention_days: 90
```

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `name` | string | Yes | Artifact identifier |
| `path` | string | No | File glob pattern |
| `source` | string | No | Stage output reference |
| `format` | string | No | Output format (json, yaml, raw) |
| `retention_days` | number | No | Days to retain (default: 30) |
| `compression` | string | No | Compression type (gzip, none) |
| `required` | boolean | No | Fail if artifact missing |
| `condition` | string | No | Conditional preservation |

### State Block

Cross-run state persistence.

```yaml
state:
  persistence: true
  ttl: "30d"                      # Time to live
  
  tracked:
    - last_successful_deploy      # Auto-tracked: timestamp
    - last_rollback               # Auto-tracked: timestamp
    - deployment_count            # Auto-tracked: counter
    - failure_count               # Auto-tracked: counter
    - consecutive_failures        # Auto-tracked: counter
    
  custom:
    - name: last_version
      value: "{{ stages.build.version }}"
      on: success
      
    - name: environment_status
      value: "{{ params.environment }}: {{ pipeline.status }}"
      
  conditions:
    pause_on_consecutive_failures: 3  # Pause after N failures
    require_manual_after_rollback: true
```

| Field | Type | Description |
|-------|------|-------------|
| `persistence` | boolean | Enable state persistence |
| `ttl` | string | Time to live (e.g., "30d", "168h") |
| `tracked` | string[] | Automatically tracked values |
| `custom` | CustomState[] | User-defined state values |
| `conditions` | Conditions | State-based behavior conditions |

### Postflight Block

Actions executed after all stages complete. Handles tracker persistence, token metric collection, and conditional handlers for success/failure outcomes.

```yaml
postflight:
  tracker:
    enabled: true
    project: "$ARGUMENTS"                    # Tracker project name
    workflow_type: "{{ pipeline.interface.name }}"  # Run workflow type
    include_token_metrics: true              # Collect from agent-metrics buffer
    token_metrics_command: "agent-metrics buffer list --since 5m -f tracker"
    field_mappings:
      score_source: "stage.gate.score"       # Where to find validator scores
      status_source: "stage.gate.decision"   # Where to find PASS/FAIL
      model_source: "agent-metrics"          # Source for model identification
      recommendations_source: "stage.output.issues"  # Where to find issues
    verify_save: true                        # Verify saved count matches

  on_success:
    - description: "Report pipeline success"
      command: "echo 'All gates passed'"

  on_failure:
    - description: "Report pipeline failure"
      command: "echo 'Pipeline failed'"

  always:
    - description: "Cleanup temporary files"
      command: "rm -rf /tmp/pipeline-*"
```

#### Tracker Configuration

The `tracker` sub-block configures automatic persistence of pipeline results to the UluOps validation tracker via `save_run`. This replaces the need for manual tracker calls in each pipeline's rendered markdown.

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `enabled` | boolean | `true` | Enable tracker persistence |
| `project` | string | — | Tracker project name. Supports `$ARGUMENTS` or template expressions |
| `workflow_type` | string | `pipeline.interface.name` | Workflow type identifier for the tracker run |
| `include_token_metrics` | boolean | `true` | Collect token usage from agent-metrics buffer |
| `token_metrics_command` | string | `agent-metrics buffer list --since 5m -f tracker` | Command to extract token metrics |
| `field_mappings` | FieldMappings | (see below) | Maps pipeline outputs to tracker fields |
| `verify_save` | boolean | `true` | After saving, verify that `total_issues` matches saved count |

#### Field Mappings

Field mappings tell the renderer how to map stage outputs to `save_run` fields.

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `score_source` | string | `stage.gate.score` | Expression to extract validator scores |
| `status_source` | string | `stage.gate.decision` | Expression to extract PASS/FAIL status. It names the stage's reported verdict, not the 1.6.0 gate key `decision` (`not_negative`, `positive`, `ignore`), which never holds PASS/FAIL |
| `model_source` | string | `agent-metrics` | Source for model identification |
| `recommendations_source` | string | `stage.output.issues` | Expression to extract issue recommendations |

#### Conditional Handlers

The `on_success`, `on_failure`, and `always` arrays define actions that run after stages complete:

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `description` | string | Yes | Human-readable description |
| `command` | string | No | Shell command to execute |
| `condition` | string | No | Conditional expression |

**Execution order:** `on_success` OR `on_failure` runs first (based on outcome), then `always` runs regardless. Which one runs is decided by `all_gates_passed` ([the run verdict](#all_gates_passed-and-the-run-verdict)).

### Scoring Block

*Declared in 1.6.0.* Twenty-five corpus pipelines authored `pipeline.scoring` against 1.5.0, which did not declare it. It sets the run's headline score; gates never read it.

```yaml
scoring:
  method: weighted_average        # average, weighted_average, min, max, sum
  weights:                        # weight per agent name, for weighted_average
    assumption-excavator: 15
    negative-space-analyst: 20
  decisions:                      # reserved
    - { label: STATED, min_score: 80, description: "..." }
```

| Field | Type | Description |
|-------|------|-------------|
| `method` | enum | How agent scores combine into the headline score |
| `weights` | Record<string, number ≥ 0> | Weight per agent name |
| `decisions` | array of `{ label, min_score?, max_score?, description? }` | **Reserved.** Declared so that pipelines carrying it validate. No runtime reads it in 1.6.0 |

Which agents enter a weighted aggregate when `weights` omits some is decided by the pipeline-scoring-weights work, not by this document.

---

## Stage Dependency Graph

Pipelines build a DAG (Directed Acyclic Graph) from stage dependencies. The fragments in this section, the next and [Data Flow Between Stages](#data-flow-between-stages) may leave out each stage's `name` (required) and use short ids for brevity.

### Execution Order

```yaml
stages:
  - id: A
    # No depends_on = root node (executed first)

  - id: B
    depends_on: [A]

  - id: C
    depends_on: [A]
    # B and C can run in parallel after A

  - id: D
    depends_on: [B, C]
    # D waits for both B and C to reach a terminal status, whatever it is
```

A stage waits for its dependencies to reach a terminal status. Any status satisfies, except that a stage downstream of one that ended FAILED or ERRORED behind `abort` is skipped ([Dependencies and ordering](#dependencies-and-ordering)).

**Visualization:**

```
    A
   / \
  B   C
   \ /
    D
```

### Parallel Execution

Independent stages may run concurrently. The `pdl-executor` skill does; core runs stages one at a time in array order. Statuses and `all_gates_passed` are the same either way:

```yaml
stages:
  - id: lint          # Root
  - id: test          # Root
  - id: typecheck     # Root
  # All three may run in parallel (core runs them in array order)
  
  - id: build
    depends_on: [lint, test, typecheck]
    # Waits for all three
```

**Visualization:**

```
  lint    test    typecheck
    \      |      /
     \     |     /
      \    |    /
       \   |   /
        build
```

### Conditional Branches

Conditions create runtime-determined paths:

```yaml
stages:
  - id: validate
    # Always runs
    
  - id: deploy-staging
    depends_on: [validate]
    condition: "params.environment != 'production'"

  - id: deploy-prod
    depends_on: [validate]
    condition: "params.environment == 'production'"
```

**Visualization:**

```
              validate
             /        \
            /          \
 [environment!=production] [environment==production]
          |                       |
   deploy-staging            deploy-prod
```

Conditions are written in the [condition language](#the-condition-language). It has three roots (`params`, `stages.<id>.passed`, step output); 1.5.0's examples here read `trigger.branch`, which no runtime ever resolved.

### Cycle Detection

A `depends_on` entry must name a stage declared earlier in the array. A forward reference is a load error, which rules out cycles:

```yaml
# ✗ Invalid: A names C, which is declared later
stages:
  - id: A
    depends_on: [C]
  - id: B
    depends_on: [A]
  - id: C
    depends_on: [B]

# Load error: forward_reference at stage:A
```

---

## Execution Semantics (normative)

*New in 1.6.0.* This section is normative. Three interpreters run a PDL pipeline: the
`pdl-executor` skill (what Claude Code runs), the commands the definition-factory renders
from a pipeline (which a model follows), and `@uluops/core`'s `PipelineExecutor` (behind
`ulu exec pipeline`). Before 1.6.0 they disagreed on stage status, failure modes, conditions,
dependencies and how a gate reads a decision. Where this section and an interpreter disagree,
the interpreter is wrong.

### Scope and conformance

- **What it governs:** the run model, gates, dependencies, steps and forwarding apply to stages
  and their agents outside a convergence loop. Loop stages keep the gate and status rules in
  [Convergence Loops](#convergence-loops).
- **Conditions it governs:** every stage and `agentRef` condition, loop stages included, is
  written in [the condition language](#the-condition-language) and validated at load. Conditions
  on triggers, rollback triggers, `workflowRef`, `commandRef`, artifacts and postflight actions
  stay free strings, and no runtime is held to a reading of them.
- **Outside it:** approvals, rollback, notifications, artifacts and state. A stage whose
  approval is rejected does not run; 1.6.0 gives it no status.
- **The oracle.** The conformance fixtures in `uluops-agent-workflows/udl/pdl/conformance/`
  (154 cases in six groups: `gates`, `decisions`, `conditions`, `steps`, `run-control`,
  `load-errors`). Each subsection below names the cases that test it. A case's `covers` field
  cites the design spec this section was written from
  (`uluops-specifications/specs/cross-repo/drafts/pdl-1_6_0/`), not this document.
- **How each runtime is checked:**
  - core runs the fixtures as unit tests, and its saved-verdict test asserts the value it
    submits, not only the in-memory result;
  - the factory's validator runs the load-error cases, and a render check confirms the rule
    text in rendered commands;
  - the skill is run against the expected files on every skill release, every
    orchestrating-model upgrade, and every harness release that changes how subagents are
    launched or agent files are loaded.
  - A fixture agent is a stub with fixed output. A case whose stub output differs from its
    fixed text is inconclusive and is re-run; it never counts as a pass.
- **What the fixtures cannot check.** In the skill and in rendered commands a model evaluates
  conditions and gates, so a misreading is a wrong answer with nothing marking it. The
  fixtures, run on the occasions above, are the only check on the skill. Nothing runs the
  fixtures against a rendered command: the render check confirms the text, not that a model
  follows it. Both are accepted residuals of a model-run interpreter.

### Stage status

Every stage ends in exactly one status.

| status | meaning |
|---|---|
| `PASSED` | ran; its gate passed, or it has no gate, every step succeeded and no agent was unjudgeable |
| `WARNED` | ran; a `warn` gate failed, or a stage with no gate failed. A step failure behind a `warn` gate, or in a stage with no gate, gives WARNED |
| `FAILED` | ran; a blocking gate failed, or a step without `continue_on_error` failed behind a blocking gate |
| `SKIPPED` | did not run: its condition was false; every agent in it was skipped by its own condition; a stage it depends on, directly or transitively, ended FAILED or ERRORED behind `abort`; a convergence-loop stage aborted the pipeline ([Convergence Loops](#convergence-loops)); or the run was stopped before it launched |
| `ERRORED` | could not be judged, whether or not it ran: an agent was unjudgeable (a timeout included); a condition read output from a step that did not pass; a condition hit an interpreter defect; or it was in flight at a stop |

- **Unjudgeable agent.** An agent with no score and no classifiable decision; or, at a gate
  that has a threshold (per-agent or aggregate), an agent with no score. A classifiable
  decision does not stand in for a missing score against a threshold. At a decision-only
  gate a classifiable decision suffices. An agent in a stage behind a blocking gate whose
  decision is absent is unjudgeable whatever its score. One unjudgeable agent makes its stage
  ERRORED.
- **Blocking class:** `abort`, `fail`, and `skip` (a deprecated alias of `fail`). `warn` is
  not blocking. A gate without `on_failure` is `abort`.
- **An ERRORED stage takes its gate's mode.** Behind `abort` its dependents are skipped, as for
  a FAILED stage. Behind `fail` it fails the run and the run continues. Behind `warn` it counts
  as WARNED, including for the run decision.
- **Every ERRORED stage is surfaced.** The runtime emits `STAGE_ERRORED` with the stage and a
  reason: `agent_unjudgeable`, `condition_error` or `stopped`. Behind `warn` an ERRORED stage
  leaves `all_gates_passed` unchanged, so the warning is where the error shows.
- **A stage with no gate never fails the run.** It is judged as a `warn` gate whose decision
  key is `not_negative`: a step without `continue_on_error` that fails, or an agent whose
  decision is negative, makes it WARNED; `all_gates_passed` is unchanged and the run continues.
  A CONDITIONAL passes it and is not accepted, since it is not blocking. An unjudgeable agent in
  a gateless stage makes it ERRORED, and it counts as ERRORED behind `warn`. (No corpus stage
  has no gate.)
- **`stages.<id>.passed`** (the condition root below) is true exactly when the stage's status
  is PASSED.

Fixtures: `gates/*` (each failure mode, each ERRORED route, the steps-only stages),
`decisions/*-without-score*`, `run-control/*`.

### `all_gates_passed` and the run verdict

`all_gates_passed` is false when any of these holds, and true otherwise:
- a stage ended FAILED;
- a stage ended ERRORED behind a blocking gate;
- a blocking gate accepted a conditional decision (below);
- the run was stopped before every stage reached a terminal status.

- **Stops.** A stop is a cancel, a deadline or a credit limit: something outside the pipeline
  ends the run. A gate's `abort` is not a stop. On a stop the runtime records it and sets
  `all_gates_passed` to false before it marks unlaunched stages SKIPPED. A stage running at the
  stop has its running agents aborted (core aborts the in-flight provider calls, so a stop
  also stops billing; the skill stops waiting on them). Each aborted agent keeps its ABORTED
  record, which still reaches submission. The stage does not evaluate its gate and ends
  ERRORED, reason `stopped`.
- **The saved verdict.** Every runtime saves exactly this value as the run's
  `all_gates_passed`.
- **The run decision.** `PASS` when `all_gates_passed` is true and no stage ended WARNED or
  ERRORED behind `warn`; `WARN` when it is true and one did; `FAIL` when it is false. Core's
  `PipelineResult.decision`, its decision category and its stage metrics follow the same
  evaluation.
- **The run outcome.** A rendered postflight prints the pipeline's on-success outcome when
  `all_gates_passed` is true and its on-failure outcome when it is false. Nothing else sets a
  run-level outcome.
- **The resolved parameters are recorded.** Every runtime writes a `params:` line listing each
  resolved run parameter into the run's `raw_markdown`, so an override such as a lens switch
  is visible on the saved run.

Fixtures: `gates/conditional-at-default-gate`, `gates/warn-negative-*`,
`run-control/cancel-*`.

### Gates

A gate evaluates the agents in its stage that their own conditions did not skip.

#### Score

- **Per-agent mode.** If any `agentRef` in the stage declares `threshold`, each agent must
  reach its own threshold, falling back to `gate.threshold`. In this mode `gate.aggregate` is a
  load error, and so is an agent with neither its own threshold nor a `gate.threshold`.
- **Aggregate mode.** Otherwise `aggregate(scores) >= gate.threshold`, with `aggregate`
  `min` (default), `max` or `average`, as in 1.5.0.
- **Decision-only.** A gate in aggregate mode with no threshold compares decisions only.

Fixtures: `gates/per-agent-*`, `gates/aggregate-mode-unchanged`, `gates/decision-only-*`,
`load-errors/per-agent-*`, `load-errors/decision-only-gate-accepted`.

#### Decision

The gate key `decision` says how the gate compares each agent's decision class:

| `decision` | a negative | a conditional | a positive |
|---|---|---|---|
| `not_negative` | fails | passes; at a blocking gate, `all_gates_passed` becomes false and `CONDITIONAL_ACCEPTED` is emitted | passes |
| `positive` | fails | fails | passes |
| `ignore` | not compared | not compared | not compared |

- **Default:** `not_negative` on a blocking gate, `ignore` on a `warn` gate.
- **A neutral decision never fails a gate.** The score decides. So does an absent decision at a
  `warn` gate or in a stage with no gate. Behind a blocking gate, an absent decision makes the
  agent unjudgeable (below).
- So, at the default, a blocking gate fails on a negative decision whatever the score: an
  auto-fail that forces REVISE at a passing score fails the stage.

Fixtures: `gates/auto-fail-revise-at-passing-score`, `gates/conditional-at-*`,
`gates/decision-ignore-at-blocking-gate`, `gates/warn-negative-*`.

#### Reading the decision and the score

An agent's decision and score are read from a fixed contract on its output. Nothing else in
the output is part of the contract.

- **Decision.** In the agent's JSON output, the value at `result.decision`; if that is absent,
  the top-level `decision`; if neither is present, the value of the agent's `Decision:` line.
- **The agent's JSON output is its output envelope:** an object that carries `result`. An object
  without `result` is not the agent's output, even when a runtime's extractor finds it (a
  category object inside a cut-off JSON block, say). Neither its decision nor its score is read.
  A runtime's own schema-enforced structured output is the envelope by construction, whatever its
  shape, since the provider enforced the runtime's schema on it; the `result` rule applies to JSON
  a runtime finds in the agent's text.
- **Rendered agents write the `Decision:` line.** A rendered agent is told to write exactly one
  line, `Decision: <TOKEN>`, the token alone, and is given its allowed tokens apart from that
  line. A list of `Decision:` lines would be read as its first line if an agent echoed it.
- **Score.** The value at `result.score`; if absent, the top-level `score`; if neither is
  present, the number on the agent's `Score:` line (`Score: 85`, `Score: 85/100` and
  `**Score:** 85` all qualify). The value must be a number from 0 to 100, or a string that is
  exactly such a number (`"85"`). Anything else at a named path is no score, with
  `SCORE_INVALID`.
- **Other sources do not gate.** A runtime may find a decision or a score elsewhere (core
  searches further containers, key names and summing fallbacks) and show it. For gating, a
  decision found only there is absent, with `FALLBACK_DECISION_SOURCE`, and a score found only
  there is no score, with `FALLBACK_SCORE_SOURCE`.
- **Conflicts.** A JSON value that does not classify (neutral, unreadable, or an unfilled
  placeholder) never overrides a classifiable `Decision:` line. When both classify and
  disagree, the JSON value is used, with `DECISION_CONFLICT`.

Fixtures: `decisions/path-*`, `decisions/score-*`, `decisions/conflict-*`,
`decisions/real-*` (the architect's and docs-validator's rendered JSON, copied, not stubbed).

#### The token rule

A decision value is reduced to one token before it is classified.

1. Cut the value to 200 characters.
2. Drop leading characters that are not letters: glyphs, `**`, backticks, quotes, `[`, `~`.
3. The token is the first run of letters, digits and underscores, upper-cased.
4. The token counts only if what follows it is the end of the value, closing punctuation
   (`)` `]` `.` `,` `:` `;` `!` `*`), or whitespace after which the next non-space character is
   not a letter (or the value ends). Anything else after it (a letter, directly or after
   whitespace; `|`; `/`; `~`; any other character) makes the value neutral.

So `**REVISE** (Score: 85)`, `✅ PROCEED`, `REVISE.` and `REVISE (pending AF-003)` read as REVISE
and PROCEED. `NOT SECURE`, `SECURE WITH CONDITIONS`, `PARTIALLY DOCUMENTED` (with a space), the
unfilled placeholder `[DOCUMENTED|PARTIALLY_DOCUMENTED|UNDERDOCUMENTED]` and `~~PROCEED~~ REVISE`
read as neutral. The rule runs in linear time, and where it fails it fails toward neutral,
never toward the wrong class.

Fixtures: `decisions/token-*`.

#### Classification

A token is classified through the agent's declared vocabulary, then the core register.
Nothing else classifies.

- **Declared vocabulary.** The ADL `decisions.vocabulary` (or `completion.vocabulary` for an
  executor: complete → positive, failed → negative, partial → conditional). The skill reads it
  from the installed agent's frontmatter `decision_vocabulary`; core reads it from the resolved
  ADL.
- **The core register** classifies without a vocabulary. It is exactly these 13 tokens, the
  list `@uluops/sdk-core` exports from `@uluops/sdk-core/decisions`:

  | class | tokens |
  |---|---|
  | positive | `PASS` `SHIP` `COMPLETE` `EXPLORED` `APPROVED` `PROCEED` |
  | negative | `FAIL` `FAILED` `BLOCK` `BLOCKED` |
  | conditional | `WARN` `HOLD` `PARTIAL` |

  The skill carries this table verbatim, and a parity check keeps it, sdk-core's export and
  the corpus `check:vocab` copy equal.
- **Synonyms do not gate.** A token in neither the vocabulary nor the register is neutral,
  whatever a runtime maps it to for display (core maps `OK`, `SUCCESS` and `REJECT`, among
  others).

Fixtures: `decisions/token-core-register-without-vocabulary`, `decisions/register-token-classifies`,
`decisions/synonym-*`.

#### Neutral, absent and saved decisions

- **Neutral:** a token that classifies as none of positive, negative or conditional. It never
  blocks; the gate decides on the score, with `NEUTRAL_DECISION`.
- **Absent:** nothing at either JSON path and no `Decision:` line. For a corpus agent that means
  extraction failed, not that the agent judged neutral. It is warned as `ABSENT_DECISION`, a code
  apart from the neutral warning so that extraction failures can be counted on their own.
  - **Behind a blocking gate, the agent is unjudgeable, whatever its score**, and its stage is
    ERRORED. A runtime cannot tell an agent that judged nothing from one whose output it failed to
    read, so a score from that output does not pass a blocking gate. This holds on every target,
    score-only renders included. It applies to agents only: a workflow or command ref is judged by
    its own definition's decision.
  - At a `warn` gate or in a stage with no gate, it is handled as neutral: the score decides.
  - The rule was measured before it was adopted: 10.56 absent decisions per 100 results from the
    blocking-gate agents (generated core runs, 2026-10-31), against a threshold of 1 per 100 fixed
    in advance.
- **No score as well.** A neutral or absent decision with no score is unjudgeable: ERRORED.
- **The saved agent decision** is the token when it classifies (`**REVISE** (Score: 85)` saves
  `REVISE`); otherwise the value as written, whitespace collapsed, cut to 50 characters (the
  first 49 and `…` when longer); `UNKNOWN` when the decision is absent. `SECURE WITH
  CONDITIONS` is saved as written and stays neutral.

Fixtures: `decisions/neutral-*`, `decisions/absent-*`, `decisions/token-secure-with-conditions`.

#### Pre-launch vocabulary check

Before any stage launches, the runtime confirms that every agent listed in a blocking-gated
stage classifies its decisions.

- **An agent passes** if it declares a vocabulary, or if it is an explorer (`agentType:
  explorer`, whose only token, EXPLORED, is in the register). The skill reads `agentType` from
  the agent's frontmatter.
- **Otherwise the run is refused** with `VOCABULARY_MISSING`, naming the agents and the fix for
  each: regenerate the corpus agents; install the named agent from the registry; or re-run
  `npx @uluops/setup`, which covers its starter-pack agents only.
- **Presence only.** The check does not detect a target repo's agent file shadowing an
  installed one, does not check that an agent can emit the negative token it declares, and
  does not compare the skill's frontmatter copy of a vocabulary with the ADL.
- **Enforcement.** Core enforces it from the release that carries this language. The skill
  ships it disabled and enables it in a later release, once regenerated agents carrying
  `decision_vocabulary` and `agentType` are installed. Rendered pipeline commands do not run the
  check, on any target; the bullet below says why non-Claude ones could not.
- **Non-Claude targets.** Pipeline commands rendered for Gemini CLI, Codex and opencode carry
  no vocabulary, gate on score only, and are exempt from the check.

Fixtures: `decisions/precheck-*`.

#### Relaunch

A runtime never relaunches an agent because of its decision or score. The only relaunch is
after a launch failure, when the agent never started. An unjudgeable result is ERRORED and is
not retried. Re-running a pipeline is an operator's act, and every run is saved, so repeated
attempts are visible.

#### Workflow and command refs

A workflow or command ref at a gate is classified through the referenced definition's own
decision (its WDL aggregation or CDL result) and the core register. The pre-launch check does
not cover it.

#### All agents skipped

If its own agents' conditions skip every agent in a stage, the stage is SKIPPED and its gate is
not evaluated. Because steps are refused when disabled and a condition reading a failed step
is ERRORED, a step that reports failure cannot produce this. A detector that fails and still
reports success can: the corpus detector idiom `… && echo "DETECTED" || echo "NOT_DETECTED"`
prints the negative token when its tool crashes. SKIPPED then cannot tell "does not apply" from
"could not check". That is an accepted residual. The corpus `check:gates` lint flags every
blocking stage whose agents are all conditional, and each needs a reasoned waiver.

Fixtures: `gates/all-agents-skipped`, `gates/one-agent-skipped`.

#### Failure modes

| `on_failure` | stage status on failure | `all_gates_passed` | rest of the run |
|---|---|---|---|
| `abort` (and absent) | FAILED | false | the stage's transitive dependents are SKIPPED; every other stage launches as usual, and stages already running finish and are judged; postflight runs |
| `fail` | FAILED | false | continues; dependents run unless their own condition says otherwise |
| `warn` | WARNED | unchanged | continues |
| `skip` (deprecated) | as `fail` | as `fail` | as `fail`; loads with `SKIP_DEPRECATED`, naming `fail` |
| no gate | WARNED, on a failed step or a negative decision | unchanged | continues |

`abort` means "the work downstream of this stage is pointless", not "halt the pipeline": a stage
that does not depend on the aborting stage still runs. An author who wants dependents to run
after a failure uses `fail`. Halting everything is what a stop does.

`on_success: skip_remaining` is not specified by this section and keeps each runtime's existing
behaviour (zero corpus uses).

Fixtures: `gates/abort-skips-dependent`, `gates/absent-on-failure-is-abort`, `gates/fail-continues`,
`gates/warn-warns`, `gates/skip-is-fail`, `run-control/abort-*`, `load-errors/skip-loads-with-warning`.

### Dependencies and ordering

- **Satisfaction.** A stage launches once every `depends_on` member has reached a terminal
  status. Any terminal status satisfies. `depends_on` orders and forwards; it gates in one case
  only, a stage downstream (directly or transitively) of one that ended FAILED or ERRORED
  behind `abort`, which is skipped. Otherwise whether a stage runs is decided by its condition
  alone. After a stop nothing launches.
- **Unique ids.** Two stages with the same id are a load error, `duplicate_stage_id`, reported at
  the second; every reference to the id would otherwise be ambiguous.
- **Ordering at load time.** A `depends_on` entry naming a stage declared later in the
  `stages` array is a load error. This matches core's array-order execution and rules out
  cycles.
- **Concurrency.** The skill may run independent stages concurrently; core runs them one at a
  time, in array order. Statuses and `all_gates_passed` are the same either way, including
  across an abort, which affects only the aborting stage's dependents. They are not the same
  across a stop, whose timing decides which stages were in flight.

Fixtures: `run-control/skipped-conditional-upstream-of-synthesis`,
`run-control/abort-with-an-independent-sibling-in-flight`, `run-control/abort-skips-only-dependents`,
`load-errors/forward-reference`.

### The condition language

Stage `condition` and `agentRef` `condition` are written in this language. A condition that
evaluates false skips its stage or agent.

#### Grammar

```ebnf
condition   = or-expr ;                         (* at most 512 code points *)
or-expr     = and-expr , { "||" , and-expr } ;
and-expr    = unary , { "&&" , unary } ;
unary       = "!" , negand | atom ;
negand      = reference | "(" , or-expr , ")" ;
atom        = reference , [ ( "==" | "!=" ) , string ] | "(" , or-expr , ")" ;
reference   = segment , { "." , segment | "[" , string , "]" } ;
segment     = letter , { letter | digit | "_" | "-" } ;
string      = "'" , { any character except "'" or a control character } , "'"
            | '"' , { any character except '"' or a control character } , '"' ;
```

- `&&` binds tighter than `||`. Parentheses group.
- **`!` precedes only a reference or a parenthesised expression.** `!params.a == 'x'` is a
  syntax error; write `!(params.a == 'x')`. Core used to read the first form as the second,
  and C-style precedence reads it as `(!params.a) == 'x'`; refusing it means no runtime can
  choose a reading silently (Alex, 2026-10-26). By the same rule `!!x` is a syntax error, since
  the second `!` is neither a reference nor a parenthesised expression; write `!(!x)` or `x`.
- **A comparison has a reference on the left and a string literal on the right.** A literal on
  the left, a reference on both sides, an ordering operator (`<`, `>`, `<=`, `>=`), `=`, and a
  number or boolean literal (`== 1`, `== true`) are syntax errors.
- **Strings do not escape.** There is no backslash escape; to embed one quote style, use the
  other.
- **Strings hold no control character** (D40): no C0 control (tab and newline included), DEL, C1
  control, U+2028 or U+2029. A condition is rendered into the commands a model follows, and a
  newline in a literal let a condition inject a markdown header there (review run #73).
- Whitespace may appear between tokens, not inside a reference.
- **The length bound is 512 code points** (D41), the unit the JSON schema's `maxLength` counts. A
  runtime counts code points, not UTF-16 units, so the schema and the semantic check agree on
  every condition; a runtime parses in linear time and checks the length before parsing.

#### Context

A reference resolves against exactly three roots.

| reference | value |
|---|---|
| `params.<name>`, `params['<name>']`, `params["<name>"]` | the trigger parameter, as a string. Declared defaults are bound first |
| `stages.<id>.passed` | `true` when the stage's status is PASSED; otherwise `false` (FAILED, WARNED, ERRORED and SKIPPED included) |
| `stages.<id>.steps['<name>'].output` | the step's trimmed stdout. Readable only when the step's status is `passed`, a `continue_on_error` step that exited 0 included. Reading a step with any other status (failed, timed out, skipped after a hard failure, failed to spawn) yields the error value E |

#### Semantics

- **Equality** compares string forms: `a == b` is `String(a) === String(b)`.
- **Truthiness** of a bare reference: false when its value is the empty string, `false` or `0`
  (step output after trimming); true otherwise. Every context value is a string, so `0` is the
  string `0`. Core before 1.6.0 treated only a numeric 0 as falsy and read the step output `0` as
  true.
- **An absent parameter** (declared, no default, no value) equals nothing and is falsy: `==` is
  false and `!=` is true.
- **Error propagation (Kleene).** E propagates as follows, and nothing else produces it:

  | expression | value |
  |---|---|
  | `!E`, `E == 's'`, `E != 's'` | E |
  | `true \|\| E`, `E \|\| true` | true |
  | `false && E`, `E && false` | false |
  | `false \|\| E`, `E \|\| false`, `true && E`, `E && true`, `E \|\| E`, `E && E` | E |

  A condition whose final value is E makes its stage or agent ERRORED (reason
  `condition_error`). So `params.security != 'off' && stages.pre.steps['Detect'].output ==
  'DETECTED'` with `security=off` is false, not ERRORED, in every runtime.

#### Step output must exist

A condition may read step output only from a stage whose steps will run, and only from a step
that passed.
- **Steps disabled (core).** Before any stage launches, core refuses a run in which any
  condition reads `stages.<id>.steps[...]` while steps are disabled, with
  `STEP_OUTPUT_STEPS_DISABLED`. The refusal names the remedy for this case, enabling steps for
  the run; downgrading a gate to `warn` does not make a condition's input exist. The same check
  refuses a steps stage behind an `abort` gate when steps are off, before the first stage
  launches rather than when the run reaches it. That refusal predates 1.6.0 and has no code
  here; its message names the same remedy.
- **The skill and rendered commands** always run steps.
- **Failed or unrun steps** yield E (above).

So no well-formed run evaluates a step that did not execute or did not pass.

#### Validation at load time

A runtime validates every stage and `agentRef` condition when it loads a pipeline (local YAML
included), in this order, and reports the first fault in each condition:

1. `condition_too_long`: over 512 code points.
2. `condition_syntax`: the grammar above does not match. A reference whose only segment is
   `true` or `false` is a boolean literal and also a syntax error, not an unknown root.
3. For each reference:
   - `unknown_root`: its first segment is neither `params` nor `stages`. The forms core used
     to accept, `stage.<id>.…` (singular) and a bare `<id>.<field>`, are unknown roots.
   - `unknown_path`: a known root, but not one of the three forms in the context table
     (`stages.a.score`, `stages.a.steps['n'].status`, `params` alone).
   - `undeclared_parameter`: `params.x` with no declared parameter `x`.
   - `unknown_stage`: `stages.x` with no stage `x`.
   - `non_ancestor_reference`: `stages.x` where `x` is not an ancestor of the condition's stage.
     An ancestor is any stage reachable by following `depends_on` transitively. A stage is not
     its own ancestor, so an `agentRef` condition cannot read its own stage's steps.
   - `undeclared_step`: `steps['n']` with no step `n` in that stage.

The same load also refuses, outside conditions: a forward reference (`forward_reference`,
above); per-agent threshold faults (`missing_threshold`, `aggregate_with_per_agent`); undeclared
keys (`unknown_key`, below); step-template placement (`template_placement`) and parameter
environment-name collisions (`parameter_env_collision`, both under Steps).

**Runtime errors.** With load validation and total semantics, a condition error at run time
means an interpreter defect. The stage or agent then ends ERRORED. Only core can observe this,
since its parser can detect its own defect; in model-run interpreters a misreading is a wrong
boolean (see Scope and conformance).

**Where condition inputs come from.** Parameters come from whoever starts the run. Step output
comes from whatever the step inspects in its working directory.

Fixtures: `conditions/*`, `load-errors/unknown-*`, `load-errors/undeclared-*`,
`load-errors/non-ancestor-*`, `load-errors/transitive-ancestor-accepted`, `load-errors/syntax-*`,
`load-errors/length-*`, `load-errors/legacy-*`.

### Steps

#### Where steps run

- Steps run in the target directory. When the target is a file, they run in the file's parent
  directory, and `params.target` still names the file.
- The target is resolved with `realpath` first, so for a symlinked file the parent is the real
  file's parent.
- A step's `working_dir` resolves against that directory.
- For a file target, step containment is the file's directory, not the file.

#### Templates in step commands

- **The only template 1.6.0 specifies in a step command is `{{ params.<name> }}`.** Core fails
  a step whose command holds `{{ stages.… }}` or `{{ trigger.… }}` with "Unresolved template",
  and 1.6.0 does not change that. Core also accepts `{{ params.x || fallback }}` today. That form
  is not a 1.6.0 template, so this section does not say what a runtime does with it; no corpus
  step or fixture uses it.
- **`{{ params.target }}`** in a step command is the absolute, resolved target path, so a
  relative target never resolves against the step's own working directory. Other parameters
  are passed as given: a pipeline that takes a path in another parameter needs an absolute value
  from its caller. The absolute path, which contains the operator's home directory, can appear
  in a failed step's error text and from there in forwarded or saved output.
- **Placement rule (load time).** In a step command a template is either the whole of a
  double-quoted word (`"{{ params.x }}"`) or a whole bare word (`{{ params.x }}`). Anything else
  is a load error, `template_placement`: inside single quotes, part of a longer quoted string or
  word, inside `$(…)`, backticks or process substitution (`<(…)`, `>(…)`, D38), or in a heredoc.
  A runtime matches one of the two fixed forms and never decides how to escape from a quote
  context it lexed.
- **Not in command position** (D39). A template may not be the first word of a step command,
  quoted or bare: the parameter would name the program that runs. A template after `;`, `&&`,
  `||`, `|` or a newline in the middle of a command is not checked, since finding command position
  there needs a shell lexer; that is a stated residual.
- **Core: environment reference.** Core replaces `"{{ params.x }}"` and a bare `{{ params.x }}`
  with `"${ULU_P_X}"` and passes each value in the step's environment, so the shell expands it
  without re-parsing it. The name is the parameter name upper-cased, with every
  non-alphanumeric character mapped to `_`.
- **Collisions.** Two declared parameters that map to the same environment name (`a-b` and
  `a_b` both give `ULU_P_A_B`) are a load error, `parameter_env_collision`, whether or not either
  is used.
- **NUL.** A parameter value containing NUL is refused before launch, `PARAM_NUL`.
- **The skill: escaping.** The skill cannot pass a value through the environment, so it escapes
  it: inside the double-quoted word it backslash-escapes `"`, `$`, `` ` `` and `\`; for a bare
  word it single-quotes the value. A model applies this rule, and only the fixtures check it.
  This is the skill's stated residual.
- Templates outside step commands (stage `outputs[].value`, for instance) never reach a shell
  and are outside this rule.

Fixtures: `steps/*`, `load-errors/placement-*`, `load-errors/param-env-collision`.

### Output forwarding

- **`forward`** (producer, on the upstream stage): `auto` (default) forwards the standard
  slice of the stage's results to the stages that depend on it; `none` forwards nothing; `full`
  forwards the slice plus raw output.
- **`receives`** (consumer, on the downstream stage): `auto` (default) receives from every
  dependency that forwards; `none` depends for ordering only.
- **One hop.** A stage receives from its direct `depends_on` members only.
- **The slice** per agent is its identity, its decision, decision class and score, a summary
  (or the first 500 characters of raw output when it has none), and its top five findings
  sorted by severity.
- **Budget.** 8,000 characters per stage (24,000 with `full`), 32,000 in total; findings shrink
  before summaries, and headers and verdict lines are never dropped. Every truncation is marked
  in place. A `full` stage keeps the first 16,000 and the last 8,000 characters of its raw output.
- **Labelled absence.** A dependency that produced no output is forwarded as `### <id> — no
  output (<reason>)`, with the reason `condition_not_met` for a stage its condition skipped, or
  the failure's error text. A FAILED stage whose agents returned output forwards that output.
  A steps-only stage has nothing to forward and is not labelled.
- **Forwarded text is relayed as produced.** An upstream output can carry injected instructions,
  or a line that imitates the `### <id>` header and so misattributes text to another stage.
  1.6.0 does not fence or escape forwarded text; that belongs to the prompt-injection work.

Fixtures: `run-control/forwarding-only-reducer`, `run-control/failed-dependency-forwards-its-output`,
`run-control/skipped-conditional-upstream-of-synthesis`, and the `upstream` entries in every
expected file.

### Strictness and declarations

- **Closed objects.** `gate`, `stage` and `agentRef` reject undeclared keys (`unknown_key`).
  Before 1.6.0 they accepted any key, so a misspelt `condtion:` validated and was ignored.
- **Declared in 1.6.0:** stage `description`, `forward` and `receives`; `agentRef.threshold`;
  gate `decision`; `on_failure: fail`; and `pipeline.scoring` (`method`, `weights`, and
  `decisions`, which is reserved: declared so that pipelines carrying it validate, read by no
  runtime).
- **Removed in 1.6.0:** a stage's `skip_if`, which core used to evaluate and fail open on, is an
  undeclared key. Write a `condition` instead.
- **Bounded:** stage and `agentRef` conditions are at most 512 code points (schema `maxLength`).
- **Agent frontmatter.** The pre-launch check reads two keys the factory renders into a Claude
  Code agent's frontmatter: `decision_vocabulary` (`positive`, `negative`, `conditional`; a null
  conditional is omitted) and `agentType`.

Fixtures: `load-errors/unknown-key-*`, `load-errors/skip-if-rejected`,
`load-errors/length-512-accepted`, `load-errors/length-513-rejected`.

### Codes

Adopted from the conformance fixtures' README, where they were defined before this section was
written. A runtime emits these identifiers as written.

**Warnings** (during a run)

| code | fields | when |
|---|---|---|
| `NEUTRAL_DECISION` | `agent`, `value` | a neutral decision; the score decides. `value` is the saved form |
| `ABSENT_DECISION` | `agent` | no decision at either JSON path and no `Decision:` line |
| `DECISION_CONFLICT` | `agent`, `json`, `line` | the JSON value and the `Decision:` line both classify and disagree; the JSON wins |
| `FALLBACK_DECISION_SOURCE` | `agent`, `source` | a decision found only outside the named paths; gated as absent |
| `FALLBACK_SCORE_SOURCE` | `agent`, `source` | a score found only outside the named paths; no score for gating |
| `SCORE_INVALID` | `agent`, `value` | a value at a named score path that is not a number from 0 to 100 |
| `CONDITIONAL_ACCEPTED` | `stage`, `agent` | a blocking gate passed a conditional decision |
| `STAGE_ERRORED` | `stage`, `reason` | every ERRORED stage; `reason` is `agent_unjudgeable`, `condition_error` or `stopped` |

**Load warning**

| code | fields | when |
|---|---|---|
| `SKIP_DEPRECATED` | `stage` | `on_failure: skip` loads as `fail` |

**Refusals** (before any stage launches)

| code | fields | when |
|---|---|---|
| `VOCABULARY_MISSING` | `agents` | an agent in a blocking-gated stage neither declares a vocabulary nor is an explorer |
| `STEP_OUTPUT_STEPS_DISABLED` | `stages` | a condition reads step output while steps are disabled (core) |
| `PARAM_NUL` | `param` | a parameter value contains NUL (core) |

**Load errors**, each reported at `stage:<id>`, `stage:<id>/agent:<ref>`,
`stage:<id>/step:<name>` or `param:<name>`

| code | when |
|---|---|
| `unknown_root` | a condition reference outside `params` and `stages` |
| `unknown_path` | a known root, but not one of the three reference forms |
| `undeclared_parameter` | `params.x` with no declared `x` |
| `unknown_stage` | `stages.x` with no stage `x` |
| `non_ancestor_reference` | `stages.x` where `x` is not an ancestor |
| `undeclared_step` | `steps['n']` with no step `n` in that stage |
| `condition_syntax` | the condition grammar does not match |
| `condition_too_long` | a condition over 512 code points |
| `forward_reference` | `depends_on` names a stage declared later |
| `duplicate_stage_id` | two stages share an id; reported at the second, before any reference is checked |
| `missing_threshold` | per-agent mode, an agent with no threshold and no `gate.threshold` |
| `aggregate_with_per_agent` | `aggregate` on a gate in per-agent mode |
| `unknown_key` | an undeclared key on `gate`, `stage` or `agentRef` |
| `template_placement` | a step template outside the two allowed placements |
| `parameter_env_collision` | two declared parameters with the same `ULU_P_<NAME>` |

`unknown_key` and `condition_too_long` are also schema errors, so any JSON-schema validator finds
them; the other load errors need a runtime's semantic validator.

---

## Convergence Loops

The `convergence` block turns a one-pass stage DAG into an iterative fix loop. It exists for assess → investigate → fix pipelines that should repeat until quality converges, without encoding the loop in hand-written command markdown.

Loop stages follow this section's gate and status rules, not [Execution Semantics](#execution-semantics-normative): the iteration-level ERRORED, `satisfied_by` exact tokens and carry context are 1.5.0's, unchanged in 1.6.0. Their conditions are written in the [condition language](#the-condition-language) and validated at load like any other. Stages outside the loop, post-loop stages included, follow Execution Semantics, with one exception: a loop-stage abort (below).

### Execution Semantics

Each iteration executes `loop_stages` in dependency order, with one critical exception: **the convergence gate is evaluated immediately after all `gate.stages` complete — not at the end of the iteration.**

```
Iteration N:
  1. Run gate.stages (e.g., assess, or pull)
  2. Compute the gate signal:
       SCORE gate    → aggregate raw agent scores across gate.stages (per gate.aggregate)
       DECISION gate → read the gate stage's completion Decision
  3. If gate satisfied AND N >= min_iterations:
       SCORE gate    → satisfied when aggregated score >= gate.threshold
       DECISION gate → satisfied when the Decision ∈ gate.satisfied_by
       → CONVERGED (exit_reason: converged). Skip remaining loop stages. Exit loop.
  4. Otherwise: run remaining loop_stages (e.g., investigate, execute)
  5. Update the stall counter: if this iteration applied ZERO mechanical
     fixes, stall_count += 1; otherwise stall_count = 0.
     If stall_count == stall_iterations: apply on_stall
       → UNCONVERGED (exit_reason: stalled). Exit loop.
  6. If N == max_iterations: apply on_max_iterations
       → UNCONVERGED (exit_reason: max_iterations). Exit loop.
  7. Next iteration.

After loop exit (either path):
  Run post-loop stages (stages not in loop_stages) exactly once.
```

This ordering guarantees two properties:

1. **The exit score is fresh.** The loop only terminates on a score measured *after* the most recent fixes — never on a stale pre-fix score.
2. **No wasted work.** A converging run never executes an investigate/fix cycle it doesn't need.

### Score Aggregation

The convergence gate aggregates over the **raw agent scores** of all agents in all `gate.stages`, per `gate.aggregate`. It is independent of each gate stage's own stage-level `gate.aggregate` — the stage gate governs the stage's advisory pass/warn, the convergence gate governs loop termination. The two may use different aggregation methods without interacting.

### Missing and Errored Scores

If any gate-stage agent fails to produce a parseable score (crash, timeout, malformed output), the iteration is **non-converging regardless of aggregate**. A missing score is reported as `ERRORED` in the score trajectory — it is never coerced to 0, because a 0 must never be able to satisfy a `min` gate inversion nor silently drag an `average`. The loop proceeds to the remaining loop stages (findings from the surviving agents are still worth fixing) unless every gate-stage agent errored, in which case the iteration counts against `max_iterations` and the runtime warns. Every started iteration counts toward both `min_iterations` and `max_iterations`, errored or not — an errored iteration cannot exit the loop anyway (it is non-converging by definition), so the accounting stays simple.

### Decision Gates

A **decision gate** (`gate.satisfied_by`) terminates the loop on the gate stage's completion **Decision** rather than a numeric score. It exists for queue-drain and task-completion loops whose natural termination signal is categorical, not graded — the canonical case being `issue-remediation`, where the `issue-batcher` pull stage reports `BATCHED` while open issues remain and `DRAINED` when the queue is empty.

The gate stage must be a **single executor-type agent** that emits a Decision (its `completion.vocabulary`) and no numeric score. Each iteration the runtime reads that stage's Decision and maps it by the agent's completion vocabulary class:

| Decision class | `completion.vocabulary` | Gate effect | Trajectory entry |
|---|---|---|---|
| terminal-complete | `complete` (e.g. `DRAINED`) | Decision ∈ `satisfied_by` → **converge** (subject to `min_iterations`) | `satisfied_by` match |
| continue | `partial` (e.g. `BATCHED`) | does not satisfy → valid **CONTINUE**; run remaining loop stages | the Decision token |
| failure | `failed` (e.g. `BLOCKED`) | **ERRORED** — non-converging AND non-continuing (skip remaining loop stages this iteration, as with an all-errored score gate) | `ERRORED` |

A Decision the runtime cannot parse is treated as `ERRORED`, exactly like a missing score — never coerced to a convergence.

**Decision gates carry no score.** `gate.aggregate` and `gate.threshold` are not permitted alongside `satisfied_by` (schema-enforced). When *every* agent in the loop is decision-only (no agent emits a score), the run has no quality score: it is headlined by `convergence.decision` (`CONVERGED`/`UNCONVERGED`), `average_score` is omitted (never 0), and `convergence.final_score` is the drain signal only (the gate threshold-equivalent on convergence). See [Tracker Integration](#convergence-loops) — a loop whose stages update issue lifecycle in place (`allow_executor_issue_updates`) submits **no** `recommendations` in postflight; re-reporting already-dispositioned issues would fingerprint-match and reopen resolved ones.

### Conditions on Loop Stages

- `gate.stages` **must not** declare a `condition` — a skipped gate stage would leave the convergence signal undefined. This is a validation error.
- Other loop stages may carry a `condition` in the [condition language](#the-condition-language); it is re-evaluated **each iteration**. Load validation applies as written. How such a condition evaluates inside an iteration (what `stages.<id>.passed` of a loop stage means mid-loop, and what the error value E does to an iteration) is not specified in 1.6.0. Neither corpus convergence pipeline has a loop-stage condition.

### Carry Context

With `carry_context: true` (the default), every loop-stage agent prompt in iteration N+1 receives a `## Prior Iteration Context` section containing:

- The score trajectory so far (per-iteration gate scores, `ERRORED` entries included)
- Iteration N's investigator finding classifications (material / contextual / immaterial, with dispositions)
- Iteration N's executor fix summary: files changed, issues fixed, issues deferred with rationale

This is the mechanism that makes the loop converge rather than re-derive: assessors re-score *changed code with known history*, the investigator skips findings already dispositioned, and the executor does not retry fixes already deferred. With `carry_context: false`, each iteration is a cold read (useful for measuring assessment stability, not for fixing).

### Cross-Iteration Artifacts and Outputs

Stage `outputs` and `artifacts` produced inside the loop are **namespaced by iteration index**: `iteration.<n>.<stage_id>.<name>`. An unqualified reference (`stages.<stage_id>.<name>`) resolves to the **final iteration**. Post-loop stages (synthesis) can therefore read both the latest state and the full history. Artifacts are never overwritten across iterations.

### Post-Loop Stages

Stages not listed in `loop_stages` run exactly once after the loop exits, regardless of how it exited. Their `depends_on` references to loop stages are satisfied by the final iteration. Typical use: a synthesis stage that reads the full iteration history.

**Status reconciliation:** under `on_max_iterations: warn`, loop stages exit with status `WARNED`, not `FAILED` — so a dependency rule that skipped on failure would not skip post-loop stages. (Under 1.6.0 only a dependency that ended FAILED or ERRORED behind `abort` skips its dependents.) An `UNCONVERGED` run still gets synthesized; that is the design intent. Loop stages end `FAILED` only via `on_max_iterations: abort` or a stage-level `on_failure: abort`. (That is 1.5.0's rule. `on_failure: fail`, new in 1.6.0, is not specified for loop stages; neither corpus convergence pipeline has a blocking gate.)

### Stall Exit

A convergence loop can only move its score through the fixes it applies. An iteration that applies **zero mechanical fixes** — the investigator classified nothing as mechanical, or the executor had nothing to do — leaves the artifact unchanged, so re-assessing it can only reproduce (modulo assessment noise) the same score. One fixless iteration may be noise; two consecutive prove the loop has exhausted its own mechanism: every remaining finding is contextual, human-gated, or immaterial.

`stall_iterations` (default `2`) exits the loop after that many consecutive fixless iterations with decision `UNCONVERGED` and `exit_reason: stalled`, instead of burning the remaining budget re-deriving the same ceiling. The counter resets to zero on any iteration that applies at least one fix. Stall exit applies regardless of `min_iterations` — like `max_iterations`, it is a failure-class exit, not a convergence exit. `on_stall` mirrors `on_max_iterations` (`warn` default: loop stages exit WARNED, post-loop stages run).

A stalled exit is a *success of triage*, not a failure of the loop: it means the loop has cleanly separated what a machine can fix from what a human must decide, and is handing the residue over.

### Non-Convergence

Reaching `max_iterations` without passing the gate is a first-class outcome, not an error. With `on_max_iterations: warn` (the default), the pipeline proceeds to post-loop stages and reports decision `UNCONVERGED` alongside the score trajectory. Use `abort` only when downstream stages must not run against an unconverged artifact. The `convergence.exit_reason` expression distinguishes the exit paths: `converged`, `max_iterations`, `stalled`, or `user_pause` (recorded by the runtime when a human halts the loop between iterations).

### Interaction with Stage Gates

Stage-level `gate` blocks still apply within each iteration — a stage gate with `on_failure: abort` aborts the whole pipeline, loop included, on the first sub-threshold iteration. This is a loop rule kept from 1.5.0: outside a loop, `abort` skips only the failed stage's dependents ([Failure modes](#failure-modes)), so a loop-stage abort is the one place `abort` still halts every remaining stage. The stages it halts end SKIPPED. That reading is stated, not ruled; neither corpus convergence pipeline has a blocking gate, and validators warn on `abort` on a loop stage. Keep loop-stage gates advisory (`warn`) and let the convergence gate own termination. Validators emit a warning for `on_failure: abort` on a loop stage.

### Tracker Persistence

Postflight tracker saves must accumulate findings and analysis records across **all** iterations — each iteration's agent outputs are part of the run record, not just the final iteration's. The iteration count, per-iteration scores, and convergence decision (`CONVERGED` / `UNCONVERGED`) belong in the run summary.

**Agent save suppression (`tracker.suppress_agent_saves`, default `true`).** Postflight is the *single* owner of run persistence. When suppression is on, the runtime appends a no-save contract to every loop-stage agent prompt:

> Do NOT save runs or create issues in the tracker (`save_run`, `create_issue`). This pipeline's postflight persists all findings from all iterations in one run. Report your findings in your response only.

Without this, agents whose own definitions instruct tracker saves (investigators, some validators) create uncoordinated run rows that double-report the pipeline's findings — one orphaned sub-run per iteration, disjoint from the pipeline's accumulated record.

**Executor exception (`tracker.allow_executor_issue_updates`, default `true`).** The executor may still perform *issue-level* updates — `update_status`, `add_issue_note` — on **pre-existing** tracker issues that its fixes resolve (issues that existed before this pipeline run started). This keeps the tracker's open-issue ledger current as fixes land, without creating run rows. Findings first surfaced by this run are not pre-existing — they reach the tracker only through postflight.

Convergence pipelines expose a dedicated `convergence.*` namespace to postflight `field_mappings`:

| Expression | Value |
|-----------|-------|
| `convergence.final_score` | The last gate evaluation's aggregated score — **not** the mean across all iterations' agents (which would double-count every re-assessment) |
| `convergence.decision` | `CONVERGED` / `UNCONVERGED` |
| `convergence.exit_reason` | `converged` \| `max_iterations` \| `stalled` \| `user_pause` |
| `convergence.iterations` | Number of iterations executed |
| `convergence.score_trajectory` | Per-iteration gate scores as an array of `number \| "ERRORED"` — the literal string `"ERRORED"` stands in for a missing score, never `0` or `null` |

### Validation Rules

Enforced by the PDL semantic validator (beyond JSON Schema, which cannot express cross-field rules):

1. Every ID in `loop_stages` must reference an existing stage. *(error)*
2. Every ID in `gate.stages` must also appear in `loop_stages`. *(error)*
3. No stage in `gate.stages` may declare a `condition`. *(error)*
4. `min_iterations` must not exceed `max_iterations`. *(error)*
5. Loop stages must not depend on post-loop stages (the loop cannot depend on stages that run after it). *(error)*
6. A loop stage with `gate.on_failure: abort` defeats convergence on the first sub-threshold iteration. *(warning)*
7. `stall_iterations` must be less than `max_iterations` — a stall window that equals or exceeds the cap can never fire. *(warning)*
8. `gate` must declare **exactly one** of `threshold` (score gate) or `satisfied_by` (decision gate); `aggregate` is permitted only with `threshold`. *(error, schema-enforced)*
9. A decision gate (`satisfied_by`) should name a single `gate.stages` entry resolving to an executor-type agent whose `completion.vocabulary` includes the `satisfied_by` tokens as its terminal-complete decision. *(warning)*

---

## Trigger Event Types

### Git Push Events

```yaml
- type: git_push
  branches:
    - main
    - "release/*"
    - "!release/beta-*"  # Exclude pattern
  tags:
    - "v*"
    - "!v*-rc*"
  paths:
    include:
      - "src/**"
      - "package.json"
    exclude:
      - "**/*.md"
      - "**/*.test.ts"
```

### Pull Request Events

| Action | Description |
|--------|-------------|
| `opened` | PR opened |
| `closed` | PR closed (merged or not) |
| `synchronize` | New commits pushed |
| `reopened` | PR reopened |
| `labeled` | Label added |
| `unlabeled` | Label removed |
| `review_requested` | Review requested |
| `review_submitted` | Review submitted |
| `converted_to_draft` | Converted to draft |
| `ready_for_review` | Ready for review |

### Schedule Expressions

Cron format: `minute hour day-of-month month day-of-week`

| Expression | Description |
|------------|-------------|
| `0 * * * *` | Every hour |
| `0 2 * * *` | Daily at 2 AM |
| `0 2 * * 1-5` | Weekdays at 2 AM |
| `0 0 1 * *` | First of month |
| `*/15 * * * *` | Every 15 minutes |

### Webhook Payload Filtering

```yaml
- type: webhook
  event: deployment
  payload_filter: |
    $.environment == 'production' &&
    $.action == 'requested'
```

---

## Approval Workflows

### Simple Approval

```yaml
approval:
  required: true
  approvers: ["@ops-team"]
```

### Multi-Level Approval

```yaml
stages:
  - id: security-review
    approval:
      required: true
      approvers: ["@security-team"]
      min_approvals: 1
      
  - id: deploy-prod
    depends_on: [security-review]
    approval:
      required: true
      approvers: ["@release-team", "@ops-team"]
      min_approvals: 2
```

### Conditional Approval

```yaml
approval:
  required: "{{ params.environment == 'production' }}"
  approvers: ["@release-team"]
  skip_for:
    - branches: ["hotfix/*"]
    - authors: ["@emergency-deployers"]
```

### Approval Timeout Behavior

| Behavior | Description |
|----------|-------------|
| `reject` | Auto-reject after timeout (default) |
| `approve` | Auto-approve after timeout |
| `extend` | Notify and extend timeout |
| `pause` | Pause pipeline indefinitely |

---

## Rollback Strategies

### Revert to Last Success

```yaml
rollback:
  enabled: true
  strategy: revert_to_last_success
```

Restores the last known good state from pipeline history.

### Revert to Previous

```yaml
rollback:
  enabled: true
  strategy: revert_to_previous
```

Restores the immediate previous state, regardless of success.

### Custom Rollback

```yaml
rollback:
  enabled: true
  strategy: custom
  
  actions:
    default:
      steps:
        - name: Scale down
          command: kubectl scale deployment/app --replicas=0
        - name: Restore backup
          command: ./scripts/restore-backup.sh
        - name: Scale up
          command: kubectl scale deployment/app --replicas=3
```

### Rollback Triggers

```yaml
rollback:
  triggers:
    # Trigger on stage failure
    - condition: "stages.deploy.failed"
      action: rollback_deploy
      
    # Trigger on low score
    - condition: "stages.verify.score < 50"
      action: full_rollback
      
    # Trigger on timeout
    - condition: "stages.health-check.timeout"
      action: emergency_rollback
      
    # Compound conditions
    - condition: |
        stages.deploy.completed &&
        stages.verify.failed &&
        state.consecutive_failures > 2
      action: rollback_and_pause
```

---

## Data Flow Between Stages

### Output Variables

Stages can export values for downstream consumption:

```yaml
stages:
  - id: build
    steps:
      - name: Build
        command: npm run build
    outputs:
      - name: version
        value: "{{ steps.build.env.npm_package_version }}"
      - name: hash
        command: git rev-parse HEAD
        
  - id: deploy
    depends_on: [build]
    # A step command resolves only {{ params.* }} templates. How a downstream stage
    # reads stages.build.outputs.version is not specified in 1.6.0.
    steps:
      - name: Deploy
        command: deploy
```

`inputs`, `outputs` and `artifacts_from` have no 1.6.0 semantics; these examples show their syntax.

### Input Parameters

Stages can receive inputs from dependencies:

```yaml
stages:
  - id: validate
    workflows:
      - ref: ship@1.0.0
    gate: { threshold: 80, on_failure: warn }
    outputs:
      - name: score
        value: "{{ workflow.score }}"
      - name: issues
        value: "{{ workflow.issues | json }}"
        
  - id: fix
    depends_on: [validate]
    condition: "!stages.validate.passed"   # validate's gate: threshold 80, on_failure warn
    inputs:
      issues: "{{ stages.validate.outputs.issues }}"
    commands:
      - ref: fix-issues@1.0.0
        args:
          issues: "{{ inputs.issues }}"
```

### Result Forwarding

A stage's agents receive a slice of its dependencies' results automatically, one hop along `depends_on`, unless the upstream stage sets `forward: none` or the downstream stage sets `receives: none`. See [Output forwarding](#output-forwarding).

### Artifact Passing

Artifacts (files) can be passed between stages:

```yaml
stages:
  - id: build
    name: Build
    steps:
      - name: Build
        command: npm run build
    artifacts:
      - name: dist
        path: "./dist/**/*"
        
  - id: deploy
    name: Deploy
    depends_on: [build]
    artifacts_from: [build]  # Import build artifacts
    steps:
      - name: Deploy
        command: aws s3 sync ./dist s3://bucket/
```

---

## Composition Rules

### What Pipelines Can Reference

| Reference Type | Allowed | Example |
|----------------|---------|---------|
| Workflows (WDL) | ✓ | `ship@1.0.0` |
| Commands (CDL) | ✓ | `validate@1.0.0` |
| Agents (ADL) | ✓ (since 1.2.0) | `ref: code-validator` (subagent_type, no version) |
| Other Pipelines | ✓ (via trigger) | `type: pipeline` |

### Version Resolution

```yaml
workflows:
  - ref: ship@1.0.0         # Exact version
  - ref: ship@>=1.0.0       # Minimum version
  - ref: ship@^1.0.0        # Compatible version (1.x.x)
  - ref: ship@~1.0.0        # Patch version (1.0.x)
  - ref: ship@latest        # Latest published
```

### Reference Validation

The registry validates references at publish time:

1. All referenced workflows/commands must exist
2. Version constraints must be satisfiable
3. No circular pipeline triggers
4. Domain compatibility is checked

---

## Runtime Behavior

### Pipeline Lifecycle

```
┌─────────────────────────────────────────────────────────────────┐
│                      PIPELINE LIFECYCLE                         │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  1. TRIGGER                                                     │
│     └─ Event received (push, PR, schedule, webhook, manual)     │
│                                                                 │
│  2. VALIDATION                                                  │
│     ├─ Check trigger conditions                                 │
│     ├─ Load validation: keys, conditions, references,           │
│     │  dependencies, thresholds, step templates                 │
│     ├─ Pre-launch checks: vocabularies; step output with        │
│     │  steps disabled; NUL in parameters                        │
│     ├─ Resolve environment variables                            │
│     ├─ Validate secrets availability                            │
│     └─ Build stage dependency graph                             │
│                                                                 │
│  3. EXECUTION                                                   │
│     ├─ Execute stages in dependency order                       │
│     ├─ Run independent stages concurrently (skill) or in array  │
│     │  order (core); the results are the same                  │
│     ├─ Wait for approvals when required                         │
│     ├─ Check gates after each stage                             │
│     └─ Collect artifacts and outputs                            │
│                                                                 │
│  4. COMPLETION                                                  │
│     ├─ Compute all_gates_passed and the run decision            │
│     ├─ Trigger rollback if needed                               │
│     ├─ Send notifications                                       │
│     ├─ Preserve artifacts                                       │
│     └─ Update state                                             │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

### Stage Execution

```
┌─────────────────────────────────────────────────────────────────┐
│                      STAGE EXECUTION                            │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  1. Wait for dependencies                                       │
│     ├─ Every depends_on stage reaches a terminal status         │
│     └─ Downstream of FAILED/ERRORED behind abort: SKIPPED       │
│                                                                 │
│  2. Check stage condition                                       │
│     ├─ false: SKIPPED                                           │
│     └─ error value E: ERRORED                                   │
│                                                                 │
│  3. Check approval (if required)                                │
│     ├─ Send approval request                                    │
│     ├─ Wait for approvals or timeout                            │
│     └─ If rejected: the stage does not run (approvals are      │
│        outside Execution Semantics; status unspecified)        │
│                                                                 │
│  4. Execute items (workflows, commands, steps)                  │
│     ├─ If parallel: execute concurrently                        │
│     ├─ If sequential: execute in order                          │
│     └─ Collect outputs and artifacts                            │
│                                                                 │
│  5. Check gate (if defined)                                     │
│     ├─ Read each agent's decision and score                     │
│     ├─ Compare scores (per-agent or aggregate) and decisions    │
│     └─ Apply on_failure action                                  │
│                                                                 │
│  6. Update stage status                                         │
│     └─ PASSED | WARNED | FAILED | SKIPPED | ERRORED             │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

### Timeout Handling

| Level | Field | Default | Behavior |
|-------|-------|---------|----------|
| Pipeline | `timeout` | 3600000 (1hr) | A stop (deadline): stages in flight end ERRORED, `all_gates_passed` is false |
| Stage | `timeout` | 600000 (10min) | What it cuts off is judged by the usual rules: an agent left without a result is unjudgeable, so the stage ends ERRORED; a step it kills has failed |
| Agent | `timeout` | — | The agent is unjudgeable; its stage ends ERRORED |
| Step | `timeout` | 60000 (1min) | Fail step |
| Approval | `timeout_hours` | 72 | Auto-reject |

### Failure Modes

The failure modes are normative in [Failure modes](#failure-modes): `abort` skips the transitive dependents of a stage that ended FAILED or ERRORED and lets every other stage run; `fail` fails the run and continues; `warn` warns and continues; `skip` is a deprecated alias of `fail`. 1.5.0's table here said `abort` stopped the pipeline immediately and `skip` skipped dependent stages, and listed a `rollback` mode that was never in the `on_failure` enum. Rollback is the [Rollback Block](#rollback-block), triggered by its own conditions.

---

## Examples

### Minimal Pipeline

```yaml
pipeline:
  interface:
    name: simple
    version: 1.0.0
    displayName: Simple Pipeline
    description: Minimal pipeline example with one stage
    domain: software

  triggers:
    - type: manual
      allowed: true

  stages:
    - id: validate
      name: Validate
      workflows:
        - ref: ship@1.0.0
```

### Monorepo Pipeline

```yaml
pipeline:
  interface:
    name: monorepo-ci
    version: 1.0.0
    displayName: Monorepo CI
    description: CI pipeline for monorepo with multiple packages
    domain: software

  triggers:
    - type: pull_request
      actions: [opened, synchronize]
      paths:
        include: ["packages/**"]

  environment:
    variables:
      - name: CHANGED_PACKAGES
        value: "{{ trigger.changed_files | packages }}"

  stages:
    - id: detect-changes
      name: Detect Changes
      steps:
        - name: Detect changed packages
          command: |
            npx lerna changed --json > changed.json
      outputs:
        - name: packages
          command: cat changed.json | jq -r '.[].name'
          
    - id: lint
      name: Lint
      depends_on: [detect-changes]
      parallel: true
      steps:
        - name: Lint changed packages
          command: npx lerna run lint --since origin/main   # a step command resolves only {{ params.* }} templates
          
    - id: test
      name: Test
      depends_on: [detect-changes]
      parallel: true
      steps:
        - name: Test changed packages
          command: npx lerna run test --since origin/main   # a step command resolves only {{ params.* }} templates
          
    - id: build
      name: Build
      depends_on: [lint, test]
      steps:
        - name: Build changed packages
          command: npx lerna run build --since origin/main   # a step command resolves only {{ params.* }} templates
```

### Blue-Green Deployment

```yaml
pipeline:
  interface:
    name: blue-green-deploy
    version: 1.0.0
    displayName: Blue-Green Deployment
    description: Zero-downtime deployment with blue-green strategy
    domain: software

  triggers:
    - type: git_push
      branches: [main]

  environment:
    secrets:
      - name: KUBE_CONFIG
        required: true

  stages:
    - id: build
      name: Build
      steps:
        - name: Build image
          command: docker build -t app:$(git rev-parse --short HEAD) .
        - name: Push image
          command: docker push app:$(git rev-parse --short HEAD)
          
    - id: deploy-green
      name: Deploy Green
      depends_on: [build]
      steps:
        - name: Deploy to green
          command: kubectl set image deployment/app-green app=app:$(git rev-parse --short HEAD)
        - name: Wait for rollout
          command: kubectl rollout status deployment/app-green --timeout=300s
          
    - id: verify-green
      name: Verify Green
      depends_on: [deploy-green]
      workflows:
        - ref: smoke-test@1.0.0
          args:
            target: "https://green.example.com"
      gate:
        threshold: 90
        on_failure: abort
        
    - id: switch-traffic
      name: Switch Traffic
      depends_on: [verify-green]
      approval:
        required: true
        approvers: ["@ops-team"]
        timeout_hours: 4
      steps:
        - name: Switch service to green
          command: kubectl patch service/app -p '{"spec":{"selector":{"version":"green"}}}'
          
    - id: verify-production
      name: Verify Production
      depends_on: [switch-traffic]
      workflows:
        - ref: smoke-test@1.0.0
          args:
            target: "https://app.example.com"
      gate:
        threshold: 95
        on_failure: abort
        
    - id: cleanup-blue
      name: Clean Up Blue
      depends_on: [verify-production]
      steps:
        - name: Scale down blue
          command: kubectl scale deployment/app-blue --replicas=0

  rollback:
    enabled: true
    triggers:
      - condition: "stages.verify-production.failed"
        action: rollback_traffic
    actions:
      rollback_traffic:
        steps:
          - name: Switch back to blue
            command: kubectl patch service/app -p '{"spec":{"selector":{"version":"blue"}}}'
          - name: Scale up blue
            command: kubectl scale deployment/app-blue --replicas=3
```

---

## JSON Schema Reference

The complete JSON Schema is available at:

- **URL:** `https://uluops.ai/schemas/pdl/v1.6.0/pipeline.json`
- **File:** `pdl-schema-v1.6.0.json`

### Schema Validation

```bash
# Validate a pipeline definition (the schema version is the one the installed udl's factory pins)
udl validate ./my-pipeline.pipeline.yaml
```

The JSON schema checks shape: closed objects, enums, the 512-code-point condition bound. The [load errors](#codes) beyond `unknown_key` and `condition_too_long` need a runtime's semantic validator. 1.5.0 named `ulu validate` and a `--schema` flag here; the validator is `udl validate`, which has no `--schema` option.

### Minimal Schema Structure

```json
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://uluops.ai/schemas/pdl/v1.6.0/pipeline.json",
  "title": "Pipeline Definition Language (PDL) Schema",
  "description": "Schema for defining multi-workflow pipelines with triggers, approvals, rollback, convergence loops, and tracker integration",
  "version": "1.6.0",
  "type": "object",
  "required": ["pipeline"],
  "properties": {
    "pipeline": {
      "type": "object",
      "required": ["interface", "stages"],
      "properties": {
        "interface": { "$ref": "#/$defs/interface" },
        "triggers": { "$ref": "#/$defs/triggers" },
        "environment": { "$ref": "#/$defs/environment" },
        "stages": { "$ref": "#/$defs/stages" },
        "convergence": { "$ref": "#/$defs/convergence" },
        "rollback": { "$ref": "#/$defs/rollback" },
        "notifications": { "$ref": "#/$defs/notifications" },
        "artifacts": { "$ref": "#/$defs/artifacts" },
        "state": { "$ref": "#/$defs/state" },
        "postflight": { "$ref": "#/$defs/postflight" },
        "scoring": { "$ref": "#/$defs/scoring" }
      }
    }
  }
}
```

---

## Revision History

| Version | Date | Changes |
|---------|------|---------|
| 1.6.0 | 2026-10-26 | Added **[Execution Semantics (normative)](#execution-semantics-normative)**: one run model and stage status set (PASSED, WARNED, FAILED, SKIPPED, ERRORED), `all_gates_passed` as the saved verdict, gates that read a decision (`gate.decision`, the output contract, a token rule, one 13-token register), per-agent thresholds, a closed condition language with three roots and Kleene error propagation, one dependency rule (any terminal status satisfies; `abort` skips only dependents), the step working directory and template rules, output forwarding, and the warning, refusal and load-error codes. Schema: `gate`, `stage` and `agentRef` closed; `on_failure: fail`; stage `description`, `forward`, `receives`; `agentRef.threshold`; `gate.decision`; `pipeline.scoring`; conditions bounded at 512 code points. Conformance fixtures: `uluops-agent-workflows/udl/pdl/conformance/` (154 cases). Design record, decisions D1-D35 and their rejected alternatives: `uluops-specifications/specs/cross-repo/drafts/pdl-1_6_0/`. Two rulings made while this text was written (Alex, 2026-10-26): `!` precedes only a reference or a parenthesised expression (core read `!a == 'x'` as `!(a == 'x')`, the design text as `(!a) == 'x'`, and the fixture could not tell them apart); WDL 3.2.0's `on_fail: skip` defaults the decision key to `not_negative`. Four more after the code review of the factory build (review run #73, Alex, 2026-10-26): process substitution joins the placement rule's forbidden contexts (D38); a template may not be a step command's first word (D39); a condition string literal holds no control character (D40); the condition bound is 512 code points (D41). Also corrected: Design Principle 1 and the composition rules forbade direct agent references, which 1.2.0 had added; the Failure Modes table described `abort` as halting the pipeline and listed a `rollback` mode not in the enum; examples used `trigger.*`, `context.*`, ordering comparisons and `condition: "true"` in stage and agent conditions, and `{{ stages.… }}` and `{{ trigger.… }}` templates in step commands, none of which a runtime resolves under 1.6.0 (conditions on triggers, rollback, workflow and command refs, artifacts and postflight are free strings and were left as written); the JSON Schema Reference named 1.2.0 and a `ulu validate --schema` flag that does not exist. **Revised 2026-10-27 (D43, Alex), before any runtime shipped 1.6.0 execution:** a stage with no gate never fails the run; it is judged as a `warn` gate with the `not_negative` decision key (the text first said it behaves as `fail`). **Revised 2026-10-31 (R-D12; D12, D44–D47, Alex):** an absent decision behind a blocking gate makes the agent unjudgeable, whatever its score, on every target (it was handled as neutral, an interim rule awaiting a measurement that read 10.56 per 100 against a threshold of 1); the agent's JSON output is its envelope, an object carrying `result` (or the runtime's own schema-enforced structured output), so a fragment found inside a cut-off block is not read; rendered agents write one `Decision: <TOKEN>` line. Conformance fixtures: 163 cases. |
| 1.5.0 | 2026-07-15 | Added **decision-gated convergence**. `convergence.gate` now accepts `satisfied_by` (a set of completion Decision tokens, e.g. `[DRAINED]`) as an alternative to `threshold` — schema-enforced mutually exclusive, exactly one required; `aggregate` is permitted only with `threshold`. A decision gate terminates the loop on the gate stage's Decision (a single executor-type agent's `completion.vocabulary`): terminal-complete (`satisfied_by`) converges, continue-class runs remaining loop stages, failure-class is `ERRORED`. Decision gates carry no score — an all-decision-only loop is headlined by `convergence.decision` with `average_score` omitted (never 0), and a loop that updates issue lifecycle in place (`allow_executor_issue_updates`) submits no postflight `recommendations` (re-reporting would fingerprint-reopen resolved issues). Motivated by `issue-remediation` (batcher `BATCHED`/`DRAINED`), which previously faked the gate as `threshold: 100`. Validation rules 8 (error, schema) + 9 (warning). |
| 1.4.0 | 2026-07-11 | Convergence hardening from the first live run (aristotle-convergence on sdk-core, 4 iterations). Added `stall_iterations` (default 2) + `on_stall`: the loop exits `UNCONVERGED`/`exit_reason: stalled` after N consecutive iterations applying zero mechanical fixes — the score provably cannot move by the loop's own mechanism, so remaining iterations are triage residue, not progress. Added `tracker` policy: `suppress_agent_saves` (default true — loop-stage agent prompts carry a no-save contract; postflight is the single owner of run persistence, preventing orphaned sub-run rows) with an `allow_executor_issue_updates` exception (issue-level updates on pre-existing issues stay allowed). Added `convergence.exit_reason` (`converged`/`max_iterations`/`stalled`/`user_pause`) to the postflight namespace. Validation rule 7 (warning): `stall_iterations < max_iterations`. |
| 1.3.0 | 2026-07-11 | Added pipeline-level `convergence` block for iterative fix loops. Designated `loop_stages` re-execute until a score gate (`gate.stages` + `aggregate` + `threshold`) passes or `max_iterations` is reached. Gate evaluates immediately after gate stages complete (fresh-score exit, no wasted fix cycle). Non-loop stages run once post-loop. Non-convergence is a first-class `UNCONVERGED` outcome (`on_max_iterations: warn`). Executable construct enforced by the PDL runtime — distinct in kind from the descriptive `iteration` block WDL 3.0.0 removed. |
| 1.2.0 | 2026-03-07 | Added `agents` execution primitive for direct agent invocation by `subagent_type` identifier. New `agentRef` schema type with `ref` (kebab-case, no version), optional `model` (sonnet/opus/haiku), `args`, `condition`, and `timeout`. Eliminates CDL indirection for pipeline-internal agent orchestration. |
| 1.1.0 | 2026-03-07 | Added postflight block for tracker persistence integration. Tracker sub-block configures automatic `save_run` calls with field mappings, token metric collection, and save verification. Conditional handlers (`on_success`, `on_failure`, `always`) for post-completion actions. |
| 1.0.0 | 2026-01-14 | Initial PDL specification. Multi-workflow/command orchestration with stages, triggers (git_push, pull_request, schedule, webhook, manual), environment (variables, secrets), approvals (multi-level, conditional), rollback (strategies, triggers, actions), notifications (slack, email, github_status, webhook), artifacts (retention, compression), and state (persistence, tracking). Interface block consistent with ADL/CDL/WDL. |

---

## Appendix: Type Definitions

### Common Types

```typescript
type Domain = 
  | 'software' 
  | 'legal' 
  | 'medical' 
  | 'financial' 
  | 'scientific' 
  | 'content' 
  | 'general'
  | 'career'
  | 'compliance'
  | 'business'
  | 'education'
  | 'documentation'
  | 'security';

type TriggerType = 
  | 'git_push' 
  | 'pull_request' 
  | 'schedule' 
  | 'webhook' 
  | 'manual' 
  | 'pipeline';

type PullRequestAction = 
  | 'opened' 
  | 'closed' 
  | 'synchronize' 
  | 'reopened' 
  | 'labeled' 
  | 'unlabeled'
  | 'review_requested'
  | 'review_submitted'
  | 'converted_to_draft'
  | 'ready_for_review';

type NotificationChannel = 
  | 'slack' 
  | 'email' 
  | 'github_status' 
  | 'webhook' 
  | 'pagerduty' 
  | 'teams';

type NotificationEvent = 
  | 'started' 
  | 'stage_started' 
  | 'stage_complete'
  | 'approval_required'
  | 'approved'
  | 'rejected'
  | 'success' 
  | 'failure' 
  | 'rollback'
  | 'timeout';

type RollbackStrategy = 
  | 'revert_to_last_success' 
  | 'revert_to_previous' 
  | 'custom' 
  | 'none';

type GateAction = 'abort' | 'fail' | 'warn' | 'skip';   // skip: deprecated alias of fail

type GateDecision = 'not_negative' | 'positive' | 'ignore';

type StageStatus = 'PASSED' | 'WARNED' | 'FAILED' | 'SKIPPED' | 'ERRORED';   // terminal statuses

type ApprovalTimeoutBehavior = 'reject' | 'approve' | 'extend' | 'pause';

type VersionReq = 
  | string                    // Exact: "1.0.0"
  | `>=${string}`            // Minimum: ">=1.0.0"
  | `^${string}`             // Compatible: "^1.0.0"
  | `~${string}`             // Patch: "~1.0.0"
  | 'latest';                // Latest published
```

### Interface Types

```typescript
interface PipelineInterface {
  name: string;              // Kebab-case identifier
  version: string;           // SemVer
  displayName: string;       // Human-readable (3-50 chars)
  description: string;       // Usage description (20-500 chars)
  domain: Domain;
  subdomain?: string;
  tags?: string[];
}
```

### Trigger Types

```typescript
interface Trigger {
  type: TriggerType;
}

interface GitPushTrigger extends Trigger {
  type: 'git_push';
  branches?: string[];
  tags?: string[];
  paths?: {
    include?: string[];
    exclude?: string[];
  };
}

interface PullRequestTrigger extends Trigger {
  type: 'pull_request';
  actions?: PullRequestAction[];
  branches?: string[];
  paths?: {
    include?: string[];
    exclude?: string[];
  };
}

interface ScheduleTrigger extends Trigger {
  type: 'schedule';
  cron: string;
  timezone?: string;
  skip_if_running?: boolean;
}

interface WebhookTrigger extends Trigger {
  type: 'webhook';
  event: string;
  secret?: string;
  payload_filter?: string;
}

interface ManualTrigger extends Trigger {
  type: 'manual';
  allowed: boolean;
  parameters?: Parameter[];
}

interface Parameter {
  name: string;
  type: 'string' | 'boolean' | 'number';
  default?: any;
  required?: boolean;
  options?: any[];
  pattern?: string;
}
```

### Environment Types

```typescript
interface Environment {
  variables?: Variable[];
  secrets?: Secret[];
}

interface Variable {
  name: string;
  value: string;
  stages?: string[];
}

interface Secret {
  name: string;
  required?: boolean;
  stages?: string[];
  provider?: string;
  path?: string;
}
```

### Stage Types

```typescript
interface Stage {
  id: string;
  name: string;
  description?: string;
  depends_on?: string[];
  condition?: string;          // condition language, <= 512 chars
  timeout?: number;
  parallel?: boolean;
  sequential?: boolean;
  forward?: 'auto' | 'none' | 'full';
  receives?: 'auto' | 'none';
  workflows?: WorkflowRef[];
  commands?: CommandRef[];
  agents?: AgentRef[];
  steps?: Step[];
  gate?: Gate;
  artifacts?: Artifact[];
  approval?: Approval;
  env?: Record<string, string>;
  inputs?: Record<string, string>;
  outputs?: Output[];
  artifacts_from?: string[];
}

interface AgentRef {
  ref: string;                 // subagent_type identifier, no version
  model?: 'sonnet' | 'opus' | 'haiku';
  args?: Record<string, any>;
  threshold?: number;          // integer 0-100; per-agent mode
  condition?: string;          // condition language, <= 512 chars
  timeout?: number;            // >= 1000
}

interface WorkflowRef {
  ref: string;
  args?: Record<string, any>;
  condition?: string;
  timeout?: number;
}

interface CommandRef {
  ref: string;
  args?: Record<string, any>;
  condition?: string;
  timeout?: number;
}

interface Step {
  name: string;
  command: string;
  working_dir?: string;
  env?: Record<string, string>;
  timeout?: number;
  continue_on_error?: boolean;
  always_run?: boolean;
  retries?: number;
  retry_delay?: number;
  expect_empty?: boolean;
  expect_match?: string;
}

interface Gate {
  threshold?: number;
  aggregate?: 'min' | 'max' | 'average';
  decision?: GateDecision;
  on_failure?: GateAction;
  on_success?: 'continue' | 'skip_remaining';
}

interface Convergence {
  loop_stages: string[];
  gate: ConvergenceGate;
  max_iterations: number;
  min_iterations?: number;
  on_max_iterations?: 'warn' | 'abort';
  stall_iterations?: number;
  on_stall?: 'warn' | 'abort';
  tracker?: ConvergenceTrackerPolicy;
  carry_context?: boolean;
}

interface ConvergenceTrackerPolicy {
  suppress_agent_saves?: boolean;
  allow_executor_issue_updates?: boolean;
}

interface ConvergenceGate {
  stages: string[];
  aggregate?: 'min' | 'max' | 'average';   // score gates only
  threshold?: number;                      // exactly one of threshold / satisfied_by
  satisfied_by?: string[];                 // decision gate (1.5.0)
}

interface Output {
  name: string;
  value?: string;
  command?: string;
}

interface Scoring {
  method?: 'average' | 'weighted_average' | 'min' | 'max' | 'sum';
  weights?: Record<string, number>;
  decisions?: { label: string; min_score?: number; max_score?: number; description?: string }[];   // reserved
}
```

### Approval Types

```typescript
interface Approval {
  required: boolean | string;
  approvers?: string[];
  min_approvals?: number;
  timeout_hours?: number;
  timeout_behavior?: ApprovalTimeoutBehavior;
  auto_reject_on_change?: boolean;
  allow_self_approval?: boolean;
  skip_for?: SkipCondition[];
  notification?: ApprovalNotification;
}

interface SkipCondition {
  branches?: string[];
  authors?: string[];
  labels?: string[];
}

interface ApprovalNotification {
  channels: string[];
  message?: string;
}
```

### Rollback Types

```typescript
interface Rollback {
  enabled: boolean;
  strategy: RollbackStrategy;
  triggers?: RollbackTrigger[];
  actions?: Record<string, RollbackAction>;
  preserve_logs?: boolean;
  notify_on_rollback?: boolean;
  max_rollback_attempts?: number;
}

interface RollbackTrigger {
  condition: string;
  action: string;
}

interface RollbackAction {
  steps: Step[];
  timeout?: number;
  notify?: boolean;
}
```

### Notification Types

```typescript
interface Notifications {
  channels?: NotificationChannelConfig[];
  templates?: Record<string, string>;
  rate_limit?: RateLimit;
}

interface NotificationChannelConfig {
  type: NotificationChannel;
  events: NotificationEvent[];
  // Type-specific fields
  webhook?: string;
  channel?: string;
  recipients?: string[];
  url?: string;
  method?: string;
  headers?: Record<string, string>;
  context?: string;
  enabled?: boolean;
}

interface RateLimit {
  max_per_hour?: number;
  deduplicate?: boolean;
}
```

### Artifact Types

```typescript
interface Artifact {
  name: string;
  path?: string;
  source?: string;
  format?: 'json' | 'yaml' | 'raw';
  retention_days?: number;
  compression?: 'gzip' | 'none';
  required?: boolean;
  condition?: string;
}
```

### State Types

```typescript
interface State {
  persistence: boolean;
  ttl?: string;
  tracked?: string[];
  custom?: CustomState[];
  conditions?: StateConditions;
}

interface CustomState {
  name: string;
  value: string;
  on?: 'success' | 'failure' | 'always';
}

interface StateConditions {
  pause_on_consecutive_failures?: number;
  require_manual_after_rollback?: boolean;
}
```

### Postflight Types

```typescript
interface Postflight {
  tracker?: PostflightTracker;
  on_success?: PostflightAction[];
  on_failure?: PostflightAction[];
  always?: PostflightAction[];
}

interface PostflightTracker {
  enabled?: boolean;               // Default: true
  project?: string;                // Tracker project name
  workflow_type?: string;          // Workflow type for tracker run
  include_token_metrics?: boolean; // Default: true
  token_metrics_command?: string;  // Command to extract metrics
  field_mappings?: PostflightFieldMappings;
  verify_save?: boolean;           // Default: true
}

interface PostflightFieldMappings {
  score_source?: string;           // Default: "stage.gate.score"
  status_source?: string;          // Default: "stage.gate.decision"
  model_source?: string;           // Default: "agent-metrics"
  recommendations_source?: string; // Default: "stage.output.issues"
}

interface PostflightAction {
  description: string;
  command?: string;
  condition?: string;
}
```

### Complete Pipeline Type

```typescript
interface Pipeline {
  interface: PipelineInterface;
  triggers?: Trigger[];
  environment?: Environment;
  stages: Stage[];
  convergence?: Convergence;
  rollback?: Rollback;
  notifications?: Notifications;
  artifacts?: Artifact[];
  state?: State;
  postflight?: Postflight;
  scoring?: Scoring;
}
```
