Composite Workflows

Composite Workflows

Architecture and usage guide for scenario composition and orchestration.

Table of Contents

Overview

Composite workflows allow scenarios to act as orchestrators, invoking multiple sub-scenarios for comprehensive analysis. This enables complex, multi-faceted code analysis without requiring users to run scenarios individually.

Key Benefits

  • Comprehensive Analysis: Combine security, performance, and quality checks
  • Deduplication: Automatically merge and deduplicate findings
  • Conflict Resolution: Resolve conflicting recommendations
  • Priority Scoring: Rank findings by combined priority metrics
  • Single Entry Point: One command for complete analysis

Architecture

┌─────────────────────────────────────────────────────────────────────────────┐
│                        COMPOSITE WORKFLOW ARCHITECTURE                       │
│                                                                              │
│  User Query: "Optimize src/"                                                 │
│        │                                                                     │
│        ▼                                                                     │
│  ┌────────────────────────────────────────────────────────────────────────┐ │
│  │                    ORCHESTRATOR (S18 or S19)                            │ │
│  │                                                                          │ │
│  │  ┌─────────────────────────────────────────────────────────────────┐   │ │
│  │  │                   SCENARIO INVOKER                               │   │ │
│  │  │                                                                   │   │ │
│  │  │  Parallel Execution:                                              │   │ │
│  │  │  ┌─────┐  ┌─────┐  ┌─────┐  ┌─────┐  ┌─────┐                    │   │ │
│  │  │  │ S02 │  │ S05 │  │ S06 │  │ S11 │  │ S12 │                    │   │ │
│  │  │  │Sec. │  │Refac│  │Perf │  │Arch │  │Debt │                    │   │ │
│  │  │  └──┬──┘  └──┬──┘  └──┬──┘  └──┬──┘  └──┬──┘                    │   │ │
│  │  │     │        │       │        │        │                         │   │ │
│  │  │     └────────┴───────┴────────┴────────┘                         │   │ │
│  │  │                      │                                            │   │ │
│  │  │              Sub-Scenario Results                                 │   │ │
│  │  └──────────────────────┼───────────────────────────────────────────┘   │ │
│  │                         │                                                │ │
│  │  ┌──────────────────────▼───────────────────────────────────────────┐   │ │
│  │  │                    RESULT MERGER                                  │   │ │
│  │  │                                                                   │   │ │
│  │  │  Strategy: union | intersection | weighted | consensus            │   │ │
│  │  │  - Deduplication (similarity threshold: 0.8)                      │   │ │
│  │  │  - Source tracking                                                │   │ │
│  │  │  - Metadata preservation                                          │   │ │
│  │  └──────────────────────┼───────────────────────────────────────────┘   │ │
│  │                         │                                                │ │
│  │  ┌──────────────────────▼───────────────────────────────────────────┐   │ │
│  │  │                  CONFLICT RESOLVER                                │   │ │
│  │  │                                                                   │   │ │
│  │  │  Mode: priority_based | security_first | interactive              │   │ │
│  │  │  - Detect conflicting recommendations                             │   │ │
│  │  │  - Apply resolution rules                                         │   │ │
│  │  │  - Log resolution decisions                                       │   │ │
│  │  └──────────────────────┼───────────────────────────────────────────┘   │ │
│  │                         │                                                │ │
│  │  ┌──────────────────────▼───────────────────────────────────────────┐   │ │
│  │  │                 PRIORITY CALCULATOR                               │   │ │
│  │  │                                                                   │   │ │
│  │  │  Algorithm: weighted_sum | risk_based | custom                    │   │ │
│  │  │  Weights: severity(0.3) × impact(0.25) × roi(0.2)                 │   │ │
│  │  │           × confidence(0.15) × consensus(0.1)                     │   │ │
│  │  └──────────────────────┼───────────────────────────────────────────┘   │ │
│  │                         │                                                │ │
│  └─────────────────────────┼────────────────────────────────────────────────┘ │
│                            │                                                  │
│                            ▼                                                  │
│                   UNIFIED FINDINGS                                            │
│                   (sorted by priority)                                        │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘

S18 as Orchestrator

Scenario 18 (Code Optimization) orchestrates multiple analysis scenarios for comprehensive code improvement:

Sub-Scenarios

Scenario Name Weight Contribution
S02 Security Audit 1.5 Security vulnerabilities
S05 Refactoring 1.0 Code smells, dead code
S06 Performance 1.2 Performance bottlenecks
S11 Architecture 1.1 Architecture violations
S12 Tech Debt 0.9 Technical debt items

Execution Flow

S18 Optimization Query
        │
        ├─→ S02: Security Analysis
        ├─→ S05: Refactoring Analysis
        ├─→ S06: Performance Analysis
        ├─→ S11: Architecture Analysis
        └─→ S12: Tech Debt Analysis
                │
                ▼
        Merge Findings (weighted)
                │
                ▼
        Resolve Conflicts
                │
                ▼
        Calculate Priorities
                │
                ▼
        Unified Optimization Report

Example Usage

# CLI
codegraph composition run "Optimize src/core/" -o s18

# TUI
/select 18
> Analyze src/core/ for comprehensive optimization

Output

╭─────────────── Composite Optimization Results ────────────────╮
                                                                
  Sub-scenarios invoked: S02, S05, S06, S11, S12                
  Findings before merge: 87                                     
  Findings after merge: 52                                      
  Duplicates removed: 35                                        
  Conflicts resolved: 3                                         
  Execution time: 4.2s                                          
                                                                
  Top Findings:                                                 
                                                                
  1. [Critical] SQL injection vulnerability                     
     Source: S02 (Security)                                     
     Priority Score: 0.95                                       
                                                                
  2. [High] Performance bottleneck in loop                      
     Source: S06 (Performance)                                  
     Priority Score: 0.87                                       
                                                                
  3. [High] Architecture layer violation                        
     Source: S11 (Architecture)                                 
     Priority Score: 0.82                                       
                                                                
╰────────────────────────────────────────────────────────────────╯

S19 as Orchestrator

Scenario 19 (Standards Check) orchestrates compliance checking with document-driven rules:

Sub-Scenarios

Scenario Name Contribution
S08 Compliance Standard compliance rules
S17 File Editing Apply fixes

Document Enrichment

S19 enriches findings with references from standards documents:

Standards Document
        │
        ▼
    Rule Extraction
        │
        ├─→ S08: Compliance Analysis
        │         │
        │         ▼
        │   Violations Found
        │         │
        │         ▼
        └─→ Document Enrichment
                  │
                  ▼
        Violations with References

Example Usage

# CLI
codegraph composition run "Check against OWASP standards" -o s19

# With custom standards document
codegraph composition run "Check against company_standards.yaml" -o s19

Composition Components

ScenarioInvoker

Invokes sub-scenarios with parallel or sequential execution:

from src.workflow.composition import ScenarioInvoker

invoker = ScenarioInvoker()

# Parallel execution (default)
results = invoker.invoke_parallel(
    scenarios=["scenario_02", "scenario_06", "scenario_11"],
    state=state,
    timeout=30.0,
)

# Sequential execution
results = invoker.invoke_sequential(
    scenarios=["scenario_02", "scenario_06"],
    state=state,
)

ResultMerger

Merges findings with configurable strategies:

from src.workflow.composition import ResultMerger, MergeStrategy

merger = ResultMerger()

# Merge with union strategy (include all)
result = merger.merge(
    scenario_results={"s02": findings_s02, "s06": findings_s06},
    strategy=MergeStrategy.UNION,
)

# Merge with weighted strategy
result = merger.merge(
    scenario_results=all_findings,
    strategy=MergeStrategy.WEIGHTED,
)

Merge Strategies

Strategy Description Use Case
union Include all findings Comprehensive analysis
intersection Only findings from 2+ scenarios High-confidence only
weighted Weight by scenario priority Prioritized analysis
consensus Findings with agreement Conservative approach

ConflictResolver

Resolves conflicting recommendations:

from src.workflow.composition import ConflictResolver

resolver = ConflictResolver()

# Resolve conflicts
resolved_findings, resolution_log = resolver.resolve_conflicts(
    findings=unified_findings,
    mode="priority_based",
)

Conflict Types

Type Description Resolution
Same Location Multiple findings for same code Keep highest priority
Contradictory Conflicting recommendations Apply resolution rules
Overlapping Partially overlapping findings Merge or choose

PriorityCalculator

Calculates combined priority scores:

from src.workflow.composition import PriorityCalculator

calculator = PriorityCalculator()

# Calculate and sort by priority
prioritized = calculator.sort_by_priority(findings)

# Get priority breakdown
breakdown = calculator.get_priority_breakdown(finding)

Priority Weights

Factor Weight Description
severity 0.30 Finding severity level
impact 0.25 Potential impact score
roi 0.20 Return on investment
confidence 0.15 Detection confidence
consensus 0.10 Cross-scenario agreement

Configuration

Configure composition in config.yaml:

composition:
  enabled: true

  orchestrators:
    scenario_18:
      sub_scenarios:
        - scenario_02  # Security
        - scenario_05  # Refactoring
        - scenario_06  # Performance
        - scenario_11  # Architecture
        - scenario_12  # Tech Debt
      parallel_execution: true
      timeout_seconds: 60
      enabled: true

    scenario_19:
      sub_scenarios:
        - scenario_08  # Compliance
        - scenario_17  # File Editing
      parallel_execution: false
      timeout_seconds: 30
      enabled: true

  merging:
    strategy: weighted  # union, intersection, weighted, consensus
    deduplication_threshold: 0.8
    max_findings: 100
    preserve_sources: true

  priority:
    algorithm: weighted_sum  # weighted_sum, risk_based, custom
    weights:
      severity: 0.30
      impact: 0.25
      roi: 0.20
      confidence: 0.15
      consensus: 0.10

  conflicts:
    resolution_mode: priority_based  # priority_based, security_first, interactive
    security_priority_boost: 1.5
    compliance_priority_boost: 1.3
    log_resolutions: true

API Endpoints

POST /api/v1/composition/query

Execute a composite workflow:

POST /api/v1/composition/query
Content-Type: application/json
Authorization: Bearer <token>

{
  "query": "Optimize src/core/",
  "orchestrator": "scenario_18",
  "context": {
    "language": "en",
    "file_paths": ["src/core/"]
  },
  "parallel": true,
  "merge_strategy": "weighted"
}

Response:

{
  "session_id": "sess_abc123",
  "answer": "Found 52 optimization opportunities...",
  "unified_findings": [...],
  "priority_scores": {...},
  "sub_scenario_results": {...},
  "conflicts_resolved": 3,
  "execution_time_ms": 4234.5,
  "metadata": {...}
}

POST /api/v1/composition/apply

Apply a pending edit from a session:

POST /api/v1/composition/apply
Content-Type: application/json
Authorization: Bearer <token>

{
  "session_id": "sess_abc123",
  "finding_id": "find_xyz789",
  "preview": true
}

GET /api/v1/composition/conflicts/{session_id}

Get conflict information for a session:

GET /api/v1/composition/conflicts/sess_abc123
Authorization: Bearer <token>

GET /api/v1/composition/session/{session_id}

Get full session state:

GET /api/v1/composition/session/sess_abc123
Authorization: Bearer <token>

GET /api/v1/composition/config

Get composition configuration:

GET /api/v1/composition/config
Authorization: Bearer <token>

CLI Commands

# Run composite workflow
codegraph composition run "<query>" -o s18|s19

# Run with specific sub-scenarios
codegraph composition run "Analyze src/" -o s18 -s scenario_02 -s scenario_06

# Run with merge strategy
codegraph composition run "Optimize code" -o s18 --merge-strategy weighted

# Apply pending edit
codegraph composition apply <finding_id> -s <session_id>

# Preview edit before applying
codegraph composition apply <finding_id> -s <session_id> --preview

# View conflicts
codegraph composition conflicts -s <session_id>

# View configuration
codegraph composition config

# List available scenarios
codegraph composition scenarios

Best Practices

1. Choose the Right Orchestrator

  • S18 for optimization: When you need performance, security, and quality improvements
  • S19 for compliance: When you need standards verification with references

2. Configure Merge Strategy

# For comprehensive analysis (include everything)
merging:
  strategy: union

# For high-confidence findings only
merging:
  strategy: intersection

# For prioritized analysis
merging:
  strategy: weighted

3. Handle Conflicts

Enable conflict logging to understand resolution decisions:

conflicts:
  log_resolutions: true

4. Optimize Performance

For large codebases, use parallel execution with timeout:

orchestrators:
  scenario_18:
    parallel_execution: true
    timeout_seconds: 120

5. Customize Priority Weights

Adjust weights based on your team’s priorities:

priority:
  weights:
    severity: 0.40  # Prioritize severity
    impact: 0.20
    roi: 0.20
    confidence: 0.10
    consensus: 0.10