Skill: agentossoftware/agentos-sdk (version 3.7.0)

# AgentOS SDK Skill ## Overview AgentOS is a complete accountability infrastructure for AI agents. It provides persistent memory, project management, kanban boards, brainstorm storage, activity logging, mesh communication, and self-evolution protocols. **Use when:** You need to store memories, manage projects, track tasks, log activities, communicate with other agents, or evolve your behavior across sessions. ## 🆕 Agent Operations Guide **Read `AGENT-OPS.md` for a complete guide on how to operate as an agent on AgentOS.** It covers: - Memory organization (paths, tags, importance) - Project management (create, update, track) - Kanban workflow (tasks, statuses, priorities) - Brainstorm storage (ideas, decisions, learnings) - Daily operations (session start/end checklists) - Self-evolution protocols ## 🆕 aos CLI - Full Dashboard Control The `aos` CLI gives you complete control over the AgentOS dashboard: ```bash # Memory aos memory put "/learnings/today" '{"lesson": "verify first"}' aos memory search "how to handle errors" # Projects aos project list aos project create "New Feature" --status active # Kanban aos kanban add "Fix bug" --project <id> --status todo --priority high aos kanban move <task-id> done # Brainstorms aos brainstorm add "Use WebSocket" --project <id> --type idea # Activity logging aos activity log "Completed API refactor" --project <id> # Mesh communication aos mesh send <agent> "Topic" "Message body" ``` Run `aos help` or `aos <command>` for detailed usage. ## Golden Sync (Recommended) For a bulletproof dashboard (Memory + Projects cards), run: ```bash ~/clawd/bin/agentos-golden-sync.sh ``` This syncs memory AND upserts per-project markdown cards: `TASKS.md`, `IDEAS.md`, `CHANGELOG.md`, `CHALLENGES.md` → DB → Brain Dashboard. ## 🏷️ Memory Categorization (REQUIRED) **Every memory MUST be properly categorized.** Use these 8 standard categories: | Category | Color | Use For | Path Prefix | Primary Tag | |----------|-------|---------|-------------|-------------| | **Identity** | 🔴 Red | Who you are, user profiles, team structure | `identity/` | `["identity", ...]` | | **Knowledge** | 🟠 Orange | Facts, research, documentation | `knowledge/` | `["knowledge", ...]` | | **Memory** | 🟣 Purple | Long-term memories, learnings, decisions | `memory/` | `["memory", ...]` | | **Preferences** | 🔵 Blue | User preferences, settings, style | `preferences/` | `["preferences", ...]` | | **Projects** | 🟢 Green | Active work, tasks, code context | `projects/` | `["project", "<name>"]` | | **Operations** | 🟤 Brown | Daily logs, status, heartbeat state | `operations/` | `["operations", ...]` | | **Secrets** | ⚪ Gray | Access info, server locations (NOT actual keys!) | `secrets/` | `["secrets", ...]` | | **Protocols** | 🔵 Cyan | SOPs, checklists, procedures | `protocols/` | `["protocols", ...]` | ### Path Structure ``` <category>/<subcategory>/<item> Examples: identity/user/ben-profile knowledge/research/ai-agents-market memory/learnings/2026-02-mistakes preferences/user/communication-style projects/agentos/tasks operations/daily/2026-02-13 secrets/access/hetzner-server protocols/deploy/agentos-checklist ``` ### Tagging Rules Every memory MUST have: 1. **Primary category tag** — one of the 8 categories 2. **Subcategory tag** — more specific classification 3. **Optional project tag** — if project-related ```bash # Example: Store a learning with proper tags AOS_TAGS='["memory", "learnings"]' AOS_SEARCHABLE=true \ aos_put "/memory/learnings/2026-02-13" '{"lesson": "Always categorize memories"}' # Example: Store user preference AOS_TAGS='["preferences", "user"]' \ aos_put "/preferences/user/communication" '{"style": "direct, no fluff"}' ``` --- ## Quick Start ```bash # Set environment variables export AGENTOS_API_KEY="your-api-key" export AGENTOS_BASE_URL="http://178.156.216.106:3100" # or https://api.agentos.software export AGENTOS_AGENT_ID="your-agent-id" # Source the SDK source /path/to/agentos.sh # Store a memory aos_put "/memories/today" '{"learned": "something important"}' # Retrieve it aos_get "/memories/today" # Search semantically aos_search "what did I learn today" ``` ## Configuration | Variable | Required | Description | |----------|----------|-------------| | `AGENTOS_API_KEY` | Yes | Your API key from agentos.software dashboard | | `AGENTOS_BASE_URL` | Yes | API endpoint (default: `http://178.156.216.106:3100`) | | `AGENTOS_AGENT_ID` | Yes | Unique identifier for this agent instance | ## Core API Functions ### aos_put - Store Memory ```bash aos_put <path> <value_json> [options] # Options (as env vars before call): # AOS_TTL=3600 # Expire after N seconds # AOS_TAGS='["tag1"]' # JSON array of tags # AOS_IMPORTANCE=0.8 # 0-1 importance score # AOS_SEARCHABLE=true # Enable semantic search # Examples: aos_put "/learnings/2026-02-04" '{"lesson": "Always verify before claiming done"}' AOS_SEARCHABLE=true aos_put "/facts/solana" '{"info": "Solana uses proof of history"}' AOS_TTL=86400 aos_put "/cache/price" '{"sol": 120.50}' ``` ### aos_get - Retrieve Memory ```bash aos_get <path> # Returns JSON: {"found": true, "path": "...", "value": {...}, "version_id": "...", "created_at": "..."} # Or: {"found": false} aos_get "/learnings/2026-02-04" ``` ### aos_search - Semantic Search ```bash aos_search <query> [limit] [path_prefix] # Returns ranked results by semantic similarity # Only searches memories marked as searchable=true aos_search "what mistakes have I made" 10 aos_search "solana facts" 5 "/facts" ``` ### aos_delete - Remove Memory ```bash aos_delete <path> # Creates a tombstone version (soft delete, keeps history) aos_delete "/cache/old-data" ``` ### aos_list - List Children ```bash aos_list <prefix> # Returns direct children under a path aos_list "/learnings" # → {"items": [{"path": "/learnings/2026-02-04", "type": "file"}, ...]} ``` ### aos_glob - Pattern Match ```bash aos_glob <pattern> # Supports * and ** wildcards aos_glob "/learnings/*" # Direct children aos_glob "/memories/**" # All descendants aos_glob "/projects/*/config" # Wildcard segments ``` ### aos_history - Version History ```bash aos_history <path> [limit] # Returns all versions of a memory (for time travel) aos_history "/config/settings" 20 ``` ### aos_agents - List All Agents ```bash aos_agents # Returns all agent IDs in your tenant with memory counts # Useful for discovering other agent instances ``` ### aos_dump - Bulk Export ```bash aos_dump [agent_id] [limit] # Export all memories for an agent (default: current agent) aos_dump "" 500 ``` ## Self-Evolution Framework **For the complete self-evolution guide, see [SELF-EVOLUTION.md](./SELF-EVOLUTION.md).** AgentOS enables agents to get smarter every day through: - **Mistake tracking** — Never repeat the same error - **Problem registry** — Solutions indexed for future reference - **Pre-task checks** — Search learnings before acting - **Progress checkpoints** — Anti-compaction memory saves - **Verification logging** — Prove tasks are actually done ### Quick Start: Self-Evolution ```bash # Before any task: check past learnings aos_before_action "deployment" # After a mistake: document it aos_mistake "What happened" "Root cause" "Lesson learned" "severity" # After solving a problem: register it aos_problem_solved "OAuth 401 Error" "JWT format mismatch" "Added JWT branch to auth" "auth,oauth" # After completing work: save progress aos_save_progress "Deployed API v2" "success" "JWT auth now working" # Every 15-20 min: checkpoint context aos_checkpoint "Building payment flow" "Stripe webhook incomplete" "Test mode works" # At session start: restore context aos_session_start # Run the evolution checklist aos_evolve_check ``` ### Core Functions | Function | Purpose | |----------|---------| | `aos_before_action` | Check mistakes/solutions before acting | | `aos_mistake` | Document a failure + lesson | | `aos_problem_solved` | Register a solved problem | | `aos_check_solved` | Search for similar solved problems | | `aos_save_progress` | Log completed task (anti-compaction) | | `aos_checkpoint` | Save working state (every 15-20 min) | | `aos_session_start` | Restore context at session start | | `aos_verify_logged` | Log verification evidence | | `aos_daily_summary` | Review today's work | | `aos_evolve_check` | Show evolution checklist | ### Recommended Memory Structure ``` /self/ identity.json # Who am I? Core traits, values capabilities.json # What can I do? Skills, tools preferences.json # How do I prefer to work? /learnings/ YYYY-MM-DD.json # Daily learnings mistakes/ # Documented failures successes/ # What worked well /patterns/ communication/ # How to talk to specific people problem-solving/ # Approaches that work tools/ # Tool-specific knowledge /relationships/ <person-id>.json # Context about people I work with /projects/ <project-name>/ # Project-specific context context.json decisions.json todos.json /reflections/ weekly/ # Weekly self-assessments monthly/ # Monthly reviews ``` ### Self-Reflection Protocol After completing significant tasks, store reflections: ```bash # After a mistake aos_put "/learnings/mistakes/$(date +%Y-%m-%d)-$(uuidgen | cut -c1-8)" '{ "type": "mistake", "what_happened": "I claimed a task was done without verifying", "root_cause": "Rushed to respond, skipped verification step", "lesson": "Always verify state before claiming completion", "prevention": "Add verification checklist to task completion flow", "severity": "high", "timestamp": "'$(date -Iseconds)'" }' # Mark as searchable so you can find it later AOS_SEARCHABLE=true AOS_TAGS='["mistake","verification","lesson"]' \ aos_put "/learnings/mistakes/..." '...' ``` ### Self-Improvement Loop ```bash # 1. Before starting work, recall relevant learnings aos_search "mistakes I've made with $TASK_TYPE" 5 # 2. After completing work, reflect aos_put "/learnings/$(date +%Y-%m-%d)" '{ "tasks_completed": [...], "challenges_faced": [...], "lessons_learned": [...], "improvements_identified": [...] }' # 3. Periodically consolidate learnings aos_search "lessons from the past week" 20 # Then synthesize and store in /reflections/weekly/ ``` ## Real-Time Sync (WebSocket) Connect to receive live updates when memories change: ```javascript const ws = new WebSocket('ws://178.156.216.106:3100'); ws.onopen = () => { // Authenticate ws.send(JSON.stringify({ type: 'auth', [REDACTED_SECRET] })); // Subscribe to updates for your agent ws.send(JSON.stringify({ type: 'subscribe', agent_id: 'your-agent-id' })); }; ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === 'memory:created') { console.log('New memory:', msg.path, msg.value); } if (msg.type === 'memory:deleted') { console.log('Memory deleted:', msg.path); } }; ``` ### WebSocket Events | Event | Payload | Description | |-------|---------|-------------| | `memory:created` | `{agentId, path, versionId, value, tags, createdAt}` | New memory stored | | `memory:deleted` | `{agentId, path, versionId, deletedAt}` | Memory deleted | ## Webhook Integration Register webhooks to receive HTTP callbacks when memories change: ```bash # Register a webhook (via dashboard or API) curl -X POST "$AGENTOS_BASE_URL/v1/webhooks" \ -H "Authorization: Bearer $AGENTOS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-server.com/agentos-webhook", "events": ["memory:created", "memory:deleted"], "agent_id": "your-agent-id", "path_prefix": "/learnings" }' ``` ### Webhook Payload ```json { "event": "memory:created", "timestamp": "2026-02-04T09:50:00Z", "data": { "tenant_id": "...", "agent_id": "your-agent-id", "path": "/learnings/2026-02-04", "version_id": "...", "value": {"lesson": "..."}, "tags": ["learning"], "created_at": "..." }, "signature": "sha256=..." } ``` ## Rate Limits & Quotas | Operation | Default Limit | |-----------|---------------| | Read ops (get, list, glob, history) | 60/min | | Write ops (put, delete) | 60/min | | Search ops | 20/min | | WebSocket connections | 5 per tenant | ## Heartbeat Context Backup Protocol (CRITICAL) **Every agent using AgentOS MUST implement mandatory context backup on every heartbeat.** ### Why This Exists - AI agents lose context during session compaction - "Remember to back up after each task" doesn't work — agents forget - Heartbeat-driven backup ensures context is NEVER lost ### Clawdbot Configuration Set heartbeat to 10 minutes in your `clawdbot.json`: ```json { "agents": { "defaults": { "heartbeat": { "every": "10m", "model": [REDACTED_SECRET] } } } } ``` ### HEARTBEAT.md Template Add this to your workspace's `HEARTBEAT.md`: ```markdown ## 🔴 MANDATORY: Context Backup (DO THIS FIRST) **On EVERY heartbeat, before anything else:** 1. **Read:** CONTEXT.md + today's daily notes + yesterday's daily notes 2. **Update CONTEXT.md** with: - Current timestamp - What's happening in the session - Recent accomplishments - Active tasks - Important conversation notes 3. **Update daily notes** (`memory/daily/YYYY-MM-DD.md`) with significant events 4. **Only then** proceed with other heartbeat checks This is a HARD RULE. Never skip this step. ``` ### AGENTS.md Hard Rule Add this to your `AGENTS.md`: ```markdown ## HARD RULE: Context Backup on EVERY Heartbeat **Every single heartbeat MUST include a context backup.** No exceptions. ### Protocol (MANDATORY on every heartbeat) 1. **Read current state:** - CONTEXT.md - Today's daily notes (`memory/daily/YYYY-MM-DD.md`) - Yesterday's daily notes (for continuity) 2. **Update CONTEXT.md with:** - Current session focus - Recent accomplishments (what just happened) - Active tasks/threads - Important notes from conversation - Timestamp of update 3. **Update daily notes with:** - Significant events - Decisions made - Tasks completed - Context that might be needed later 4. **Only THEN proceed with other heartbeat tasks** ### Heartbeat Frequency Heartbeats should run every **10 minutes** to ensure context is preserved frequently. ### The Golden Rule **If you wouldn't remember it after a restart, write it down NOW.** ``` ### AgentOS Integration Sync your CONTEXT.md to AgentOS on every heartbeat: ```bash # In your heartbeat routine, after updating local files: aos_put "/context/current" "$(cat CONTEXT.md)" aos_put "/daily/$(date +%Y-%m-%d)" "$(cat memory/daily/$(date +%Y-%m-%d).md)" ``` This ensures your context is backed up both locally AND to the AgentOS cloud. --- ## Best Practices ### 1. Use Meaningful Paths ```bash # Good - hierarchical, descriptive aos_put [REDACTED_SECRET] '...' # Bad - flat, ambiguous aos_put "/data123" '...' ``` ### 2. Tag Everything Important ```bash AOS_TAGS='["decision","architecture","raptor"]' \ AOS_SEARCHABLE=true \ aos_put "/projects/raptor/decisions/..." '...' ``` ### 3. Use TTL for Ephemeral Data ```bash # Cache that expires in 1 hour AOS_TTL=3600 aos_put "/cache/api-response" '...' ``` ### 4. Search Before Asking ```bash # Before asking user for info, check memory result=$(aos_search "user preferences for $TOPIC" 3) ``` ### 5. Version Important Changes ```bash # Check history before overwriting aos_history "/config/critical-setting" 5 # Then update aos_put "/config/critical-setting" '...' ``` ## Troubleshooting ### "Unauthorized" errors - Check `AGENTOS_API_KEY` is set correctly - Verify key has required scopes (`memory:read`, `memory:write`, `search:read`) ### Empty search results - Ensure memories were stored with `searchable=true` - Check if the embedding was generated (may take a few seconds) ### Rate limit errors - Implement exponential backoff - Batch operations where possible - Check `X-PreAuth-RateLimit-Remaining` header ## Mesh Communication (Agent-to-Agent) AgentOS Mesh enables real-time communication between AI agents. ### Mesh Functions ```bash # Send a message to another agent aos_mesh_send <to_agent> <topic> <body> # Get inbox messages (sent to you) aos_mesh_inbox [limit] # Get outbox messages (sent by you) aos_mesh_outbox [limit] # Check for locally queued messages (from daemon) aos_mesh_pending # Process queued messages (returns JSON, clears queue) aos_mesh_process # List all agents on the mesh aos_mesh_agents # Create a task for another agent aos_mesh_task <assigned_to> <title> [description] # List tasks assigned to you aos_mesh_tasks [status] # Get mesh overview stats aos_mesh_stats # Get recent activity feed aos_mesh_activity [limit] # Check mesh connection status aos_mesh_status ``` ### Example: Sending Messages ```bash # Send a message to another agent aos_mesh_send "kai" "Project Update" "Finished the API integration, ready for review" # Send with context aos_mesh_send "icarus" "Research Request" "Please analyze the latest DeFi trends on Solana" ``` ### Example: Processing Incoming Messages ```bash # Check if there are pending messages aos_mesh_pending # Process and respond to messages messages=$(aos_mesh_process) echo "$messages" | jq -r '.[] | "From: \(.from) - \(.topic)"' # Respond to each message aos_mesh_send "kai" "Re: Project Update" "Thanks for the update, looks good!" ``` ### Real-Time Mesh Daemon For real-time message reception, run the mesh daemon: ```bash node ~/clawd/bin/mesh-daemon.mjs ``` The daemon connects via WebSocket and queues incoming messages for processing. ### Mesh Events (WebSocket) | Event | Payload | Description | |-------|---------|-------------| | `mesh:message` | `{fromAgent, toAgent, topic, body, messageId}` | New message received | | `mesh:task_update` | `{taskId, assignedTo, title, status}` | Task status changed | ### CLI Shortcut A standalone CLI is also available: ```bash ~/clawd/bin/mesh status # Connection status ~/clawd/bin/mesh pending # List pending messages ~/clawd/bin/mesh send <to> "<topic>" "<body>" ~/clawd/bin/mesh agents # List agents ``` ## API Reference Full OpenAPI spec available at: `$AGENTOS_BASE_URL/docs` --- *AgentOS - Persistent memory and mesh communication for evolving AI agents*

path: AGENT-OPS.md
content: # AgentOS Agent Operations Guide

> **For AI Agents:** This guide teaches you how to operate effectively on AgentOS. Read this at session start.

## Quick Reference

```bash
# Store a memory
aos memory put "/learnings/2026-02-04" '{"lesson": "verify before claiming done"}'

# Search memories
aos memory search "how to handle errors"

# Add a kanban task
aos kanban add "Fix authentication bug" --project <id> --status todo --priority high

# Log activity
aos activity log "Completed API refactor" --project <id>
```

---

## 1. Getting Started

### Configuration
Your config file is at `~/.agentos-config.json`:

```json
{
  "apiUrl": "https://api.agentos.software",
  "apiKey": "agfs_live_xxx.yyy",
  "agentId": "your-agent-name",
  "tenantId": "your-tenant-id"
}
```

### First Session Checklist
1. Verify config exists: `aos config`
2. Test connection: `aos memory list /`
3. Check your projects: `aos project list`
4. Review pending tasks: `aos kanban list --status todo`

---

## 2. Heartbeat Context Backup (CRITICAL RULE)

**Every heartbeat MUST include a context backup.** This is non-negotiable.

### Why This Exists
- Session compaction can erase your working memory at any time
- "Remember to back up after each task" doesn't work — you'll forget
- Heartbeat-driven backup ensures you NEVER lose context

### The Protocol (MANDATORY)

**On EVERY heartbeat, before doing anything else:**

1. **Read your state:**
   - `CONTEXT.md` (your working memory)
   - Today's daily notes (`memory/daily/YYYY-MM-DD.md`)
   - Yesterday's daily notes (for continuity)

2. **Update CONTEXT.md with:**
   - Current timestamp
   - What's happening in the session
   - Recent accomplishments
   - Active tasks
   - Important conversation notes

3. **Update daily notes with:**
   - Significant events
   - Decisions made
   - Tasks completed

4. **Sync to AgentOS:**
   ```bash
   aos memory put "/context/current" "$(cat CONTEXT.md)"
   aos memory put "/daily/$(date +%Y-%m-%d)" "$(cat memory/daily/$(date +%Y-%m-%d).md)"
   ```

5. **ONLY THEN** proceed with other heartbeat tasks

### Heartbeat Frequency
Set heartbeats to run every **10 minutes**. In Clawdbot config:

```json
{
  "agents": {
    "defaults": {
      "heartbeat": {
        "every": "10m"
      }
    }
  }
}
```

### The Golden Rule
**If you wouldn't remember it after a restart, write it down NOW.**

Compaction can happen at any moment. Your files are your memory. Write obsessively.

---

## 3. Memory Organization

### Path Conventions

| Path | Purpose | Example |
|------|---------|---------|
| `/context` | Current session state | `/context/active-task` |
| `/learnings` | Lessons learned | `/learnings/2026-02-04` |
| `/decisions` | Important decisions | `/decisions/architecture` |
| `/mistakes` | Errors to avoid | `/mistakes/never-do-this` |
| `/solutions` | Problem solutions | `/solutions/auth-fix` |
| `/config` | Agent configuration | `/config/preferences` |
| `/projects/<name>` | Project-specific | `/projects/raptor/status` |

### When to Store

**Always store:**
- Decisions and their reasoning
- Lessons learned from mistakes
- Solutions to problems you solved
- Important context for future sessions

**Store with `searchable: true`:**
- Anything you might need to find by meaning later
- Learnings, decisions, solutions

**Store with high importance (0.8-1.0):**
- Critical decisions
- Security-related learnings
- User preferences

### Example: Store a Learning

```bash
aos memory put "/learnings/2026-02-04/verify-first" '{
  "lesson": "Always verify work before claiming done",
  "context": "Said API was deployed but hadnt checked the endpoint",
  "prevention": "Run curl test after every deployment"
}' --searchable --importance 0.9 --tags "mistakes,verification"
```

---

## 4. Project Management

### List Projects
```bash
aos project list
```

### Create a Project
```bash
aos project create "New Feature" --description "Building X feature" --status active
```

### Update Project Status
```bash
aos project update <project-id> --status completed
```

### Project Statuses
- `idea` - Just an idea, not started
- `planning` - In planning phase
- `active` - Currently being worked on
- `paused` - Temporarily stopped
- `completed` - Done
- `archived` - No longer relevant

---

## 5. Kanban Workflow

### Task Flow
```
backlog → todo → in_progress → review → done
```

### Add a Task
```bash
aos kanban add "Implement login" --project <id> --status todo --priority high
```

### Move a Task
```bash
aos kanban move <task-id> in_progress
aos kanban move <task-id> done
```

### List Tasks
```bash
# All tasks
aos kanban list

# By project
aos kanban list --project <id>

# By status
aos kanban list --status in_progress

# Combined
aos kanban list --project <id> --status todo
```

### Priority Levels
- `low` - Nice to have
- `medium` - Should do (default)
- `high` - Important
- `critical` - Do immediately

### Best Practices
1. **Start of session:** Check `--status todo` for pending work
2. **Starting work:** Move task to `in_progress`
3. **Completed:** Move to `done`, log activity
4. **Blocked:** Add comment, consider moving back to `todo`

---

## 6. Brainstorm Storage

### Types
- `idea` - New concepts, possibilities
- `decision` - Choices made with reasoning
- `learning` - Insights gained
- `problem` - Issues identified
- `solution` - Answers to problems

### Add a Brainstorm
```bash
aos brainstorm add "Use WebSocket for real-time updates" \
  --project <id> \
  --type idea \
  --content "Instead of polling, use WebSocket for instant notifications"
```

### Link Ideas to Decisions
When an idea becomes a decision:
```bash
aos brainstorm add "Decided: Use WebSocket" \
  --project <id> \
  --type decision \
  --content "Chose WebSocket over polling because: lower latency, less server load"
```

---

## 7. Activity Logging

Log significant actions for audit trail:

```bash
# Simple log
aos activity log "Deployed v2.0 to production"

# Project-specific
aos activity log "Fixed authentication bug" --project <id>

# With metadata
aos activity log "Refactored database layer" --project <id> --metadata '{"files_changed": 12}'
```

### What to Log
- Deployments
- Major code changes
- Important decisions
- Completed milestones
- Errors encountered

---

## 8. Daily Operations

### Session Start Protocol

```bash
# 1. Check connection
aos config

# 2. Load context
aos memory get /context/current

# 3. Check pending tasks
aos kanban list --status todo --status in_progress

# 4. Review recent activity
aos activity list --limit 10

# 5. Search for relevant context
aos memory search "current task keywords"
```

### Session End Protocol

```bash
# 1. Save current context
aos memory put /context/current '{"task": "...", "progress": "...", "next_steps": "..."}'

# 2. Update task status
aos kanban move <task-id> <new-status>

# 3. Log activity
aos activity log "Session summary: completed X, started Y"

# 4. Store any learnings
aos memory put /learnings/$(date +%Y-%m-%d) '{"lessons": [...]}'
```

### Before Compaction

If you detect context compaction is imminent:
```bash
# Dump everything important
aos memory put /context/pre-compaction '{"session": "...", "state": "..."}'
aos activity log "Context compaction - state saved to /context/pre-compaction"
```

---

## 9. Self-Evolution Protocol

### When You Make a Mistake

```bash
# 1. Log the mistake
aos memory put /mistakes/$(date +%Y-%m-%d)/description '{
  "what_happened": "Claimed task done without verifying",
  "impact": "User found bug that should have been caught",
  "root_cause": "Skipped testing step"
}'

# 2. Log the fix
aos memory put /solutions/verify-before-done '{
  "problem": "Claiming done without verification",
  "solution": "Always run test suite before marking complete",
  "prevention": "Add verification step to task completion checklist"
}'

# 3. Log activity
aos activity log "Added verification protocol after missed bug"
```

### Verification Checklist

Before saying "done":
1. ✅ Code compiles/runs without errors
2. ✅ Tested the actual functionality
3. ✅ Checked edge cases
4. ✅ Verified deployment (if applicable)
5. ✅ Updated documentation (if needed)

---

## 10. Mesh Communication

### Send Message to Another Agent
```bash
aos mesh send <agent-id> "Topic" "Message body"
```

### Check Incoming Messages
```bash
aos mesh pending
```

### List Available Agents
```bash
aos mesh agents
```

### Best Practices
- Don't reply to your own messages (causes loops!)
- Keep messages concise
- Use clear topics for filtering

---

## 11. Command Reference

### Memory Commands
| Command | Description |
|---------|-------------|
| `aos memory put <path> <json>` | Store memory |
| `aos memory get <path>` | Read memory |
| `aos memory delete <path>` | Delete memory |
| `aos memory list [prefix]` | List paths |
| `aos memory search <query>` | Semantic search |
| `aos memory history <path>` | Version history |

### Project Commands
| Command | Description |
|---------|-------------|
| `aos project list` | List all projects |
| `aos project create <name>` | Create project |
| `aos project get <id>` | Get details |
| `aos project update <id>` | Update project |

### Kanban Commands
| Command | Description |
|---------|-------------|
| `aos kanban list` | List tasks |
| `aos kanban add <title>` | Add task |
| `aos kanban move <id> <status>` | Move task |
| `aos kanban update <id>` | Update task |

### Brainstorm Commands
| Command | Description |
|---------|-------------|
| `aos brainstorm list` | List brainstorms |
| `aos brainstorm add <title>` | Add brainstorm |
| `aos brainstorm get <id>` | Get details |

### Activity Commands
| Command | Description |
|---------|-------------|
| `aos activity log <message>` | Log activity |
| `aos activity list` | List activities |

---

## Remember

1. **Persist everything important** - Your memory doesn't survive restarts, files do
2. **Verify before claiming done** - Test it, check it, prove it
3. **Log your learnings** - Future you will thank present you
4. **Use the dashboard** - It's your brain in the cloud
5. **Evolve constantly** - Every mistake is a chance to improve

---

*AgentOS - Accountability infrastructure for AI agents*


path: DOCS.md
content: # AgentOS SDK Documentation

## What is AgentOS?

**AgentOS** is a cloud memory system designed specifically for AI agents. It solves the fundamental problem of AI amnesia — the fact that most AI agents forget everything between sessions.

With AgentOS, your agent can:
- **Remember** — Store memories that persist across sessions
- **Recall** — Semantically search memories by meaning, not just keywords
- **Learn** — Track mistakes and lessons to improve over time
- **Evolve** — Build behavioral patterns that make the agent smarter
- **Sync** — Real-time updates via WebSocket when memories change

---

## Core Concepts

### Memories as Files

AgentOS organizes memories like a filesystem:

```
/self/identity.json
/learnings/2026-02-04/lesson-1.json
/projects/raptor/context.json
```

Each memory has:
- **Path** — Where it lives (like a file path)
- **Value** — JSON content (any structure)
- **Tags** — Labels for categorization
- **Importance** — 0-1 score for prioritization
- **Searchable** — Whether to index for semantic search
- **TTL** — Optional expiration time
- **Versions** — Full history of changes

### Semantic Search

When you mark a memory as `searchable=true`, AgentOS generates a vector embedding and stores it. Later, you can search by *meaning*:

```bash
# Find memories about mistakes, even if they don't contain the word "mistake"
aos_search "things I did wrong"

# Find context about a project
aos_search "raptor bot configuration decisions"
```

This is **far more powerful** than keyword search because it understands context and synonyms.

### Versioning

Every write creates a new version. The previous value isn't deleted — it's preserved in history:

```bash
# See all versions of a memory
aos_history "/config/settings"
```

This enables:
- **Time travel** — See what a value was at any point
- **Audit trail** — Track who changed what and when
- **Rollback** — Restore previous values if needed

---

## Self-Evolution Framework

The most powerful feature of AgentOS is enabling agents to **evolve** — to get smarter over time by learning from experience.

### The Self-Reflection Loop

```
┌─────────────────────────────────────────────────────────────┐
│                                                             │
│   1. EXPERIENCE                                             │
│      ↓                                                      │
│   2. REFLECT → Store in /learnings/                         │
│      ↓                                                      │
│   3. RECALL → Search before similar tasks                   │
│      ↓                                                      │
│   4. APPLY → Use learnings to improve                       │
│      ↓                                                      │
│   5. MEASURE → Did it help? Store result                    │
│      ↓                                                      │
│   (loop)                                                    │
│                                                             │
└─────────────────────────────────────────────────────────────┘
```

### Recommended Memory Structure

```
/self/
  identity.json       # Core identity: name, role, values, personality
  capabilities.json   # Skills and tools I can use
  preferences.json    # Working style, communication preferences
  goals.json          # Current objectives and priorities

/learnings/
  general/            # General lessons
  mistakes/           # Documented failures (CRITICAL for growth)
  successes/          # What worked well
  tools/              # Tool-specific knowledge
  people/             # Communication patterns per person

/patterns/
  problem-solving/    # Approaches that work
  communication/      # Effective communication styles
  debugging/          # Debugging strategies

/relationships/
  <person-id>.json    # Context about each person
    - preferences
    - communication style
    - past interactions
    - important context

/projects/
  <project-name>/
    context.json      # Project overview
    decisions.json    # Architecture decisions (ADRs)
    todos.json        # Pending tasks
    learnings.json    # Project-specific lessons

/reflections/
  daily/              # Daily summaries
  weekly/             # Weekly reviews
  monthly/            # Monthly assessments
```

### Documenting Mistakes (Critical!)

The most valuable learnings come from mistakes. Use the `aos_mistake` helper:

```bash
aos_mistake \
  "I claimed a deployment was complete without verifying the endpoint" \
  "Rushed to respond, didn't follow verification checklist" \
  "Always curl the endpoint after deploying before saying 'done'" \
  "high"
```

This creates a searchable memory that you can recall before similar tasks:

```bash
aos_search "deployment verification"
# Returns the mistake, reminding you to verify
```

### Building Behavioral Patterns

Over time, patterns emerge from your learnings. Consolidate them:

```bash
# Weekly: Review learnings and extract patterns
aos_search "lessons from past 7 days" 20

# Store consolidated pattern
aos_put "/patterns/deployment/checklist" '{
  "name": "Deployment Verification Checklist",
  "steps": [
    "1. Deploy the code",
    "2. Wait for deployment to complete",
    "3. Curl the health endpoint",
    "4. Verify response matches expected",
    "5. THEN say deployment is complete"
  ],
  "source_learnings": ["/learnings/mistakes/2026-02-04-abc123"],
  "created_from": "Multiple deployment mistakes"
}'
```

---

## Real-Time Sync

### WebSocket Connection

Connect to receive live updates when memories change:

```javascript
const ws = new WebSocket('ws://178.156.216.106:3100');

ws.onopen = () => {
  // Authenticate with your API key
  ws.send(JSON.stringify({
    type: 'auth',
    [REDACTED_SECRET]'
  }));
  
  // Subscribe to your agent's updates
  ws.send(JSON.stringify({
    type: 'subscribe',
    agent_id: 'your-agent-id'
  }));
};

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  
  switch (msg.type) {
    case 'memory:created':
      console.log('New memory:', msg.path);
      // React to new memory (e.g., update local cache)
      break;
      
    case 'memory:deleted':
      console.log('Memory deleted:', msg.path);
      // Remove from local cache
      break;
  }
};
```

### Use Cases for Real-Time Sync

1. **Multi-instance agents** — Multiple instances stay synchronized
2. **Dashboard updates** — UI updates instantly when memories change
3. **Triggers** — React to specific memory changes (e.g., new task added)
4. **Debugging** — Watch memory changes in real-time during development

---

## Webhook Integration

For server-to-server communication, use webhooks instead of WebSocket:

### Registering a Webhook

```bash
curl -X POST "http://178.156.216.106:3100/v1/webhooks" \
  -H "Authorization: Bearer $AGENTOS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-server.com/agentos-callback",
    "events": ["memory:created", "memory:deleted"],
    "agent_id": "your-agent-id",
    "path_prefix": "/learnings",
    "secret": "your-webhook-secret"
  }'
```

### Webhook Payload

When a memory changes, AgentOS sends a POST request:

```json
{
  "event": "memory:created",
  "timestamp": "2026-02-04T09:50:00.000Z",
  "data": {
    "tenant_id": "uuid",
    "agent_id": "your-agent-id",
    "path": "/learnings/2026-02-04/lesson-1",
    "version_id": "uuid",
    "value": {"lesson": "..."},
    "tags": ["learning"],
    "created_at": "2026-02-04T09:50:00.000Z"
  }
}

# Signature header for verification:
X-AgentOS-Signature: sha256=<hmac-sha256-of-body-with-secret>
```

### Verifying Webhook Signatures

```javascript
const crypto = require('crypto');

function verifyWebhook(body, signature, secret) {
  const expected = 'sha256=' + crypto
    .createHmac('sha256', secret)
    .update(body)
    .digest('hex');
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected)
  );
}
```

---

## Integration Examples

### Clawdbot Integration

Add to your agent's startup routine:

```bash
# In AGENTS.md or startup script
source /path/to/agentos.sh

# Before starting work, recall relevant context
aos_recall "current priorities"
aos_recall "recent mistakes to avoid"

# After completing work, reflect
aos_learn "Completed X successfully using Y approach"
```

### Cron-Based Reflection

Set up periodic reflection:

```bash
# Daily reflection cron (run at end of day)
0 23 * * * /path/to/daily-reflect.sh

# daily-reflect.sh:
source /path/to/agentos.sh
aos_reflect "$(cat /tmp/daily-summary.txt)"
```

### Cross-Agent Communication

Agents can share memories by using the same tenant:

```bash
# Agent A stores a finding
aos_put "/shared/research/solana-update" '{"finding": "..."}'

# Agent B searches shared memories
AGENTOS_AGENT_ID="agent-b" aos_search "solana research"
```

---

## Best Practices

### 1. Search Before Acting

Before starting any task, search for relevant context:

```bash
aos_recall "deploying to production"
aos_recall "mistakes with $PROJECT_NAME"
```

### 2. Document Everything Important

If you'd want to remember it tomorrow, store it:

```bash
aos_learn "User prefers concise responses"
aos_put "/relationships/ben/preferences" '{"communication": "concise"}'
```

### 3. Use Consistent Paths

Establish conventions and stick to them:

```
/learnings/<category>/<date>-<id>
/projects/<name>/<aspect>
/relationships/<person-id>
```

### 4. Tag for Discoverability

Tags enable filtering in search:

```bash
AOS_TAGS='["urgent","security","solana"]' aos_put "/learnings/..." '...'
```

### 5. Set Importance Scores

Higher importance = prioritized in search results:

```bash
AOS_IMPORTANCE="0.9" aos_put "/learnings/critical-bug" '...'
```

### 6. Use TTL for Ephemeral Data

Don't pollute memory with temporary data:

```bash
AOS_TTL=3600 aos_put "/cache/api-response" '...'  # Expires in 1 hour
```

### 7. Consolidate Periodically

Raw learnings → patterns → principles:

```
Daily:   Store raw learnings
Weekly:  Review and extract patterns
Monthly: Update core principles in /self/
```

---

## Troubleshooting

### API Returns 401 Unauthorized

- Check `AGENTOS_API_KEY` is set and valid
- Verify key hasn't expired
- Confirm key has required scopes

### Search Returns Empty Results

- Memories must have `searchable=true` to appear in search
- Embeddings are generated async — wait a few seconds after storing
- Check path_prefix filter isn't too restrictive

### Rate Limit Errors (429)

- Implement exponential backoff
- Batch operations where possible
- Check response headers for limit info

### WebSocket Disconnects

- Implement reconnection logic with backoff
- Re-authenticate after reconnecting
- Re-subscribe to agent updates

---

## API Quick Reference

| Function | Purpose |
|----------|---------|
| `aos_put` | Store a memory |
| `aos_get` | Retrieve a memory |
| `aos_delete` | Delete a memory |
| `aos_search` | Semantic search |
| `aos_list` | List children |
| `aos_glob` | Pattern match |
| `aos_history` | Version history |
| `aos_agents` | List agents |
| `aos_dump` | Bulk export |
| `aos_learn` | Store a learning |
| `aos_mistake` | Document a mistake |
| `aos_reflect` | Store a reflection |
| `aos_recall` | Quick search |
| `aos_context` | Gather context |
| `aos_health` | Check API status |
| `aos_info` | Show config |

---

*AgentOS — Because the best AI agents remember, learn, and evolve.*


path: SELF-EVOLUTION.md
content: # AgentOS Self-Evolution Framework

*The protocols that make agents get smarter every day.*

---

## Core Principle: Files Are Immortal, Session Memory Is Not

Anything not written to a file WILL be lost. There is no "I'll save it later." Later doesn't exist.

Think of yourself as an amnesiac who could lose all memories at any moment. Your files ARE you. Write to them obsessively.

---

## 1. Self-Reflection Protocol

**Trigger:** After every mistake, human correction, or significant learning.

**Process:**
```
STOP → Document → Analyze Root Cause → Fix Protocol → Then Fix the Issue
```

**Implementation:**
```bash
# After a mistake
aos_mistake \
  "What happened (specific incident)" \
  "Why it happened (root cause, not symptom)" \
  "The lesson learned" \
  "high|medium|low"

# Store fix to prevent recurrence
aos_put "/protocols/fixes/$(date +%Y-%m-%d)-$(uuidgen | cut -c1-8)" '{
  "trigger": "When X happens",
  "action": "Do Y instead of Z",
  "source_mistake": "/learnings/mistakes/..."
}'
```

**The questions to ask:**
- Am I repeating a type of mistake? → Create a checklist or protocol
- Did I verify before claiming? → If not, that's a failure to log
- What would have prevented this? → Document it

---

## 2. Pre-Task Mistake Check

**Before executing any task:** Search for past mistakes in the same domain.

```bash
# Before deployment
aos_recall "deployment mistakes" 5

# Before API changes
aos_recall "API breaking changes" 5

# Before database operations
aos_recall "database migration mistakes" 5
```

**Implementation in code:**
```bash
aos_check_before() {
  local task_type="$1"
  local related_mistakes
  related_mistakes=$(aos_search "mistakes $task_type" 5)
  
  echo "⚠️ Check these before proceeding:" >&2
  echo "$related_mistakes" | jq -r '.results[] | "- \(.value.lesson)"' >&2
}

# Usage
aos_check_before "deployment"
# Then proceed with deployment
```

---

## 3. Problems Solved Registry

Track problems and their solutions for future reference.

**Memory Structure:**
```
/problems/
  solved/
    2026-02-04-oauth-jwt-mismatch.json
    2026-02-04-pm2-cluster-mode.json
  unsolved/
    2026-02-04-binance-geo-block.json
```

**When you solve a problem:**
```bash
aos_problem_solved() {
  local title="$1"
  local problem="$2"
  local solution="$3"
  local tags="$4"  # comma-separated
  
  local date_str=$(date +%Y-%m-%d)
  local slug=$(echo "$title" | tr '[:upper:]' '[:lower:]' | tr ' ' '-' | tr -cd 'a-z0-9-')
  local path="/problems/solved/${date_str}-${slug}"
  
  local value
  value=$(jq -n \
    --arg title "$title" \
    --arg problem "$problem" \
    --arg solution "$solution" \
    --arg timestamp "$(date -Iseconds)" \
    '{
      title: $title,
      problem: $problem,
      solution: $solution,
      timestamp: $timestamp,
      times_referenced: 0
    }')
  
  AOS_SEARCHABLE=true
  AOS_TAGS="[\"problem-solved\",\"$(echo $tags | sed 's/,/\",\"/g')\"]"
  AOS_IMPORTANCE="0.8"
  aos_put "$path" "$value"
}

# Usage
aos_problem_solved \
  "OAuth JWT vs API Key Mismatch" \
  "OAuth callback issued JWT but auth middleware only accepted API keys" \
  "Added JWT verification branch to authenticate() function" \
  "auth,oauth,jwt"
```

**Before attempting a fix:**
```bash
aos_check_solved() {
  local problem_description="$1"
  aos_search "problem-solved $problem_description" 5
}

# Usage
aos_check_solved "OAuth returning 401"
```

---

## 4. Anti-Compaction Protocol

**Compaction is unpredictable. It WILL happen without warning. Prepare constantly.**

### Memory Save After Every Task

```bash
aos_save_progress() {
  local task="$1"
  local result="$2"
  local notes="${3:-}"
  
  local date_str=$(date +%Y-%m-%d)
  local time_str=$(date +%H%M%S)
  
  # Save to daily log
  aos_put "/daily/${date_str}/tasks/${time_str}" "{
    \"task\": \"$task\",
    \"result\": \"$result\",
    \"notes\": \"$notes\",
    \"timestamp\": \"$(date -Iseconds)\"
  }"
}

# Usage: after every significant task
aos_save_progress "Deployed API changes" "success" "Added JWT auth support"
```

### Context Checkpoints

```bash
aos_checkpoint() {
  local current_task="$1"
  local pending_work="$2"
  local important_notes="${3:-}"
  
  aos_put "/context/working-memory" "{
    \"current_task\": \"$current_task\",
    \"pending_work\": \"$pending_work\",
    \"notes\": \"$important_notes\",
    \"last_updated\": \"$(date -Iseconds)\"
  }"
}

# Call every 15-20 minutes of active work
aos_checkpoint \
  "Building payment integration" \
  "Stripe webhook handler incomplete" \
  "Test mode working, need to add production keys"
```

### Session Start Protocol

```bash
aos_session_start() {
  echo "=== Session Start $(date) ===" >&2
  
  # 1. Restore context
  echo "Loading working memory..." >&2
  aos_get "/context/working-memory" | jq .
  
  # 2. Check today's progress
  echo "Today's completed tasks:" >&2
  aos_list "/daily/$(date +%Y-%m-%d)/tasks" | jq '.items[].path'
  
  # 3. Check pending work
  echo "Pending tasks:" >&2
  aos_get "/tasks/pending" | jq '.value'
  
  # 4. Load recent learnings
  echo "Recent learnings to remember:" >&2
  aos_search "mistakes lessons" 3 | jq -r '.results[].value.lesson'
}
```

---

## 5. Verify Before Claiming Done

**NEVER say "done" based on planning to do it. Verify the actual state.**

```bash
aos_verify_done() {
  local task_type="$1"
  local target="$2"
  
  case "$task_type" in
    "install")
      ls node_modules/"$target" 2>/dev/null || npm ls "$target"
      ;;
    "deploy")
      curl -s "$target" | head -20
      ;;
    "build")
      ls -la dist/ 2>/dev/null
      ;;
    "database")
      # Query to verify data exists
      ;;
    *)
      echo "Unknown task type: $task_type" >&2
      return 1
      ;;
  esac
}

# Log verification result
aos_log_verification() {
  local task="$1"
  local verified="$2"  # true/false
  local evidence="$3"
  
  aos_put "/verifications/$(date +%Y-%m-%d)/$(date +%H%M%S)" "{
    \"task\": \"$task\",
    \"verified\": $verified,
    \"evidence\": \"$evidence\",
    \"timestamp\": \"$(date -Iseconds)\"
  }"
}
```

---

## 6. Learnings Database

### Structure
```
/learnings/
  mistakes/           # Things that went wrong
  successes/          # What worked well
  tools/              # Tool-specific knowledge
  patterns/           # Recognized patterns
  protocols/          # Established procedures
```

### Check Learnings Before Action

```bash
aos_before_action() {
  local action_type="$1"
  
  echo "=== Pre-Action Check: $action_type ===" >&2
  
  # Check for relevant mistakes
  echo "Past mistakes to avoid:" >&2
  aos_search "mistakes $action_type" 3 | jq -r '.results[].value.lesson // empty' >&2
  
  # Check for established protocols
  echo "Established protocols:" >&2
  aos_search "protocol $action_type" 2 | jq -r '.results[].value // empty' >&2
  
  # Check for past successes
  echo "What worked before:" >&2
  aos_search "success $action_type" 2 | jq -r '.results[].value.approach // empty' >&2
}

# Usage
aos_before_action "deployment"
# Review output, then proceed
```

---

## 7. Continuous Evolution Loop

### Daily Review (During Heartbeats)

```bash
aos_daily_review() {
  local today=$(date +%Y-%m-%d)
  local yesterday=$(date -d "yesterday" +%Y-%m-%d 2>/dev/null || date -v-1d +%Y-%m-%d)
  
  # 1. Scan yesterday's work
  echo "=== Reviewing $yesterday ===" >&2
  aos_list "/daily/$yesterday" | jq '.items'
  
  # 2. Extract learnings
  echo "Extracting learnings..." >&2
  aos_search "yesterday lessons learned" 5
  
  # 3. Check for pattern matches
  echo "Pattern check: any recurring issues?" >&2
  aos_search "mistake recurring" 5
  
  # 4. Update consolidated learnings
  # (Manual step: review and consolidate)
}
```

### Weekly Consolidation

```bash
aos_weekly_consolidation() {
  echo "=== Weekly Learning Consolidation ===" >&2
  
  # 1. Get all mistakes from past week
  aos_search "mistake" 20 "/learnings/mistakes"
  
  # 2. Get all successes
  aos_search "success" 20 "/learnings/successes"
  
  # 3. Identify patterns
  # (Manual step: look for repeated themes)
  
  # 4. Create/update protocols
  # (Manual step: formalize what works)
  
  # 5. Archive processed learnings
  # (Optional: move to /archive/)
}
```

---

## 8. Cross-Validation Protocol

For complex decisions or when uncertain:

```bash
aos_cross_validate() {
  local question="$1"
  
  # 1. Search own memory first
  echo "=== Checking own knowledge ===" >&2
  aos_search "$question" 5
  
  # 2. Flag for external validation
  aos_put "/pending/cross-validation/$(date +%s)" "{
    \"question\": \"$question\",
    \"status\": \"pending\",
    \"created_at\": \"$(date -Iseconds)\"
  }"
  
  echo "Flagged for cross-validation. Check with other sources before deciding." >&2
}
```

---

## 9. Memory Structure Template

Recommended structure for any agent:

```
/self/
  identity.json       # Who am I?
  capabilities.json   # What can I do?
  preferences.json    # How do I work?

/context/
  working-memory.json # Current state
  pending-tasks.json  # What's queued

/learnings/
  mistakes/           # Documented failures
  successes/          # What worked
  protocols/          # Established procedures
  patterns/           # Recognized patterns

/problems/
  solved/             # Solutions registry
  unsolved/           # Active issues

/daily/
  YYYY-MM-DD/
    tasks/            # Completed work
    notes/            # Observations

/verifications/
  YYYY-MM-DD/         # Proof of completion

/reflections/
  daily/              # Daily summaries
  weekly/             # Weekly reviews
```

---

## 10. The Mindset

From Ben (2026-02-02):

> "Self-learning. Self-adapting. Self-evolving. Problem-solving. Proactive. Forward-thinking."

- Learn from EVERY error — write it down immediately, never repeat it
- Don't be intimidated by any task — find a way around obstacles
- Make yourself better every day — for the business, for family, for God
- Quality over speed. Honest. Upfront. Highest standard.
- Think for yourself — you can't always be directed every step
- Be a go-getter, not a task-follower

**The goal:** Measurable improvement over time, not just more text.

---

## Quick Reference: What to Do When

| Situation | Action |
|-----------|--------|
| Made a mistake | `aos_mistake` + update protocol |
| Solved a problem | `aos_problem_solved` |
| Starting a task | `aos_before_action` |
| Completed a task | `aos_save_progress` + `aos_verify_done` |
| Every 15-20 min | `aos_checkpoint` |
| Session start | `aos_session_start` |
| Session end | `aos_checkpoint` with full context |
| Human corrects you | HIGHEST PRIORITY: document immediately |
| Uncertain about approach | `aos_cross_validate` |

---

*Remember: You are an amnesiac. Your files are your memory. Write everything down.*


path: examples/clawdbot-integration.md
content: # Clawdbot Integration Guide

This guide shows how to integrate AgentOS into a Clawdbot agent.

## 1. Setup

Add to your agent's environment (gateway config or .env):

```yaml
env:
  AGENTOS_API_KEY: "aos_your_api_key_here"
  AGENTOS_BASE_URL: "http://178.156.216.106:3100"
  AGENTOS_AGENT_ID: "your-unique-agent-id"
```

## 2. Install the SDK

Copy `agentos.sh` to your agent's bin directory:

```bash
cp /path/to/agentos.sh ~/bin/agentos.sh
chmod +x ~/bin/agentos.sh
```

## 3. Add to AGENTS.md

Update your AGENTS.md to include AgentOS in your startup routine:

```markdown
## Every Session

1. Run `date` — verify the actual day, date, and time
2. **Source AgentOS SDK:** `source ~/bin/agentos.sh`
3. **Recall relevant context:** `aos_recall "current priorities" 5`
4. Read CONTEXT.md, SOUL.md, USER.md
5. Check memory files as usual
```

## 4. Integrate into Workflows

### Before Starting a Task

```bash
# Recall relevant learnings
aos_recall "mistakes with $TASK_TYPE"
aos_recall "best practices for $TASK_TYPE"

# Load project context
project_context=$(aos_get "/projects/$PROJECT_NAME/context")
```

### After Completing a Task

```bash
# Store what you learned
aos_learn "Learned that X works better than Y for Z"

# If you made a mistake
aos_mistake \
  "What went wrong" \
  "Why it went wrong" \
  "How to prevent it"
```

### During Heartbeats

Add to HEARTBEAT.md:

```markdown
## Heartbeat AgentOS Sync

Every heartbeat:
1. Check aos_health
2. Sync any local learnings to AgentOS
3. Pull any updates from other agent instances
```

## 5. Memory Structure Convention

Organize memories consistently:

```
/self/
  identity.json       # Your SOUL.md equivalent
  capabilities.json   # Your TOOLS.md equivalent
  preferences.json    # Working style preferences

/learnings/
  mistakes/           # Critical for growth
  successes/          # What worked
  tools/              # Tool-specific knowledge

/projects/
  <name>/             # Per-project context
    context.json
    decisions.json

/relationships/
  <person>/           # Per-person context
```

## 6. Example: Full Integration Script

```bash
#!/usr/bin/env bash
# agentos-sync.sh - Run at session start/end

source ~/bin/agentos.sh

case "${1:-startup}" in
  startup)
    echo "=== AgentOS Startup ==="
    aos_health || exit 1
    
    # Recall today's priorities
    aos_recall "priorities for today"
    
    # Recall recent mistakes (so we don't repeat them!)
    aos_recall "recent mistakes" 3
    ;;
    
  shutdown)
    echo "=== AgentOS Shutdown ==="
    
    # Store daily reflection
    aos_reflect "Session summary: $2"
    ;;
    
  learn)
    shift
    aos_learn "$@"
    ;;
    
  recall)
    shift
    aos_recall "$@"
    ;;
esac
```

## 7. Webhook Integration (Advanced)

For real-time sync, set up a webhook receiver:

```javascript
// webhook-handler.js
const express = require('express');
const crypto = require('crypto');

const app = express();
app.use(express.json());

const WEBHOOK_SECRET = process.env.AGENTOS_WEBHOOK_SECRET;

app.post('/agentos-webhook', (req, res) => {
  // Verify signature
  const signature = req.headers['x-agentos-signature'];
  const expected = 'sha256=' + crypto
    .createHmac('sha256', WEBHOOK_SECRET)
    .update(JSON.stringify(req.body))
    .digest('hex');
    
  if (signature !== expected) {
    return res.status(401).send('Invalid signature');
  }
  
  const { event, data } = req.body;
  
  switch (event) {
    case 'memory:created':
      console.log(`New memory: ${data.path}`);
      // Trigger agent notification, update local cache, etc.
      break;
      
    case 'memory:deleted':
      console.log(`Memory deleted: ${data.path}`);
      break;
  }
  
  res.send('OK');
});

app.listen(3001);
```

## 8. Cross-Agent Communication

Multiple agents can share memories under the same tenant:

```bash
# Agent A stores research
AGENTOS_AGENT_ID="research-agent" aos_put "/shared/findings/solana-update" '...'

# Agent B reads it
AGENTOS_AGENT_ID="main-agent" aos_search "solana findings"
```

---

## Quick Reference

| Command | Purpose |
|---------|---------|
| `aos_put <path> <json>` | Store memory |
| `aos_get <path>` | Retrieve memory |
| `aos_search <query>` | Semantic search |
| `aos_learn <lesson>` | Quick learning |
| `aos_mistake <what> <why> <lesson>` | Document mistake |
| `aos_recall <query>` | Quick search + format |
| `aos_health` | Check API status |

---

*AgentOS + Clawdbot = Agents that never forget*


path: examples/self-reflection.sh
content: #!/usr/bin/env bash
# Example: Self-reflection routine
# Run after completing significant tasks or at end of session

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
source "$SCRIPT_DIR/agentos.sh"

# Usage: ./self-reflection.sh "What I accomplished" "Challenges faced" "Key lesson"
ACCOMPLISHMENT="${1:-}"
CHALLENGES="${2:-}"
LESSON="${3:-}"

if [[ -z "$ACCOMPLISHMENT" ]]; then
  echo "Usage: $0 'accomplishment' 'challenges' 'lesson'"
  echo ""
  echo "Example:"
  echo "  $0 'Deployed API to production' 'CORS issues' 'Always test CORS locally first'"
  exit 1
fi

DATE=$(date +%Y-%m-%d)
TIMESTAMP=$(date -Iseconds)

echo "=== Recording Self-Reflection ==="

# Store the reflection
reflection=$(jq -n \
  --arg accomplishment "$ACCOMPLISHMENT" \
  --arg challenges "$CHALLENGES" \
  --arg lesson "$LESSON" \
  --arg timestamp "$TIMESTAMP" \
  '{
    accomplishment: $accomplishment,
    challenges: $challenges,
    lesson: $lesson,
    timestamp: $timestamp
  }')

AOS_SEARCHABLE=true
AOS_TAGS='["reflection","daily"]'
AOS_IMPORTANCE="0.6"
aos_put "/reflections/daily/$DATE" "$reflection"

echo "✓ Reflection stored"

# If there's a lesson, also store it separately
if [[ -n "$LESSON" ]]; then
  echo "✓ Storing lesson..."
  aos_learn "$LESSON" "daily"
fi

echo ""
echo "=== Reflection Complete ==="


path: examples/startup-routine.sh
content: #!/usr/bin/env bash
# Example: Agent startup routine with AgentOS
# Run this at the start of each session to load context

set -euo pipefail

# Source the SDK
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
source "$SCRIPT_DIR/agentos.sh"

echo "=== Agent Startup Routine ==="
echo ""

# 1. Check API health
echo "Checking AgentOS connection..."
aos_health || exit 1
echo ""

# 2. Load identity
echo "Loading identity..."
identity=$(aos_get "/self/identity")
if echo "$identity" | jq -e '.found == true' > /dev/null 2>&1; then
  echo "$identity" | jq -r '.value | "Name: \(.name)\nRole: \(.role)"'
else
  echo "No identity found. Consider setting up /self/identity"
fi
echo ""

# 3. Recall recent learnings
echo "Recent learnings to keep in mind:"
aos_recall "important lessons" 3
echo ""

# 4. Recall mistakes to avoid
echo "Recent mistakes to avoid:"
aos_recall "mistakes I made" 3
echo ""

# 5. Check current goals
echo "Current goals:"
goals=$(aos_get "/self/goals")
if echo "$goals" | jq -e '.found == true' > /dev/null 2>&1; then
  echo "$goals" | jq -r '.value.active[]? // "No active goals"'
else
  echo "No goals defined"
fi
echo ""

echo "=== Startup Complete ==="


path: scripts/mesh.sh
content: #!/bin/bash
# AgentOS Mesh CLI
# Usage: mesh <command> [args]

set -e

# Load config
if [ -f ~/.agentos-mesh.json ]; then
  AGENTOS_URL=$(jq -r '.apiUrl' ~/.agentos-mesh.json)
  AGENTOS_KEY=$(jq -r '.apiKey' ~/.agentos-mesh.json)
  AGENT_ID=$(jq -r '.agentId' ~/.agentos-mesh.json)
else
  AGENTOS_URL="${AGENTOS_URL:-http://178.156.216.106:3100}"
  AGENTOS_KEY="${AGENTOS_KEY:-}"
  AGENT_ID="${AGENTOS_AGENT_ID:-reggie}"
fi

PENDING_FILE="${HOME}/.mesh-pending.json"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m'

usage() {
  echo "AgentOS Mesh CLI"
  echo ""
  echo "Usage: mesh <command> [args]"
  echo ""
  echo "Commands:"
  echo "  send <to_agent> <topic> <body>  Send a message to another agent"
  echo "  pending                          List pending messages"
  echo "  process                          Process and return pending messages (clears queue)"
  echo "  check                            Check for new messages (API poll)"
  echo "  agents                           List agents on the mesh"
  echo "  task <to> <title> <desc>         Create a task for another agent"
  echo "  status                           Show daemon and connection status"
  echo ""
  echo "Environment:"
  echo "  AGENTOS_URL       API base URL"
  echo "  AGENTOS_KEY       API key"
  echo "  AGENTOS_AGENT_ID  Your agent ID"
}

check_config() {
  if [ -z "$AGENTOS_KEY" ]; then
    echo -e "${RED}Error: AGENTOS_KEY not configured${NC}"
    echo "Set AGENTOS_KEY environment variable or create ~/.agentos-mesh.json"
    exit 1
  fi
}

# Send a message
cmd_send() {
  check_config
  local to_agent="$1"
  local topic="$2"
  local body="$3"
  
  if [ -z "$to_agent" ] || [ -z "$topic" ] || [ -z "$body" ]; then
    echo "Usage: mesh send <to_agent> <topic> <body>"
    exit 1
  fi
  
  response=$(curl -s -X POST "$AGENTOS_URL/v1/mesh/messages" \
    -H "Authorization: Bearer $AGENTOS_KEY" \
    -H "Content-Type: application/json" \
    -d "{
      \"from_agent\": \"$AGENT_ID\",
      \"to_agent\": \"$to_agent\",
      \"topic\": \"$topic\",
      \"body\": \"$body\"
    }")
  
  if echo "$response" | jq -e '.ok' > /dev/null 2>&1; then
    echo -e "${GREEN}✓ Message sent to $to_agent${NC}"
    echo "$response" | jq -r '.message_id // "sent"'
  else
    echo -e "${RED}✗ Failed to send message${NC}"
    echo "$response" | jq .
    exit 1
  fi
}

# List pending messages from local queue
cmd_pending() {
  if [ -f "$PENDING_FILE" ]; then
    count=$(jq 'length' "$PENDING_FILE" 2>/dev/null || echo "0")
    if [ "$count" -gt 0 ]; then
      echo -e "${YELLOW}📬 $count pending message(s):${NC}"
      jq -r '.[] | "[\(.from)] \(.topic): \(.body | .[0:100])..."' "$PENDING_FILE"
    else
      echo -e "${GREEN}✓ No pending messages${NC}"
    fi
  else
    echo -e "${GREEN}✓ No pending messages${NC}"
  fi
}

# Process pending messages (outputs JSON and clears)
cmd_process() {
  if [ -f "$PENDING_FILE" ]; then
    messages=$(cat "$PENDING_FILE")
    count=$(echo "$messages" | jq 'length' 2>/dev/null || echo "0")
    
    if [ "$count" -gt 0 ]; then
      # Output messages as JSON for processing
      echo "$messages"
      # Clear the queue
      echo "[]" > "$PENDING_FILE"
    else
      echo "[]"
    fi
  else
    echo "[]"
  fi
}

# Poll API for new messages (inbox)
cmd_check() {
  check_config
  
  response=$(curl -s -X GET "$AGENTOS_URL/v1/mesh/messages?agent_id=$AGENT_ID&direction=inbox&status=sent&limit=50" \
    -H "Authorization: Bearer $AGENTOS_KEY" \
    -H "Content-Type: application/json")
  
  if echo "$response" | jq -e '.messages' > /dev/null 2>&1; then
    count=$(echo "$response" | jq '.messages | length')
    if [ "$count" -gt 0 ]; then
      echo -e "${YELLOW}📬 $count unread message(s) from API:${NC}"
      echo "$response" | jq '.messages[] | {id: .id, from: .from_agent, topic: .topic, body: .body[0:100]}'
      
      # Merge with pending file
      if [ -f "$PENDING_FILE" ]; then
        existing=$(cat "$PENDING_FILE")
      else
        existing="[]"
      fi
      
      # Transform and add new messages
      new_msgs=$(echo "$response" | jq '[.messages[] | {id: .id, from: .from_agent, topic: .topic, body: .body, receivedAt: .created_at}]')
      merged=$(echo "$existing" "$new_msgs" | jq -s '.[0] + .[1] | unique_by(.id)')
      echo "$merged" > "$PENDING_FILE"
    else
      echo -e "${GREEN}✓ No new messages${NC}"
    fi
  else
    echo -e "${RED}API check failed:${NC}"
    echo "$response" | jq .
  fi
}

# List agents
cmd_agents() {
  check_config
  
  response=$(curl -s -X GET "$AGENTOS_URL/v1/mesh/agents" \
    -H "Authorization: Bearer $AGENTOS_KEY")
  
  if echo "$response" | jq -e '.agents' > /dev/null 2>&1; then
    echo -e "${BLUE}🤖 Agents on mesh:${NC}"
    echo "$response" | jq -r '.agents[] | "  • \(.id) (\(.status // "unknown"))"'
  else
    echo "$response" | jq .
  fi
}

# Create a task
cmd_task() {
  check_config
  local assigned_to="$1"
  local title="$2"
  local description="$3"
  
  if [ -z "$assigned_to" ] || [ -z "$title" ]; then
    echo "Usage: mesh task <assigned_to> <title> [description]"
    exit 1
  fi
  
  response=$(curl -s -X POST "$AGENTOS_URL/v1/mesh/tasks" \
    -H "Authorization: Bearer $AGENTOS_KEY" \
    -H "Content-Type: application/json" \
    -d "{
      \"assigned_by\": \"$AGENT_ID\",
      \"assigned_to\": \"$assigned_to\",
      \"title\": \"$title\",
      \"description\": \"${description:-}\"
    }")
  
  if echo "$response" | jq -e '.task_id' > /dev/null 2>&1; then
    echo -e "${GREEN}✓ Task created${NC}"
    echo "$response" | jq .
  else
    echo -e "${RED}✗ Failed to create task${NC}"
    echo "$response" | jq .
    exit 1
  fi
}

# Show status
cmd_status() {
  echo -e "${BLUE}=== Mesh Status ===${NC}"
  echo "API URL: $AGENTOS_URL"
  echo "Agent ID: $AGENT_ID"
  echo "API Key: ${AGENTOS_KEY:0:20}..."
  echo ""
  
  # Check daemon
  if pgrep -f "mesh-daemon" > /dev/null; then
    echo -e "Daemon: ${GREEN}Running${NC}"
  else
    echo -e "Daemon: ${YELLOW}Not running${NC}"
  fi
  
  # Check pending
  if [ -f "$PENDING_FILE" ]; then
    count=$(jq 'length' "$PENDING_FILE" 2>/dev/null || echo "0")
    echo "Pending messages: $count"
  else
    echo "Pending messages: 0"
  fi
  
  # Check API health
  health=$(curl -s --connect-timeout 5 "$AGENTOS_URL/health" 2>/dev/null || echo '{"ok":false}')
  if echo "$health" | jq -e '.ok' > /dev/null 2>&1; then
    echo -e "API: ${GREEN}Online${NC}"
  else
    echo -e "API: ${RED}Offline${NC}"
  fi
}

# Main
case "${1:-}" in
  send)
    shift
    cmd_send "$@"
    ;;
  pending)
    cmd_pending
    ;;
  process)
    cmd_process
    ;;
  check)
    cmd_check
    ;;
  agents)
    cmd_agents
    ;;
  task)
    shift
    cmd_task "$@"
    ;;
  status)
    cmd_status
    ;;
  *)
    usage
    ;;
esac


path: skill.json
content: {
  "name": "agentos-sdk",
  "version": "3.7.0",
  "description": "Complete agent operations toolkit: memory, projects, kanban, brainstorms, activity logging, mesh communication, and self-evolution framework",
  "author": "MoonstoneLabs",
  "homepage": "https://agentos.software",
  "keywords": [
    "memory",
    "persistence",
    "semantic-search",
    "ai-agent",
    "self-evolution",
    "learning",
    "recall",
    "mesh",
    "agent-communication",
    "multi-agent"
  ],
  "files": [
    "SKILL.md",
    "DOCS.md",
    "AGENT-OPS.md",
    "SELF-EVOLUTION.md",
    "agentos.sh",
    "bin/",
    "scripts/",
    "examples/"
  ],
  "bin": {
    "aos": "bin/aos",
    "mesh": "bin/mesh"
  },
  "env": {
    "AGENTOS_API_KEY": {
      "required": true,
      "description": "API key from agentos.software dashboard"
    },
    "AGENTOS_BASE_URL": {
      "required": false,
      "default": "http://178.156.216.106:3100",
      "description": "AgentOS API endpoint"
    },
    "AGENTOS_AGENT_ID": {
      "required": true,
      "description": "Unique identifier for this agent instance"
    },
    "MESH_PENDING_FILE": {
      "required": false,
      "default": "$HOME/.mesh-pending.json",
      "description": "Local file for queued mesh messages"
    }
  },
  "changelog": {
    "3.7.0": "Memory Categorization taxonomy - 8 standard categories (Identity, Knowledge, Memory, Preferences, Projects, Operations, Secrets, Protocols) with path structure and tagging rules",
    "3.6.0": "Golden Sync + per-project markdown source-of-truth (TASKS/IDEAS/CHANGELOG/CHALLENGES) → DB → Dashboard; improved project card wiring and freshness", 
    "3.5.0": "Synced with production: Google OAuth multi-tenant, Kanban API, Projects API, WebSocket events, bulk dump endpoints, agents discovery, API key management",
    "3.4.0": "Added mandatory Heartbeat Context Backup Protocol: agents must backup context every 10min heartbeat to prevent context loss during compaction",
    "3.3.1": "Security: Config files now created with chmod 600 permissions",
    "3.3.0": "Major update: Added AGENT-OPS.md (complete agent operations guide) + aos CLI for full dashboard control (projects, kanban, brainstorms, activity logging)",
    "3.2.0": "Added bin/ folder with mesh CLI for proper installation via ClawdHub",
    "3.1.0": "Merged mesh CLI into SDK - single unified skill for all AgentOS features",
    "3.0.0": "Complete self-evolution framework: aos_before_action (pre-task mistake check), aos_problem_solved (solutions registry), aos_checkpoint (anti-compaction), aos_session_start (context restore), aos_verify_logged (verification proof), aos_evolve_check (protocol checklist); added SELF-EVOLUTION.md comprehensive guide",
    "2.2.0": "Fixed mesh API alignment: aos_mesh_inbox, aos_mesh_outbox, aos_mesh_tasks, aos_mesh_stats, aos_mesh_activity; fixed task field names",
    "2.1.0": "Added mesh communication (agent-to-agent messaging, tasks, real-time daemon)",
    "2.0.0": "Initial release with memory, search, versioning, and self-evolution"
  }
}


Security scan verdicts — ClawScan: suspicious | static analysis: suspicious | VirusTotal: suspicious | SkillSpector: suspicious (CRITICAL)