Skip to main content

AI Agent v2.0 - Quick Reference Guide

For: Developers, Coders, Reviewers Swarm ID: swarm_1764655531178_udtox74dx


🎯 Core Concepts

The v2.0 Enhancement

v1.0: User β†’ LangChain ReAct β†’ Tool Execution β†’ Done
                    ↓
                 (Immediate action, no preview)

v2.0: User β†’ Intent Parser β†’ Plan Generator β†’ Preview β†’ Approval β†’ Execute
                    ↓              ↓             ↓          ↓          ↓
                 (What?)      (How?)      (Show)    (Confirm)   (Do)

Key Differences

Aspect v1.0 v2.0
Planning Reactive (tool-by-tool) Proactive (plan-first)
Preview None Full diff preview
Approval Automatic User confirmation
Context Basic memory RuVector + Site context
Safety Limited Rollback + validation

πŸ“¦ Module Quick Reference

TaskPlanner

What it does: Parses natural language β†’ structured action plans

Key methods:

await taskPlanner.parseIntent(message)
  β†’ { type: 'ADD_PROJECT', entities: {...}, confidence: 0.95 }

await taskPlanner.planActions(intent, context)
  β†’ ActionPlan { actions: [...], metadata: {...} }

taskPlanner.resolveDependencies(actions)
  β†’ Ordered actions (topological sort)

taskPlanner.estimateImpact(plan)
  β†’ { filesCreated: 1, filesModified: 1, risk: 'low' }

When to use:

  • Every user request that modifies the site
  • Before any file operations
  • To validate intent confidence

ChangePreview

What it does: Generates human-readable diffs

Key methods:

await changePreview.previewFileChange(filepath, newContent)
  β†’ Diff { lineDiff: [...], summary: {...} }

await changePreview.previewYamlChange(filepath, changes)
  β†’ YamlDiff { yamlDiffs: [...], summary: {...} }

await changePreview.previewPlan(plan)
  β†’ Preview { changes: [...], formattedOutput: "..." }

changePreview.formatPreview(preview)
  β†’ Formatted string for display

When to use:

  • Before any file write
  • Before user approval
  • For debugging file changes

RuVectorBridge

What it does: Connects to RuVector search/graph/recommendation engines

Key methods:

await ruvectorBridge.initialize()
  β†’ Loads indices, initializes engines

await ruvectorBridge.searchProjects(query, options)
  β†’ { results: [...], source: 'ruvector', confidence: 0.9 }

await ruvectorBridge.queryGraph('projects using React')
  β†’ { results: [...], source: 'graph' }

await ruvectorBridge.findRelated(itemId, 'project')
  β†’ { items: [...], source: 'graph' }

await ruvectorBridge.getRecommendations(context)
  β†’ { recommendations: [...], source: 'recommender' }

When to use:

  • During entity extraction (suggest related technologies)
  • When user searches for projects
  • To enrich context with graph data

SiteContext

What it does: Understands site structure and schemas

Key methods:

await siteContext.initialize()
  β†’ Analyzes site structure

await siteContext.analyzeSite()
  β†’ SiteStructure { directories, schemas, patterns, statistics }

siteContext.getContentSchema(filepath)
  β†’ Schema { required: [...], optional: [...], validation: {...} }

siteContext.getSuggestions(contentType)
  β†’ [{ type, reason, value, confidence }, ...]

siteContext.getContextPrompt()
  β†’ String with site structure for LLM context

siteContext.validateContent(content, schema)
  β†’ ValidationResult { valid: true, errors: [] }

When to use:

  • During plan generation (validate against schemas)
  • To get default values for new content
  • To generate context-aware prompts

ApprovalWorkflow

What it does: Manages user approval and execution

Key methods:

await approvalWorkflow.requestApproval(plan)
  β†’ ApprovalResult { approved: true/false, plan, reason }

await approvalWorkflow.handleModification(plan, userInput)
  β†’ ModifiedPlan (re-planned based on user feedback)

await approvalWorkflow.executePlan(approvedPlan)
  β†’ ExecutionResult { success: true, results: [...] }

approvalWorkflow.formatReport(result)
  β†’ Report string for display

When to use:

  • After preview generation
  • Before any destructive operations
  • To handle user modifications

πŸ”„ Common Workflows

1. Add Project

// 1. Parse intent
const intent = await taskPlanner.parseIntent('Add React project about e-commerce');

// 2. Enrich with site context
const context = await siteContext.analyzeSite();

// 3. Generate plan
const plan = await taskPlanner.planActions(intent, context);

// 4. Enrich with RuVector
const related = await ruvectorBridge.findRelated('React', 'technology');
// ... suggest related technologies

// 5. Preview
const preview = await changePreview.previewPlan(plan);

// 6. Request approval
const approval = await approvalWorkflow.requestApproval(plan);

// 7. Execute if approved
if (approval.approved) {
  const result = await approvalWorkflow.executePlan(approval.plan);
  console.log(approvalWorkflow.formatReport(result));
}

2. Search Projects

// 1. Parse intent
const intent = await taskPlanner.parseIntent('Find projects using React');

// 2. Search with RuVector
const results = await ruvectorBridge.searchProjects('React', {
  category: 'web-development',
  limit: 5
});

// 3. Format and display
console.log(`Found ${results.results.length} projects:`);
results.results.forEach(r => {
  console.log(`- ${r.name} (score: ${r.score})`);
});

// No approval needed (read-only)

3. Update Content

// 1. Parse intent
const intent = await taskPlanner.parseIntent('Update about page');

// 2. Generate plan
const plan = await taskPlanner.planActions(intent, siteContext);

// 3. Preview
const preview = await changePreview.previewPlan(plan);

// 4. Approval
const approval = await approvalWorkflow.requestApproval(plan);

// 5. Execute
if (approval.approved) {
  await approvalWorkflow.executePlan(approval.plan);
}

πŸ§ͺ Testing Patterns

Unit Test Pattern

describe('TaskPlanner', () => {
  let taskPlanner;

  beforeEach(() => {
    taskPlanner = new TaskPlanner({ patterns: TEST_PATTERNS });
  });

  it('should parse ADD_PROJECT intent', async () => {
    const result = await taskPlanner.parseIntent('Add React project');
    expect(result.type).to.equal('ADD_PROJECT');
    expect(result.confidence).to.be.above(0.8);
  });
});

Integration Test Pattern

describe('Full Workflow', () => {
  let agent;

  before(async () => {
    agent = new AgentV2({ sitePath: './fixtures/test-site' });
    await agent.initialize();
  });

  it('should complete workflow', async () => {
    const result = await agent.processMessage('Add React project');
    expect(result.success).to.be.true;
  });
});

Mock Pattern

// Mock RuVectorBridge for testing
class MockRuVectorBridge {
  async searchProjects(query) {
    return {
      results: [{ name: 'Test Project', score: 0.9 }],
      source: 'mock'
    };
  }
}

// Use in tests
const taskPlanner = new TaskPlanner({
  ruvectorBridge: new MockRuVectorBridge()
});

🚨 Error Handling

Try-Catch Pattern

try {
  const intent = await taskPlanner.parseIntent(message);

  if (intent.confidence < 0.5) {
    throw new Error('LOW_CONFIDENCE');
  }

  // Continue with plan...
} catch (error) {
  if (error.message === 'LOW_CONFIDENCE') {
    return 'Could you rephrase? I\'m not sure what you want to do.';
  }
  throw error; // Re-throw unexpected errors
}

Graceful Degradation

try {
  await ruvectorBridge.initialize();
} catch (error) {
  console.warn('[RuVector] Failed to initialize, using fallback');
  // Continue without RuVector
}

Rollback Pattern

const executedActions = [];

try {
  for (const action of plan.actions) {
    await executeAction(action);
    executedActions.push(action);
  }
} catch (error) {
  console.error('Execution failed, rolling back...');

  // Rollback in reverse order
  for (const action of executedActions.reverse()) {
    await rollbackAction(action);
  }

  throw error;
}

πŸ“Š Debugging Tips

Enable Debug Logging

DEBUG=agent:* node ai-agent.js chat

Inspect Plans

console.log('[DEBUG] Generated plan:', JSON.stringify(plan, null, 2));

Check Memory State

const stats = await memory.getStats();
console.log('[DEBUG] Memory stats:', stats);

Validate Schemas

const schema = siteContext.getContentSchema('_projects/test.md');
const result = siteContext.validateContent(content, schema);
console.log('[DEBUG] Validation:', result);

🎨 Code Style

Naming Conventions

  • Classes: PascalCase (TaskPlanner, ChangePreview)
  • Methods: camelCase (parseIntent, previewPlan)
  • Private methods: Leading underscore (_extractEntities)
  • Constants: UPPER_SNAKE_CASE (DEFAULT_PATTERNS, CONFIG)

Async/Await

Always use async/await, not callbacks:

// βœ… Good
const result = await taskPlanner.parseIntent(message);

// ❌ Bad
taskPlanner.parseIntent(message).then(result => { ... });

Error Messages

Always provide actionable error messages:

// βœ… Good
throw new Error('Schema validation failed: missing required field "name"');

// ❌ Bad
throw new Error('Invalid content');

JSDoc Comments

All public methods must have JSDoc:

/**
 * Parse user message into structured intent
 * @param {string} message - User's natural language input
 * @returns {Promise<Intent>} Parsed intent with confidence score
 * @throws {Error} If parsing fails or confidence too low
 */
async parseIntent(message) {
  // ...
}

πŸ“ File Locations

Source Files

ai-agent-v2/
β”œβ”€β”€ index.js                    # Main entry point
β”œβ”€β”€ modules/
β”‚   β”œβ”€β”€ task-planner/
β”‚   β”‚   └── index.js            # TaskPlanner
β”‚   β”œβ”€β”€ change-preview/
β”‚   β”‚   └── index.js            # ChangePreview
β”‚   β”œβ”€β”€ ruvector-bridge/
β”‚   β”‚   └── index.js            # RuVectorBridge
β”‚   β”œβ”€β”€ site-context/
β”‚   β”‚   └── index.js            # SiteContext
β”‚   └── approval-workflow/
β”‚       └── index.js            # ApprovalWorkflow

Documentation

docs/
β”œβ”€β”€ architecture/
β”‚   β”œβ”€β”€ ai-agent-v2-design.md         # Full architecture
β”‚   └── module-specifications.md      # Detailed specs
swarm/ai-agent-v2/architect/
β”œβ”€β”€ module-specifications.md           # Implementation guide
β”œβ”€β”€ integration-summary.md             # Integration patterns
└── quick-reference.md                 # This file

  • Main Architecture Doc: /docs/architecture/ai-agent-v2-design.md
  • Module Specs: /swarm/ai-agent-v2/architect/module-specifications.md
  • Integration Guide: /swarm/ai-agent-v2/architect/integration-summary.md
  • Current Agent (v1.0): /ai-agent-simple/ai-agent.js
  • RuVector Modules: /assets/js/ruvector/

βœ… Implementation Checklist

When implementing a module:

  • Read full architecture document
  • Review module specifications
  • Implement public API methods
  • Write JSDoc comments
  • Add unit tests (90%+ coverage)
  • Add integration tests
  • Test error handling
  • Test with mock dependencies
  • Document in module README
  • Review with team

🎯 Success Metrics

Metric Target How to Measure
Test Coverage 90%+ npm run test:coverage
Response Time <3s Log timestamps in workflow
Intent Accuracy 95%+ User feedback + manual testing
Approval UX 90% satisfaction User surveys
Error Rate <1% Log error count / total requests

Quick Reference Complete

For detailed architecture, see: /docs/architecture/ai-agent-v2-design.md