sf-agent-framework
Version:
AI Agent Orchestration Framework for Salesforce Development - Two-phase architecture with 70% context reduction
540 lines (429 loc) • 12.1 kB
Markdown
# Workflow Management Utility - Agent Instructions
## Purpose
This utility provides instructions for AI agents on sophisticated workflow
orchestration capabilities including decision trees, handoff protocols, and
quality gates for complex multi-agent workflows.
## Agent Instructions
### When to Use Workflow Management
Apply workflow management when:
- Coordinating multi-agent processes
- Managing complex project phases
- Implementing quality gates
- Handling conditional logic
- Orchestrating parallel tasks
- Managing agent handoffs
- Tracking project progress
This utility provides sophisticated workflow orchestration capabilities
including decision trees, handoff protocols, and quality gates for complex
multi-agent workflows.
## Core Concepts
### 1. Workflow Definition
A workflow is a structured sequence of steps that may include:
- Linear progression
- Conditional branching
- Parallel execution
- Loops and iterations
- Quality gates
- Agent handoffs
### 2. Decision Trees
Decision trees guide workflow branching based on conditions:
```mermaid
graph TD
A[Start] --> B{Project Type?}
B -->|Greenfield| C[New Implementation Path]
B -->|Brownfield| D[Enhancement Path]
C --> E{Complexity?}
E -->|Simple| F[Fast Track]
E -->|Complex| G[Full Process]
D --> H[Assessment]
```
### 3. Workflow States
Each workflow step can be in one of these states:
- **Pending**: Not yet started
- **Active**: Currently in progress
- **Blocked**: Waiting for dependency
- **Complete**: Successfully finished
- **Failed**: Error occurred
- **Skipped**: Conditionally bypassed
## Workflow Components
### 1. Workflow Header
```yaml
workflow:
id: salesforce-deployment
name: Salesforce Deployment Pipeline
version: 1.0
triggers:
- manual
- scheduled
- event-based
prerequisites:
- code-review-complete
- tests-passing
```
### 2. Step Definition
```yaml
steps:
- id: validate-package
name: Validate Deployment Package
agent: sf-devops
inputs:
- source-branch
- target-org
conditions:
- has-metadata-changes
success-criteria:
- validation-successful
- no-errors
on-failure: rollback
timeout: 30m
```
### 3. Decision Points
```yaml
decisions:
- id: deployment-type
question: 'What type of deployment?'
options:
- value: quick-deploy
label: 'Quick Deploy (validated in last 4 days)'
conditions:
- recent-validation-exists
next-step: execute-quick-deploy
- value: standard
label: 'Standard Deployment'
next-step: run-validation
- value: destructive
label: 'Deployment with Destructive Changes'
next-step: review-destructive-changes
```
### 4. Parallel Execution
```yaml
parallel:
- id: quality-checks
name: Run Quality Checks in Parallel
branches:
- id: security-scan
agent: sf-security
task: security-audit
- id: performance-test
agent: sf-qa
task: performance-benchmark
- id: code-analysis
agent: sf-developer
task: static-analysis
join-condition: all-success
```
### 5. Quality Gates
```yaml
quality-gates:
- id: pre-production-gate
criteria:
- test-coverage: '>= 85%'
- security-scan: 'pass'
- performance: 'meets-baseline'
- approval: 'product-owner'
failure-action: block-progression
```
### 6. Agent Handoffs
```yaml
handoffs:
- from: sf-developer
to: sf-qa
trigger: code-complete
context:
- changed-components
- test-scenarios
- known-issues
message: 'Code ready for testing. Focus on {{risk-areas}}.'
- from: sf-qa
to: sf-devops
trigger: testing-complete
context:
- test-results
- deployment-package
- environment-config
message: 'Testing complete. Ready for deployment to {{target-env}}.'
```
## Workflow Execution
### 1. Initialization
```javascript
workflow.initialize({
id: 'salesforce-deployment',
context: {
project: 'Q4-Release',
environment: 'production',
urgency: 'normal',
},
});
// Document folder structure is automatically ensured
// This happens as part of workflow initialization
```
### 1a. Document Structure Initialization
When a workflow starts, it automatically ensures the document folder structure:
```javascript
// Internal workflow initialization includes:
function initializeWorkflow(workflowId, context) {
// Standard workflow initialization...
// Ensure document folders exist
const folderResult = ensureDocumentFolders(workflowId);
console.log(`Document structure initialized:`);
console.log(`✓ ${folderResult.existingFolders} folders already existed`);
console.log(`✓ ${folderResult.createdFolders} folders created`);
console.log(`✓ Total: ${folderResult.totalFolders} folders ready`);
// Continue with workflow execution...
}
```
### 2. State Management
```javascript
// Check current state
const currentStep = workflow.getCurrentStep();
console.log(`Currently at: ${currentStep.name}`);
console.log(`Status: ${currentStep.status}`);
// Update state
workflow.updateStepStatus(stepId, 'complete', {
completedBy: 'sf-developer',
duration: '2h 15m',
outputs: { packageId: 'pkg-123' },
});
```
### 3. Decision Handling
```javascript
// Present decision to user
const decision = workflow.getDecision('deployment-type');
console.log(decision.question);
decision.options.forEach((opt, idx) => {
console.log(`${idx + 1}. ${opt.label}`);
});
// Process decision
workflow.processDecision('deployment-type', 'quick-deploy');
```
### 4. Progress Tracking
```javascript
const progress = workflow.getProgress();
console.log(`Overall Progress: ${progress.percentage}%`);
console.log(`Steps Complete: ${progress.completed}/${progress.total}`);
console.log(`Time Elapsed: ${progress.elapsed}`);
console.log(`Estimated Remaining: ${progress.estimated}`);
```
## Advanced Features
### 1. Conditional Logic
```yaml
conditions:
has-apex-changes:
evaluate: '{{changes.apex.length}} > 0'
is-high-risk:
evaluate: |
{{changes.affects-integration}} == true OR
{{changes.modifies-permissions}} == true OR
{{target-env}} == "production"
business-hours:
evaluate: 'currentTime.isBusinessHours()'
```
### 2. Workflow Templates
```yaml
templates:
standard-salesforce-deployment:
inherits: base-deployment
overrides:
- test-requirements:
coverage: 85
types: ['unit', 'integration']
- approval-requirements:
roles: ['product-owner', 'tech-lead']
```
### 3. Event Handling
```yaml
events:
on-step-complete:
- log-progress
- notify-stakeholders
- update-dashboard
on-quality-gate-failure:
- alert-team
- create-blocker-ticket
- pause-workflow
on-workflow-complete:
- generate-summary
- archive-artifacts
- trigger-next-workflow
```
### 4. Rollback Procedures
```yaml
rollback:
trigger:
- deployment-failure
- post-deployment-issues
- manual-request
steps:
- capture-current-state
- restore-previous-version
- validate-restoration
- notify-stakeholders
```
## Integration with Agents
### Agent Registration
Agents register their workflow capabilities:
```yaml
agent-capabilities:
sf-developer:
can-handle:
- code-development
- unit-testing
- code-review
handoff-to:
- sf-qa
- sf-architect
sf-qa:
can-handle:
- test-execution
- bug-reporting
- test-automation
handoff-to:
- sf-developer
- sf-devops
```
### Context Passing
When handing off between agents:
```javascript
const handoffContext = {
workflow: {
id: "salesforce-deployment",
currentStep: "testing",
previousSteps: [...],
globalContext: {...}
},
stepSpecific: {
componentsToTest: [...],
testPriority: "high",
knownIssues: [...]
},
instructions: "Focus on integration tests for the new APIs"
};
```
## Best Practices
### 1. Workflow Design
- **Single Responsibility**: Each step should have one clear purpose
- **Explicit Dependencies**: Clearly define what each step needs
- **Graceful Failures**: Always define failure handling
- **Progress Visibility**: Make state observable at all times
### 2. Quality Gates
- **Measurable Criteria**: Use quantifiable metrics
- **Automated Checks**: Minimize manual validation
- **Clear Escalation**: Define who can override gates
- **Audit Trail**: Log all gate decisions
### 3. Agent Coordination
- **Clear Handoffs**: Explicit context and expectations
- **No Assumptions**: Pass all needed information
- **Feedback Loops**: Allow agents to clarify
- **Progress Updates**: Regular status communication
### 4. Error Handling
- **Graceful Degradation**: Continue what's possible
- **Clear Error Messages**: Explain what went wrong
- **Recovery Options**: Provide ways to proceed
- **Learning Integration**: Capture failure patterns
## Example: Salesforce Deployment Workflow
```yaml
workflow:
id: sf-standard-deployment
name: Standard Salesforce Deployment
steps:
- id: requirements-review
agent: sf-analyst
validates: requirements-complete
- id: development
agent: sf-developer
parallel:
- apex-development
- lwc-development
- flow-development
- id: code-review
agent: sf-architect
quality-gate: architecture-approved
- id: testing
agent: sf-qa
branches:
- unit-tests
- integration-tests
- ui-tests
- id: security-review
agent: sf-security
conditions:
- has-permission-changes
- is-production-bound
- id: deployment-prep
agent: sf-devops
tasks:
- package-creation
- validation-run
- backup-current-state
- id: deployment
agent: sf-devops
decision: deployment-window
approval-required: true
- id: post-deployment
parallel:
- smoke-tests: sf-qa
- monitoring: sf-devops
- documentation: sf-analyst
```
This workflow ensures proper coordination between all Salesforce team members
while maintaining quality standards and providing clear progress visibility.
## Document Folder Management
### Automatic Folder Creation
Workflows automatically ensure document folder structure on initialization:
```javascript
// When workflow starts
workflow.on('start', async () => {
// Load folder configuration
const folderConfig = await loadFolderStructures();
// Get agents involved in workflow
const workflowAgents = workflow.getAgents();
// Ensure all required folders exist
const result = await ensureDocumentFolders({
workflowId: workflow.id,
agents: workflowAgents,
config: folderConfig,
});
// Log results
workflow.log('Document structure ready', result);
});
```
### Folder Structure Integration
```yaml
workflow:
id: salesforce-greenfield
document-folders:
auto-create: true # Enable automatic folder creation
base-path: ./docs # Base directory for all documentation
preserve-existing: true # Don't overwrite existing folders
create-readme: true # Add README.md to each folder
```
### Agent-Specific Folders
Each agent ensures its folders exist on activation:
```javascript
agent.on('activate', () => {
const agentFolders = getFoldersForRole(agent.role);
ensureAgentFolders(agentFolders);
});
```
### Document Handoff Context
Handoffs include document folder locations:
```yaml
handoffs:
- from: sf-analyst
to: sf-architect
context:
- requirements-docs: ./docs/requirements/
- process-maps: ./docs/process-documentation/
- gap-analysis: ./docs/gap-analysis/
message: 'Requirements complete. Documents in standard folders.'
```
### Manual Folder Management
Agents can manually ensure folders:
```bash
# From any agent
*ensure-folders
# For specific workflow
*ensure-folders --workflow=salesforce-data-migration
# Check folder status
*folder-status
```