|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +/** |
| 4 | + * Demo: Document-Based Context Persistence for AI Agents |
| 5 | + * |
| 6 | + * This shows how AI agents can maintain persistent context across sessions, |
| 7 | + * similar to how experienced developers maintain mental models of projects. |
| 8 | + * |
| 9 | + * Run: node demo-ai-context.js |
| 10 | + */ |
| 11 | + |
| 12 | +// Simple types for demonstration |
| 13 | +const DevlogTypes = { |
| 14 | + feature: "feature", |
| 15 | + bugfix: "bugfix", |
| 16 | + task: "task" |
| 17 | +}; |
| 18 | + |
| 19 | +const DevlogStatus = { |
| 20 | + todo: "todo", |
| 21 | + inProgress: "in-progress", |
| 22 | + done: "done" |
| 23 | +}; |
| 24 | + |
| 25 | +class DocumentBasedContext { |
| 26 | + |
| 27 | + /** |
| 28 | + * Create a development task with rich context |
| 29 | + */ |
| 30 | + createTaskDocument(taskData) { |
| 31 | + const now = new Date().toISOString(); |
| 32 | + const id = `task-${Date.now()}`; |
| 33 | + |
| 34 | + return { |
| 35 | + // Basic task info |
| 36 | + id, |
| 37 | + title: taskData.title, |
| 38 | + type: "feature", |
| 39 | + description: taskData.description, |
| 40 | + status: "todo", |
| 41 | + priority: "medium", |
| 42 | + createdAt: now, |
| 43 | + updatedAt: now, |
| 44 | + |
| 45 | + // Rich business & technical context |
| 46 | + context: { |
| 47 | + businessContext: taskData.businessContext, |
| 48 | + technicalContext: taskData.technicalContext, |
| 49 | + acceptanceCriteria: taskData.acceptanceCriteria, |
| 50 | + decisions: [], |
| 51 | + risks: [], |
| 52 | + dependencies: [] |
| 53 | + }, |
| 54 | + |
| 55 | + // AI-specific persistent memory |
| 56 | + aiMemory: { |
| 57 | + currentUnderstanding: `New task: ${taskData.title}. Goal: ${taskData.businessContext}`, |
| 58 | + keyInsights: taskData.initialInsights || [], |
| 59 | + openQuestions: [], |
| 60 | + relatedPatterns: taskData.relatedPatterns || [], |
| 61 | + suggestedNextSteps: [ |
| 62 | + "Analyze requirements", |
| 63 | + "Design solution", |
| 64 | + "Identify risks" |
| 65 | + ], |
| 66 | + lastAIUpdate: now, |
| 67 | + memoryVersion: 1 |
| 68 | + } |
| 69 | + }; |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * AI agent updates its understanding as work progresses |
| 74 | + */ |
| 75 | + updateAIMemory(document, update) { |
| 76 | + const now = new Date().toISOString(); |
| 77 | + |
| 78 | + // Accumulate insights over time |
| 79 | + if (update.newInsights) { |
| 80 | + document.aiMemory.keyInsights.push(...update.newInsights); |
| 81 | + } |
| 82 | + |
| 83 | + // Track questions and answers |
| 84 | + if (update.questionsAnswered) { |
| 85 | + document.aiMemory.openQuestions = document.aiMemory.openQuestions.filter( |
| 86 | + q => !update.questionsAnswered.some(answered => q.includes(answered)) |
| 87 | + ); |
| 88 | + } |
| 89 | + |
| 90 | + if (update.newQuestions) { |
| 91 | + document.aiMemory.openQuestions.push(...update.newQuestions); |
| 92 | + } |
| 93 | + |
| 94 | + // Update current understanding |
| 95 | + if (update.progressSummary) { |
| 96 | + document.aiMemory.currentUnderstanding = update.progressSummary; |
| 97 | + } |
| 98 | + |
| 99 | + // Update next steps |
| 100 | + if (update.nextSteps) { |
| 101 | + document.aiMemory.suggestedNextSteps = update.nextSteps; |
| 102 | + } |
| 103 | + |
| 104 | + // Track patterns across projects |
| 105 | + if (update.patternsDiscovered) { |
| 106 | + document.aiMemory.relatedPatterns.push(...update.patternsDiscovered); |
| 107 | + } |
| 108 | + |
| 109 | + document.aiMemory.lastAIUpdate = now; |
| 110 | + document.aiMemory.memoryVersion += 1; |
| 111 | + document.updatedAt = now; |
| 112 | + |
| 113 | + return document; |
| 114 | + } |
| 115 | + |
| 116 | + /** |
| 117 | + * Record important decisions with rationale |
| 118 | + */ |
| 119 | + recordDecision(document, decision) { |
| 120 | + const now = new Date().toISOString(); |
| 121 | + |
| 122 | + const decisionRecord = { |
| 123 | + id: `decision-${Date.now()}`, |
| 124 | + timestamp: now, |
| 125 | + decision: decision.decision, |
| 126 | + rationale: decision.rationale, |
| 127 | + alternatives: decision.alternatives || [], |
| 128 | + madeBy: decision.madeBy |
| 129 | + }; |
| 130 | + |
| 131 | + document.context.decisions.push(decisionRecord); |
| 132 | + |
| 133 | + // Add to AI memory as insight |
| 134 | + document.aiMemory.keyInsights.push( |
| 135 | + `Decision: ${decision.decision}. Why: ${decision.rationale}` |
| 136 | + ); |
| 137 | + |
| 138 | + document.aiMemory.lastAIUpdate = now; |
| 139 | + document.aiMemory.memoryVersion += 1; |
| 140 | + |
| 141 | + return document; |
| 142 | + } |
| 143 | + |
| 144 | + /** |
| 145 | + * Generate AI-optimized context for feeding to language models |
| 146 | + */ |
| 147 | + getAIContextSummary(document) { |
| 148 | + return ` |
| 149 | +# Development Task: ${document.title} |
| 150 | +
|
| 151 | +## Current Status: ${document.status} |
| 152 | +
|
| 153 | +## Business Goal |
| 154 | +${document.context.businessContext} |
| 155 | +
|
| 156 | +## Technical Context |
| 157 | +${document.context.technicalContext} |
| 158 | +
|
| 159 | +## Current AI Understanding |
| 160 | +${document.aiMemory.currentUnderstanding} |
| 161 | +
|
| 162 | +## Key Insights Learned |
| 163 | +${document.aiMemory.keyInsights.map(insight => `• ${insight}`).join('\n')} |
| 164 | +
|
| 165 | +## Open Questions |
| 166 | +${document.aiMemory.openQuestions.map(q => `• ${q}`).join('\n')} |
| 167 | +
|
| 168 | +## Related Patterns from Other Projects |
| 169 | +${document.aiMemory.relatedPatterns.map(pattern => `• ${pattern}`).join('\n')} |
| 170 | +
|
| 171 | +## Acceptance Criteria |
| 172 | +${document.context.acceptanceCriteria.map(criteria => `• ${criteria}`).join('\n')} |
| 173 | +
|
| 174 | +## Decisions Made |
| 175 | +${document.context.decisions.map(d => |
| 176 | + `• ${d.decision} (by ${d.madeBy}): ${d.rationale}` |
| 177 | +).join('\n')} |
| 178 | +
|
| 179 | +## Suggested Next Steps |
| 180 | +${document.aiMemory.suggestedNextSteps.map(step => `• ${step}`).join('\n')} |
| 181 | +
|
| 182 | +--- |
| 183 | +Memory Version: ${document.aiMemory.memoryVersion} | Last Updated: ${document.aiMemory.lastAIUpdate} |
| 184 | +`.trim(); |
| 185 | + } |
| 186 | + |
| 187 | + /** |
| 188 | + * Demonstrate AI workflow with persistent context |
| 189 | + */ |
| 190 | + demonstrateAIWorkflow() { |
| 191 | + console.log("🤖 Demonstrating Document-Based AI Context Persistence\n"); |
| 192 | + |
| 193 | + // 1. AI agent starts new feature |
| 194 | + console.log("📝 Step 1: AI Agent creates new feature task..."); |
| 195 | + let taskDoc = this.createTaskDocument({ |
| 196 | + title: "Add user authentication system", |
| 197 | + description: "Implement JWT-based auth with role-based access control", |
| 198 | + businessContext: "Secure API endpoints for customer portal launch. Need admin vs user access levels.", |
| 199 | + technicalContext: "Node.js/Express + PostgreSQL. Consider JWT middleware vs passport.js integration.", |
| 200 | + acceptanceCriteria: [ |
| 201 | + "Users can register and login", |
| 202 | + "JWT tokens issued with roles", |
| 203 | + "API endpoints protected by role", |
| 204 | + "Password reset functionality", |
| 205 | + "Token refresh mechanism" |
| 206 | + ], |
| 207 | + initialInsights: [ |
| 208 | + "Similar JWT pattern used in billing service", |
| 209 | + "Need GDPR compliance consideration" |
| 210 | + ], |
| 211 | + relatedPatterns: [ |
| 212 | + "JWT refresh pattern from billing-service", |
| 213 | + "RBAC middleware from admin-dashboard" |
| 214 | + ] |
| 215 | + }); |
| 216 | + |
| 217 | + console.log(`✅ Created task document: ${taskDoc.id}\n`); |
| 218 | + |
| 219 | + // 2. AI agent makes progress |
| 220 | + console.log("🔄 Step 2: AI Agent updates understanding after analysis..."); |
| 221 | + taskDoc = this.updateAIMemory(taskDoc, { |
| 222 | + progressSummary: "Analyzed user table schema. Designed JWT structure. Started auth middleware implementation.", |
| 223 | + newInsights: [ |
| 224 | + "User table already has 'role' column - perfect for RBAC", |
| 225 | + "Need to add 'last_login' and 'refresh_token' columns", |
| 226 | + "Custom middleware simpler than passport-jwt for our use case" |
| 227 | + ], |
| 228 | + newQuestions: [ |
| 229 | + "Should we implement login rate limiting?", |
| 230 | + "How long should refresh tokens be valid?", |
| 231 | + "Do admin users need 2FA?" |
| 232 | + ], |
| 233 | + nextSteps: [ |
| 234 | + "Implement JWT generation and validation", |
| 235 | + "Create role-based route protection middleware", |
| 236 | + "Add database migrations for user table", |
| 237 | + "Build password reset flow" |
| 238 | + ] |
| 239 | + }); |
| 240 | + |
| 241 | + console.log("✅ Updated AI memory with new insights and questions\n"); |
| 242 | + |
| 243 | + // 3. AI agent makes technical decision |
| 244 | + console.log("🎯 Step 3: AI Agent makes technical decision..."); |
| 245 | + taskDoc = this.recordDecision(taskDoc, { |
| 246 | + decision: "Use bcrypt with 12 rounds for password hashing", |
| 247 | + rationale: "Balances security with performance. 12 rounds gives strong security while keeping response times under 100ms on our servers.", |
| 248 | + alternatives: [ |
| 249 | + "argon2 (newer but complex setup)", |
| 250 | + "scrypt (good but bcrypt more adopted)" |
| 251 | + ], |
| 252 | + madeBy: "ai-agent" |
| 253 | + }); |
| 254 | + |
| 255 | + console.log("✅ Recorded decision with rationale\n"); |
| 256 | + |
| 257 | + // 4. Generate context for next AI session |
| 258 | + console.log("📋 Step 4: Generate AI context for next session..."); |
| 259 | + const contextSummary = this.getAIContextSummary(taskDoc); |
| 260 | + |
| 261 | + console.log("=" .repeat(60)); |
| 262 | + console.log("AI CONTEXT SUMMARY (for next session)"); |
| 263 | + console.log("=" .repeat(60)); |
| 264 | + console.log(contextSummary); |
| 265 | + console.log("=" .repeat(60)); |
| 266 | + |
| 267 | + console.log(`\n🎉 Demo complete! The AI agent now has persistent context across sessions.`); |
| 268 | + console.log(`📊 Memory version: ${taskDoc.aiMemory.memoryVersion}`); |
| 269 | + console.log(`💡 Total insights: ${taskDoc.aiMemory.keyInsights.length}`); |
| 270 | + console.log(`❓ Open questions: ${taskDoc.aiMemory.openQuestions.length}`); |
| 271 | + console.log(`🔗 Related patterns: ${taskDoc.aiMemory.relatedPatterns.length}`); |
| 272 | + |
| 273 | + return taskDoc; |
| 274 | + } |
| 275 | +} |
| 276 | + |
| 277 | +// Run the demonstration |
| 278 | +if (require.main === module) { |
| 279 | + const demo = new DocumentBasedContext(); |
| 280 | + demo.demonstrateAIWorkflow(); |
| 281 | +} |
| 282 | + |
| 283 | +module.exports = { DocumentBasedContext }; |
0 commit comments