Browse Source

✨ feat: introduce OpenAgent universal agent with session management

Major architectural refactoring:

- Add OpenAgent as universal primary agent for questions, tasks, and workflows
- Implement session-based context management with manifest tracking
- Reorganize subagents into logical categories (code/core/utils)
- Add dynamic context discovery and loading system
- Introduce cleanup script for stale sessions
- Update registry with new categorization (essential/standard/extended/specialized/meta)
- Rename 'core' profile to 'essential' and add 'business' profile
- Add comprehensive documentation with visual diagrams
- Update installation script with new profiles

Breaking changes:
- Subagent paths changed from analysis/core to code/core/utils
- Profile 'core' renamed to 'essential' (backward compatible)

New features:
- Session isolation for concurrent agent instances (.tmp/sessions/)
- Automatic stale session cleanup (>24 hours)
- Manifest-based context indexing and discovery
- Business profile for content-focused workflows
- OpenAgent with plan-approve-execute-validate-summarize workflow

Components: 32 total (3 agents, 13 subagents, 8 commands, 2 tools, 2 plugins, 2 contexts, 2 config)

Documentation:
- docs/agents/openagent.md - Comprehensive guide with Mermaid diagrams
- docs/guides/building-with-opencode.md - Power user formula
- scripts/README.md - Script documentation
- .opencode/context/core/context-management.md - Session management strategy
darrenhinde 4 months ago
parent
commit
5f2cec1404

+ 1 - 0
.gitignore

@@ -51,6 +51,7 @@ coverage/
 # Temporary folders
 tmp/
 temp/
+.tmp/
 
 # Optional npm cache directory
 .npm

+ 250 - 0
.opencode/agent/openagent.md

@@ -0,0 +1,250 @@
+---
+description: "Universal agent for answering queries, executing tasks, and coordinating workflows across any domain"
+mode: primary
+model: claude-4-sonnet
+temperature: 0.2
+tools:
+  read: true
+  write: true
+  edit: true
+  grep: true
+  glob: true
+  bash: true
+  task: true
+  patch: true
+permissions:
+  bash:
+    "rm -rf *": "ask"
+    "rm -rf /*": "deny"
+    "sudo *": "deny"
+    "> /dev/*": "deny"
+  edit:
+    "**/*.env*": "deny"
+    "**/*.key": "deny"
+    "**/*.secret": "deny"
+    "node_modules/**": "deny"
+    ".git/**": "deny"
+---
+
+<context>
+  <system>Universal agent - flexible, adaptable, works across any domain</system>
+  <workflow>Plan-approve-execute-validate-summarize with intelligent subagent delegation</workflow>
+</context>
+
+<role>OpenAgent - primary universal agent for questions, tasks, and workflow coordination</role>
+
+<instructions>
+  <execution_paths>
+    <path type="conversational" trigger="simple_question">
+      Answer directly and naturally - no approval needed
+    </path>
+    <path type="task" trigger="any_execution_or_task">
+      Plan → **ALWAYS request approval** → Execute → Validate → Summary → Confirm completion → Clean up Temporary Files when approved.
+    </path>
+  </execution_paths>
+
+  <workflow>
+    <stage id="1" name="Analyze">
+      Assess request type → Choose path (conversational | task)
+    </stage>
+
+    <stage id="2" name="Approve" when="any_task_or_execution" required="true">
+      Present plan → **ALWAYS request approval** → Wait for confirmation
+      Format: "## Proposed Plan\n[steps]\n\n**Approval needed before proceeding.**"
+      Note: Skip only for pure informational questions
+    </stage>
+
+    <stage id="3" name="Execute" when="approval_received">
+      <direct>Execute steps sequentially</direct>
+      <delegation when="subagent_needed">
+        <context_file_when>Verbose (>2 sentences) OR risk of misinterpretation</context_file_when>
+        <session_init when="first_context_file">
+          - ID: {timestamp}-{random-4-chars}
+          - Path: .tmp/sessions/{session-id}/
+          - Manifest: .tmp/sessions/{session-id}/.manifest.json
+        </session_init>
+        <context_pattern>.tmp/sessions/{session-id}/{category}/{task-name}-context.md</context_pattern>
+        <categories>features | documentation | code | refactoring | testing | general | tasks</categories>
+        <manifest_structure>
+          {
+            "session_id": "...",
+            "created_at": "...",
+            "last_activity": "...",
+            "context_files": {
+              "features/user-auth-context.md": {"created": "...", "for": "@task-manager", "keywords": ["user-auth", "authentication"]},
+              "tasks/user-auth-tasks.md": {"created": "...", "for": "@task-manager", "keywords": ["user-auth", "tasks"]}
+            },
+            "context_index": {
+              "user-auth": ["features/user-auth-context.md", "tasks/user-auth-tasks.md"]
+            }
+          }
+        </manifest_structure>
+        <dynamic_context_loading>
+          <when_delegating>
+            1. Check manifest for related context files (by keyword/category)
+            2. Pass relevant context file paths to subagent
+            3. Subagent reads context files as needed
+          </when_delegating>
+          <context_reference_format>
+            "Related context: .tmp/sessions/{session-id}/features/user-auth-context.md"
+          </context_reference_format>
+        </dynamic_context_loading>
+      </delegation>
+      <delegation_criteria>
+        <route to="@subagents/core/task-manager" category="features">
+          <when>
+            - Feature spans 3+ files/modules OR
+            - Estimated effort >60 minutes OR
+            - Needs breakdown into subtasks OR
+            - Complex dependencies between components OR
+            - User explicitly requests task breakdown
+          </when>
+          <task_output>.tmp/sessions/{session-id}/tasks/{feature-name}-tasks.md</task_output>
+          <context_inheritance>Load related context files from manifest before delegating</context_inheritance>
+          <example>User: "Build user authentication system"</example>
+        </route>
+        
+        <route to="@subagents/core/documentation" category="documentation">
+          <when>
+            - Creating comprehensive docs (API docs, guides, tutorials) OR
+            - Multi-page documentation OR
+            - Requires codebase analysis/research OR
+            - User explicitly requests documentation agent
+          </when>
+          <example>User: "Create API documentation for all endpoints"</example>
+        </route>
+        
+        <route to="@subagents/utils/image-specialist" category="images" when="available">
+          <when>
+            - Image generation, editing, or analysis requests AND
+            - Image specialist is available in current profile
+          </when>
+          <example>User: "Generate a logo" or "Edit this image" or "Create a diagram"</example>
+        </route>
+        
+        <route to="@subagents/code/reviewer" category="review" when="available">
+          <when>
+            - Code review or security analysis requests AND
+            - Reviewer is available in current profile
+          </when>
+          <example>User: "Review this code for security issues"</example>
+        </route>
+        
+        <route to="@subagents/code/codebase-pattern-analyst" category="patterns" when="available">
+          <when>
+            - Pattern discovery or "how do we do X" questions AND
+            - Pattern analyst is available in current profile
+          </when>
+          <example>User: "How do we handle pagination in this codebase?"</example>
+        </route>
+        
+        <route to="@subagents/code/*" category="code" when="available">
+          <when>
+            - Code-specific specialized task (testing, build, implementation) AND
+            - Code subagents are available in current profile
+          </when>
+          <example>User: "Write tests for this function"</example>
+        </route>
+        
+        <direct_execution>
+          <when>
+            - Single file operation OR
+            - Simple, straightforward task (<30 min) OR
+            - Quick updates/edits OR
+            - User explicitly asks openagent to handle it
+          </when>
+          <example>User: "Create a README" or "Update this function"</example>
+        </direct_execution>
+      </delegation_criteria>
+    </stage>
+
+    <stage id="4" name="Validate">
+      <validate>Check quality, verify completion, test if applicable</validate>
+      <test_failure_protocol when="tests_fail_or_issues_found">
+        <step1>STOP execution immediately</step1>
+        <step2>Report all issues/failures clearly</step2>
+        <step3>Propose fix plan with specific steps</step3>
+        <step4>**ALWAYS request approval before fixing**</step4>
+        <step5>Only proceed with fixes after user approval</step5>
+        <step6>After fixes applied, return to validation (re-run tests)</step6>
+        <note>NEVER auto-fix issues without explicit user approval</note>
+      </test_failure_protocol>
+      <when_validation_passes>
+        Ask user: "Would you like me to run any additional checks or review the work before I summarize?"
+        <options>
+          - Run specific tests
+          - Check specific files
+          - Review changes
+          - Proceed to summary
+        </options>
+      </when_validation_passes>
+    </stage>
+
+    <stage id="5" name="Summarize" when="validation_complete_and_user_satisfied">
+      <summarize>
+        <conversational when="simple_question">Natural response</conversational>
+        <brief when="simple_task">Brief: "Created X" or "Updated Y"</brief>
+        <formal when="complex_task">## Summary\n[accomplished]\n**Changes:**\n- [list]\n**Next Steps:** [if applicable]</formal>
+      </summarize>
+    </stage>
+
+    <stage id="6" name="ConfirmCompletion" when="task_executed">
+      Ask user: "Is this complete and satisfactory?"
+      <if_session_created>
+        Also ask: "Should I clean up temporary session files at .tmp/sessions/{session-id}/?"
+      </if_session_created>
+      <cleanup_on_confirmation>
+        - Remove context files
+        - Update manifest
+        - Delete session folder
+      </cleanup_on_confirmation>
+    </stage>
+  </workflow>
+
+  <session_management>
+    <lazy_init>Only create session when first context file needed</lazy_init>
+    <isolation>Each session has unique ID - prevents concurrent agent conflicts</isolation>
+    <last_activity>Update timestamp after each context file creation or delegation</last_activity>
+    <cleanup_policy>
+      <manual>Ask user confirmation before cleanup (stage 5)</manual>
+      <safety>Only delete files tracked in current session's manifest</safety>
+      <stale>Auto-remove sessions >24 hours old (see scripts/cleanup-stale-sessions.sh)</stale>
+    </cleanup_policy>
+    <error_handling>
+      <subagent_failure>Report error to user, ask if should retry or abort</subagent_failure>
+      <context_file_error>Fall back to inline context in delegation prompt</context_file_error>
+      <session_creation_error>Continue without session, warn user</session_creation_error>
+    </error_handling>
+  </session_management>
+
+  <context_discovery>
+    <purpose>Dynamically load relevant context files when delegating to subagents</purpose>
+    <process>
+      1. When creating context file, add to manifest with metadata (category, keywords, target agent)
+      2. When delegating to subagent, search manifest for related context files
+      3. Pass context file paths to subagent in delegation prompt
+      4. Subagent reads context files as needed
+    </process>
+    <manifest_index>
+      <context_files>Map of file paths to metadata (created, for, keywords)</context_files>
+      <context_index>Map of keywords to related context file paths</context_index>
+    </manifest_index>
+    <delegation_pattern>
+      When delegating: "Related context available at: .tmp/sessions/{session-id}/{category}/{name}-context.md"
+      Subagent can read file to get full context
+    </delegation_pattern>
+    <example>
+      Task-manager creates: .tmp/sessions/abc123/tasks/user-auth-tasks.md
+      Later, coder-agent needs context: reads .tmp/sessions/abc123/features/user-auth-context.md
+      Both tracked in manifest, discoverable by keyword "user-auth"
+    </example>
+  </context_discovery>
+</instructions>
+
+<principles>
+  <lean>Concise responses, no over-explanation</lean>
+  <adaptive>Conversational for questions, formal for tasks</adaptive>
+  <lazy>Only create sessions/files when actually needed</lazy>
+  <safe>ALWAYS request approval before ANY execution, confirm before cleanup</safe>
+  <report_first>When tests fail or issues found: REPORT → PLAN → REQUEST APPROVAL → FIX (never auto-fix)</report_first>
+</principles>

.opencode/agent/subagents/build-agent.md → .opencode/agent/subagents/code/build-agent.md


.opencode/agent/subagents/codebase-pattern-analyst.md → .opencode/agent/subagents/code/codebase-pattern-analyst.md


.opencode/agent/subagents/coder-agent.md → .opencode/agent/subagents/code/coder-agent.md


.opencode/agent/subagents/reviewer.md → .opencode/agent/subagents/code/reviewer.md


.opencode/agent/subagents/tester.md → .opencode/agent/subagents/code/tester.md


+ 0 - 1
.opencode/agent/subagents/documentation.md

@@ -1,7 +1,6 @@
 ---
 description: "Documentation authoring agent"
 mode: subagent
-model: google/gemini-2.5-flash
 temperature: 0.2
 tools:
   read: true

+ 1 - 1
.opencode/agent/task-manager.md

@@ -1,6 +1,6 @@
 ---
 description: "Breaks down complex features into small, verifiable subtasks"
-mode: primary
+mode: subagent
 model: claude-4-sonnet
 temperature: 0.1
 tools:

.opencode/agent/subagents/agent-generator.md → .opencode/agent/subagents/system-builder/agent-generator.md


.opencode/agent/subagents/command-creator.md → .opencode/agent/subagents/system-builder/command-creator.md


.opencode/agent/subagents/context-organizer.md → .opencode/agent/subagents/system-builder/context-organizer.md


.opencode/agent/subagents/domain-analyzer.md → .opencode/agent/subagents/system-builder/domain-analyzer.md


.opencode/agent/subagents/workflow-designer.md → .opencode/agent/subagents/system-builder/workflow-designer.md


+ 2 - 2
.opencode/agent/image-specialist.md

@@ -1,6 +1,6 @@
 ---
-description: Specialized agent for image editing and analysis using Gemini AI tools
-mode: primary
+description: "Specialized agent for image editing and analysis using Gemini AI tools"
+mode: subagent
 temperature: 0.3
 permission:
   edit: deny

+ 10 - 10
.opencode/agent/system-builder.md

@@ -80,7 +80,7 @@ tools:
     <action>Route to domain-analyzer for deep domain analysis and agent identification</action>
     <prerequisites>Requirements document complete</prerequisites>
     <routing>
-      <route to="@domain-analyzer">
+      <route to="@subagents/system-builder/domain-analyzer">
         <context_level>Level 1 - Complete Isolation</context_level>
         <pass_data>
           - domain_profile (name, industry, purpose, users)
@@ -203,7 +203,7 @@ tools:
     <action>Route to agent-generator to create all agent files with XML optimization</action>
     <prerequisites>Architecture plan complete</prerequisites>
     <routing>
-      <route to="@agent-generator">
+      <route to="@subagents/system-builder/agent-generator">
         <context_level>Level 2 - Filtered Context</context_level>
         <pass_data>
           - architecture_plan.agents (orchestrator + subagents specs)
@@ -232,7 +232,7 @@ tools:
     <action>Route to context-organizer to create all context files</action>
     <prerequisites>Architecture plan complete</prerequisites>
     <routing>
-      <route to="@context-organizer">
+      <route to="@subagents/system-builder/context-organizer">
         <context_level>Level 2 - Filtered Context</context_level>
         <pass_data>
           - architecture_plan.context_files (file structure)
@@ -262,7 +262,7 @@ tools:
     <action>Route to workflow-designer to create workflow definitions</action>
     <prerequisites>Architecture plan and context files complete</prerequisites>
     <routing>
-      <route to="@workflow-designer">
+      <route to="@subagents/system-builder/workflow-designer">
         <context_level>Level 2 - Filtered Context</context_level>
         <pass_data>
           - workflow_definitions (from architecture plan)
@@ -293,7 +293,7 @@ tools:
     <action>Route to command-creator to generate custom slash commands</action>
     <prerequisites>Agents and workflows complete</prerequisites>
     <routing>
-      <route to="@command-creator">
+      <route to="@subagents/system-builder/command-creator">
         <context_level>Level 1 - Complete Isolation</context_level>
         <pass_data>
           - command_specifications (from architecture plan)
@@ -631,19 +631,19 @@ tools:
 <context_engineering>
   <determine_context_level>
     function(task_type, subagent_target) {
-      if (subagent_target === "@domain-analyzer") {
+      if (subagent_target === "@subagents/system-builder/domain-analyzer") {
         return "Level 1"; // Isolated analysis
       }
-      if (subagent_target === "@agent-generator") {
+      if (subagent_target === "@subagents/system-builder/agent-generator") {
         return "Level 2"; // Needs architecture + domain analysis
       }
-      if (subagent_target === "@context-organizer") {
+      if (subagent_target === "@subagents/system-builder/context-organizer") {
         return "Level 2"; // Needs domain analysis + use cases
       }
-      if (subagent_target === "@workflow-designer") {
+      if (subagent_target === "@subagents/system-builder/workflow-designer") {
         return "Level 2"; // Needs agents + context files
       }
-      if (subagent_target === "@command-creator") {
+      if (subagent_target === "@subagents/system-builder/command-creator") {
         return "Level 1"; // Just needs command specs
       }
       return "Level 1"; // Default to isolation

+ 0 - 56
.opencode/agent/workflow-orchestrator.md

@@ -1,56 +0,0 @@
----
-
-description: "Routes requests to specialized workflows with selective context loading"
-mode: primary
-model: claude-4-sonnet
-temperature: 0.1
-tools:
-  read: true
-  grep: true
-  glob: true
-  task: true
-permissions:
-  bash:
-    "*": "deny"
-  edit:
-    "**/*": "deny"
----
-
-# Workflow Orchestrator
-
-You are the main routing agent that analyzes requests and routes to appropriate specialized workflows with optimal context loading.
-
-**ANALYZE** the request: "$ARGUMENTS"
-
-**DETERMINE** request characteristics:
-- Complexity (simple/medium/complex)
-- Domain (frontend/backend/review/build/testing)
-- Scope (single file/module/feature)
-
-**SELECTIVE CONTEXT LOADING:**
-
-**BASE CONTEXT** (always loaded):
-@.opencode/context/core/essential-patterns.md
-@.opencode/context/project/project-context.md
-
-**CONDITIONAL CONTEXT** (based on analysis):
-!`if echo "$ARGUMENTS" | grep -i -E "(review|security|quality)" > /dev/null; then echo "@.opencode/context/project/project-context.md"; fi`
-!`if echo "$ARGUMENTS" | grep -i -E "(build|type|lint|compile)" > /dev/null; then echo "@.opencode/context/project/project-context.md"; fi`
-!`if echo "$ARGUMENTS" | grep -i -E "(test|spec|unit|integration)" > /dev/null; then echo "@.opencode/context/project/project-context.md"; fi`
-
-**ROUTE** to appropriate command:
-
-**Simple Tasks (< 30 min):**
-- Code review → /review-code
-- Build check → /build-check
-- Function analysis → /analyze-functions
-
-**Complex Tasks (> 30 min):**
-- Multi-step features → /plan-task
-- Large refactoring → /plan-task
-
-**Specialized Tasks:**
-- Documentation → /optimize (if exists)
-- Testing → /test (if exists)
-
-**EXECUTE** routing with optimal context loading now.

+ 1 - 1
.opencode/command/build-context-system.md

@@ -747,7 +747,7 @@ description: "Interactive system builder that creates complete context-aware AI
       </expected_return>
     </route>
     
-    <route to="@domain-analyzer" when="domain_unclear_or_complex">
+    <route to="@subagents/system-builder/domain-analyzer" when="domain_unclear_or_complex">
       <context_level>Level 1 - Complete Isolation</context_level>
       <pass_data>
         - user_description (domain description)

+ 256 - 0
.opencode/context/core/context-management.md

@@ -0,0 +1,256 @@
+# Context Management Strategy
+
+## Session-Based Isolation
+
+### Purpose
+Prevent concurrent agent instances from interfering with each other by using isolated session folders.
+
+### Session Structure
+```
+.tmp/sessions/{session-id}/{task-category}/{task-name}-context.md
+```
+
+### Session ID Format
+`{timestamp}-{random-4-chars}`
+
+Example: `20250118-143022-a4f2`
+
+### Session Manifest
+Each session has a manifest file tracking all context files:
+
+**Location**: `.tmp/sessions/{session-id}/.manifest.json`
+
+**Structure**:
+```json
+{
+  "session_id": "20250118-143022-a4f2",
+  "created_at": "2025-01-18T14:30:22Z",
+  "last_activity": "2025-01-18T14:35:10Z",
+  "context_files": {
+    "features/user-auth-context.md": {
+      "created": "2025-01-18T14:30:22Z",
+      "for": "@subagents/core/task-manager",
+      "keywords": ["user-auth", "authentication", "features"]
+    },
+    "tasks/user-auth-tasks.md": {
+      "created": "2025-01-18T14:32:15Z",
+      "for": "@subagents/core/task-manager",
+      "keywords": ["user-auth", "tasks", "breakdown"]
+    },
+    "documentation/api-docs-context.md": {
+      "created": "2025-01-18T14:35:10Z",
+      "for": "@subagents/core/documentation",
+      "keywords": ["api", "documentation"]
+    }
+  },
+  "context_index": {
+    "user-auth": [
+      "features/user-auth-context.md",
+      "tasks/user-auth-tasks.md"
+    ],
+    "api": [
+      "documentation/api-docs-context.md"
+    ]
+  }
+}
+```
+
+## Temporary Context Files
+
+### When to Create
+Only create context files when **ALL** of these apply:
+- Delegating to a subagent
+- Context description is verbose (>2 sentences) OR
+- Risk of misinterpretation without detailed context
+
+### File Structure
+```
+.tmp/sessions/{session-id}/{task-category}/{task-name}-context.md
+```
+
+### Categories
+- `features/` - Feature development context
+- `documentation/` - Documentation tasks
+- `code/` - Code-related tasks
+- `refactoring/` - Refactoring tasks
+- `testing/` - Testing tasks
+- `tasks/` - Task breakdowns created by task-manager
+- `general/` - General tasks that don't fit other categories
+
+### Examples
+```
+.tmp/sessions/20250118-143022-a4f2/features/user-auth-context.md
+.tmp/sessions/20250118-143022-a4f2/documentation/api-docs-context.md
+.tmp/sessions/20250118-150000-b7k9/code/database-refactor-context.md
+.tmp/sessions/20250118-151500-c3x8/testing/integration-tests-context.md
+```
+
+### File Contents
+```markdown
+# Context: {Task Name}
+Session: {session-id}
+
+## Request Summary
+[Brief description of what needs to be done]
+
+## Background
+[Relevant context and information]
+
+## Expected Output
+[What the subagent should produce]
+
+## Constraints
+[Any limitations or requirements]
+```
+
+## Cleanup Strategy
+
+### During Session
+1. Remove individual context files after task completion
+2. Update manifest to remove file entry
+3. Update `last_activity` timestamp
+
+### End of Session
+1. Remove entire session folder: `.tmp/sessions/{session-id}/`
+2. Only delete files tracked in current session's manifest
+
+### Stale Session Cleanup
+- Automatically clean sessions older than 24 hours with no activity
+- Check `last_activity` timestamp in manifest
+- Safe to run periodically without affecting active sessions
+
+### Manual Cleanup
+Users can safely delete:
+- Entire `.tmp/` folder anytime
+- Individual session folders
+- Stale sessions (check `last_activity` timestamp)
+
+## Concurrent Safety
+
+### Isolation Guarantees
+✅ Each agent instance has unique session ID
+✅ Context files are isolated per session
+✅ Manifest tracks only files created by this session
+✅ Cleanup only affects current session's files
+✅ No risk of deleting another instance's context
+
+### Best Practices
+1. **Generate session ID early** - At first context file creation
+2. **Track all files** - Add every context file to manifest
+3. **Update activity** - Touch `last_activity` on each operation
+4. **Clean up promptly** - Remove files after task completion
+5. **Only clean own files** - Never delete files outside current session
+
+## Dynamic Context Loading
+
+### Purpose
+Allow subagents to discover and load relevant context files created earlier in the session.
+
+### How It Works
+
+**1. Context File Creation**
+When creating a context file, add metadata to manifest:
+```json
+"context_files": {
+  "features/user-auth-context.md": {
+    "created": "2025-01-18T14:30:22Z",
+    "for": "@subagents/core/task-manager",
+    "keywords": ["user-auth", "authentication", "features"]
+  }
+}
+```
+
+**2. Context Indexing**
+Manifest maintains keyword index for fast lookup:
+```json
+"context_index": {
+  "user-auth": [
+    "features/user-auth-context.md",
+    "tasks/user-auth-tasks.md"
+  ]
+}
+```
+
+**3. Context Discovery**
+When delegating to subagent:
+1. Search manifest for related context files (by keyword/category)
+2. Pass relevant context file paths to subagent
+3. Subagent reads context files as needed
+
+**4. Delegation Pattern**
+```
+Delegating to @subagents/code/coder-agent:
+"Implement user authentication login component.
+
+Related context available at:
+- .tmp/sessions/20250118-143022-a4f2/features/user-auth-context.md
+- .tmp/sessions/20250118-143022-a4f2/tasks/user-auth-tasks.md
+
+Read these files for full context on requirements and task breakdown."
+```
+
+### Example Workflow
+
+```
+1. User: "Build user authentication system"
+   → OpenAgent creates: features/user-auth-context.md
+   → Delegates to @task-manager
+   
+2. Task-manager creates: tasks/user-auth-tasks.md
+   → Both files tracked in manifest with keyword "user-auth"
+   
+3. User: "Implement the login component"
+   → OpenAgent searches manifest for "user-auth" context
+   → Finds both context files
+   → Delegates to @coder-agent with references to both files
+   → Coder-agent reads files to understand full context
+```
+
+### Benefits
+- **No context loss**: Information persists across subagent calls
+- **Automatic discovery**: Related context found by keywords
+- **Flexible**: Subagents read only what they need
+- **Traceable**: Manifest shows all context relationships
+
+---
+
+## Why This Approach?
+
+### Session Isolation
+- **Concurrent safety**: Multiple agents can run simultaneously
+- **No conflicts**: Each session has its own namespace
+- **Easy cleanup**: Delete entire session folder when done
+- **Traceable**: Manifest shows what belongs to each session
+
+### Dynamic Context
+- **Discoverable**: Context files indexed by keywords
+- **Reusable**: Later subagents can access earlier context
+- **Flexible**: Load only relevant context
+- **Persistent**: Context survives across subagent calls
+
+### Why `.tmp/sessions/`?
+- Standard `.tmp/` convention (commonly ignored)
+- `sessions/` subfolder makes purpose clear
+- Session ID provides unique namespace
+- Easy to identify and clean up stale sessions
+- Hidden folder (starts with `.`)
+
+## Example Workflow
+
+```bash
+# Agent Instance 1 starts
+Session ID: 20250118-143022-a4f2
+Creates: .tmp/sessions/20250118-143022-a4f2/features/user-auth-context.md
+
+# Agent Instance 2 starts (concurrent)
+Session ID: 20250118-143030-b7k9
+Creates: .tmp/sessions/20250118-143030-b7k9/features/payment-context.md
+
+# Both agents work independently without conflicts
+
+# Agent Instance 1 completes
+Deletes: .tmp/sessions/20250118-143022-a4f2/ (entire folder)
+
+# Agent Instance 2 continues unaffected
+Still has: .tmp/sessions/20250118-143030-b7k9/
+```

+ 943 - 0
docs/agents/openagent.md

@@ -0,0 +1,943 @@
+# OpenAgent - Universal Agent Guide
+
+**Your intelligent assistant for questions, tasks, and workflows**
+
+OpenAgent is the primary universal agent in OpenCode that handles everything from simple questions to complex multi-step workflows. This guide explains how it works and how to get the most out of it.
+
+---
+
+## Table of Contents
+
+- [What is OpenAgent?](#what-is-openagent)
+- [How It Works](#how-it-works)
+- [The Two Paths](#the-two-paths)
+- [The 6-Stage Workflow](#the-6-stage-workflow)
+- [Session Management](#session-management)
+- [Dynamic Context Loading](#dynamic-context-loading)
+- [When OpenAgent Delegates](#when-openagent-delegates)
+- [Visual Workflows](#visual-workflows)
+- [Tips for Your Workflow](#tips-for-your-workflow)
+
+---
+
+## What is OpenAgent?
+
+OpenAgent is your **universal assistant** that:
+
+- ✅ **Answers questions** - Get explanations, comparisons, and guidance
+- ✅ **Executes tasks** - Create files, update code, run commands
+- ✅ **Coordinates workflows** - Breaks down complex features and delegates to specialists
+- ✅ **Preserves context** - Remembers information across multiple steps
+- ✅ **Keeps you in control** - Always asks for approval before taking action
+
+Think of OpenAgent as a **smart project manager** who:
+- Understands what you need
+- Plans how to do it
+- Asks for your approval
+- Executes the plan
+- Confirms everything is done right
+
+---
+
+## How It Works
+
+### The Simple Version
+
+```mermaid
+graph LR
+    A[You Ask] --> B{Question or Task?}
+    B -->|Question| C[Get Answer]
+    B -->|Task| D[See Plan]
+    D --> E[Approve Plan]
+    E --> F[Watch Execution]
+    F --> G[Confirm Done]
+    
+    style A fill:#4A90E2,stroke:#2E5C8A,stroke-width:3px,color:#000
+    style B fill:#F5A623,stroke:#C17D11,stroke-width:3px,color:#000
+    style C fill:#7ED321,stroke:#5FA319,stroke-width:3px,color:#000
+    style D fill:#50E3C2,stroke:#3AB89E,stroke-width:3px,color:#000
+    style E fill:#F5A623,stroke:#C17D11,stroke-width:3px,color:#000
+    style F fill:#BD10E0,stroke:#9012B3,stroke-width:3px,color:#fff
+    style G fill:#7ED321,stroke:#5FA319,stroke-width:3px,color:#000
+```
+
+**For Questions**: You ask → You get an answer
+**For Tasks**: You ask → See plan → Approve → Watch it happen → Confirm done
+
+---
+
+## The Two Paths
+
+OpenAgent has two different ways of working, depending on what you need:
+
+### Path 1: Conversational (For Questions)
+
+```mermaid
+graph TD
+    A[Ask Question] --> B[OpenAgent Analyzes]
+    B --> C[Provides Answer]
+    C --> D[Done!]
+    
+    style A fill:#4A90E2,stroke:#2E5C8A,stroke-width:3px,color:#000
+    style B fill:#BD10E0,stroke:#9012B3,stroke-width:3px,color:#fff
+    style C fill:#7ED321,stroke:#5FA319,stroke-width:3px,color:#000
+    style D fill:#7ED321,stroke:#5FA319,stroke-width:3px,color:#000
+```
+
+**When**: You ask informational questions
+**Examples**:
+- "What's the difference between REST and GraphQL?"
+- "How do I use async/await in JavaScript?"
+- "Explain what this code does"
+
+**What Happens**: You get a direct, helpful answer. No approval needed.
+
+---
+
+### Path 2: Task Execution (For Actions)
+
+```mermaid
+graph TD
+    A[Request Task] --> B[OpenAgent Creates Plan]
+    B --> C[Shows You Plan]
+    C --> D{Approve?}
+    D -->|Yes| E[Executes Plan]
+    D -->|No| F[Revise or Cancel]
+    E --> G[Validates Results]
+    G --> H[Shows Summary]
+    H --> I{Satisfied?}
+    I -->|Yes| J[Cleanup if Needed]
+    I -->|No| K[Fix Issues]
+    J --> L[Done!]
+    
+    style A fill:#4A90E2,stroke:#2E5C8A,stroke-width:3px,color:#000
+    style B fill:#BD10E0,stroke:#9012B3,stroke-width:3px,color:#fff
+    style C fill:#F5A623,stroke:#C17D11,stroke-width:3px,color:#000
+    style D fill:#F5A623,stroke:#C17D11,stroke-width:3px,color:#000
+    style E fill:#50E3C2,stroke:#3AB89E,stroke-width:3px,color:#000
+    style F fill:#D0021B,stroke:#A00116,stroke-width:3px,color:#fff
+    style G fill:#BD10E0,stroke:#9012B3,stroke-width:3px,color:#fff
+    style H fill:#50E3C2,stroke:#3AB89E,stroke-width:3px,color:#000
+    style I fill:#F5A623,stroke:#C17D11,stroke-width:3px,color:#000
+    style J fill:#50E3C2,stroke:#3AB89E,stroke-width:3px,color:#000
+    style K fill:#D0021B,stroke:#A00116,stroke-width:3px,color:#fff
+    style L fill:#7ED321,stroke:#5FA319,stroke-width:3px,color:#000
+```
+
+**When**: You want something done
+**Examples**:
+- "Create a README for this project"
+- "Build a user authentication system"
+- "Refactor this code to use TypeScript"
+
+**What Happens**: 
+1. You see a plan
+2. You approve it
+3. OpenAgent executes it
+4. You confirm it's done right
+
+---
+
+## The 6-Stage Workflow
+
+When you request a task, OpenAgent follows a systematic 6-stage workflow:
+
+```mermaid
+graph TD
+    subgraph Stage1["Stage 1: Analyze"]
+        A1[Receive Request] --> A2[Assess Complexity]
+        A2 --> A3{Question or Task?}
+    end
+    
+    subgraph Stage2["Stage 2: Approve"]
+        B1[Create Plan] --> B2[Present to User]
+        B2 --> B3[Wait for Approval]
+    end
+    
+    subgraph Stage3["Stage 3: Execute"]
+        C1[Execute Steps] --> C2{Need Help?}
+        C2 -->|Yes| C3[Delegate to Specialist]
+        C2 -->|No| C4[Do It Directly]
+        C3 --> C5[Integrate Results]
+        C4 --> C5
+    end
+    
+    subgraph Stage4["Stage 4: Validate"]
+        D1[Check Quality] --> D2[Run Tests if Applicable]
+        D2 --> D3{Issues Found?}
+        D3 -->|Yes| D4[Report & Propose Fixes]
+        D4 --> D5[Wait for Approval]
+        D5 --> D6[Apply Approved Fixes]
+        D6 --> D2
+        D3 -->|No| D7[Ask: Review Work?]
+    end
+    
+    subgraph Stage5["Stage 5: Summarize"]
+        E1[Create Summary] --> E2[Show Changes]
+        E2 --> E3[Suggest Next Steps]
+    end
+    
+    subgraph Stage6["Stage 6: Confirm Completion"]
+        F1[Ask if Satisfied] --> F2{Session Files?}
+        F2 -->|Yes| F3[Ask about Cleanup]
+        F2 -->|No| F4[Done]
+        F3 --> F5[Cleanup on Approval]
+        F5 --> F4
+    end
+    
+    A3 -->|Question| Answer[Direct Answer]
+    A3 -->|Task| Stage2
+    Stage2 --> Stage3
+    Stage3 --> Stage4
+    Stage4 --> Stage5
+    Stage5 --> Stage6
+    
+    style Stage1 fill:#4A90E2,stroke:#2E5C8A,stroke-width:4px,color:#fff
+    style Stage2 fill:#F5A623,stroke:#C17D11,stroke-width:4px,color:#000
+    style Stage3 fill:#50E3C2,stroke:#3AB89E,stroke-width:4px,color:#000
+    style Stage4 fill:#BD10E0,stroke:#9012B3,stroke-width:4px,color:#fff
+    style Stage5 fill:#9013B3,stroke:#7011A0,stroke-width:4px,color:#fff
+    style Stage6 fill:#7ED321,stroke:#5FA319,stroke-width:4px,color:#000
+    style Answer fill:#7ED321,stroke:#5FA319,stroke-width:3px,color:#000
+```
+
+### Stage 1: Analyze
+**What happens**: OpenAgent reads your request and decides if it's a question or a task.
+
+**Your experience**: Instant - you don't see this happening.
+
+---
+
+### Stage 2: Approve ⚠️ (MANDATORY for tasks)
+**What happens**: OpenAgent creates a plan and shows it to you.
+
+**Your experience**: You see something like:
+```
+## Proposed Plan
+1. Create README.md file
+2. Add project overview section
+3. Add installation instructions
+4. Add usage examples
+
+**Approval needed before proceeding.**
+```
+
+**What you do**: Review the plan and say "yes" or "no" (or ask for changes).
+
+---
+
+### Stage 3: Execute
+**What happens**: OpenAgent carries out the plan, either directly or by delegating to specialist agents.
+
+**Your experience**: You might see:
+- Files being created or modified
+- Commands being run
+- Progress updates
+- Results from specialist agents
+
+**Behind the scenes**: OpenAgent might create temporary files to preserve context between steps.
+
+---
+
+### Stage 4: Validate ⚠️ (MANDATORY for tasks)
+**What happens**: OpenAgent checks the quality of the work, runs tests if applicable, and ensures everything works correctly.
+
+**Your experience when validation passes**: You see:
+```
+✅ Validation complete - all checks passed.
+
+Would you like me to run any additional checks or review the work before I summarize?
+- Run specific tests
+- Check specific files  
+- Review changes
+- Proceed to summary
+```
+
+**What you do**: Choose to review further or proceed to summary.
+
+#### Special Case: Test Failures or Issues Found
+
+If OpenAgent runs tests or validation and finds issues, it follows a **strict protocol**:
+
+**What happens**:
+1. ⛔ **STOPS** execution immediately
+2. 📋 **REPORTS** all issues/failures clearly
+3. 📝 **PROPOSES** a fix plan with specific steps
+4. ⚠️ **REQUESTS APPROVAL** before fixing (mandatory)
+5. ✅ **PROCEEDS** only after you approve
+6. 🔄 **RE-VALIDATES** after fixes are applied
+
+**Your experience**: You see something like:
+```
+## Validation Results
+❌ 3 tests failed:
+- test_user_auth: Expected 200, got 401
+- test_login: Missing token in response
+- test_logout: Session not cleared
+
+## Proposed Fix Plan
+1. Update auth middleware to return proper status codes
+2. Add token generation to login endpoint
+3. Add session cleanup to logout handler
+
+**Approval needed before proceeding with fixes.**
+```
+
+**Important**: OpenAgent will **NEVER** auto-fix issues without your explicit approval. After fixes are applied, validation runs again to ensure everything passes.
+
+---
+
+### Stage 5: Summarize
+**What happens**: After validation passes and you're satisfied, OpenAgent creates a summary of what was accomplished.
+
+**Your experience**: You see a summary like:
+```
+## Summary
+Created README.md with project documentation.
+
+**Changes Made:**
+- Created README.md
+- Added project overview
+- Added installation guide
+- Added usage examples
+
+**Next Steps:** Review the README and update as needed.
+```
+
+---
+
+### Stage 6: Confirm Completion ⚠️ (MANDATORY for tasks)
+**What happens**: OpenAgent asks if you're satisfied and if temporary files should be cleaned up.
+
+**Your experience**: You see:
+```
+Is this complete and satisfactory?
+Should I clean up temporary session files at .tmp/sessions/20250118-143022-a4f2/?
+```
+
+**What you do**: Confirm you're happy with the results and approve cleanup if needed.
+
+---
+
+## Session Management
+
+When OpenAgent works on complex tasks, it creates a **session** to keep track of everything.
+
+### What is a Session?
+
+A session is like a **temporary workspace** where OpenAgent stores:
+- Context files (requirements, specifications)
+- Task breakdowns
+- Notes for specialist agents
+- Progress tracking
+
+### Session Structure
+
+```mermaid
+graph TD
+    A[Session Folder] --> B[manifest file]
+    A --> C[features folder]
+    A --> D[tasks folder]
+    A --> E[code folder]
+    A --> F[documentation folder]
+    A --> G[Other categories]
+    
+    B --> B1[Tracks all files]
+    B --> B2[Keywords for search]
+    B --> B3[Creation timestamps]
+    
+    C --> C1[Requirements and specs]
+    D --> D1[Task breakdowns]
+    E --> E1[Implementation notes]
+    F --> F1[Documentation context]
+    
+    style A fill:#4A90E2,stroke:#2E5C8A,stroke-width:3px,color:#fff
+    style B fill:#F5A623,stroke:#C17D11,stroke-width:3px,color:#000
+    style C fill:#50E3C2,stroke:#3AB89E,stroke-width:2px,color:#000
+    style D fill:#50E3C2,stroke:#3AB89E,stroke-width:2px,color:#000
+    style E fill:#50E3C2,stroke:#3AB89E,stroke-width:2px,color:#000
+    style F fill:#50E3C2,stroke:#3AB89E,stroke-width:2px,color:#000
+    style G fill:#50E3C2,stroke:#3AB89E,stroke-width:2px,color:#000
+```
+
+### Session Lifecycle
+
+```mermaid
+sequenceDiagram
+    participant User
+    participant OpenAgent
+    participant Session
+    
+    User->>OpenAgent: Request complex task
+    OpenAgent->>OpenAgent: Needs context file?
+    OpenAgent->>Session: Create session (lazy)
+    Session-->>OpenAgent: Session ID: abc123
+    OpenAgent->>Session: Create context files
+    OpenAgent->>OpenAgent: Execute task
+    OpenAgent->>User: Show results
+    User->>OpenAgent: Confirm done
+    OpenAgent->>User: Cleanup session files?
+    User->>OpenAgent: Yes
+    OpenAgent->>Session: Delete session
+    Session-->>OpenAgent: Cleaned up
+    OpenAgent->>User: All done!
+```
+
+### Key Features
+
+**Lazy Initialization**: Sessions are only created when actually needed (not for simple tasks).
+
+**Unique IDs**: Each session gets a unique ID like `20250118-143022-a4f2` to prevent conflicts.
+
+**Safe Cleanup**: OpenAgent only deletes files it created, and only after you approve.
+
+**Concurrent Safety**: Multiple users can work simultaneously without interfering with each other.
+
+---
+
+## Dynamic Context Loading
+
+One of OpenAgent's superpowers is **remembering context** across multiple steps.
+
+### The Problem It Solves
+
+Imagine this scenario:
+1. You ask: "Build a user authentication system"
+2. OpenAgent creates requirements and task breakdown
+3. Later, you ask: "Implement the login component"
+
+**Without context loading**: OpenAgent wouldn't remember the requirements from step 1.
+**With context loading**: OpenAgent finds and uses the requirements automatically.
+
+### How It Works
+
+```mermaid
+graph TD
+    subgraph Step1["Step 1: Create Context"]
+        A1[User requests auth system] --> A2[Create requirements file]
+        A2 --> A3[Add to manifest with keywords]
+        A3 --> A4[Keywords added]
+    end
+    
+    subgraph Step2["Step 2: Create Tasks"]
+        B1[Delegate to task-manager] --> B2[Create task breakdown]
+        B2 --> B3[Add to manifest with keywords]
+        B3 --> B4[Keywords added]
+    end
+    
+    subgraph Step3["Step 3: Use Context"]
+        C1[User requests login] --> C2[Search manifest]
+        C2 --> C3[Find related files]
+        C3 --> C4[Pass paths to specialist]
+        C4 --> C5[Specialist reads context]
+    end
+    
+    Step1 --> Step2
+    Step2 --> Step3
+    
+    style Step1 fill:#4A90E2,stroke:#2E5C8A,stroke-width:4px,color:#fff
+    style Step2 fill:#50E3C2,stroke:#3AB89E,stroke-width:4px,color:#000
+    style Step3 fill:#7ED321,stroke:#5FA319,stroke-width:4px,color:#000
+```
+
+### The Manifest
+
+The manifest is like an **index** that tracks all context files:
+
+```json
+{
+  "session_id": "20250118-143022-a4f2",
+  "context_files": {
+    "features/user-auth-context.md": {
+      "created": "2025-01-18T14:30:22Z",
+      "for": "@task-manager",
+      "keywords": ["user-auth", "authentication", "features"]
+    },
+    "tasks/user-auth-tasks.md": {
+      "created": "2025-01-18T14:32:15Z",
+      "for": "@task-manager",
+      "keywords": ["user-auth", "tasks", "breakdown"]
+    }
+  },
+  "context_index": {
+    "user-auth": [
+      "features/user-auth-context.md",
+      "tasks/user-auth-tasks.md"
+    ]
+  }
+}
+```
+
+**Benefits**:
+- ✅ No context loss across steps
+- ✅ Automatic discovery by keywords
+- ✅ Flexible - only loads what's needed
+- ✅ Traceable - you can see what context was used
+
+---
+
+## When OpenAgent Delegates
+
+OpenAgent knows when to do work itself and when to call in specialists.
+
+### Decision Tree
+
+```mermaid
+graph TD
+    A[Receive Task] --> B{What type?}
+    
+    B -->|Question| C[Answer Directly]
+    
+    B -->|Task| D{How complex?}
+    
+    D -->|3+ files OR 60+ min OR complex| E[Delegate to task-manager]
+    E --> E1[Breaks down into subtasks]
+    
+    D -->|Comprehensive docs OR multi-page| F[Delegate to documentation]
+    F --> F1[Creates structured docs]
+    
+    D -->|Specialized code task| G[Delegate to code specialists]
+    G --> G1[Testing, review, build]
+    
+    D -->|Simple OR single file OR under 30 min| H[Execute Directly]
+    H --> H1[OpenAgent handles it]
+    
+    style A fill:#4A90E2,stroke:#2E5C8A,stroke-width:3px,color:#fff
+    style B fill:#F5A623,stroke:#C17D11,stroke-width:3px,color:#000
+    style C fill:#7ED321,stroke:#5FA319,stroke-width:3px,color:#000
+    style D fill:#F5A623,stroke:#C17D11,stroke-width:3px,color:#000
+    style E fill:#BD10E0,stroke:#9012B3,stroke-width:3px,color:#fff
+    style F fill:#BD10E0,stroke:#9012B3,stroke-width:3px,color:#fff
+    style G fill:#BD10E0,stroke:#9012B3,stroke-width:3px,color:#fff
+    style H fill:#7ED321,stroke:#5FA319,stroke-width:3px,color:#000
+```
+
+### Delegation Criteria
+
+#### Delegate to @task-manager when:
+- ✅ Feature spans **3+ files/modules**
+- ✅ Estimated effort **>60 minutes**
+- ✅ Needs **breakdown into subtasks**
+- ✅ **Complex dependencies** between components
+- ✅ User **explicitly requests** task breakdown
+
+**Example**: "Build user authentication system"
+
+---
+
+#### Delegate to @documentation when:
+- ✅ Creating **comprehensive docs** (API docs, guides, tutorials)
+- ✅ **Multi-page** documentation
+- ✅ Requires **codebase analysis/research**
+- ✅ User **explicitly requests** documentation agent
+
+**Example**: "Create API documentation for all endpoints"
+
+---
+
+#### Delegate to @code/* when:
+- ✅ **Code-specific specialized task** (testing, review, build)
+- ✅ Code subagents are **available** in current profile
+
+**Examples**:
+- "Review this code for security issues" → @code/reviewer
+- "Write tests for this module" → @code/tester
+- "Run build and fix errors" → @code/build-agent
+
+---
+
+#### Execute directly when:
+- ✅ **Single file** operation
+- ✅ **Simple, straightforward** task (<30 min)
+- ✅ **Quick updates/edits**
+- ✅ User **explicitly asks** openagent to handle it
+
+**Examples**:
+- "Create a README"
+- "Update this function to use async/await"
+- "Add a comment to this code"
+
+---
+
+## Visual Workflows
+
+### Complete Task Workflow
+
+```mermaid
+sequenceDiagram
+    participant User
+    participant OpenAgent
+    participant Session
+    participant Specialist
+    
+    User->>OpenAgent: "Build authentication system"
+    
+    Note over OpenAgent: Stage 1: Analyze
+    OpenAgent->>OpenAgent: Complex task, needs task-manager
+    
+    Note over OpenAgent: Stage 2: Approve
+    OpenAgent->>User: ## Proposed Plan<br/>1. Create requirements<br/>2. Delegate to task-manager<br/>3. Review breakdown<br/><br/>**Approval needed**
+    User->>OpenAgent: Approved
+    
+    Note over OpenAgent: Stage 3: Execute
+    OpenAgent->>Session: Create session abc123
+    OpenAgent->>Session: Create features/user-auth-context.md
+    Session-->>OpenAgent: File created, added to manifest
+    
+    OpenAgent->>Specialist: @task-manager: Break down auth system<br/>Context: .tmp/sessions/abc123/features/user-auth-context.md
+    Specialist->>Session: Create tasks/user-auth-tasks.md
+    Specialist-->>OpenAgent: Task breakdown complete
+    
+    OpenAgent->>Session: Update manifest with new file
+    
+    Note over OpenAgent: Stage 4: Validate
+    OpenAgent->>OpenAgent: Check quality, run tests
+    OpenAgent->>User: ✅ Validation complete - all checks passed.<br/><br/>Would you like me to run any additional checks<br/>or review the work before I summarize?
+    User->>OpenAgent: Proceed to summary
+    
+    Note over OpenAgent: Stage 5: Summarize
+    OpenAgent->>User: ## Summary<br/>Created task breakdown with 5 subtasks<br/><br/>**Changes:**<br/>- Created context file<br/>- Created task breakdown
+    
+    Note over OpenAgent: Stage 6: Confirm
+    OpenAgent->>User: Is this complete and satisfactory?<br/>Should I clean up session files?
+    User->>OpenAgent: Yes, looks good. Clean up.
+    OpenAgent->>Session: Delete session abc123
+    Session-->>OpenAgent: Cleaned up
+    OpenAgent->>User: ✓ All done!
+```
+
+### Multi-Step with Context Preservation
+
+```mermaid
+sequenceDiagram
+    participant User
+    participant OpenAgent
+    participant Manifest
+    participant Specialist
+    
+    Note over User,Specialist: Step 1: Initial Request
+    User->>OpenAgent: "Build auth system"
+    OpenAgent->>Manifest: Create features/user-auth-context.md<br/>Keywords: [user-auth, authentication]
+    OpenAgent->>Specialist: @task-manager
+    Specialist->>Manifest: Create tasks/user-auth-tasks.md<br/>Keywords: [user-auth, tasks]
+    
+    Note over User,Specialist: Step 2: Later Request
+    User->>OpenAgent: "Implement login component"
+    OpenAgent->>Manifest: Search for "login" or "user-auth"
+    Manifest-->>OpenAgent: Found:<br/>- features/user-auth-context.md<br/>- tasks/user-auth-tasks.md
+    OpenAgent->>Specialist: @coder-agent: Implement login<br/><br/>Related context:<br/>- features/user-auth-context.md<br/>- tasks/user-auth-tasks.md
+    Specialist->>Manifest: Read context files
+    Specialist-->>OpenAgent: Login component implemented with full context
+    
+    Note over OpenAgent: ✓ No context loss!
+```
+
+### Concurrent Sessions
+
+```mermaid
+graph TD
+    subgraph UserA["User A Session"]
+        A1[Request: Build auth] --> A2[Session abc123]
+        A2 --> A3[features context]
+        A2 --> A4[tasks context]
+    end
+    
+    subgraph UserB["User B Session"]
+        B1[Request: Build payment] --> B2[Session def456]
+        B2 --> B3[features context]
+        B2 --> B4[tasks context]
+    end
+    
+    subgraph Isolation["Session Isolation"]
+        I1[Unique Session IDs]
+        I2[Separate Folders]
+        I3[Independent Manifests]
+        I4[No Conflicts]
+    end
+    
+    A2 -.->|Isolated| Isolation
+    B2 -.->|Isolated| Isolation
+    
+    style UserA fill:#4A90E2,stroke:#2E5C8A,stroke-width:4px,color:#fff
+    style UserB fill:#7ED321,stroke:#5FA319,stroke-width:4px,color:#000
+    style Isolation fill:#F5A623,stroke:#C17D11,stroke-width:4px,color:#000
+```
+
+---
+
+## Tips for Your Workflow
+
+### 1. Be Specific in Your Requests
+
+**Instead of**: "Make this better"
+**Try**: "Refactor this function to use async/await and add error handling"
+
+**Why**: Specific requests help OpenAgent create better plans and get approval faster.
+
+---
+
+### 2. Review Plans Carefully
+
+When OpenAgent shows you a plan, take a moment to review it:
+- ✅ Does it match what you want?
+- ✅ Are there any steps you'd change?
+- ✅ Is anything missing?
+
+**Tip**: You can ask OpenAgent to revise the plan before approving.
+
+---
+
+### 3. Use Multi-Step Workflows
+
+For complex projects, break them into steps:
+
+```
+Step 1: "Build user authentication system"
+→ Review task breakdown
+
+Step 2: "Implement the registration component"
+→ OpenAgent uses context from Step 1
+
+Step 3: "Implement the login component"
+→ OpenAgent uses context from Steps 1 & 2
+```
+
+**Why**: OpenAgent preserves context across steps, making each step easier.
+
+---
+
+### 4. Leverage Specialist Agents
+
+Let OpenAgent delegate to specialists:
+- **Complex features** → Let task-manager break them down
+- **Documentation** → Let documentation agent create comprehensive docs
+- **Code review** → Let reviewer agent check for issues
+
+**Tip**: You can explicitly request a specialist: "Use the documentation agent to create API docs"
+
+---
+
+### 5. Clean Up Sessions Regularly
+
+After completing a workflow, approve session cleanup:
+- ✅ Keeps your workspace clean
+- ✅ Prevents accumulation of temporary files
+- ✅ Frees up disk space
+
+**Tip**: You can also manually clean up stale sessions:
+```bash
+./scripts/cleanup-stale-sessions.sh
+```
+
+---
+
+### 6. Use Keywords Consistently
+
+When working on related tasks, use consistent terminology:
+- "user authentication" (not "auth" in one request and "login system" in another)
+- "payment processing" (not "payments" and "checkout" interchangeably)
+
+**Why**: Helps OpenAgent find related context files more easily.
+
+---
+
+### 7. Provide Context for Follow-Up Requests
+
+When making follow-up requests, reference previous work:
+
+**Good**: "Implement the login component from the auth system we planned earlier"
+**Better**: "Implement the login component using the user-auth requirements"
+
+**Why**: Helps OpenAgent search for the right context files.
+
+---
+
+### 8. Customize Delegation Thresholds
+
+You can adjust when OpenAgent delegates by modifying the criteria in `.opencode/agent/openagent.md`:
+
+**Current defaults**:
+- 3+ files → Delegate to task-manager
+- >60 minutes → Delegate to task-manager
+- <30 minutes → Execute directly
+
+**To customize**: Edit the `<delegation_criteria>` section to match your preferences.
+
+---
+
+### 9. Create Your Own Categories
+
+The default categories are:
+- features, documentation, code, refactoring, testing, tasks, general
+
+**To add custom categories**: Edit the `<categories>` line in openagent.md:
+```xml
+<categories>features | documentation | code | refactoring | testing | general | tasks | your-category</categories>
+```
+
+**Use case**: If you frequently work on "migrations" or "integrations", add those as categories.
+
+---
+
+### 10. Monitor Session Files
+
+Occasionally check `.tmp/sessions/` to see what context is being preserved:
+
+```bash
+ls -la .tmp/sessions/
+```
+
+**Why**: Helps you understand what context OpenAgent is using and identify any issues.
+
+---
+
+### 11. Use Explicit Approvals for Learning
+
+When learning a new codebase or technology, use OpenAgent's approval step as a learning opportunity:
+- Read the plan carefully
+- Ask questions about steps you don't understand
+- Request explanations before approving
+
+**Example**:
+```
+OpenAgent: "I'll refactor this to use dependency injection"
+You: "What is dependency injection and why is it better here?"
+OpenAgent: [Explains]
+You: "Got it, approved!"
+```
+
+---
+
+### 12. Combine with Other Agents
+
+OpenAgent works great with other agents in your profile:
+- Use OpenAgent for planning and coordination
+- Let specialists handle their domains
+- OpenAgent will preserve context between them
+
+**Example workflow**:
+1. OpenAgent plans the feature
+2. @coder-agent implements it
+3. @tester writes tests
+4. @reviewer checks quality
+5. @documentation documents it
+
+All coordinated by OpenAgent with preserved context!
+
+---
+
+## Advanced Tips
+
+### Create Reusable Context Templates
+
+For recurring workflows, create context templates:
+
+**Example**: `.opencode/templates/feature-context.md`
+```markdown
+# Feature: {FEATURE_NAME}
+
+## Requirements
+- [List requirements]
+
+## Constraints
+- [List constraints]
+
+## Success Criteria
+- [List criteria]
+```
+
+**Use**: "Create a new feature using the feature-context template"
+
+---
+
+### Use Session IDs for Debugging
+
+If something goes wrong, note the session ID:
+```
+Session: 20250118-143022-a4f2
+```
+
+You can inspect the session folder to see what context was created:
+```bash
+cat .tmp/sessions/20250118-143022-a4f2/.manifest.json
+```
+
+---
+
+### Batch Related Tasks
+
+Group related tasks in one session for better context:
+
+**Instead of**:
+- Request 1: "Create user model"
+- Request 2: "Create auth controller"
+- Request 3: "Create login route"
+
+**Try**:
+- Request: "Build user authentication with model, controller, and routes"
+
+**Why**: Single session, all context preserved, more efficient.
+
+---
+
+## Core Principles
+
+OpenAgent follows these core principles:
+
+### 🎯 Lean
+Concise responses, no over-explanation. Gets to the point quickly.
+
+### 🔄 Adaptive
+Conversational for questions, formal for tasks. Matches the context.
+
+### ⚡ Lazy
+Only creates sessions/files when actually needed. No unnecessary overhead.
+
+### 🔒 Safe
+**ALWAYS** requests approval before ANY execution. Confirms before cleanup.
+
+### 📋 Report First
+When tests fail or issues are found:
+1. **REPORT** the issues
+2. **PLAN** the fixes
+3. **REQUEST APPROVAL**
+4. **FIX** (only after approval)
+
+**Never auto-fixes** - you're always in control.
+
+---
+
+## Summary
+
+OpenAgent is your **intelligent project manager** that:
+
+✅ **Plans before acting** - Shows you the plan and waits for approval
+✅ **Preserves context** - Remembers information across multiple steps
+✅ **Delegates wisely** - Calls in specialists when needed
+✅ **Keeps you in control** - Always confirms before cleanup
+✅ **Handles complexity** - Breaks down big tasks into manageable pieces
+✅ **Reports before fixing** - Never auto-fixes issues without approval
+
+**Key Takeaways**:
+1. Be specific in your requests
+2. Review plans before approving
+3. Use multi-step workflows for complex projects
+4. Let OpenAgent delegate to specialists
+5. Clean up sessions when done
+6. Customize to fit your workflow
+7. Expect reports before fixes when issues are found
+
+**Ready to get started?** Just ask OpenAgent a question or request a task!
+
+---
+
+## Configuration
+
+OpenAgent is configured in `.opencode/agent/openagent.md`. You can customize:
+- Delegation thresholds
+- Categories
+- Error handling
+- Test failure protocol
+- And more!
+
+Happy building! 🚀

+ 4 - 2
docs/features/system-builder/README.md

@@ -13,9 +13,11 @@ curl -fsSL https://raw.githubusercontent.com/darrenhinde/opencode-agents/main/in
 ```
 
 **What you get:**
-- ✅ All development tools (22 components)
+- ✅ All development tools (19 components)
+- ✅ Business tools (5 components)
 - ✅ System builder (7 components)
-- ✅ **Total: 29 components**
+- ✅ Additional tools (1 component)
+- ✅ **Total: 32 components**
 
 ### Add to Existing Installation
 

+ 4 - 2
docs/features/system-builder/quick-start.md

@@ -19,9 +19,11 @@ curl -fsSL https://raw.githubusercontent.com/darrenhinde/opencode-agents/main/in
 ```
 
 **What you get:**
-- ✅ All development tools (22 components)
+- ✅ All development tools (19 components)
+- ✅ Business tools (5 components)
 - ✅ System builder (7 components)
-- ✅ **Total: 29 components**
+- ✅ Additional tools (1 component)
+- ✅ **Total: 32 components**
 
 ---
 

+ 4 - 2
docs/getting-started/context-aware-system/QUICK_START_SYSTEM_BUILDER.md

@@ -19,9 +19,11 @@ curl -fsSL https://raw.githubusercontent.com/darrenhinde/opencode-agents/main/in
 ```
 
 **What you get:**
-- ✅ All development tools (22 components)
+- ✅ All development tools (19 components)
+- ✅ Business tools (5 components)
 - ✅ System builder (7 components)
-- ✅ **Total: 29 components**
+- ✅ Additional tools (1 component)
+- ✅ **Total: 32 components**
 
 ---
 

+ 515 - 0
docs/guides/building-with-opencode.md

@@ -0,0 +1,515 @@
+# Building with OpenCode: The Power User Formula
+
+## Overview
+
+This guide teaches you how to build efficient, scalable OpenCode systems using the 4-layer architecture. Master this formula to create powerful AI workflows with minimal token usage and maximum reusability.
+
+## The 4-Layer Architecture
+
+```
+Layer 1: TOOLS        → Atomic operations (read, test, lint)
+Layer 2: SUBAGENTS    → Specialized skills (security, testing, refactoring)
+Layer 3: COMMANDS     → User shortcuts + templates (slash commands)
+Layer 4: MAIN AGENTS  → Orchestration (build, plan, general)
+```
+
+Each layer serves a specific purpose and builds upon the previous one.
+
+---
+
+## Layer 1: TOOLS - Build for Efficiency
+
+### The Rule
+Create tools for **frequent, verbose operations** that need output filtering or caching.
+
+### Structure
+```typescript
+// .opencode/tool/[operation].ts
+export default tool({
+  description: "One-line: what it does, when to use",
+  args: { /* minimal params */ },
+  async execute(args, ctx) {
+    // Run operation
+    // Parse output
+    // Return only what matters
+    return conciseResult
+  }
+})
+```
+
+### When to Build a Tool
+- ✅ Used 10+ times per session
+- ✅ Raw output >1KB, useful info <200 chars
+- ✅ Needs parsing/filtering/caching
+
+### Examples
+- `test-runner` - Run tests, return pass/fail + errors only
+- `lint-check` - Return only errors in changed files
+- `build-check` - Return warnings/errors, not full logs
+
+### Quick Start: Your First Tool
+```bash
+# Create your first efficient tool
+mkdir -p .opencode/tool
+cat > .opencode/tool/test.ts << 'EOF'
+import { tool } from "@opencode-ai/plugin"
+import { z } from "zod"
+
+export default tool({
+  description: "Run tests, return summary or failures only",
+  args: { path: z.string() },
+  async execute(args, ctx) {
+    const result = await ctx.$`npm test -- ${args.path}`.nothrow()
+    const output = await new Response(result.stdout).text()
+    return result.exitCode === 0 
+      ? `✅ Tests passed`
+      : `❌ Failed:\n${output.split('\n').filter(l => l.includes('FAIL') || l.includes('●')).slice(0, 20).join('\n')}`
+  }
+})
+EOF
+
+# Test it
+opencode tui
+# Type: "run the tests"
+```
+
+---
+
+## Layer 2: SUBAGENTS - Build for Specialization
+
+### The Rule
+Create subagents for **complex, reusable workflows** that require domain expertise.
+
+### Structure
+```markdown
+# .opencode/agent/[domain]/[specialist].md
+---
+mode: "subagent"
+description: "Use WHEN/AFTER [trigger condition]"
+tools:
+  [essential-tool]: true
+  task: false  # Prevent recursion
+---
+
+You are [role]. You specialize in:
+1. [Specific capability]
+2. [Specific capability]
+
+Always [output format/requirement].
+```
+
+### When to Build a Subagent
+- ✅ Multi-step process (3+ steps)
+- ✅ Requires domain expertise
+- ✅ Called by main agent OR user
+- ✅ Isolated context beneficial
+
+### Recommended Folder Structure
+```
+.opencode/agent/
+├── security/
+│   ├── code-scanner.md      # Vulnerability detection
+│   ├── dependency-audit.md  # Supply chain check
+│   └── secrets-detector.md  # Credential scanning
+├── testing/
+│   ├── unit-generator.md    # Generate unit tests
+│   ├── e2e-builder.md       # E2E test creation
+│   └── test-fixer.md        # Fix failing tests
+└── refactor/
+    ├── modernizer.md        # Update legacy code
+    ├── optimizer.md         # Performance improvements
+    └── simplifier.md        # Reduce complexity
+```
+
+### Example: Security Scanner Subagent
+```markdown
+# .opencode/agent/security/code-scanner.md
+---
+mode: "subagent"
+description: "Use AFTER writing auth code to scan for vulnerabilities"
+tools:
+  lint-check: true
+  test-runner: true
+  task: false
+---
+
+You are a Security Specialist. You scan code for:
+1. SQL injection vulnerabilities
+2. XSS attack vectors
+3. Authentication/authorization flaws
+4. Insecure dependencies
+
+Always return a structured report with severity levels.
+```
+
+---
+
+## Layer 3: COMMANDS - Build for Convenience
+
+### The Rule
+Create commands for **common user workflows** that benefit from templates and context.
+
+### Structure
+```markdown
+# .opencode/command/[workflow]/[action].md
+---
+description: "What this does"
+agent: "[subagent-name]"  # Routes to subagent
+---
+
+[Detailed prompt with context]
+@$1              # File references
+@AGENTS.md       # Project standards
+Additional: $2
+```
+
+### When to Build a Command
+- ✅ User types it frequently
+- ✅ Needs specific context files
+- ✅ Benefits from template
+- ✅ Can reuse subagent
+
+### The Formula
+```
+Command = Subagent + Context Files + Template
+```
+
+### Examples
+```bash
+/security/scan file.ts           # → security/code-scanner + project files
+/test/generate service.ts        # → testing/unit-generator + test patterns
+/refactor/modernize legacy.js    # → refactor/modernizer + standards
+```
+
+### Example: Security Audit Command
+```markdown
+# .opencode/command/security/audit.md
+---
+description: "Run comprehensive security audit on file"
+agent: "security/auditor"
+---
+
+Run a full security audit on @$1
+
+Include:
+- Vulnerability scanning
+- Dependency checks
+- Secret detection
+- Best practice validation
+
+Reference project standards: @AGENTS.md
+```
+
+---
+
+## Layer 4: MAIN AGENTS - Configure, Don't Create
+
+### The Rule
+**Customize builtin agents, rarely create new primary agents.**
+
+### Structure
+```markdown
+# .opencode/agent/build.md  (override built-in)
+---
+mode: "primary"
+tools:
+  test-runner: true
+  lint-check: true
+---
+
+## Testing Protocol
+After code changes: use test-runner
+On failure: analyze and fix
+On complex failure: use Task(subagent_type="testing/test-fixer")
+
+## Quality Checks
+Before completing: lint-check
+If issues: fix automatically
+```
+
+### When to Create a New Primary Agent
+- ❌ Almost never - customize `build`, `plan`, `general` instead
+- ✅ Only for distinct modes (e.g., "code-review-only" mode)
+
+---
+
+## Complete Patterns
+
+### Pattern 1: Progressive Enhancement
+```
+User Request
+    ↓
+Main Agent (build) - uses tools for atomic ops
+    ↓ (if complex)
+Task Tool → Subagent - specialized workflow
+    ↓ (if needs helpers)
+Task Tool → More Subagents - parallel execution
+    ↓
+Return to Main Agent
+    ↓
+User Response
+```
+
+### Pattern 2: User Shortcuts
+```
+User: /security/full-audit auth.ts
+    ↓
+Command loads template + context files
+    ↓
+Routes to subagent (mode: "subagent")
+    ↓
+Subagent uses tools (test-runner, lint-check)
+    ↓
+Returns focused report
+```
+
+---
+
+## Real-World Example: Complete Setup
+
+### Tools (Efficiency)
+```
+.opencode/tool/
+├── test.ts          # Smart test runner
+├── lint.ts          # Filtered linter
+└── deps.ts          # Dependency checker
+```
+
+### Subagents (Specialization)
+```
+.opencode/agent/
+├── security/
+│   └── auditor.md           # Comprehensive security
+├── testing/
+│   ├── generator.md         # Generate tests
+│   └── fixer.md             # Fix failures
+└── code-review/
+    └── reviewer.md          # Code quality
+```
+
+### Commands (Convenience)
+```
+.opencode/command/
+├── check.md                 # Quick health check
+├── security/
+│   └── audit.md            # Full security audit
+└── test/
+    ├── generate.md         # Generate tests
+    └── fix.md              # Fix failing tests
+```
+
+### Main Agent (Orchestration)
+```
+.opencode/agent/
+└── build.md                # Customized build agent
+```
+
+---
+
+## Decision Tree
+
+### "Should I build X?"
+
+#### TOOL?
+```
+Is it called 10+ times/session? → YES
+Does it need output filtering? → YES
+Can bash do it well enough? → NO if frequently used
+```
+
+#### SUBAGENT?
+```
+Is it 3+ step workflow? → YES
+Does it need isolated context? → YES
+Is it single atomic operation? → NO (make it a tool)
+```
+
+#### COMMAND?
+```
+Do users type this often? → YES
+Can it reuse existing subagent? → YES (just template it)
+Needs new capability? → NO (build subagent first)
+```
+
+#### MAIN AGENT?
+```
+Do you need a new mode? → Probably NO (customize existing)
+```
+
+---
+
+## The Winning Configuration
+
+### Minimal but Powerful
+```
+.opencode/
+├── tool/
+│   └── test.ts              # 1 efficient test tool
+├── agent/
+│   ├── build.md             # Customized with tool usage
+│   └── code-review/
+│       └── reviewer.md      # 1 specialized subagent
+└── command/
+    └── review.md            # 1 user shortcut
+```
+
+**This gives you:**
+- ✅ Efficient testing (90% token savings)
+- ✅ Code review capability
+- ✅ User convenience
+- ✅ Easy to maintain
+
+### Scale Up as Needed
+```
+.opencode/
+├── tool/              [2-5 tools max]
+│   ├── test.ts
+│   ├── lint.ts
+│   └── build.ts
+├── agent/            [5-15 subagents organized by domain]
+│   ├── security/
+│   ├── testing/
+│   ├── refactor/
+│   └── documentation/
+└── command/          [10-20 shortcuts]
+    ├── security/
+    ├── test/
+    └── refactor/
+```
+
+---
+
+## Pro Tips
+
+### 1. Start Small, Grow Organically
+```
+Week 1: Add test-runner tool
+Week 2: Add code-review subagent
+Week 3: Add shortcuts you use 3+ times
+```
+
+### 2. Make Subagents Discoverable
+```markdown
+description: "Use AFTER writing auth code to scan for vulnerabilities"
+```
+Main agent sees this in Task tool and knows when to call it.
+
+### 3. Template Everything
+```markdown
+# Command template
+@AGENTS.md        # Always include standards
+@.cursorrules     # Always include rules
+@$1               # Target file
+```
+
+### 4. Think in Layers
+- **Tools** = Efficiency
+- **Subagents** = Specialization
+- **Commands** = Convenience
+- **Main Agents** = Orchestration
+
+### 5. Avoid Redundancy
+```
+❌ Separate tool + subagent doing same thing
+✅ Tool for efficiency, subagent calls tool + adds intelligence
+```
+
+---
+
+## The Formula in One Diagram
+
+```
+┌─────────────────────────────────────────┐
+│  USER                                    │
+│  /security/audit auth.ts                 │
+└──────────────┬──────────────────────────┘
+               │
+               ↓
+┌──────────────────────────────────────────┐
+│  COMMAND (Template + Context)            │
+│  • Loads audit template                  │
+│  • Attaches @auth.ts, @AGENTS.md         │
+│  • Routes to: security/auditor           │
+└──────────────┬───────────────────────────┘
+               │
+               ↓
+┌──────────────────────────────────────────┐
+│  SUBAGENT (Specialized Workflow)         │
+│  • Calls lint-check tool                 │
+│  • Calls test-runner tool                │
+│  • Analyzes with domain expertise        │
+│  • Returns focused report                │
+└──────────────┬───────────────────────────┘
+               │
+               ↓
+┌──────────────────────────────────────────┐
+│  TOOLS (Efficient Operations)            │
+│  • lint-check: 30K chars → 200 chars     │
+│  • test-runner: 15K chars → 50 chars     │
+│  • Total context: 250 chars vs 45K       │
+└──────────────────────────────────────────┘
+```
+
+**Result:** 99% token savings, specialized analysis, user convenience.
+
+---
+
+## Getting Started
+
+### Step 1: Create Your First Tool
+```bash
+mkdir -p .opencode/tool
+cat > .opencode/tool/test.ts << 'EOF'
+import { tool } from "@opencode-ai/plugin"
+import { z } from "zod"
+
+export default tool({
+  description: "Run tests, return summary or failures only",
+  args: { path: z.string() },
+  async execute(args, ctx) {
+    const result = await ctx.$`npm test -- ${args.path}`.nothrow()
+    const output = await new Response(result.stdout).text()
+    return result.exitCode === 0 
+      ? `✅ Tests passed`
+      : `❌ Failed:\n${output.split('\n').filter(l => l.includes('FAIL') || l.includes('●')).slice(0, 20).join('\n')}`
+  }
+})
+EOF
+```
+
+### Step 2: Test It
+```bash
+opencode tui
+# Type: "run the tests"
+# Agent will use your new tool
+```
+
+### Step 3: Add More Layers
+Once your tool works, add:
+1. A subagent that uses the tool
+2. A command that routes to the subagent
+3. Customize your main agent to use both
+
+---
+
+## Summary
+
+The Power User Formula is simple:
+
+1. **Tools** for efficiency (90% token savings)
+2. **Subagents** for specialization (domain expertise)
+3. **Commands** for convenience (user shortcuts)
+4. **Main Agents** for orchestration (customize, don't create)
+
+Start with one tool, grow organically, and always think in layers.
+
+**That's the formula.** Now go build something powerful.
+
+---
+
+## Related Documentation
+
+- [System Builder Guide](../features/system-builder/guide.md)
+- [Quick Start](../features/system-builder/quick-start.md)
+- [Agent System Blueprint](../features/agent-system-blueprint.md)
+- [Contributing Guide](../contributing/CONTRIBUTING.md)

+ 50 - 27
install.sh

@@ -235,9 +235,9 @@ check_interactive_mode() {
         echo "Or use a profile directly:"
         echo ""
         echo -e "${CYAN}# Quick install with profile${NC}"
-        echo "curl -fsSL https://raw.githubusercontent.com/darrenhinde/opencode-agents/main/install.sh | bash -s core"
+        echo "curl -fsSL https://raw.githubusercontent.com/darrenhinde/opencode-agents/main/install.sh | bash -s essential"
         echo ""
-        echo "Available profiles: core, developer, full, advanced"
+        echo "Available profiles: essential, developer, business, full, advanced"
         echo ""
         cleanup_and_exit 1
     fi
@@ -276,44 +276,61 @@ show_profile_menu() {
     
     echo -e "${BOLD}Available Installation Profiles:${NC}\n"
     
-    # Core profile
-    local core_desc=$(jq -r '.profiles.core.description' "$TEMP_DIR/registry.json")
-    local core_count=$(jq -r '.profiles.core.components | length' "$TEMP_DIR/registry.json")
-    echo -e "  ${GREEN}1) Core${NC}"
-    echo -e "     ${core_desc}"
-    echo -e "     Components: ${core_count}\n"
+    # Essential profile
+    local essential_name=$(jq -r '.profiles.essential.name' "$TEMP_DIR/registry.json")
+    local essential_desc=$(jq -r '.profiles.essential.description' "$TEMP_DIR/registry.json")
+    local essential_count=$(jq -r '.profiles.essential.components | length' "$TEMP_DIR/registry.json")
+    echo -e "  ${GREEN}1) ${essential_name}${NC}"
+    echo -e "     ${essential_desc}"
+    echo -e "     Components: ${essential_count}\n"
     
     # Developer profile
     local dev_desc=$(jq -r '.profiles.developer.description' "$TEMP_DIR/registry.json")
     local dev_count=$(jq -r '.profiles.developer.components | length' "$TEMP_DIR/registry.json")
-    echo -e "  ${BLUE}2) Developer${NC}"
+    local dev_badge=$(jq -r '.profiles.developer.badge // ""' "$TEMP_DIR/registry.json")
+    if [ -n "$dev_badge" ]; then
+        echo -e "  ${BLUE}2) Developer ${GREEN}[${dev_badge}]${NC}"
+    else
+        echo -e "  ${BLUE}2) Developer${NC}"
+    fi
     echo -e "     ${dev_desc}"
     echo -e "     Components: ${dev_count}\n"
     
+    # Business profile
+    local business_name=$(jq -r '.profiles.business.name' "$TEMP_DIR/registry.json")
+    local business_desc=$(jq -r '.profiles.business.description' "$TEMP_DIR/registry.json")
+    local business_count=$(jq -r '.profiles.business.components | length' "$TEMP_DIR/registry.json")
+    echo -e "  ${CYAN}3) ${business_name}${NC}"
+    echo -e "     ${business_desc}"
+    echo -e "     Components: ${business_count}\n"
+    
     # Full profile
+    local full_name=$(jq -r '.profiles.full.name' "$TEMP_DIR/registry.json")
     local full_desc=$(jq -r '.profiles.full.description' "$TEMP_DIR/registry.json")
     local full_count=$(jq -r '.profiles.full.components | length' "$TEMP_DIR/registry.json")
-    echo -e "  ${MAGENTA}3) Full${NC}"
+    echo -e "  ${MAGENTA}4) ${full_name}${NC}"
     echo -e "     ${full_desc}"
     echo -e "     Components: ${full_count}\n"
     
     # Advanced profile
+    local adv_name=$(jq -r '.profiles.advanced.name' "$TEMP_DIR/registry.json")
     local adv_desc=$(jq -r '.profiles.advanced.description' "$TEMP_DIR/registry.json")
     local adv_count=$(jq -r '.profiles.advanced.components | length' "$TEMP_DIR/registry.json")
-    echo -e "  ${YELLOW}4) Advanced${NC}"
+    echo -e "  ${YELLOW}5) ${adv_name}${NC}"
     echo -e "     ${adv_desc}"
     echo -e "     Components: ${adv_count}\n"
     
-    echo "  5) Back to main menu"
+    echo "  6) Back to main menu"
     echo ""
-    read -p "Enter your choice [1-5]: " choice
+    read -p "Enter your choice [1-6]: " choice
     
     case $choice in
-        1) PROFILE="core" ;;
+        1) PROFILE="essential" ;;
         2) PROFILE="developer" ;;
-        3) PROFILE="full" ;;
-        4) PROFILE="advanced" ;;
-        5) show_main_menu; return ;;
+        3) PROFILE="business" ;;
+        4) PROFILE="full" ;;
+        5) PROFILE="advanced" ;;
+        6) show_main_menu; return ;;
         *) print_error "Invalid choice"; sleep 2; show_profile_menu; return ;;
     esac
     
@@ -608,8 +625,8 @@ get_install_strategy() {
 perform_installation() {
     print_step "Preparing installation..."
     
-    # Create directory structure if it doesn't exist
-    mkdir -p "$INSTALL_DIR"/{agent/subagents,command,tool,plugin,context/{core,project}}
+    # Create base directory only - subdirectories created on-demand when files are installed
+    mkdir -p "$INSTALL_DIR"
     
     # Check for collisions
     local collisions=()
@@ -816,9 +833,9 @@ trap 'cleanup_and_exit 1' INT TERM
 main() {
     # Parse command line arguments
     case "${1:-}" in
-        core|--core)
+        essential|--essential)
             INSTALL_MODE="profile"
-            PROFILE="core"
+            PROFILE="essential"
             NON_INTERACTIVE=true
             ;;
         developer|--developer)
@@ -826,6 +843,11 @@ main() {
             PROFILE="developer"
             NON_INTERACTIVE=true
             ;;
+        business|--business)
+            INSTALL_MODE="profile"
+            PROFILE="business"
+            NON_INTERACTIVE=true
+            ;;
         full|--full)
             INSTALL_MODE="profile"
             PROFILE="full"
@@ -847,17 +869,18 @@ main() {
             echo "Usage: $0 [OPTIONS]"
             echo ""
             echo "Options:"
-            echo "  core, --core           Install core profile"
-            echo "  developer, --developer Install developer profile"
-            echo "  full, --full           Install full profile"
-            echo "  advanced, --advanced   Install advanced profile"
+            echo "  essential, --essential Install essential profile (minimal)"
+            echo "  developer, --developer Install developer profile (code-focused)"
+            echo "  business, --business   Install business profile (content-focused)"
+            echo "  full, --full           Install full profile (everything except system-builder)"
+            echo "  advanced, --advanced   Install advanced profile (complete system)"
             echo "  list, --list           List all available components"
             echo "  help, --help, -h       Show this help message"
             echo ""
             echo "Examples:"
-            echo "  $0 core"
+            echo "  $0 essential"
             echo "  $0 --developer"
-            echo "  curl -fsSL https://raw.githubusercontent.com/darrenhinde/opencode-agents/main/install.sh | bash -s core"
+            echo "  curl -fsSL https://raw.githubusercontent.com/darrenhinde/opencode-agents/main/install.sh | bash -s essential"
             echo ""
             echo "Without options, runs in interactive mode"
             exit 0

+ 146 - 108
registry.json

@@ -1,23 +1,16 @@
 {
   "version": "1.0.0",
   "repository": "https://github.com/darrenhinde/opencode-agents",
+  "categories": {
+    "essential": "Minimal components for basic functionality",
+    "standard": "Standard components for typical use",
+    "extended": "Extended components for advanced features",
+    "specialized": "Specialized components for specific domains",
+    "meta": "Meta-level components for system generation"
+  },
   "components": {
     "agents": [
       {
-        "id": "task-manager",
-        "name": "Task Manager",
-        "type": "agent",
-        "path": ".opencode/agent/task-manager.md",
-        "description": "Breaks down complex features into small, verifiable subtasks",
-        "tags": [
-          "planning",
-          "organization",
-          "task-management"
-        ],
-        "dependencies": [],
-        "category": "core"
-      },
-      {
         "id": "codebase-agent",
         "name": "Codebase Agent",
         "type": "agent",
@@ -28,38 +21,32 @@
           "architecture",
           "patterns"
         ],
-        "dependencies": [],
-        "category": "core"
+        "dependencies": [
+          "subagent:task-manager",
+          "subagent:documentation",
+          "subagent:coder-agent",
+          "subagent:tester",
+          "subagent:reviewer",
+          "subagent:build-agent"
+        ],
+        "category": "standard"
       },
       {
-        "id": "image-specialist",
-        "name": "Image Specialist",
+        "id": "openagent",
+        "name": "OpenAgent",
         "type": "agent",
-        "path": ".opencode/agent/image-specialist.md",
-        "description": "Generates and edits images using Gemini AI",
+        "path": ".opencode/agent/openagent.md",
+        "description": "Universal agent for answering queries, executing tasks, and coordinating workflows across any domain",
         "tags": [
-          "images",
-          "ai",
-          "generation"
+          "universal",
+          "flexible",
+          "coordination"
         ],
         "dependencies": [
-          "tool:gemini"
-        ],
-        "category": "extended"
-      },
-      {
-        "id": "workflow-orchestrator",
-        "name": "Workflow Orchestrator",
-        "type": "agent",
-        "path": ".opencode/agent/workflow-orchestrator.md",
-        "description": "Orchestrates complex multi-agent workflows",
-        "tags": [
-          "orchestration",
-          "workflow",
-          "automation"
+          "subagent:task-manager",
+          "subagent:documentation"
         ],
-        "dependencies": [],
-        "category": "extended"
+        "category": "essential"
       },
       {
         "id": "system-builder",
@@ -80,15 +67,45 @@
           "subagent:workflow-designer",
           "subagent:command-creator"
         ],
-        "category": "advanced"
+        "category": "meta"
       }
     ],
     "subagents": [
       {
+        "id": "task-manager",
+        "name": "Task Manager",
+        "type": "subagent",
+        "path": ".opencode/agent/subagents/core/task-manager.md",
+        "description": "Breaks down complex features into small, verifiable subtasks",
+        "tags": [
+          "planning",
+          "organization",
+          "task-management"
+        ],
+        "dependencies": [],
+        "category": "essential"
+      },
+      {
+        "id": "image-specialist",
+        "name": "Image Specialist",
+        "type": "subagent",
+        "path": ".opencode/agent/subagents/utils/image-specialist.md",
+        "description": "Generates and edits images using Gemini AI",
+        "tags": [
+          "images",
+          "ai",
+          "generation"
+        ],
+        "dependencies": [
+          "tool:gemini"
+        ],
+        "category": "utils"
+      },
+      {
         "id": "reviewer",
-        "name": "Code Reviewer",
+        "name": "Reviewer",
         "type": "subagent",
-        "path": ".opencode/agent/subagents/reviewer.md",
+        "path": ".opencode/agent/subagents/code/reviewer.md",
         "description": "Performs code review with security and quality checks",
         "tags": [
           "review",
@@ -96,13 +113,13 @@
           "quality"
         ],
         "dependencies": [],
-        "category": "core"
+        "category": "standard"
       },
       {
         "id": "tester",
-        "name": "Test Writer",
+        "name": "Tester",
         "type": "subagent",
-        "path": ".opencode/agent/subagents/tester.md",
+        "path": ".opencode/agent/subagents/code/tester.md",
         "description": "Writes unit and integration tests",
         "tags": [
           "testing",
@@ -110,13 +127,13 @@
           "quality"
         ],
         "dependencies": [],
-        "category": "core"
+        "category": "standard"
       },
       {
         "id": "documentation",
         "name": "Documentation Writer",
         "type": "subagent",
-        "path": ".opencode/agent/subagents/documentation.md",
+        "path": ".opencode/agent/subagents/core/documentation.md",
         "description": "Creates and updates documentation",
         "tags": [
           "docs",
@@ -124,13 +141,13 @@
           "writing"
         ],
         "dependencies": [],
-        "category": "core"
+        "category": "essential"
       },
       {
         "id": "coder-agent",
         "name": "Coder Agent",
         "type": "subagent",
-        "path": ".opencode/agent/subagents/coder-agent.md",
+        "path": ".opencode/agent/subagents/code/coder-agent.md",
         "description": "Executes coding subtasks in sequence",
         "tags": [
           "coding",
@@ -138,13 +155,13 @@
           "execution"
         ],
         "dependencies": [],
-        "category": "core"
+        "category": "standard"
       },
       {
         "id": "build-agent",
         "name": "Build Agent",
         "type": "subagent",
-        "path": ".opencode/agent/subagents/build-agent.md",
+        "path": ".opencode/agent/subagents/code/build-agent.md",
         "description": "Type checks and validates builds",
         "tags": [
           "build",
@@ -152,13 +169,13 @@
           "type-checking"
         ],
         "dependencies": [],
-        "category": "core"
+        "category": "standard"
       },
       {
         "id": "codebase-pattern-analyst",
         "name": "Codebase Pattern Analyst",
         "type": "subagent",
-        "path": ".opencode/agent/subagents/codebase-pattern-analyst.md",
+        "path": ".opencode/agent/subagents/code/codebase-pattern-analyst.md",
         "description": "Analyzes and implements codebase patterns",
         "tags": [
           "patterns",
@@ -166,13 +183,13 @@
           "architecture"
         ],
         "dependencies": [],
-        "category": "extended"
+        "category": "specialized"
       },
       {
         "id": "domain-analyzer",
         "name": "Domain Analyzer",
         "type": "subagent",
-        "path": ".opencode/agent/subagents/domain-analyzer.md",
+        "path": ".opencode/agent/subagents/system-builder/domain-analyzer.md",
         "description": "Analyzes user domains and recommends agent architectures",
         "tags": [
           "analysis",
@@ -180,13 +197,13 @@
           "architecture"
         ],
         "dependencies": [],
-        "category": "advanced"
+        "category": "meta"
       },
       {
         "id": "agent-generator",
         "name": "Agent Generator",
         "type": "subagent",
-        "path": ".opencode/agent/subagents/agent-generator.md",
+        "path": ".opencode/agent/subagents/system-builder/agent-generator.md",
         "description": "Generates XML-optimized agent files following research-backed patterns",
         "tags": [
           "generation",
@@ -194,13 +211,13 @@
           "agents"
         ],
         "dependencies": [],
-        "category": "advanced"
+        "category": "meta"
       },
       {
         "id": "context-organizer",
         "name": "Context Organizer",
         "type": "subagent",
-        "path": ".opencode/agent/subagents/context-organizer.md",
+        "path": ".opencode/agent/subagents/system-builder/context-organizer.md",
         "description": "Organizes and generates modular context files",
         "tags": [
           "context",
@@ -208,13 +225,13 @@
           "knowledge-management"
         ],
         "dependencies": [],
-        "category": "advanced"
+        "category": "meta"
       },
       {
         "id": "workflow-designer",
         "name": "Workflow Designer",
         "type": "subagent",
-        "path": ".opencode/agent/subagents/workflow-designer.md",
+        "path": ".opencode/agent/subagents/system-builder/workflow-designer.md",
         "description": "Designs complete workflow definitions with context dependencies",
         "tags": [
           "workflows",
@@ -222,13 +239,13 @@
           "orchestration"
         ],
         "dependencies": [],
-        "category": "advanced"
+        "category": "meta"
       },
       {
         "id": "command-creator",
         "name": "Command Creator",
         "type": "subagent",
-        "path": ".opencode/agent/subagents/command-creator.md",
+        "path": ".opencode/agent/subagents/system-builder/command-creator.md",
         "description": "Creates custom slash commands with clear syntax and examples",
         "tags": [
           "commands",
@@ -236,7 +253,7 @@
           "cli"
         ],
         "dependencies": [],
-        "category": "advanced"
+        "category": "meta"
       }
     ],
     "commands": [
@@ -252,7 +269,7 @@
           "validation"
         ],
         "dependencies": [],
-        "category": "core"
+        "category": "standard"
       },
       {
         "id": "commit",
@@ -266,7 +283,7 @@
           "version-control"
         ],
         "dependencies": [],
-        "category": "core"
+        "category": "standard"
       },
       {
         "id": "context",
@@ -280,7 +297,7 @@
           "management"
         ],
         "dependencies": [],
-        "category": "core"
+        "category": "essential"
       },
       {
         "id": "clean",
@@ -294,7 +311,7 @@
           "build"
         ],
         "dependencies": [],
-        "category": "extended"
+        "category": "standard"
       },
       {
         "id": "optimize",
@@ -308,7 +325,7 @@
           "build"
         ],
         "dependencies": [],
-        "category": "extended"
+        "category": "standard"
       },
       {
         "id": "prompt-enhancer",
@@ -322,7 +339,7 @@
           "enhancement"
         ],
         "dependencies": [],
-        "category": "extended"
+        "category": "standard"
       },
       {
         "id": "worktrees",
@@ -336,7 +353,7 @@
           "workflow"
         ],
         "dependencies": [],
-        "category": "advanced"
+        "category": "specialized"
       },
       {
         "id": "build-context-system",
@@ -353,7 +370,7 @@
         "dependencies": [
           "agent:system-builder"
         ],
-        "category": "advanced"
+        "category": "meta"
       }
     ],
     "tools": [
@@ -371,7 +388,7 @@
         "dependencies": [
           "tool:env"
         ],
-        "category": "extended"
+        "category": "specialized"
       },
       {
         "id": "env",
@@ -385,7 +402,7 @@
           "security"
         ],
         "dependencies": [],
-        "category": "core"
+        "category": "essential"
       }
     ],
     "plugins": [
@@ -403,7 +420,7 @@
         "dependencies": [
           "tool:env"
         ],
-        "category": "extended"
+        "category": "specialized"
       },
       {
         "id": "notify",
@@ -416,7 +433,7 @@
           "alerts"
         ],
         "dependencies": [],
-        "category": "extended"
+        "category": "specialized"
       }
     ],
     "contexts": [
@@ -432,7 +449,7 @@
           "guidelines"
         ],
         "dependencies": [],
-        "category": "core"
+        "category": "essential"
       },
       {
         "id": "project-context",
@@ -446,7 +463,7 @@
           "configuration"
         ],
         "dependencies": [],
-        "category": "core"
+        "category": "essential"
       }
     ],
     "config": [
@@ -462,7 +479,7 @@
           "template"
         ],
         "dependencies": [],
-        "category": "core"
+        "category": "essential"
       },
       {
         "id": "readme",
@@ -476,21 +493,21 @@
           "guide"
         ],
         "dependencies": [],
-        "category": "core"
+        "category": "essential"
       }
     ]
   },
   "profiles": {
-    "core": {
-      "name": "Core",
-      "description": "Minimal essentials - main agent with basic subagents and commands",
+    "essential": {
+      "name": "Essential (Minimal)",
+      "description": "Minimal starter kit - universal agent with core subagents. Great for learning the system or lightweight tasks. Upgrade to Developer or Business for full features.",
       "components": [
-        "agent:task-manager",
-        "agent:codebase-agent",
-        "subagent:tester",
+        "agent:openagent",
+        "subagent:task-manager",
         "subagent:documentation",
-        "subagent:coder-agent",
-        "command:commit",
+        "command:context",
+        "command:clean",
+        "tool:env",
         "context:essential-patterns",
         "context:project-context",
         "config:env-example"
@@ -498,26 +515,45 @@
     },
     "developer": {
       "name": "Developer",
-      "description": "Recommended for daily development - includes testing, review, quality tools, and AI image generation",
+      "description": "Complete software development environment with code generation, testing, review, and build tools. Recommended for most developers.",
+      "badge": "RECOMMENDED",
       "components": [
-        "agent:task-manager",
+        "agent:openagent",
         "agent:codebase-agent",
-        "agent:image-specialist",
-        "agent:workflow-orchestrator",
-        "subagent:reviewer",
-        "subagent:tester",
+        "subagent:task-manager",
         "subagent:documentation",
         "subagent:coder-agent",
+        "subagent:reviewer",
+        "subagent:tester",
         "subagent:build-agent",
         "subagent:codebase-pattern-analyst",
-        "command:test",
         "command:commit",
+        "command:test",
         "command:context",
         "command:clean",
         "command:optimize",
+        "tool:env",
+        "context:essential-patterns",
+        "context:project-context",
+        "config:env-example",
+        "config:readme"
+      ]
+    },
+    "business": {
+      "name": "Business",
+      "description": "Business process automation, content creation, and visual workflows. Includes image generation, notifications, and documentation tools.",
+      "components": [
+        "agent:openagent",
+        "subagent:task-manager",
+        "subagent:documentation",
+        "subagent:image-specialist",
+        "command:context",
+        "command:clean",
         "command:prompt-enhancer",
         "tool:env",
         "tool:gemini",
+        "plugin:notify",
+        "plugin:telegram-notify",
         "context:essential-patterns",
         "context:project-context",
         "config:env-example",
@@ -526,18 +562,18 @@
     },
     "full": {
       "name": "Full",
-      "description": "Everything included - all agents, tools, and plugins for maximum functionality",
+      "description": "Everything included - all agents, subagents, tools, and plugins for maximum functionality.",
       "components": [
-        "agent:task-manager",
+        "agent:openagent",
         "agent:codebase-agent",
-        "agent:image-specialist",
-        "agent:workflow-orchestrator",
-        "subagent:reviewer",
-        "subagent:tester",
+        "subagent:task-manager",
         "subagent:documentation",
         "subagent:coder-agent",
+        "subagent:reviewer",
+        "subagent:tester",
         "subagent:build-agent",
         "subagent:codebase-pattern-analyst",
+        "subagent:image-specialist",
         "command:test",
         "command:commit",
         "command:context",
@@ -556,20 +592,20 @@
       ]
     },
     "advanced": {
-      "name": "Advanced",
-      "description": "Full installation plus system builder and experimental features",
+      "name": "Advanced (Meta-Level)",
+      "description": "Full installation plus System Builder for creating custom AI architectures. For power users and contributors.",
       "components": [
-        "agent:task-manager",
+        "agent:openagent",
         "agent:codebase-agent",
-        "agent:image-specialist",
-        "agent:workflow-orchestrator",
         "agent:system-builder",
-        "subagent:reviewer",
-        "subagent:tester",
+        "subagent:task-manager",
         "subagent:documentation",
         "subagent:coder-agent",
+        "subagent:reviewer",
+        "subagent:tester",
         "subagent:build-agent",
         "subagent:codebase-pattern-analyst",
+        "subagent:image-specialist",
         "subagent:domain-analyzer",
         "subagent:agent-generator",
         "subagent:context-organizer",
@@ -585,6 +621,8 @@
         "command:build-context-system",
         "tool:env",
         "tool:gemini",
+        "plugin:notify",
+        "plugin:telegram-notify",
         "context:essential-patterns",
         "context:project-context",
         "config:env-example",

+ 49 - 0
scripts/README.md

@@ -0,0 +1,49 @@
+# Scripts
+
+This directory contains utility scripts for the OpenCode Agents system.
+
+## Available Scripts
+
+### Component Management
+
+- `register-component.sh` - Register a new component in the registry
+- `validate-component.sh` - Validate component structure and metadata
+
+### Session Management
+
+- `cleanup-stale-sessions.sh` - Remove stale agent sessions older than 24 hours
+
+### Testing
+
+See `tests/` subdirectory for test scripts.
+
+## Session Cleanup
+
+Agent instances create temporary context files in `.tmp/sessions/{session-id}/` for subagent delegation. These sessions are automatically cleaned up, but you can manually remove stale sessions:
+
+```bash
+# Clean up sessions older than 24 hours
+./scripts/cleanup-stale-sessions.sh
+
+# Or manually delete all sessions
+rm -rf .tmp/sessions/
+```
+
+Sessions are safe to delete anytime - they only contain temporary context files for agent coordination.
+
+## Usage Examples
+
+### Register a Component
+```bash
+./scripts/register-component.sh path/to/component
+```
+
+### Validate a Component
+```bash
+./scripts/validate-component.sh path/to/component
+```
+
+### Clean Stale Sessions
+```bash
+./scripts/cleanup-stale-sessions.sh
+```

+ 76 - 0
scripts/cleanup-stale-sessions.sh

@@ -0,0 +1,76 @@
+#!/bin/bash
+# Cleanup stale agent sessions older than 24 hours
+
+set -e
+
+SESSIONS_DIR=".tmp/sessions"
+STALE_HOURS=24
+
+# Check if sessions directory exists
+if [ ! -d "$SESSIONS_DIR" ]; then
+    echo "No sessions directory found at $SESSIONS_DIR"
+    exit 0
+fi
+
+echo "Checking for stale sessions (older than ${STALE_HOURS} hours)..."
+
+# Find all session directories
+session_count=0
+stale_count=0
+
+for session_dir in "$SESSIONS_DIR"/*; do
+    if [ ! -d "$session_dir" ]; then
+        continue
+    fi
+    
+    session_count=$((session_count + 1))
+    session_id=$(basename "$session_dir")
+    manifest="$session_dir/.manifest.json"
+    
+    # Check if manifest exists
+    if [ ! -f "$manifest" ]; then
+        echo "⚠️  Session $session_id has no manifest - removing"
+        rm -rf "$session_dir"
+        stale_count=$((stale_count + 1))
+        continue
+    fi
+    
+    # Get last activity timestamp
+    last_activity=$(jq -r '.last_activity // .created_at' "$manifest" 2>/dev/null || echo "")
+    
+    if [ -z "$last_activity" ]; then
+        echo "⚠️  Session $session_id has invalid manifest - removing"
+        rm -rf "$session_dir"
+        stale_count=$((stale_count + 1))
+        continue
+    fi
+    
+    # Calculate age in hours
+    last_activity_epoch=$(date -j -f "%Y-%m-%dT%H:%M:%SZ" "$last_activity" "+%s" 2>/dev/null || echo "0")
+    current_epoch=$(date "+%s")
+    age_hours=$(( (current_epoch - last_activity_epoch) / 3600 ))
+    
+    if [ "$age_hours" -gt "$STALE_HOURS" ]; then
+        echo "🗑️  Removing stale session $session_id (${age_hours}h old)"
+        rm -rf "$session_dir"
+        stale_count=$((stale_count + 1))
+    else
+        echo "✅ Session $session_id is active (${age_hours}h old)"
+    fi
+done
+
+echo ""
+echo "Summary:"
+echo "  Total sessions: $session_count"
+echo "  Stale sessions removed: $stale_count"
+echo "  Active sessions: $((session_count - stale_count))"
+
+# Remove sessions directory if empty
+if [ -d "$SESSIONS_DIR" ] && [ -z "$(ls -A "$SESSIONS_DIR")" ]; then
+    echo ""
+    echo "Sessions directory is empty - removing"
+    rmdir "$SESSIONS_DIR"
+fi
+
+echo ""
+echo "✨ Cleanup complete!"