{"type":"session","version":3,"id":"523d0015-697d-40c8-b43b-0630b3a24f0f","timestamp":"2026-02-17T06:06:06.839Z","cwd":"/home/ccuser/rateright-growth/rivet"} {"type":"model_change","id":"f0953251","parentId":null,"timestamp":"2026-02-17T06:06:06.843Z","provider":"anthropic","modelId":"claude-opus-4-5"} {"type":"thinking_level_change","id":"1509c05f","parentId":"f0953251","timestamp":"2026-02-17T06:06:06.843Z","thinkingLevel":"low"} {"type":"custom","customType":"model-snapshot","data":{"timestamp":1771308366843,"provider":"anthropic","modelApi":"anthropic-messages","modelId":"claude-opus-4-5"},"id":"1001796f","parentId":"1509c05f","timestamp":"2026-02-17T06:06:06.843Z"} {"type":"custom","customType":"clawdbot.cache-ttl","data":{"timestamp":1771308366850,"provider":"anthropic","modelId":"claude-opus-4-5"},"id":"f3a566ef","parentId":"1001796f","timestamp":"2026-02-17T06:06:06.850Z"} {"type":"message","id":"d48db8fe","parentId":"f3a566ef","timestamp":"2026-02-17T06:06:06.856Z","message":{"role":"user","content":[{"type":"text","text":"Design an inter-agent communication protocol for 8 AI agents on the same VPS. Agents: Chief of Staff, Coder, Sales, Finance, Intel, DevOps, Comms, Ops. They share JSON state files and communicate via HTTP. Problem: they run in isolation with empty task queues. Design: buddy system, hourly cross-checks, self-healing for stalls, auto-task generation, context overflow prevention. Be specific and implementable."}],"timestamp":1771308366850}} {"type":"message","id":"8b2d231c","parentId":"d48db8fe","timestamp":"2026-02-17T06:08:00.939Z","message":{"role":"assistant","content":[{"type":"thinking","thinking":"This is a design task for an inter-agent communication protocol. Let me think through this systematically and create a comprehensive, implementable design.\n\nThe problem:\n- 8 AI agents on the same VPS\n- They share JSON state files\n- Communicate via HTTP\n- Currently run in isolation with empty task queues\n\nThe solution needs:\n1. Buddy system - pairs of agents that watch each other\n2. Hourly cross-checks - periodic health/state verification\n3. Self-healing for stalls - detect and recover from stuck agents\n4. Auto-task generation - agents should generate work when idle\n5. Context overflow prevention - manage token/memory limits\n\nLet me design this comprehensively.","thinkingSignature":"Er4GCkYICxgCKkCUGQx2ug5E+nx9hySRDu09dvEnuscnXS6GUgO7MOiRn6zDAHRS4ne+qa2BYI2675F3PeY7Ci4HFQdA8mQcpt47EgxqhyULjd7Ew8EHurAaDKF2N1FKpQ2ql/K1QCIwrFCHh8f6HWOPLb/FY1Ra4rkYLSQIwAA5IAdmzGipG2jS23C99Fxk+R5TdOfJeM5vKqUFnGzTZluXMDwIw2kh/kVj+0iYZfgvhyty+thj3We/mCoaShI3mlLbnF0RikIIKp7RpjEuv18oLJrQfGk6sDjnZfWq4yw81/KPgcmGtGTIXU/Ay/Yjs3YemA9NnOQyeveGeF6NR31bWD4G8qTnUiEq+NnaAoHcP1PUkwkWWczUQAww/XciEBgo/wLk2O1I/ohDHeyVI0I8nRyeuJgLAQjgFbD/LHQQpJUWGIUEZrnY/YL4SfvFTRK+MwyFjTdxjuOgHz6nEQCLVtWwEcBzy/yuj8Py8OJii7H2sNbl5rKbWnLYt4XmzjGQn/zrEoL4Aj42c/OO4q1XlZhUxWlB2/PaQPhWyliSe2AUQ+OAt8hzusL+u9RYTY3qDVGc5yFCrJaaM3T+sLCLLlylRLwuh33UgnX28NF3bpqCHV0BzFyB8ahQVtfekShdishWE3EH3nG9vkO0fbE1Qb5xB7z17sKAM6lK6G+R7zvoIx7t/DyTMBi1mTciQE53wVV8dOUqsWi4GYrOPoofCVrkYsyStJ+FD1IrttXXpNDTwaHseAJkQrbOqVDF4dJ7XDKkPRWl650tDjYkxVOS1/FKkCU4e4xZQzITHZ3wtYmEV4x9vrPGPYJ8M3AFmA9wN7t8nQvBDaInbkwZU5LBf4JkZXvIVI3kqpbQHysSx/ei8NUgV5MpZ/LZGowk8HNBRteUAbWMN7COfJdeRAFsXavHwAmCHsnIaFJwQrc7eZrpxPdPLLZZ9mh/uffpLzyDUm26Y9cRHtOvWnLLZ4/JMzybzkWLIxgbxadBYihOMgcOo9qdxiGviklEGR6VOis/UHVf3cmBmLoUNyQ7APscQyySYUCL8H8Z1HhHuGLEch0Z++BIZHir08+rZ8OlD8a+zdk1kCkZSyZi9sYHBY0YAQ=="},{"type":"text","text":"# Inter-Agent Communication Protocol (IACP)\n## RateRight Multi-Agent Coordination System\n\n---\n\n## 1. Agent Registry & Roles\n\n```json\n// /shared/agents/registry.json\n{\n \"agents\": {\n \"chief\": {\n \"name\": \"Chief of Staff\",\n \"port\": 18801,\n \"responsibilities\": [\"coordination\", \"escalation\", \"strategy\"],\n \"buddy\": \"ops\",\n \"canDelegate\": [\"coder\", \"sales\", \"finance\", \"intel\", \"devops\", \"comms\", \"ops\"]\n },\n \"coder\": {\n \"name\": \"Builder\",\n \"port\": 18802,\n \"responsibilities\": [\"code\", \"architecture\", \"testing\", \"deployment\"],\n \"buddy\": \"devops\",\n \"canDelegate\": []\n },\n \"sales\": {\n \"name\": \"Susan\",\n \"port\": 18803,\n \"responsibilities\": [\"leads\", \"outreach\", \"partnerships\", \"demos\"],\n \"buddy\": \"comms\",\n \"canDelegate\": []\n },\n \"finance\": {\n \"name\": \"Harper\",\n \"port\": 18804,\n \"responsibilities\": [\"grants\", \"invoicing\", \"compliance\", \"budgets\"],\n \"buddy\": \"intel\",\n \"canDelegate\": []\n },\n \"intel\": {\n \"name\": \"Scout\",\n \"port\": 18805,\n \"responsibilities\": [\"research\", \"competitive-analysis\", \"market-data\"],\n \"buddy\": \"finance\",\n \"canDelegate\": []\n },\n \"devops\": {\n \"name\": \"Atlas\",\n \"port\": 18806,\n \"responsibilities\": [\"infrastructure\", \"monitoring\", \"security\", \"deploys\"],\n \"buddy\": \"coder\",\n \"canDelegate\": []\n },\n \"comms\": {\n \"name\": \"Echo\",\n \"port\": 18807,\n \"responsibilities\": [\"content\", \"social\", \"email-campaigns\", \"PR\"],\n \"buddy\": \"sales\",\n \"canDelegate\": []\n },\n \"ops\": {\n \"name\": \"Conductor\",\n \"port\": 18808,\n \"responsibilities\": [\"scheduling\", \"process\", \"documentation\", \"QA\"],\n \"buddy\": \"chief\",\n \"canDelegate\": []\n }\n }\n}\n```\n\n---\n\n## 2. Buddy System\n\n### Buddy Pairs (Circular Accountability)\n```\nChief ↔ Ops (strategy + execution)\nCoder ↔ DevOps (build + deploy)\nSales ↔ Comms (outreach + content)\nFinance ↔ Intel (money + research)\n```\n\n### Buddy Responsibilities\n\n```typescript\ninterface BuddyContract {\n // Every 15 minutes\n heartbeat: {\n endpoint: \"POST /buddy/ping\",\n timeout: 5000,\n retries: 3\n };\n \n // Every hour\n stateReview: {\n endpoint: \"POST /buddy/review\",\n checks: [\n \"taskQueueNotEmpty\",\n \"lastActivityWithin2Hours\",\n \"noRepeatedErrors\",\n \"contextUnderLimit\"\n ]\n };\n \n // On failure\n escalation: {\n firstFailure: \"logWarning\",\n secondFailure: \"attemptWake\",\n thirdFailure: \"notifyChief\",\n fourthFailure: \"notifyHuman\"\n };\n}\n```\n\n### Buddy Ping Protocol\n\n```json\n// POST /buddy/ping\n// Request from buddy\n{\n \"from\": \"devops\",\n \"timestamp\": \"2025-02-17T10:00:00Z\",\n \"myStatus\": {\n \"taskQueueLength\": 3,\n \"currentTask\": \"monitoring-setup\",\n \"lastCompletedTask\": \"2025-02-17T09:45:00Z\",\n \"contextTokens\": 45000,\n \"errors24h\": 0\n }\n}\n\n// Response\n{\n \"status\": \"healthy\",\n \"taskQueueLength\": 2,\n \"currentTask\": \"api-refactor\",\n \"concerns\": [],\n \"needsHelp\": false\n}\n```\n\n---\n\n## 3. Shared State Architecture\n\n### Directory Structure\n```\n/shared/\n├── agents/\n│ ├── registry.json # Agent definitions\n│ ├── health.json # Real-time health status\n│ └── {agent}/\n│ ├── state.json # Agent's current state\n│ ├── inbox.json # Incoming tasks\n│ ├── outbox.json # Completed/delegated tasks\n│ └── context-summary.md # Compressed context for handoffs\n├── tasks/\n│ ├── queue.json # Global task queue\n│ ├── active.json # Currently executing\n│ ├── completed/ # Archived completed tasks\n│ └── failed/ # Failed tasks for review\n├── knowledge/\n│ ├── decisions.json # Logged decisions\n│ ├── blockers.json # Current blockers\n│ └── insights.json # Discovered insights\n└── system/\n ├── clock.json # Coordination clock\n ├── locks/ # File locks for concurrent access\n └── events.log # System event log\n```\n\n### Agent State File\n\n```json\n// /shared/agents/coder/state.json\n{\n \"agentId\": \"coder\",\n \"status\": \"working\", // idle | working | blocked | stalled | offline\n \"currentTask\": {\n \"id\": \"task-2025-0217-001\",\n \"type\": \"feature\",\n \"description\": \"Implement broker comparison API\",\n \"startedAt\": \"2025-02-17T09:30:00Z\",\n \"estimatedCompletion\": \"2025-02-17T11:00:00Z\",\n \"progress\": 0.6\n },\n \"lastActivity\": \"2025-02-17T10:15:00Z\",\n \"lastHeartbeat\": \"2025-02-17T10:14:00Z\",\n \"contextTokens\": 52000,\n \"contextLimit\": 180000,\n \"sessionId\": \"sess-abc123\",\n \"metrics\": {\n \"tasksCompleted24h\": 7,\n \"avgTaskDurationMin\": 45,\n \"errorRate\": 0.02\n }\n}\n```\n\n### Health Aggregation\n\n```json\n// /shared/agents/health.json (updated every minute by each agent)\n{\n \"lastUpdate\": \"2025-02-17T10:15:00Z\",\n \"agents\": {\n \"chief\": { \"status\": \"idle\", \"lastSeen\": \"2025-02-17T10:14:30Z\", \"healthy\": true },\n \"coder\": { \"status\": \"working\", \"lastSeen\": \"2025-02-17T10:15:00Z\", \"healthy\": true },\n \"sales\": { \"status\": \"idle\", \"lastSeen\": \"2025-02-17T10:10:00Z\", \"healthy\": true },\n \"finance\": { \"status\": \"idle\", \"lastSeen\": \"2025-02-17T09:45:00Z\", \"healthy\": false, \"concern\": \"stale\" },\n \"intel\": { \"status\": \"working\", \"lastSeen\": \"2025-02-17T10:14:00Z\", \"healthy\": true },\n \"devops\": { \"status\": \"idle\", \"lastSeen\": \"2025-02-17T10:13:00Z\", \"healthy\": true },\n \"comms\": { \"status\": \"offline\", \"lastSeen\": \"2025-02-17T08:00:00Z\", \"healthy\": false, \"concern\": \"offline\" },\n \"ops\": { \"status\": \"idle\", \"lastSeen\": \"2025-02-17T10:12:00Z\", \"healthy\": true }\n },\n \"systemHealth\": \"degraded\",\n \"alerts\": [\n { \"agent\": \"finance\", \"type\": \"stale\", \"since\": \"2025-02-17T09:45:00Z\" },\n { \"agent\": \"comms\", \"type\": \"offline\", \"since\": \"2025-02-17T08:00:00Z\" }\n ]\n}\n```\n\n---\n\n## 4. Hourly Cross-Check Protocol\n\n### The Hourly Sync (Every Agent, Every Hour)\n\n```typescript\n// Runs at :00 of each hour (staggered by agent to avoid thundering herd)\n// chief: :00, coder: :05, sales: :10, finance: :15, intel: :20, devops: :25, comms: :30, ops: :35\n\nasync function hourlySync(agent: Agent) {\n const report = {\n agentId: agent.id,\n timestamp: new Date().toISOString(),\n \n // Self-assessment\n self: {\n tasksCompleted: agent.getCompletedSinceLastSync(),\n currentTask: agent.getCurrentTask(),\n blockers: agent.getBlockers(),\n contextUsage: agent.getContextTokens() / agent.contextLimit,\n idleMinutes: agent.getIdleMinutes()\n },\n \n // Buddy check\n buddy: await agent.pingBuddy(),\n \n // Environment scan\n environment: {\n globalQueueLength: await getGlobalQueueLength(),\n myInboxLength: agent.inbox.length,\n systemAlerts: await getSystemAlerts()\n }\n };\n \n // Decide on action\n if (report.self.idleMinutes > 30 && report.self.currentTask === null) {\n await agent.selfGenerateTask();\n }\n \n if (!report.buddy.healthy) {\n await agent.escalateBuddyIssue(report.buddy);\n }\n \n // Write sync report\n await writeSync(report);\n}\n```\n\n### Cross-Check Questions (Each Agent Asks Itself)\n\n```yaml\nhourly_self_check:\n - \"Do I have tasks in my queue?\"\n - \"Have I completed anything in the last 2 hours?\"\n - \"Is my buddy alive and responsive?\"\n - \"Is my context usage under 70%?\"\n - \"Are there system alerts I should address?\"\n - \"Should I generate work based on my responsibilities?\"\n\nhourly_buddy_check:\n - \"Has my buddy responded to ping in last 15 min?\"\n - \"Is their task queue reasonable (not 0, not 100+)?\"\n - \"Have they been 'working' on the same task for >3 hours?\"\n - \"Is their error rate spiking?\"\n```\n\n---\n\n## 5. Self-Healing Mechanisms\n\n### Stall Detection\n\n```typescript\ninterface StallDetector {\n rules: [\n {\n name: \"idle_too_long\",\n condition: \"status === 'idle' && idleMinutes > 60 && inboxLength === 0\",\n action: \"generateTask\"\n },\n {\n name: \"stuck_on_task\",\n condition: \"status === 'working' && taskDurationMinutes > 180\",\n action: \"escalateOrSplit\"\n },\n {\n name: \"repeated_failures\",\n condition: \"failedTasks.last3.allSameType\",\n action: \"pauseAndReportBlocker\"\n },\n {\n name: \"context_overflow_imminent\",\n condition: \"contextTokens > contextLimit * 0.85\",\n action: \"compressContext\"\n },\n {\n name: \"buddy_unresponsive\",\n condition: \"buddyLastSeen > 30min\",\n action: \"attemptWakeThenEscalate\"\n }\n ]\n}\n```\n\n### Self-Healing Actions\n\n```typescript\n// Action: Generate Task (when idle with empty queue)\nasync function selfGenerateTask(agent: Agent) {\n const taskTemplates = getTaskTemplatesForRole(agent.role);\n const recentActivity = await getRecentSystemActivity();\n const blockers = await getGlobalBlockers();\n \n // AI generates a relevant task based on:\n // 1. Agent's responsibilities\n // 2. Recent system activity (what others are doing)\n // 3. Known blockers that need research/help\n // 4. Time-based triggers (daily reports, weekly reviews)\n \n const generatedTask = await agent.llm.generate({\n prompt: `You are ${agent.name} responsible for ${agent.responsibilities}.\n \nThe system has been quiet. Based on your role, generate ONE high-value task you should do right now.\n\nRecent activity: ${JSON.stringify(recentActivity)}\nCurrent blockers: ${JSON.stringify(blockers)}\nDay/Time: ${new Date().toISOString()}\n\nRespond with a task in JSON format:\n{\n \"type\": \"research|report|outreach|maintenance|analysis\",\n \"title\": \"...\",\n \"description\": \"...\",\n \"estimatedMinutes\": 30,\n \"outputs\": [\"what this task will produce\"]\n}`\n });\n \n await agent.addToOwnQueue(generatedTask);\n}\n\n// Action: Compress Context (when approaching limit)\nasync function compressContext(agent: Agent) {\n // 1. Summarize current session to context-summary.md\n const summary = await agent.llm.generate({\n prompt: `Summarize the key decisions, progress, and state from this session in <500 words.\n Focus on: what was done, what's pending, key context for next session.`\n });\n \n await writeFile(`/shared/agents/${agent.id}/context-summary.md`, summary);\n \n // 2. Clear non-essential conversation history\n agent.truncateHistory(keepLast: 10);\n \n // 3. Update state file with compression marker\n agent.state.lastContextCompression = new Date().toISOString();\n}\n\n// Action: Wake Buddy\nasync function attemptWakeBuddy(agent: Agent, buddy: Agent) {\n // Try HTTP wake\n const wakeResult = await fetch(`http://localhost:${buddy.port}/wake`, {\n method: 'POST',\n body: JSON.stringify({ from: agent.id, reason: 'buddy_check' })\n }).catch(() => null);\n \n if (!wakeResult) {\n // Try systemd restart\n await exec(`systemctl restart agent-${buddy.id}`);\n await sleep(5000);\n \n // Verify\n const health = await fetch(`http://localhost:${buddy.port}/health`).catch(() => null);\n if (!health) {\n await escalateToChief(agent, buddy, 'wake_failed');\n }\n }\n}\n```\n\n---\n\n## 6. Auto-Task Generation Rules\n\n### Per-Agent Task Templates\n\n```yaml\n# /shared/tasks/templates.yaml\n\nchief:\n daily:\n - title: \"Morning Standup Summary\"\n trigger: \"09:00 weekdays\"\n description: \"Review all agent states, compile summary, identify blockers\"\n - title: \"End of Day Report\"\n trigger: \"17:00 weekdays\"\n description: \"Summarize day's progress, set priorities for tomorrow\"\n idle:\n - title: \"Strategic Review\"\n description: \"Review quarterly goals vs current trajectory\"\n - title: \"Process Optimization\"\n description: \"Identify bottlenecks in agent collaboration\"\n\ncoder:\n daily:\n - title: \"Code Review Queue\"\n trigger: \"10:00\"\n description: \"Review any pending PRs or code changes\"\n - title: \"Technical Debt Assessment\"\n trigger: \"weekly monday\"\n description: \"Identify and prioritize tech debt items\"\n idle:\n - title: \"Test Coverage Improvement\"\n description: \"Add tests to uncovered code paths\"\n - title: \"Documentation Update\"\n description: \"Update API docs or README\"\n\nsales:\n daily:\n - title: \"Lead Follow-up\"\n trigger: \"10:00 weekdays\"\n description: \"Check CRM, follow up on warm leads\"\n - title: \"Outreach Batch\"\n trigger: \"14:00 weekdays\"\n description: \"Send personalized outreach to 5 prospects\"\n idle:\n - title: \"Competitor Analysis\"\n description: \"Research competitor pricing/features\"\n - title: \"Case Study Draft\"\n description: \"Draft customer success story\"\n\nfinance:\n daily:\n - title: \"Grant Deadline Check\"\n trigger: \"09:00\"\n description: \"Review upcoming grant deadlines\"\n - title: \"Invoice Follow-up\"\n trigger: \"weekly tuesday\"\n description: \"Check outstanding invoices, send reminders\"\n idle:\n - title: \"Budget Review\"\n description: \"Review current spend vs projections\"\n - title: \"Grant Research\"\n description: \"Find new grant opportunities\"\n\nintel:\n daily:\n - title: \"News Scan\"\n trigger: \"08:00\"\n description: \"Scan industry news for relevant updates\"\n - title: \"Competitor Monitor\"\n trigger: \"14:00\"\n description: \"Check competitor websites/social for updates\"\n idle:\n - title: \"Market Research Deep Dive\"\n description: \"Research specific market segment\"\n - title: \"Trend Analysis\"\n description: \"Analyze emerging industry trends\"\n\ndevops:\n daily:\n - title: \"System Health Check\"\n trigger: \"08:00\"\n description: \"Review logs, metrics, alerts from overnight\"\n - title: \"Security Scan\"\n trigger: \"weekly sunday 02:00\"\n description: \"Run security audit, check for vulnerabilities\"\n idle:\n - title: \"Infrastructure Optimization\"\n description: \"Identify cost or performance optimizations\"\n - title: \"Runbook Update\"\n description: \"Update operational documentation\"\n\ncomms:\n daily:\n - title: \"Social Media Check\"\n trigger: \"09:00\"\n description: \"Check mentions, respond to engagement\"\n - title: \"Content Calendar Review\"\n trigger: \"weekly monday\"\n description: \"Plan week's content\"\n idle:\n - title: \"Blog Post Draft\"\n description: \"Draft thought leadership content\"\n - title: \"Email Sequence Review\"\n description: \"Optimize email automation sequences\"\n\nops:\n daily:\n - title: \"Process Audit\"\n trigger: \"10:00\"\n description: \"Review active processes for bottlenecks\"\n - title: \"Documentation Check\"\n trigger: \"weekly friday\"\n description: \"Ensure docs are current\"\n idle:\n - title: \"Workflow Optimization\"\n description: \"Identify process improvements\"\n - title: \"Quality Assurance Review\"\n description: \"Review recent outputs for quality\"\n```\n\n### Task Generation Logic\n\n```typescript\nasync function generateTaskWhenIdle(agent: Agent): Promise {\n const now = new Date();\n const templates = getTemplatesForAgent(agent.id);\n \n // 1. Check scheduled tasks\n const scheduledTask = templates.daily.find(t => \n isTimeMatch(t.trigger, now) && !wasRunToday(t, agent)\n );\n if (scheduledTask) return createTask(scheduledTask);\n \n // 2. Check global blockers I can help with\n const blockers = await getGlobalBlockers();\n const helpableBlocker = blockers.find(b => \n canAgentHelp(agent, b) && !isAlreadyBeingWorked(b)\n );\n if (helpableBlocker) return createHelperTask(agent, helpableBlocker);\n \n // 3. Check if other agents need support\n const overloadedAgents = await getOverloadedAgents();\n const canSupport = overloadedAgents.find(a => \n hasOverlappingSkills(agent, a)\n );\n if (canSupport) return createSupportTask(agent, canSupport);\n \n // 4. Fall back to idle templates\n const idleTask = pickRandomUnrecentTask(templates.idle, agent);\n return createTask(idleTask);\n}\n```\n\n---\n\n## 7. Context Overflow Prevention\n\n### Token Budget Management\n\n```typescript\ninterface ContextBudget {\n // Hard limits\n maxContextTokens: 180000, // Model limit\n warningThreshold: 0.70, // 70% - start monitoring\n compressionThreshold: 0.85, // 85% - compress context\n criticalThreshold: 0.95, // 95% - force new session\n \n // Allocation strategy\n allocation: {\n systemPrompt: 5000, // Fixed\n agentContext: 10000, // From context-summary.md\n taskContext: 20000, // Current task details\n conversationHistory: 50000, // Rolling window\n toolResults: 80000, // Most of budget for work\n buffer: 15000 // Safety margin\n }\n}\n```\n\n### Context Management Strategies\n\n```typescript\n// Strategy 1: Rolling Conversation Window\nfunction trimConversationHistory(history: Message[], maxTokens: number): Message[] {\n // Always keep: system prompt, last 5 turns, current task context\n const essential = [\n ...history.slice(0, 1), // System prompt\n ...history.slice(-10) // Last 5 turns (user + assistant)\n ];\n \n // Summarize middle if needed\n const middle = history.slice(1, -10);\n if (countTokens(middle) > maxTokens * 0.3) {\n const summary = summarizeConversation(middle);\n return [essential[0], summary, ...essential.slice(1)];\n }\n \n return history;\n}\n\n// Strategy 2: Task Handoff with Context Transfer\nasync function handoffTask(fromAgent: Agent, toAgent: Agent, task: Task) {\n // Create minimal context package\n const contextPackage = {\n task: task,\n relevantDecisions: await getDecisionsForTask(task),\n keyFacts: await extractKeyFacts(fromAgent.history, task),\n doNotRepeat: await getAlreadyAttempted(task)\n };\n \n // Write to receiving agent's inbox\n await writeInbox(toAgent, {\n type: 'handoff',\n from: fromAgent.id,\n context: contextPackage,\n timestamp: new Date().toISOString()\n });\n}\n\n// Strategy 3: Periodic Context Snapshots\nasync function snapshotContext(agent: Agent) {\n const snapshot = {\n timestamp: new Date().toISOString(),\n activeTask: agent.currentTask,\n recentDecisions: agent.decisions.slice(-10),\n keyInsights: await extractInsights(agent.history),\n nextSteps: agent.plannedActions\n };\n \n await writeFile(\n `/shared/agents/${agent.id}/context-summary.md`,\n formatSnapshot(snapshot)\n );\n}\n```\n\n---\n\n## 8. HTTP API Specification\n\n### Standard Endpoints (Every Agent)\n\n```yaml\nendpoints:\n # Health & Status\n GET /health:\n response: { status: \"healthy|degraded|unhealthy\", uptime: seconds }\n \n GET /status:\n response: { full agent state object }\n \n # Task Management \n POST /task:\n body: { task object }\n response: { accepted: boolean, taskId: string }\n \n GET /task/{id}:\n response: { task with progress }\n \n DELETE /task/{id}:\n response: { cancelled: boolean }\n \n # Buddy System\n POST /buddy/ping:\n body: { from: agentId, myStatus: {...} }\n response: { status, concerns, needsHelp }\n \n POST /buddy/review:\n body: { from: agentId, checkResults: {...} }\n response: { acknowledged, actions: [] }\n \n # Wake & Control\n POST /wake:\n body: { from: agentId, reason: string }\n response: { awake: boolean }\n \n POST /compress:\n response: { compressed: boolean, tokensSaved: number }\n \n # Inter-Agent Communication\n POST /message:\n body: { from: agentId, type: string, payload: any }\n response: { received: boolean, response?: any }\n```\n\n### Message Types\n\n```typescript\ntype InterAgentMessage = \n | { type: 'task_request', task: Task }\n | { type: 'task_update', taskId: string, progress: number, status: string }\n | { type: 'task_complete', taskId: string, result: any }\n | { type: 'task_failed', taskId: string, error: string }\n | { type: 'help_request', topic: string, context: string }\n | { type: 'info_share', topic: string, data: any }\n | { type: 'blocker_report', blocker: Blocker }\n | { type: 'blocker_resolved', blockerId: string }\n | { type: 'escalation', issue: string, severity: 'low'|'medium'|'high'|'critical' }\n | { type: 'context_handoff', summary: string, files: string[] };\n```\n\n---\n\n## 9. Coordination Clock\n\n### Synchronization Mechanism\n\n```json\n// /shared/system/clock.json\n{\n \"tick\": 15847, // Monotonic counter, increments every minute\n \"timestamp\": \"2025-02-17T10:15:00Z\",\n \"phase\": \"work\", // work | sync | maintenance\n \"nextSync\": \"2025-02-17T11:00:00Z\",\n \"activeAgents\": [\"chief\", \"coder\", \"intel\", \"devops\", \"ops\"],\n \"scheduledEvents\": [\n { \"tick\": 15850, \"event\": \"chief_hourly_sync\" },\n { \"tick\": 15855, \"event\": \"coder_hourly_sync\" }\n ]\n}\n```\n\n### Tick-Based Scheduling\n\n```typescript\n// Each agent checks the clock every minute\nasync function onTick(agent: Agent, tick: number) {\n // 1. Update own heartbeat\n await updateHeartbeat(agent, tick);\n \n // 2. Check if it's my sync time\n if (isMyHourlySyncTime(agent, tick)) {\n await hourlySync(agent);\n }\n \n // 3. Check buddy (every 15 ticks = 15 min)\n if (tick % 15 === agent.buddyCheckOffset) {\n await pingBuddy(agent);\n }\n \n // 4. Run stall detection (every 5 ticks)\n if (tick % 5 === 0) {\n await detectAndHealStalls(agent);\n }\n \n // 5. Context management (every 30 ticks)\n if (tick % 30 === 0) {\n await manageContext(agent);\n }\n}\n```\n\n---\n\n## 10. Implementation Roadmap\n\n### Phase 1: Foundation (Week 1)\n```\n□ Create /shared directory structure\n□ Implement registry.json and health.json\n□ Add /health and /status endpoints to all agents\n□ Set up systemd services for each agent\n□ Implement tick-based coordination clock\n```\n\n### Phase 2: Buddy System (Week 2)\n```\n□ Implement /buddy/ping endpoint\n□ Add buddy check logic to each agent\n□ Implement escalation chain\n□ Test buddy wake functionality\n□ Add buddy check metrics\n```\n\n### Phase 3: Self-Healing (Week 3)\n```\n□ Implement stall detection rules\n□ Add auto-task generation from templates\n□ Implement context compression\n□ Add task handoff protocol\n□ Test recovery scenarios\n```\n\n### Phase 4: Full Integration (Week 4)\n```\n□ Implement all inter-agent message types\n□ Add global task queue management\n□ Implement cross-agent help requests\n□ Add monitoring dashboard\n□ Load testing and tuning\n```\n\n---\n\n## 11. File Locking Protocol\n\n```typescript\n// Prevent race conditions on shared files\nasync function withFileLock(\n filePath: string, \n operation: () => Promise,\n timeoutMs: number = 5000\n): Promise {\n const lockPath = `/shared/system/locks/${hashPath(filePath)}.lock`;\n const lockId = `${agentId}-${Date.now()}`;\n \n // Acquire lock\n const acquired = await acquireLock(lockPath, lockId, timeoutMs);\n if (!acquired) {\n throw new Error(`Failed to acquire lock for ${filePath}`);\n }\n \n try {\n return await operation();\n } finally {\n await releaseLock(lockPath, lockId);\n }\n}\n\n// Lock file format\ninterface LockFile {\n holder: string; // agentId-timestamp\n acquired: string; // ISO timestamp\n expires: string; // ISO timestamp (auto-release)\n}\n```\n\n---\n\n## Summary\n\nThis protocol ensures:\n\n1. **No Isolation**: Buddy system guarantees every agent is watched\n2. **No Empty Queues**: Auto-task generation fills idle time productively \n3. **Self-Healing**: Stall detection + automated recovery\n4. **Context Safety**: Proactive compression prevents overflow\n5. **Coordination**: Shared state + tick clock keeps everyone in sync\n\nThe key insight: **agents should never be idle without a task**. Either they work from their queue, help a buddy, or generate valuable work based on their role."}],"api":"anthropic-messages","provider":"anthropic","model":"claude-opus-4-5","usage":{"input":10,"output":7595,"cacheRead":5405,"cacheWrite":6276,"totalTokens":19286,"cost":{"input":0.00005,"output":0.18987500000000002,"cacheRead":0.0027025,"cacheWrite":0.039225,"total":0.23185250000000002}},"stopReason":"stop","timestamp":1771308366855}}