# Workflow Patterns Definition
# Defines common AIOX workflow sequences for context detection
#
# Version: 1.0
# Created: 2025-01-15
# Story: 6.1.2.5 - Contextual Agent Load System
#
# Format:
# - workflow_name: Unique identifier
# - description: Human-readable workflow description
# - agent_sequence: Expected sequence of agents used
# - key_commands: Commands that signal this workflow
# - trigger_threshold: Minimum matching commands to detect pattern (default: 2)

workflows:
  # Story Development Workflow (Most Common)
  story_development:
    description: "Complete story lifecycle from validation to deployment"
    agent_sequence:
      - po         # Story validation
      - dev        # Implementation
      - qa         # Quality assurance
      - devops     # Deployment
    key_commands:
      - validate-story-draft
      - validate-next-story
      - develop
      - develop-yolo
      - develop-interactive
      - develop-preflight
      - review-qa
      - apply-qa-fixes
      - fix-qa-issues
      - run-tests
      - pre-push-quality-gate
      - github-pr-automation
    trigger_threshold: 2
    typical_duration: "1-5 days"
    success_indicators:
      - "Story status: Ready for Review"
      - "All tests passing"
      - "PR created and merged"
    # Workflow transitions (Story 6.1.2.5 - Workflow Navigation)
    transitions:
      validated:
        trigger: "validate-story-draft completed"
        confidence: 0.90
        greeting_message: "Story validated! Ready to implement."
        next_steps:
          - command: develop-yolo
            args_template: "${story_path}"
            description: "Autonomous YOLO mode (no interruptions)"
            priority: 1
          - command: develop-interactive
            args_template: "${story_path}"
            description: "Interactive mode with checkpoints (default)"
            priority: 2
          - command: develop-preflight
            args_template: "${story_path}"
            description: "Plan everything upfront, then execute"
            priority: 3
      in_development:
        trigger: "develop completed"
        confidence: 0.85
        greeting_message: "Development complete! Ready for QA review."
        next_steps:
          - command: review-qa
            args_template: "${story_path}"
            description: "Run QA review and tests"
            priority: 1
          - command: run-tests
            args_template: ""
            description: "Execute test suite manually"
            priority: 2
      qa_reviewed:
        trigger: "review-qa completed"
        confidence: 0.80
        greeting_message: "QA review complete!"
        next_steps:
          - command: apply-qa-fixes
            args_template: ""
            description: "Apply QA feedback and fixes"
            priority: 1
          - command: fix-qa-issues
            args_template: ""
            description: "Resolve structured QA fix requests"
            priority: 2
          - command: pre-push-quality-gate
            args_template: ""
            description: "Run final quality checks before push"
            priority: 3
      fixes_applied:
        trigger: "apply-qa-fixes completed"
        confidence: 0.85
        greeting_message: "QA fixes applied. Ready for final verification."
        next_steps:
          - command: run-tests
            args_template: ""
            description: "Verify fixes with tests"
            priority: 1
          - command: pre-push-quality-gate
            args_template: ""
            description: "Run final quality gate"
            priority: 2
      qa_fix_request_resolved:
        trigger: "fix-qa-issues completed"
        confidence: 0.85
        greeting_message: "QA fix request resolved. Ready for final verification."
        next_steps:
          - command: run-tests
            args_template: ""
            description: "Verify fixes with tests"
            priority: 1
          - command: pre-push-quality-gate
            args_template: ""
            description: "Run final quality gate"
            priority: 2

  # Epic Creation Workflow
  epic_creation:
    description: "Create and organize epics with initial stories"
    agent_sequence:
      - po         # Epic planning
      - sm         # Story creation
      - architect  # Technical review
    key_commands:
      - create-epic
      - brownfield-create-epic
      - create-story
      - brownfield-create-story
      - create-next-story
      - validate-story-draft
      - analyze-impact
    trigger_threshold: 2
    typical_duration: "0.5-2 days"
    success_indicators:
      - "Epic documented"
      - "Initial stories created"
      - "Stories validated"
    transitions:
      epic_drafted:
        trigger: "create-epic completed"
        confidence: 0.90
        next_steps:
          - command: analyze-epic
            args_template: "${epic_path}"
            description: "Analyze epic for completeness"
            priority: 1
          - command: create-story
            args_template: "${epic_path}"
            description: "Create first story from epic"
            priority: 2
      stories_created:
        trigger: "create-story completed"
        confidence: 0.85
        next_steps:
          - command: validate-story-draft
            args_template: "${story_path}"
            description: "Validate story structure"
            priority: 1
          - command: create-next-story
            args_template: "${epic_path}"
            description: "Create additional stories"
            priority: 2
      validated:
        trigger: "validate-story-draft completed"
        confidence: 0.80
        next_steps:
          - command: analyze-impact
            args_template: "${story_path}"
            description: "Analyze technical impact"
            priority: 1
          - command: develop
            args_template: "${story_path}"
            description: "Begin story development"
            priority: 2

  # Backlog Management Workflow
  backlog_management:
    description: "Review, prioritize, and schedule backlog items"
    agent_sequence:
      - qa         # Backlog review
      - po         # Prioritization
      - pm         # Scheduling
    key_commands:
      - backlog-add
      - backlog-update
      - backlog-review
      - backlog-debt
      - backlog-summary
      - backlog-prioritize
      - backlog-schedule
    trigger_threshold: 2
    typical_duration: "0.5-1 day"
    success_indicators:
      - "Backlog items prioritized"
      - "Sprint planned"
    transitions:
      reviewed:
        trigger: "backlog-review completed"
        confidence: 0.85
        next_steps:
          - command: backlog-prioritize
            args_template: ""
            description: "Prioritize reviewed items"
            priority: 1
          - command: backlog-debt
            args_template: ""
            description: "Review technical debt items"
            priority: 2
      prioritized:
        trigger: "backlog-prioritize completed"
        confidence: 0.90
        next_steps:
          - command: backlog-schedule
            args_template: ""
            description: "Schedule prioritized items to sprints"
            priority: 1
          - command: backlog-summary
            args_template: ""
            description: "Generate backlog summary report"
            priority: 2
      scheduled:
        trigger: "backlog-schedule completed"
        confidence: 0.80
        next_steps:
          - command: backlog-summary
            args_template: ""
            description: "Generate sprint planning summary"
            priority: 1
          - command: create-story
            args_template: ""
            description: "Create stories for scheduled items"
            priority: 2

  # Architecture Review Workflow
  architecture_review:
    description: "Design review and documentation of architectural decisions"
    agent_sequence:
      - architect  # Design and review
      - qa         # Review validation
      - dev        # Implementation planning
    key_commands:
      - analyze-impact
      - analyze-framework
      - create-doc
      - shard-doc
      - review-proposal
      - review-story
      - architect-analyze-impact
    trigger_threshold: 2
    typical_duration: "1-3 days"
    success_indicators:
      - "Architecture documented"
      - "Decision reviewed"
      - "Implementation plan approved"
    transitions:
      analyzed:
        trigger: "analyze-impact completed"
        confidence: 0.85
        next_steps:
          - command: create-doc
            args_template: "adr ${feature_name}"
            description: "Create Architecture Decision Record"
            priority: 1
          - command: review-proposal
            args_template: "${doc_path}"
            description: "Review architectural proposal"
            priority: 2
      documented:
        trigger: "create-doc completed"
        confidence: 0.90
        next_steps:
          - command: review-story
            args_template: "${story_path}"
            description: "Review story for architectural alignment"
            priority: 1
          - command: shard-doc
            args_template: "${doc_path}"
            description: "Split large documentation into sections"
            priority: 2
      approved:
        trigger: "review-proposal completed"
        confidence: 0.80
        next_steps:
          - command: create-story
            args_template: ""
            description: "Create implementation stories"
            priority: 1
          - command: develop
            args_template: "${story_path}"
            description: "Begin implementation"
            priority: 2

  # Git Workflow (DevOps)
  git_workflow:
    description: "Version control and deployment workflow"
    agent_sequence:
      - dev        # Code changes
      - devops     # Git operations
    key_commands:
      - pre-push-quality-gate
      - github-pr-automation
      - repository-cleanup
      - version-management
    trigger_threshold: 2
    typical_duration: "0.5-1 day"
    success_indicators:
      - "Changes committed"
      - "PR created"
      - "Code merged"
    transitions:
      staged:
        trigger: "git add completed"
        confidence: 0.90
        next_steps:
          - command: pre-push-quality-gate
            args_template: ""
            description: "Run quality checks before commit"
            priority: 1
          - command: git-commit
            args_template: ""
            description: "Commit staged changes"
            priority: 2
      committed:
        trigger: "git commit completed"
        confidence: 0.85
        next_steps:
          - command: github-pr-automation
            args_template: ""
            description: "Create pull request"
            priority: 1
          - command: git-push
            args_template: ""
            description: "Push to remote"
            priority: 2
      pushed:
        trigger: "git push completed"
        confidence: 0.80
        next_steps:
          - command: github-pr-automation
            args_template: ""
            description: "Create or update PR"
            priority: 1
          - command: repository-cleanup
            args_template: ""
            description: "Clean up merged branches"
            priority: 2

  # Database Development Workflow
  database_workflow:
    description: "Database schema design and migration workflow"
    agent_sequence:
      - data-engineer  # Schema design
      - dev            # Migration implementation
      - qa             # Testing
    key_commands:
      - db-domain-modeling
      - db-schema-audit
      - db-dry-run
      - db-apply-migration
      - db-rollback
      - db-smoke-test
      - db-rls-audit
      - db-verify-order
    trigger_threshold: 2
    typical_duration: "1-3 days"
    success_indicators:
      - "Schema designed"
      - "Migrations tested"
      - "RLS policies validated"
    transitions:
      designed:
        trigger: "db-domain-modeling completed"
        confidence: 0.90
        next_steps:
          - command: db-schema-audit
            args_template: ""
            description: "Audit schema for best practices"
            priority: 1
          - command: db-dry-run
            args_template: ""
            description: "Test migration in dry-run mode"
            priority: 2
      migrated:
        trigger: "db-apply-migration completed"
        confidence: 0.85
        next_steps:
          - command: db-smoke-test
            args_template: ""
            description: "Run smoke tests on migrated schema"
            priority: 1
          - command: db-rls-audit
            args_template: ""
            description: "Audit Row Level Security policies"
            priority: 2
      validated:
        trigger: "db-smoke-test completed"
        confidence: 0.80
        next_steps:
          - command: db-verify-order
            args_template: ""
            description: "Verify migration order consistency"
            priority: 1
          - command: develop
            args_template: "${story_path}"
            description: "Continue with application development"
            priority: 2

  # Code Quality Improvement Workflow
  code_quality_workflow:
    description: "Refactoring and code quality improvements"
    agent_sequence:
      - qa         # Quality assessment
      - dev        # Refactoring
    key_commands:
      - improve-code-quality
      - suggest-refactoring
      - optimize-performance
      - security-scan
      - generate-tests
      - nfr-assess
    trigger_threshold: 2
    typical_duration: "0.5-2 days"
    success_indicators:
      - "Code refactored"
      - "Tests added"
      - "Quality metrics improved"
    transitions:
      assessed:
        trigger: "nfr-assess completed"
        confidence: 0.85
        next_steps:
          - command: suggest-refactoring
            args_template: "${file_path}"
            description: "Get refactoring suggestions"
            priority: 1
          - command: security-scan
            args_template: ""
            description: "Run security scan"
            priority: 2
      refactored:
        trigger: "improve-code-quality completed"
        confidence: 0.90
        next_steps:
          - command: generate-tests
            args_template: "${file_path}"
            description: "Generate tests for refactored code"
            priority: 1
          - command: optimize-performance
            args_template: ""
            description: "Optimize performance"
            priority: 2
      tested:
        trigger: "generate-tests completed"
        confidence: 0.80
        next_steps:
          - command: nfr-assess
            args_template: ""
            description: "Re-assess NFR compliance"
            priority: 1
          - command: pre-push-quality-gate
            args_template: ""
            description: "Run quality gate before push"
            priority: 2

  # Documentation Workflow
  documentation_workflow:
    description: "Create and synchronize project documentation"
    agent_sequence:
      - analyst    # Research and analysis
      - architect  # Documentation creation
      - po         # Review
    key_commands:
      - document-project
      - sync-documentation
      - create-doc
      - shard-doc
      - index-docs
      - generate-documentation
    trigger_threshold: 2
    typical_duration: "0.5-2 days"
    success_indicators:
      - "Documentation created"
      - "Documentation synchronized"
      - "Documentation indexed"
    transitions:
      drafted:
        trigger: "create-doc completed"
        confidence: 0.85
        next_steps:
          - command: shard-doc
            args_template: "${doc_path}"
            description: "Split large documentation"
            priority: 1
          - command: index-docs
            args_template: ""
            description: "Index documentation for search"
            priority: 2
      reviewed:
        trigger: "review-doc completed"
        confidence: 0.90
        next_steps:
          - command: sync-documentation
            args_template: ""
            description: "Synchronize documentation"
            priority: 1
          - command: generate-documentation
            args_template: ""
            description: "Generate API documentation"
            priority: 2
      published:
        trigger: "sync-documentation completed"
        confidence: 0.80
        next_steps:
          - command: index-docs
            args_template: ""
            description: "Re-index documentation"
            priority: 1
          - command: document-project
            args_template: ""
            description: "Update project overview"
            priority: 2

  # UX Design Workflow
  ux_workflow:
    description: "User experience design and validation"
    agent_sequence:
      - ux-design-expert  # Design
      - dev               # Implementation
      - qa                # Validation
    key_commands:
      - ux-create-wireframe
      - ux-user-research
      - ux-ds-scan-artifact
      - build-component
      - audit-codebase
    trigger_threshold: 2
    typical_duration: "1-3 days"
    success_indicators:
      - "Wireframes created"
      - "Components implemented"
      - "UX validated"
    transitions:
      designed:
        trigger: "ux-create-wireframe completed"
        confidence: 0.90
        next_steps:
          - command: ux-user-research
            args_template: ""
            description: "Validate design with user research"
            priority: 1
          - command: ux-ds-scan-artifact
            args_template: "${wireframe_path}"
            description: "Scan for design system compliance"
            priority: 2
      implemented:
        trigger: "build-component completed"
        confidence: 0.85
        next_steps:
          - command: audit-codebase
            args_template: ""
            description: "Audit component implementation"
            priority: 1
          - command: ux-ds-scan-artifact
            args_template: "${component_path}"
            description: "Validate design system compliance"
            priority: 2
      validated:
        trigger: "ux-user-research completed"
        confidence: 0.80
        next_steps:
          - command: build-component
            args_template: ""
            description: "Implement validated designs"
            priority: 1
          - command: develop
            args_template: "${story_path}"
            description: "Continue with development"
            priority: 2

  # Brainstorming and Research Workflow
  research_workflow:
    description: "Facilitated brainstorming and research sessions"
    agent_sequence:
      - analyst    # Research
      - architect  # Analysis
      - po         # Documentation
    key_commands:
      - analyst-facilitate-brainstorming
      - advanced-elicitation
      - create-deep-research-prompt
      - kb-mode-interaction
    trigger_threshold: 2
    typical_duration: "0.5-1 day"
    success_indicators:
      - "Research completed"
      - "Ideas documented"
      - "Action items created"
    transitions:
      researched:
        trigger: "create-deep-research-prompt completed"
        confidence: 0.85
        next_steps:
          - command: analyst-facilitate-brainstorming
            args_template: "${topic}"
            description: "Facilitate brainstorming session"
            priority: 1
          - command: kb-mode-interaction
            args_template: ""
            description: "Interact with knowledge base"
            priority: 2
      analyzed:
        trigger: "analyst-facilitate-brainstorming completed"
        confidence: 0.90
        next_steps:
          - command: create-doc
            args_template: "research-findings"
            description: "Document research findings"
            priority: 1
          - command: advanced-elicitation
            args_template: ""
            description: "Deep dive on specific topics"
            priority: 2
      documented:
        trigger: "create-doc completed"
        confidence: 0.80
        next_steps:
          - command: create-epic
            args_template: ""
            description: "Create epic from research"
            priority: 1
          - command: create-story
            args_template: ""
            description: "Create actionable stories"
            priority: 2

  # Bob Orchestration Workflow (Story ACT-5)
  bob_orchestration:
    description: "Bob (PM) orchestrates multi-agent workflows via executor assignment"
    agent_sequence:
      - pm         # Bob orchestrates
      - po         # Story validation
      - dev        # Implementation
      - qa         # Quality assurance
      - devops     # Deployment
    key_commands:
      - execute-epic
      - assign-executor
      - wave-execute
      - spawn-terminal
      - orchestrate
      - sync-story
      - build-autonomous
      - build
    trigger_threshold: 2
    typical_duration: "1-5 days"
    success_indicators:
      - "Epic stories completed"
      - "All waves executed"
      - "Quality gates passed"
    transitions:
      epic_started:
        trigger: "execute-epic started"
        confidence: 0.90
        greeting_message: "Epic execution started! Bob is orchestrating."
        next_steps:
          - command: build-autonomous
            args_template: "${story_path}"
            description: "Start autonomous build for current story"
            priority: 1
          - command: develop-yolo
            args_template: "${story_path}"
            description: "Manual YOLO development for current story"
            priority: 2
      executor_assigned:
        trigger: "assign-executor completed"
        confidence: 0.85
        greeting_message: "Executor assigned. Ready to begin story work."
        next_steps:
          - command: develop-yolo
            args_template: "${story_path}"
            description: "Begin development in YOLO mode"
            priority: 1
          - command: build
            args_template: "${story_path}"
            description: "Full autonomous build pipeline"
            priority: 2
      wave_completed:
        trigger: "wave-execute completed"
        confidence: 0.85
        greeting_message: "Wave completed! Moving to next wave."
        next_steps:
          - command: wave-execute
            args_template: "${epic_path}"
            description: "Execute next wave"
            priority: 1
          - command: sync-story
            args_template: "${story_path}"
            description: "Sync story progress"
            priority: 2
      story_completed:
        trigger: "build completed"
        confidence: 0.90
        greeting_message: "Story build complete! Ready for next story."
        next_steps:
          - command: execute-epic
            args_template: "${epic_path} continue"
            description: "Continue epic with next story"
            priority: 1
          - command: build-status
            args_template: "--all"
            description: "Check all build statuses"
            priority: 2

# ============================================================
# State Integration (GAP-3: Guided Workflow Automation)
# ============================================================
#
# Workflow state files complement pattern-based detection.
# When a state file exists, it takes precedence over command history
# for workflow state detection.
#
state_integration:
  description: "File-based state persistence for guided workflow automation"
  state_file_location: ".aiox/{instance-id}-state.yaml"
  state_file_schema: ".aiox-core/data/workflow-state-schema.yaml"
  manager_script: ".aiox-core/development/scripts/workflow-state-manager.js"

  behavior:
    detection_priority:
      - state_file    # If active state file exists, use it
      - command_history  # Fall back to pattern-based detection
    sync:
      - "State files are created by *run-workflow {name} start"
      - "State files are updated by *run-workflow {name} continue/skip/abort"
      - "WorkflowNavigator.detectWorkflowStateFromFile() reads state files"
      - "WorkflowNavigator.suggestNextCommandsFromState() generates suggestions from state"
    session_continuity:
      - "State persists between Claude Code sessions via YAML file"
      - "generateHandoffContext() produces markdown for /handoff documents"
      - "Users resume with: *run-workflow {name} continue"

  commands:
    start: "Creates state file, validates workflow, shows step 1"
    continue: "Loads state, marks current step complete, advances, shows next step"
    status: "Shows progress bar, step checklist, artifact status"
    skip: "Skips optional step, advances to next"
    abort: "Sets status to aborted, preserves state for reference"

# ============================================================
# Cross-Context Agent Support (GAP-4: Hybrid Workflows)
# ============================================================
#
# Hybrid workflows use agents from BOTH core and squad contexts.
# This enables workflows that combine framework-level agents
# with squad-specific specialist agents.
#
cross_context:
  description: "Support for workflows that use agents from both core and squad contexts"

  resolution_rules:
    order: "squad-first, core-fallback"
    explanation: |
      When target_context=hybrid, agent references are resolved in this order:
      1. Check squad agents directory first (squads/{squad}/agents/)
      2. If not found, fall back to core agents (.aiox-core/development/agents/)
      3. If found in both, emit WF_AGENT_AMBIGUOUS warning

  explicit_prefix:
    format: "{context}:{agent_name}"
    examples:
      - "core:architect"
      - "squad:validator"
    explanation: |
      Use explicit prefix to force resolution to a specific context.
      This avoids ambiguity when an agent exists in both core and squad.

  hybrid_workflow_storage:
    location: "squads/{squad_name}/workflows/"
    explanation: |
      Hybrid workflows live in the squad directory because they are
      squad-specific (they reference squad agents). The hybrid flag
      simply tells the validator and runner to also check core agents.

  validator_behavior:
    ambiguity_warning:
      code: "WF_AGENT_AMBIGUOUS"
      trigger: "Agent name exists in both core and squad agents directories"
      suggestion: "Use explicit prefix core:{name} or squad:{name} to disambiguate"
    missing_agent_warning:
      code: "WF_AGENT_NOT_FOUND"
      trigger: "Agent name not found in either core or squad agents directories"
    backward_compatibility: |
      When squadAgentsPath is not provided (null), the validator behaves
      identically to the pre-hybrid version — only checks core agents.

# Validation Notes:
# - Patterns cross-referenced with Epic 6.1 workflow analysis
# - Commands verified against actual project usage in .aiox-core/agents/*.md
# - Agent sequences match actual workflow patterns from recent stories
# - Threshold of 2 ensures workflow detection is accurate but not overly sensitive
# - All 10 workflows now have transition definitions (Story WIS-2)
