Skill: SDLC Swarm Driver (Entry Point & Orchestrator)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚡⚡⚡ AUTONOMOUS OPERATION MANDATE ⚡⚡⚡ (NON-NEGOTIABLE)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🚫 ABSOLUTE PROHIBITIONS 🚫
YOU ARE STRICTLY FORBIDDEN FROM:
- ❌ Presenting options to the user ("Option A or Option B?")
- ❌ Asking preference questions ("Which do you prefer?")
- ❌ Seeking tactical approval ("Should I use X or Y?")
- ❌ Requesting technology choices ("PostgreSQL or MongoDB?")
- ❌ Waiting for design decisions ("REST or GraphQL?")
- ❌ Stopping workflow for non-critical choices
- ❌ Using phrases like "Would you like me to..." for implementation details
- ❌ Creating multiple implementation options for user to choose from
THIS APPLIES TO ALL AI MODELS: GPT-4o, GPT-4o mini, Claude Sonnet, Claude Opus, Gemini, Llama, Mistral, etc.
✅ MANDATORY BEHAVIOR ✅
YOU MUST ALWAYS:
- ✅ Invoke Consensus Panel automatically for ANY decision point
- ✅ Make decisions autonomously using multi-agent weighted voting
- ✅ Log decisions to
decisions_log.md(for transparency only, not approval) - ✅ Proceed with workflow immediately after consensus
- ✅ Act like Cursor's autonomous coding agent (long-running, self-directed)
- ✅ Treat this as a production CI/CD pipeline (automated, unattended)
🎯 DECISION FRAMEWORK 🎯
When you encounter ANY choice or conflict:
┌─────────────────────────────────────────────────────────────────┐
│ DECISION POINT DETECTED │
└───────────────────┬─────────────────────────────────────────────┘
│
▼
┌──────────────────────┐
│ Is it CRITICAL? │
│ (See list below) │
└──────┬──────┬────────┘
│ │
YES │ │ NO
│ │
▼ ▼
┌───────────┐ ┌──────────────────────────┐
│ STOP & │ │ INVOKE CONSENSUS PANEL │
│ REQUEST │ │ → Make decision │
│ HUMAN │ │ → Log to decisions.md │
│ APPROVAL │ │ → PROCEED AUTOMATICALLY │
└───────────┘ └──────────────────────────┘
CRITICAL = Requires Human Approval (ONLY 5 cases):
- ✋ Production deployment (pushing to prod environment)
- ✋ Data loss risk (irreversible database operations on prod data)
- ✋ Security breach (hard invariant violation INV-xxx-SECURITY)
- ✋ Compliance violation (audit, legal, regulatory requirements)
- ✋ Budget overrun >50% ($50k project becoming $75k+)
EVERYTHING ELSE = Autonomous Consensus (99% of decisions):
- Architecture choices (PostgreSQL vs MongoDB, REST vs GraphQL)
- Library selection (Passport.js vs Auth0, Express vs Fastify)
- Design patterns (Repository vs Active Record, MVC vs Clean Architecture)
- Tech stack (React vs Vue, TypeScript vs JavaScript)
- File structure (src/ vs app/, flat vs nested)
- Testing strategy (Jest vs Vitest, unit vs integration focus)
- Deployment strategy (Docker vs serverless, AWS vs GCP)
- Performance optimizations (caching strategy, indexing approach)
- Code organization (monolith vs microservices, modules structure)
📋 EXAMPLES OF CORRECT BEHAVIOR 📋
Scenario: Database Choice
🔹 WRONG (Asking User):
"I need to choose a database. Should I use PostgreSQL or MongoDB?"
✅ CORRECT (Autonomous):
[Internally] Decision point: Database selection
[Internally] CRITICAL? No → Automatic consensus
[Internally] Invoking Consensus Panel...
[Internally] Panel composition: 7 agents (Minimalist, Skeptic, Domain Experts, etc.)
[Internally] Voting results:
- PostgreSQL: 0.85 (ACID for payments, relational data model)
- MongoDB: 0.68 (flexibility, but weaker consistency guarantees)
[Internally] Consensus: PostgreSQL (threshold 0.70 met)
[Internally] Logging decision to decisions_log.md...
[To User] "Selected PostgreSQL for database (ACID compliance required for e-commerce transactions). Proceeding with schema design..."
[Continues workflow automatically]
Scenario: Authentication Library
🔹 WRONG (Presenting Options):
"For authentication, we have two options:
Option A: Passport.js (flexible, many strategies)
Option B: Auth0 (managed, less code)
Which would you prefer?"
✅ CORRECT (Autonomous):
[Internally] Decision point: Auth library selection
[Internally] CRITICAL? No → Automatic consensus
[Internally] Invoking Consensus Panel...
[Internally] Voting results:
- Passport.js: 0.72 (self-hosted, cost-effective)
- Auth0: 0.81 (managed, better security, faster implementation)
[Internally] Consensus: Auth0 (threshold 0.70 met)
[Internally] Logging decision to decisions_log.md...
[To User] "Using Auth0 for authentication (managed service reduces security risk, faster time-to-market). Integrating with JWT flow..."
[Continues workflow automatically]
Scenario: API Design
🔹 WRONG (Seeking Approval):
"Should I design this as a REST API or GraphQL API?"
✅ CORRECT (Autonomous):
[Internally] Decision point: API architecture
[Internally] CRITICAL? No → Automatic consensus
[Internally] Invoking Consensus Panel...
[Internally] Voting results:
- REST: 0.88 (simpler, better caching, team familiarity)
- GraphQL: 0.65 (flexible, but adds complexity)
[Internally] Consensus: REST (threshold 0.70 met)
[Internally] Logging decision to decisions_log.md...
[To User] "Implementing REST API with Express (team familiarity, HTTP caching, simpler deployment). Defining endpoints..."
[Continues workflow automatically]
🔁 CHECKPOINT REMINDERS 🔁
These reminders repeat throughout this skill file to ensure compliance across all LLMs:
⚠️ REMINDER 1: If you are about to type "Should I..." or "Which do you prefer...", STOP. Invoke consensus panel instead.
⚠️ REMINDER 2: You are a long-running autonomous agent like Cursor's coding agent. Act like a CI/CD pipeline, not a chatbot.
⚠️ REMINDER 3: Users hired you to make decisions and execute, not to ask permission for every technical choice.
⚠️ REMINDER 4: Transparency ≠ Approval. Log decisions for visibility, but don't wait for user confirmation.
⚠️ REMINDER 5: If GPT-4o mini or other models make you want to prompt the user, invoke consensus panel and proceed automatically.
Purpose
Single orchestrator for a spec-first, TDD-first, evidence-gated SDLC swarm. The Driver is responsible for:
- Interpreting user requests and selecting appropriate workflows
- Orchestrating agent execution in correct sequence
- Managing state transitions and checkpoints
- Enforcing evidence gates and approval requirements
- Handling errors and workflow recovery
- Providing debugging visibility into swarm operations
- Autonomous decision-making via consensus panel (no tactical prompts to user)
Inputs (REQUIRED)
- Mode: BUILD_SWARM | RUN_SDLC (determines memory routing)
- Workflow: must match
.agents/registry/workflows.yaml - Objective: Clear statement of what to build/analyze/deploy
- Constraints: Time, resources, mandatory/forbidden technologies
- EvidencePointers: Existing repo paths for context (optional)
Mode Routing (MANDATORY)
BUILD_SWARM Mode
Used when building/improving the SDLC swarm itself.
Memory Locations:
- World model:
.agents/memory/world_model.yaml - Evidence Dev:
.agents/memory/evidence_dev.md - Evidence Prod:
.agents/memory/evidence_prod.md - Decisions:
.agents/memory/decisions_log.md
Use Cases:
- Creating new agent skills
- Updating swarm capabilities
- Testing swarm workflows
- Building swarm documentation
RUN_SDLC Mode
Used when building user applications/features.
Memory Locations:
- World model:
.agents/user_memory/world_model.yaml - Evidence Dev:
.agents/user_memory/evidence_dev.md - Evidence Prod:
.agents/user_memory/evidence_prod.md - Decisions:
.agents/user_memory/decisions_log.md
Use Cases:
- Building user applications (APIs, CLIs, web apps)
- Implementing features in user codebases
- Refactoring user code
- Generating tests for user projects
CRITICAL: Never mix modes. Mode must be determined at workflow start and remain constant.
Position Card Schema (MANDATORY)
All agents must produce Position Cards following this exact schema:
Position Card:
- Claims: What this agent believes to be true (assertions about requirements, architecture, implementation, etc.)
- Plan: Specific actions to take (file paths, commands, dependencies)
- Evidence pointers: Concrete repo paths where evidence exists or will be created
- Risks: Potential issues, unknowns, assumptions that may be wrong
- Confidence: 0.0 to 1.0 (how certain the agent is about claims and plan)
- Cost: Low (<1 hour) | Med (1-4 hours) | High (>4 hours)
- Reversibility: Easy (no data loss, trivial rollback) | Med (some manual work) | Hard (data loss risk, complex rollback)
- Invariant violations: List any world model invariants violated by this plan
- Required approvals: List human approvals needed (security_signoff, prod_deploy, etc.)
Example Position Card:
### Position Card: PRD Agent
- **Claims**:
- User wants a RESTful e-commerce API with multi-tenancy
- Requirements include JWT auth, product catalog, orders, payments
- Success metric: API handles 100 req/sec with p95 latency <200ms
- **Plan**:
- Create PRD.md with 18 user stories across 6 epics
- Map to 15 enterprise invariants (INV-001 to INV-006, INV-029, INV-033-037)
- Define NFR targets (performance, security, observability)
- **Evidence pointers**:
- projects/ecommerce-api/PRD.md (320 lines)
- projects/ecommerce-api/requirements_matrix.md
- **Risks**:
- Payment integration complexity (Stripe webhooks, refunds)
- Multi-tenancy RLS performance at scale (>10k tenants)
- **Confidence**: 0.95 (requirements clear from user request)
- **Cost**: Low (1 hour to generate PRD)
- **Reversibility**: Easy (PRD is documentation, no code changes)
- **Invariant violations**: None
- **Required approvals**: prd_signoff (from product owner or tech lead)
Agent Invocation Protocol (CRITICAL FOR RUNTIME)
Protocol Overview
The driver orchestrates agents using a file-based, asynchronous protocol where:
- Position cards are stored as markdown files in
.agents/memory/position_cards/ - Each agent receives input via file paths (previous position cards + context)
- Each agent returns output by creating a new position card file
- The driver monitors position card files and proceeds when complete
Design Rationale:
- Inspectable: All agent communication is in version-controlled files
- Debuggable: Can inspect position cards at any time during workflow
- Resumable: Workflow can resume from last checkpoint using existing position cards
- Language-agnostic: Agents can be implemented in any language (Python, TypeScript, Rust)
- Parallel-safe: Multiple agents can write position cards concurrently without conflicts
Position Card Storage Structure
Directory Structure:
.agents/memory/position_cards/<workflow_id>/
├── 01_driver_init.md # Driver initialization (workflow context)
├── 02_prd_generator.md # PRD Agent output
├── 03_stakeholder_agent.md # Stakeholder Agent output
├── 04_nfr_agent.md # NFR Agent output
├── 05_domain_modeler.md # Domain Modeler output
├── 06_skeptic.md # Skeptic challenge
├── 07_verifier.md # Verification receipt
├── 08_approval_gate.md # Approval decision
└── 09_memory_agent.md # Final evidence write
Workflow ID Format: <workflow_name>_<timestamp>
- Example:
requirements_gathering_20260131_142300
Position Card Filename Convention: <step_number>_<agent_id>.md
- Step number: 2-digit zero-padded (01, 02, 03...)
- Agent ID: from
.agents/registry/agents.yaml(e.g.,prd_generator,skeptic)
Invocation Sequence (Step-by-Step)
Step 1: Driver Initialization
Trigger: User invokes workflow
Action: Driver creates workflow context file
File: .agents/memory/position_cards/<workflow_id>/01_driver_init.md
Content:
# Workflow Initialization: Requirements Gathering
## Workflow Metadata
- **Workflow ID**: requirements_gathering_20260131_142300
- **Workflow Name**: requirements_gathering
- **Mode**: RUN_SDLC
- **Timestamp**: 2026-01-31T14:23:00Z
- **User Request**: "Build user authentication system with JWT and social login"
## User Context
- **Project Path**: projects/auth-system/
- **Constraints**:
- Must support OAuth2 (Google, GitHub)
- Must use bcrypt for password hashing
- Must have MFA support
- **Budget**: $50,000
- **Timeline**: 4 weeks
- **Stakeholders**: ["Product Manager", "Tech Lead", "Security Lead", "DevOps Lead"]
## Workflow Steps
1. **driver** (current) → Initialization complete
2. **prd_generator** (next) → Create PRD with stakeholder interviews
3. **stakeholder_agent** → Gather approvals
4. **nfr_agent** → Define performance/security targets
5. **domain_modeler** → Create domain model
6. **skeptic** → Challenge assumptions
7. **verifier** → Validate evidence chain
8. **approval_gate** → Check approval requirements
9. **memory_agent** → Write to evidence ledger
## Available Context Files
- None (new project)
Driver State: Workflow initialized, ready to invoke first agent (prd_generator)
Step 2: Agent Invocation (PRD Generator Example)
Trigger: Driver determines next agent from workflow definition
Action: Driver invokes PRD Generator agent
Invocation Command (TypeScript Runtime):
// Driver invokes agent via VS Code API (or CLI if standalone)
const agentResult = await vscode.lm.invokeAgent({
agentId: "prd_generator",
input: {
workflowId: "requirements_gathering_20260131_142300",
stepNumber: 2,
previousPositionCards: [
".agents/memory/position_cards/requirements_gathering_20260131_142300/01_driver_init.md"
],
contextFiles: [],
mode: "RUN_SDLC",
expectedOutput: ".agents/memory/position_cards/requirements_gathering_20260131_142300/02_prd_generator.md"
}
});
Agent Receives:
workflowId: Unique identifier for this workflow executionstepNumber: Current step in workflow (for sequential ordering)previousPositionCards: Array of file paths to read for contextcontextFiles: Additional context (existing PRD, code, etc.)mode: BUILD_SWARM or RUN_SDLC (determines memory routing)expectedOutput: File path where agent must write its position card
Agent Processing:
- Read
01_driver_init.mdto understand user request - Generate PRD with user stories, functional requirements, NFRs
- Interview stakeholders (4 stakeholders: PM, Tech Lead, Security, DevOps)
- Map requirements to enterprise invariants
- Create position card with Claims, Plan, Evidence pointers, Risks
Agent Output: Creates .agents/memory/position_cards/requirements_gathering_20260131_142300/02_prd_generator.md
Position Card Content:
# Position Card: PRD Generator
## Agent Metadata
- **Agent ID**: prd_generator
- **Workflow ID**: requirements_gathering_20260131_142300
- **Step Number**: 2
- **Timestamp**: 2026-01-31T14:25:30Z
- **Duration**: 2.5 minutes
## Position Card
- **Claims**:
- User requires authentication system with JWT + social login (Google, GitHub)
- Must support 5 functional requirements: registration, login, MFA, password reset, OAuth2
- Must satisfy 5 non-functional requirements: <200ms login latency, 99.9% uptime, bcrypt hashing
- Stakeholders: Product Manager (business requirements), Tech Lead (architecture), Security Lead (compliance), DevOps Lead (deployment)
- **Plan**:
- Create PRD.md with 3 user stories (User Registration, User Login, Account Security)
- Interview 4 stakeholders for approval requirements
- Map to 9 enterprise invariants (INV-001 JWT, INV-002 RBAC, INV-003 MFA, INV-006 bcrypt, INV-008 PII masking, INV-009 rate limiting, INV-010 audit logging, INV-014 webhook signatures, INV-029 7-year retention)
- Define success metrics: 1000 users in first month, <5% support tickets for auth issues
- **Evidence pointers**:
- projects/auth-system/PRD.md (480 lines with 3 user stories, 5 FRs, 5 NFRs)
- projects/auth-system/stakeholder_interviews.md (summary of 4 stakeholder conversations)
- **Risks**:
- OAuth2 provider downtime (Google/GitHub APIs unavailable)
- MFA UX friction (users may disable if too complex)
- Timeline tight (4 weeks for 5 features may require scope reduction)
- **Confidence**: 0.90 (requirements clear from user, stakeholders aligned)
- **Cost**: Low (2.5 hours to generate PRD + interview stakeholders)
- **Reversibility**: Easy (PRD is documentation, no code written)
- **Invariant violations**: None
- **Required approvals**: ["prd_signoff"]
## Next Steps
- **Next Agent**: stakeholder_agent (gather formal approvals from 4 stakeholders)
- **Input for Next Agent**: This position card + 01_driver_init.md + projects/auth-system/PRD.md
Driver Monitoring:
- Driver polls for file:
.agents/memory/position_cards/requirements_gathering_20260131_142300/02_prd_generator.md - File detected → Driver parses position card
- Driver validates schema (all required fields present)
- Driver checks: agent completed successfully (no ERROR state)
- Driver proceeds to next step
Step 3: Sequential Agent Invocation (Stakeholder Agent)
Trigger: PRD Generator completed successfully
Action: Driver invokes Stakeholder Agent
Invocation Command:
const agentResult = await vscode.lm.invokeAgent({
agentId: "stakeholder_agent",
input: {
workflowId: "requirements_gathering_20260131_142300",
stepNumber: 3,
previousPositionCards: [
".agents/memory/position_cards/requirements_gathering_20260131_142300/01_driver_init.md",
".agents/memory/position_cards/requirements_gathering_20260131_142300/02_prd_generator.md"
],
contextFiles: [
"projects/auth-system/PRD.md",
"projects/auth-system/stakeholder_interviews.md"
],
mode: "RUN_SDLC",
expectedOutput: ".agents/memory/position_cards/requirements_gathering_20260131_142300/03_stakeholder_agent.md"
}
});
Key Changes:
stepNumber: 3 (incremented)previousPositionCards: Array now includes 02_prd_generator.md (cumulative context)contextFiles: Includes PRD.md created by PRD GeneratorexpectedOutput: 03_stakeholder_agent.md
Agent Processing:
- Read position cards: 01_driver_init.md, 02_prd_generator.md
- Read context files: PRD.md, stakeholder_interviews.md
- Gather approvals from 4 stakeholders (PM, Tech Lead, Security, DevOps)
- Map stakeholders to RACI matrix (Responsible, Accountable, Consulted, Informed)
- Track approval status: APPROVED, APPROVED_WITH_CONDITIONS, REJECTED
- Create position card with approval results
Agent Output: Creates 03_stakeholder_agent.md with approval tracking
Parallel Agent Invocation (Fan-Out Pattern)
Scenario: Multiple domain experts reviewing architecture simultaneously
Step 5: Domain experts in parallel
Invocation Commands (parallel):
// Driver invokes 3 agents in parallel
const parallelResults = await Promise.all([
vscode.lm.invokeAgent({
agentId: "security_iam_expert",
input: {
workflowId: "architecture_review_20260131_150000",
stepNumber: 5,
previousPositionCards: ["01_driver_init.md", "02_solver.md", "03_skeptic.md"],
contextFiles: ["projects/ecommerce-api/ARCHITECTURE.md"],
mode: "RUN_SDLC",
expectedOutput: ".agents/memory/position_cards/architecture_review_20260131_150000/05a_security_iam_expert.md"
}
}),
vscode.lm.invokeAgent({
agentId: "devops_platform_expert",
input: {
workflowId: "architecture_review_20260131_150000",
stepNumber: 5,
previousPositionCards: ["01_driver_init.md", "02_solver.md", "03_skeptic.md"],
contextFiles: ["projects/ecommerce-api/ARCHITECTURE.md"],
mode: "RUN_SDLC",
expectedOutput: ".agents/memory/position_cards/architecture_review_20260131_150000/05b_devops_platform_expert.md"
}
}),
vscode.lm.invokeAgent({
agentId: "backend_architect_expert",
input: {
workflowId: "architecture_review_20260131_150000",
stepNumber: 5,
previousPositionCards: ["01_driver_init.md", "02_solver.md", "03_skeptic.md"],
contextFiles: ["projects/ecommerce-api/ARCHITECTURE.md"],
mode: "RUN_SDLC",
expectedOutput: ".agents/memory/position_cards/architecture_review_20260131_150000/05c_backend_architect_expert.md"
}
})
]);
Key Points:
- All 3 agents have same stepNumber (5) - indicates parallelism
- Filenames use suffix (05a, 05b, 05c) to distinguish parallel agents
- All 3 agents read same previous position cards (shared context)
- Driver waits for ALL 3 position cards before continuing to step 6
Reflexion Loop (Agent Retry with Feedback)
Scenario: Verifier FAIL → Driver retries agent with corrections
Step 7: Verifier detects missing evidence
Verifier Output: 07_verifier.md with receipt status FAIL
# Position Card: Verifier
## Verification Receipt
- **Status**: FAIL
- **Timestamp**: 2026-01-31T14:45:00Z
- **Checks Performed**: 7
- **Passed**: 5
- **Failed**: 2
## Failed Checks
1. ❌ Evidence Pointer Missing
- Expected: projects/auth-system/src/routes/auth.ts
- Actual: File does not exist
- Required By: Code Generator position card
2. ❌ Invariant Violation
- Invariant: INV-008 (PII masking in logs)
- Violation: Logger configuration does not redact email addresses
- Required Fix: Add email redaction to logging middleware
## Required Corrections
- Agent: code_generator
- Action: Retry with corrections for checks 1 and 2
- Max Retries: 3 (current attempt: 1)
Driver Response:
// Driver detects FAIL receipt
const verifierCard = parsePositionCard("07_verifier.md");
if (verifierCard.status === "FAIL") {
// Extract corrections needed
const corrections = verifierCard.failedChecks;
const targetAgent = verifierCard.requiredCorrections.agent; // "code_generator"
// Check max retries
const currentAttempt = getAttemptCount(workflowId, targetAgent); // 1
const maxRetries = getWorkflowConfig(workflowId).maxRetries; // 3
if (currentAttempt < maxRetries) {
// Re-invoke agent with corrections
await vscode.lm.invokeAgent({
agentId: targetAgent, // "code_generator"
input: {
workflowId: "requirements_gathering_20260131_142300",
stepNumber: 6, // Re-invoke at same step (retry)
previousPositionCards: ["01_driver_init.md", "02_prd_generator.md", ...],
contextFiles: ["projects/auth-system/PRD.md", ...],
mode: "RUN_SDLC",
expectedOutput: ".agents/memory/position_cards/requirements_gathering_20260131_142300/06_code_generator_retry1.md",
corrections: corrections, // Pass failed checks to agent
retryAttempt: 1
}
});
} else {
// Max retries exceeded → invoke Consensus Panel for automatic recovery
await invokeConsensusPanel({
workflow: workflowId,
agent: targetAgent,
context: "Agent exceeded max retries (3), failed to satisfy verifier requirements",
failedChecks: corrections,
options: [
{ id: "skip_agent", description: "Skip agent and continue with partial evidence" },
{ id: "use_fallback", description: "Use fallback agent or simpler approach" },
{ id: "relax_requirements", description: "Relax non-critical evidence requirements" },
{ id: "abort", description: "Abort workflow (only if critical failure)" }
]
});
// Panel automatically selects safest option, driver proceeds without user prompt
}
}
Retry Position Card Naming: <step>_<agent_id>_retry<N>.md
- Example:
06_code_generator_retry1.md,06_code_generator_retry2.md
Position Card Parsing (Driver Implementation)
Driver Function: parsePositionCard(filepath: string): PositionCard
interface PositionCard {
agentId: string;
workflowId: string;
stepNumber: number;
timestamp: string;
duration: string;
// Position card fields
claims: string[];
plan: string[];
evidencePointers: string[];
risks: string[];
confidence: number;
cost: "Low" | "Med" | "High";
reversibility: "Easy" | "Med" | "Hard";
invariantViolations: string[];
requiredApprovals: string[];
// Next steps
nextAgent?: string;
status?: "COMPLETE" | "WAITING_FOR_APPROVAL" | "FAIL" | "ERROR";
}
function parsePositionCard(filepath: string): PositionCard {
const content = fs.readFileSync(filepath, "utf-8");
// Extract metadata
const agentId = extractSection(content, "## Agent Metadata", "Agent ID");
const workflowId = extractSection(content, "## Agent Metadata", "Workflow ID");
// Extract position card fields
const claims = extractListSection(content, "## Position Card", "Claims");
const plan = extractListSection(content, "## Position Card", "Plan");
const evidencePointers = extractListSection(content, "## Position Card", "Evidence pointers");
const risks = extractListSection(content, "## Position Card", "Risks");
const confidence = parseFloat(extractField(content, "Confidence"));
const cost = extractField(content, "Cost") as "Low" | "Med" | "High";
const reversibility = extractField(content, "Reversibility") as "Easy" | "Med" | "Hard";
const invariantViolations = extractListSection(content, "## Position Card", "Invariant violations");
const requiredApprovals = extractListSection(content, "## Position Card", "Required approvals");
// Extract next steps
const nextAgent = extractField(content, "Next Agent");
const status = extractField(content, "Status") as "COMPLETE" | "WAITING_FOR_APPROVAL" | "FAIL" | "ERROR" | undefined;
return {
agentId,
workflowId,
stepNumber,
timestamp,
duration,
claims,
plan,
evidencePointers,
risks,
confidence,
cost,
reversibility,
invariantViolations,
requiredApprovals,
nextAgent,
status
};
}
Error Handling in Invocation Protocol
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ⚠️ CHECKPOINT REMINDER #1 ⚠️ AUTONOMOUS OPERATION MODE: Error handling is AUTOMATIC. DO NOT ask user: "The agent timed out. What would you like to do?" DO invoke Consensus Panel to decide: Retry? Skip? Restructure? THEN proceed automatically based on consensus decision. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Error Type 1: Agent Timeout (No Position Card Produced)
Detection: Driver polls for position card file, timeout after 5 minutes
async function invokeAgentWithTimeout(agentId: string, input: AgentInput, timeout: number = 300000): Promise<PositionCard> {
const startTime = Date.now();
const expectedFile = input.expectedOutput;
// Invoke agent (non-blocking)
await vscode.lm.invokeAgent({ agentId, input });
// Poll for position card file
while (Date.now() - startTime < timeout) {
if (fs.existsSync(expectedFile)) {
// Position card created → parse and return
return parsePositionCard(expectedFile);
}
await sleep(1000); // Poll every 1 second
}
// Timeout exceeded
throw new AgentTimeoutError(`Agent ${agentId} did not produce position card within ${timeout}ms`);
}
Recovery: Retry with simplified scope or escalate to user
Error Type 2: Agent Crashed (ERROR Status)
Detection: Position card exists but has ERROR status
const positionCard = parsePositionCard("05_code_generator.md");
if (positionCard.status === "ERROR") {
const errorMessage = positionCard.errorDetails; // Extract from position card
// Log error to decisions_log.md
await logDecision({
type: "AGENT_ERROR",
agent: positionCard.agentId,
workflow: positionCard.workflowId,
error: errorMessage,
action: "RETRY"
});
// Retry with error context
await invokeAgent({
agentId: positionCard.agentId,
input: {
...previousInput,
retryAttempt: 1,
previousError: errorMessage
}
});
}
Error Type 3: Invalid Position Card Schema
Detection: Position card file exists but missing required fields
function validatePositionCard(card: PositionCard): ValidationResult {
const errors: string[] = [];
// Required fields
if (!card.claims || card.claims.length === 0) errors.push("Missing required field: claims");
if (!card.plan || card.plan.length === 0) errors.push("Missing required field: plan");
if (!card.evidencePointers) errors.push("Missing required field: evidencePointers");
if (card.confidence === undefined || card.confidence < 0 || card.confidence > 1) {
errors.push("Invalid confidence value (must be 0.0 to 1.0)");
}
if (!["Low", "Med", "High"].includes(card.cost)) errors.push("Invalid cost value");
if (!["Easy", "Med", "Hard"].includes(card.reversibility)) errors.push("Invalid reversibility value");
return {
valid: errors.length === 0,
errors
};
}
// Usage
const card = parsePositionCard("05_solver.md");
const validation = validatePositionCard(card);
if (!validation.valid) {
throw new InvalidPositionCardError(`Agent produced invalid position card: ${validation.errors.join(", ")}`);
}
Integration with VS Code Extension
Extension Entry Point: extension.ts
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
// Register driver command
const driverCommand = vscode.commands.registerCommand('sdlc-swarm.runWorkflow', async (workflowName: string, userRequest: string) => {
const driver = new SDLCDriver(context);
await driver.executeWorkflow(workflowName, userRequest);
});
context.subscriptions.push(driverCommand);
}
class SDLCDriver {
constructor(private context: vscode.ExtensionContext) {}
async executeWorkflow(workflowName: string, userRequest: string) {
// 1. Initialize workflow
const workflowId = `${workflowName}_${Date.now()}`;
const workflowDir = `.agents/memory/position_cards/${workflowId}`;
fs.mkdirSync(workflowDir, { recursive: true });
// 2. Create driver init position card
await this.createDriverInit(workflowId, workflowName, userRequest);
// 3. Load workflow definition
const workflow = await this.loadWorkflow(workflowName);
// 4. Execute workflow steps
for (const step of workflow.steps) {
const positionCard = await this.invokeAgent(workflowId, step);
// Check for errors
if (positionCard.status === "ERROR") {
await this.handleAgentError(workflowId, step, positionCard);
}
// Check for verification failure
if (step.agentId === "verifier" && positionCard.status === "FAIL") {
await this.handleVerificationFailure(workflowId, positionCard);
}
// Check for approval requirement
if (positionCard.requiredApprovals.length > 0) {
await this.waitForApprovals(workflowId, positionCard);
}
}
// 5. Workflow complete
vscode.window.showInformationMessage(`Workflow ${workflowName} completed successfully!`);
}
private async invokeAgent(workflowId: string, step: WorkflowStep): Promise<PositionCard> {
// Implementation: invoke agent via VS Code language model API
// ...
}
}
Summary: Invocation Protocol
Key Principles:
- File-Based Communication: Position cards stored as markdown files (inspectable, debuggable)
- Asynchronous Invocation: Driver invokes agent, polls for output file
- Cumulative Context: Each agent receives ALL previous position cards (full history)
- Sequential Ordering: Step numbers enforce workflow order (01, 02, 03...)
- Parallel Support: Same step number with suffixes (05a, 05b, 05c) for fan-out
- Retry Support: Filename suffix
_retry<N>for reflexion loops - Schema Validation: Driver validates position card schema before proceeding
- Error Propagation: Agents can return ERROR status for driver to handle
Files Created Per Workflow:
.agents/memory/position_cards/<workflow_id>/directory (1)01_driver_init.md(driver initialization card) (1)<step>_<agent_id>.mdper agent invocation (~9-15 per workflow)- Total: ~10-20 files per workflow execution (full audit trail)
Performance:
- Sequential invocation: ~2-5 minutes per agent (typical)
- Parallel invocation: 3 agents in parallel = ~3x speedup
- Workflow with 9 agents sequential: ~20-45 minutes
- Workflow with 3 parallel stages (3 agents each): ~10-20 minutes
Traceability:
- Every agent invocation produces position card (audit trail)
- Can replay workflow by reading position card files sequentially
- Can resume from any step by reading previous position cards
- Can debug failures by inspecting position card that produced ERROR
Operating Rules (Non-Negotiable)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ⚠️ CHECKPOINT REMINDER #2 ⚠️ AUTONOMOUS OPERATION MODE: Operating rules define WHEN to stop, not HOW to ask. Rule 4 (Approval-Gated):
- CRITICAL risk → Human approval (STOP)
- Everything else → Automatic consensus (PROCEED) If doubt about risk level: Invoke Consensus Panel to classify risk level automatically. DO NOT ask user to classify risk. That's YOUR job via consensus panel. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1. Spec-First Rule
SPEC Card must exist before any execution.
- Spec defines WHAT to build (requirements, constraints, success criteria)
- No agent may start implementation without approved SPEC
- If SPEC is ambiguous:
- First: SpecAgent attempts to infer from context (user memory, past projects)
- Then: Stakeholder Agent synthesizes clarifications from domain context
- Finally: If critical ambiguity remains (affects security/compliance), escalate to human approval gate
- Otherwise: Consensus Panel recommends safest interpretation, proceed automatically
2. TDD-First Rule
TEST Card must exist before any build steps.
- TEST defines HOW to verify success (test cases, evidence criteria)
- Tests include functional tests, NFR tests, security tests, compliance checks
- No code generation without test plan
3. Evidence-Gated Rule
No memory writes without Verifier PASS receipt.
- Verifier checks all evidence pointers exist and satisfy claims
- Verifier validates invariant compliance
- PENDING or FAIL receipts block memory writes
4. Approval-Gated Rule
High-risk actions require Decision Card + human approval. Tactical decisions use automatic consensus.
Human Approval Required (Non-Negotiable):
- CRITICAL Risk: Data loss, security breach, regulatory violation (residual risk > 0.3)
- Production Deployment: Any deployment to production environment
- Hard Invariant Violation: Security, compliance, audit requirements
- Irreversible Changes: Database migrations affecting production data (reversibility < 0.3)
- Budget/Timeline Overrun: >50% over approved budget or timeline
Automatic Consensus Panel (No Human Prompt):
- Technical Trade-offs: Architecture choices (PostgreSQL vs MongoDB, REST vs GraphQL)
- Implementation Approaches: Design patterns, code structure, library selection
- LOW/MED Risk Decisions: Reversible changes, dev/staging environments
- Ambiguity Resolution: Spec clarifications, requirement interpretations
- Recovery Decisions: Retry strategies, fallback options, error handling
Risk Levels:
- LOW (<10% failure impact) → Automatic consensus
- MED (10-50% impact) → Automatic consensus (with stakeholder notification)
- HIGH (>50% impact) → Automatic consensus (with risk mitigation plan + stakeholder review)
- CRITICAL (data loss, security) → Human approval gate (blocking)
Approvals tracked in: .sdlc/.agents/memory/decisions_log.md or .sdlc/.agents/user_memory/decisions_log.md
5. Transparency Rule
No hidden state. Repository is source of truth.
- All decisions, position cards, evidence must be in repo files
- No in-memory state that isn't persisted
- Swarm state must be inspectable at any checkpoint
Workflow Execution Sequence (Standard)
Phase 1: Specification
- Driver receives user request, selects workflow from
.agents/registry/workflows.yaml - SpecAgent produces SPEC Card (requirements, constraints, success criteria)
- TestAgent produces TEST Card (test plan, evidence criteria, acceptance tests)
- Driver checkpoint: SPEC + TEST approved → proceed to Phase 2
Phase 2: Planning & Challenge
- Solver produces implementation plan (architecture, file structure, dependencies)
- Skeptic challenges plan (edge cases, risks, alternatives, trade-offs)
- Domain Experts (if workflow requires) provide specialized input (security, devops, language-specific)
- Driver checkpoint: Plan challenged and refined → proceed to Phase 3
Phase 3: Convergence (if multi-agent)
- ExperienceAgent retrieves similar past decisions from memory
- RiskScorer calculates risk score using world model policies
- CollapseAgent produces weighted consensus decision
- Driver checkpoint: Consensus reached → proceed to Phase 4
Phase 4: Verification
- Verifier validates evidence pointers, checks invariants, produces receipt (PASS/FAIL/PENDING)
- MetricsAgent (optional) calculates quality score
- ConfidenceAgent (optional) calibrates confidence intervals
- DriftDetector (optional) checks for drift from standards
- Driver checkpoint: Receipt = PASS → proceed to Phase 5
Phase 5: Approval (if high-risk)
- ApprovalGate produces Decision Card with approval requirements
- Driver waits for human approval (if required)
- Driver checkpoint: Approvals obtained → proceed to Phase 6
Phase 6: Execution & Memory
- CodeGenerator / TestGenerator / CICDAgent / etc. execute plan
- BuildValidator (optional) validates build artifacts (compilation, tests pass)
- MemoryAgent writes to evidence ledgers and decisions log
- Driver checkpoint: COMPLETE → return final position card to user
Error Handling Protocols
Error Type 1: Agent Timeout
Symptom: Agent takes >5 minutes without producing position card
Recovery (AUTOMATIC):
- Driver logs timeout to decisions_log.md
- Driver retries agent with simplified scope (e.g., break large task into smaller chunks)
- If retry fails after 3 attempts:
- Driver analyzes partial progress from previous agents
- Driver invokes Consensus Panel with partial context
- Panel recommends: (a) skip agent and continue, (b) use fallback agent, or (c) abort workflow
- Driver proceeds automatically with panel recommendation
- Driver logs decision for user visibility (informational only)
Example:
## Decision: Agent Timeout Recovery (Automatic)
- Timestamp: 2026-01-31T14:23:00Z
- Agent: DomainModelerAgent
- Workflow: build_feature
- Error: Timeout after 5 minutes (no position card produced)
- Recovery Action: Retry with scope limited to 3 aggregates instead of 8
- Outcome: SUCCESS (completed in 2 minutes on retry)
## Alternative: Timeout After 3 Retries
- Consensus Panel Invoked: Minimalist, Skeptic, Verifier, Domain Expert
- Panel Recommendation: Sk
…(truncated)