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
π Quick Links
- 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