Kaynağa Gözat

feat(plugin): enhance context management and skill invocation (#239)

* fix(shellcheck): declare and assign separately in router.sh (SC2155)

* feat(plugin): enhance context management and skill invocation

- Update .context-manifest.json to include profile and detailed source information.
- Revise context-scout.md to clarify context root discovery and navigation.
- Modify commands to replace deprecated skills with updated ones (brainstorming → approach, systematic-debugging → debugger).
- Streamline install-context.md for clarity and remove interactive profile selection.
- Improve oac-status.md to provide a more comprehensive status report.
- Add OAC system paths to session-start.sh for better context management.
- Remove obsolete skills and improve documentation for existing commands.
Darren Hinde 5 ay önce
ebeveyn
işleme
a8fc9c7715
100 değiştirilmiş dosya ile 21287 ekleme ve 160 silme
  1. 7 6
      plugins/claude-code/.context-manifest.json
  2. 6 0
      plugins/claude-code/.oac.json.example
  3. 7 34
      plugins/claude-code/agents/context-scout.md
  4. 2 2
      plugins/claude-code/commands/brainstorm.md
  5. 1 1
      plugins/claude-code/commands/debug.md
  6. 3 104
      plugins/claude-code/commands/install-context.md
  7. 19 9
      plugins/claude-code/commands/oac-status.md
  8. 1 2
      plugins/claude-code/hooks/hooks.json
  9. 0 0
      plugins/claude-code/hooks/run-hook.cmd
  10. 9 2
      plugins/claude-code/hooks/session-start.sh
  11. 40 0
      plugins/claude-code/scripts/.context-manifest.json
  12. 3795 0
      plugins/claude-code/scripts/context/CODEBASE_STANDARDS.md
  13. 37 0
      plugins/claude-code/scripts/context/content-creation/examples/navigation.md
  14. 441 0
      plugins/claude-code/scripts/context/content-creation/formats/audio-content.md
  15. 341 0
      plugins/claude-code/scripts/context/content-creation/formats/image-content.md
  16. 73 0
      plugins/claude-code/scripts/context/content-creation/formats/navigation.md
  17. 476 0
      plugins/claude-code/scripts/context/content-creation/formats/video-content.md
  18. 409 0
      plugins/claude-code/scripts/context/content-creation/formats/written-content.md
  19. 56 0
      plugins/claude-code/scripts/context/content-creation/navigation.md
  20. 372 0
      plugins/claude-code/scripts/context/content-creation/principles/audience-targeting.md
  21. 286 0
      plugins/claude-code/scripts/context/content-creation/principles/copywriting-frameworks.md
  22. 242 0
      plugins/claude-code/scripts/context/content-creation/principles/hooks.md
  23. 72 0
      plugins/claude-code/scripts/context/content-creation/principles/navigation.md
  24. 348 0
      plugins/claude-code/scripts/context/content-creation/principles/tone-voice.md
  25. 462 0
      plugins/claude-code/scripts/context/content-creation/workflows/audience-review.md
  26. 459 0
      plugins/claude-code/scripts/context/content-creation/workflows/content-ideas.md
  27. 367 0
      plugins/claude-code/scripts/context/content-creation/workflows/content-matrix.md
  28. 78 0
      plugins/claude-code/scripts/context/content-creation/workflows/navigation.md
  29. 522 0
      plugins/claude-code/scripts/context/content-creation/workflows/remix-repurpose.md
  30. 39 0
      plugins/claude-code/scripts/context/core/config/navigation.md
  31. 7 0
      plugins/claude-code/scripts/context/core/config/paths.json
  32. 450 0
      plugins/claude-code/scripts/context/core/context-system.md
  33. 87 0
      plugins/claude-code/scripts/context/core/context-system/CHANGELOG.md
  34. 493 0
      plugins/claude-code/scripts/context/core/context-system/examples/navigation-examples.md
  35. 39 0
      plugins/claude-code/scripts/context/core/context-system/examples/navigation.md
  36. 122 0
      plugins/claude-code/scripts/context/core/context-system/guides/compact.md
  37. 173 0
      plugins/claude-code/scripts/context/core/context-system/guides/creation.md
  38. 133 0
      plugins/claude-code/scripts/context/core/context-system/guides/navigation-design-basics.md
  39. 185 0
      plugins/claude-code/scripts/context/core/context-system/guides/navigation-templates.md
  40. 50 0
      plugins/claude-code/scripts/context/core/context-system/guides/navigation.md
  41. 152 0
      plugins/claude-code/scripts/context/core/context-system/guides/organizing-context.md
  42. 573 0
      plugins/claude-code/scripts/context/core/context-system/guides/workflows.md
  43. 53 0
      plugins/claude-code/scripts/context/core/context-system/navigation.md
  44. 275 0
      plugins/claude-code/scripts/context/core/context-system/operations/error.md
  45. 202 0
      plugins/claude-code/scripts/context/core/context-system/operations/extract.md
  46. 342 0
      plugins/claude-code/scripts/context/core/context-system/operations/harvest.md
  47. 223 0
      plugins/claude-code/scripts/context/core/context-system/operations/migrate.md
  48. 50 0
      plugins/claude-code/scripts/context/core/context-system/operations/navigation.md
  49. 224 0
      plugins/claude-code/scripts/context/core/context-system/operations/organize.md
  50. 237 0
      plugins/claude-code/scripts/context/core/context-system/operations/update.md
  51. 145 0
      plugins/claude-code/scripts/context/core/context-system/standards/codebase-references.md
  52. 64 0
      plugins/claude-code/scripts/context/core/context-system/standards/frontmatter.md
  53. 151 0
      plugins/claude-code/scripts/context/core/context-system/standards/mvi.md
  54. 48 0
      plugins/claude-code/scripts/context/core/context-system/standards/navigation.md
  55. 240 0
      plugins/claude-code/scripts/context/core/context-system/standards/structure.md
  56. 396 0
      plugins/claude-code/scripts/context/core/context-system/standards/templates.md
  57. 210 0
      plugins/claude-code/scripts/context/core/essential-patterns.md
  58. 39 0
      plugins/claude-code/scripts/context/core/guides/navigation.md
  59. 322 0
      plugins/claude-code/scripts/context/core/guides/resuming-sessions.md
  60. 93 0
      plugins/claude-code/scripts/context/core/navigation.md
  61. 152 0
      plugins/claude-code/scripts/context/core/standards/code-analysis.md
  62. 164 0
      plugins/claude-code/scripts/context/core/standards/code-quality.md
  63. 164 0
      plugins/claude-code/scripts/context/core/standards/code.md
  64. 150 0
      plugins/claude-code/scripts/context/core/standards/docs.md
  65. 150 0
      plugins/claude-code/scripts/context/core/standards/documentation.md
  66. 51 0
      plugins/claude-code/scripts/context/core/standards/navigation.md
  67. 249 0
      plugins/claude-code/scripts/context/core/standards/project-intelligence-management.md
  68. 77 0
      plugins/claude-code/scripts/context/core/standards/project-intelligence.md
  69. 149 0
      plugins/claude-code/scripts/context/core/standards/security-patterns.md
  70. 127 0
      plugins/claude-code/scripts/context/core/standards/test-coverage.md
  71. 127 0
      plugins/claude-code/scripts/context/core/standards/tests.md
  72. 192 0
      plugins/claude-code/scripts/context/core/system/context-guide.md
  73. 85 0
      plugins/claude-code/scripts/context/core/system/context-paths.md
  74. 40 0
      plugins/claude-code/scripts/context/core/system/navigation.md
  75. 129 0
      plugins/claude-code/scripts/context/core/task-management/guides/managing-tasks.md
  76. 42 0
      plugins/claude-code/scripts/context/core/task-management/guides/navigation.md
  77. 115 0
      plugins/claude-code/scripts/context/core/task-management/guides/splitting-tasks.md
  78. 39 0
      plugins/claude-code/scripts/context/core/task-management/lookup/navigation.md
  79. 204 0
      plugins/claude-code/scripts/context/core/task-management/lookup/task-commands.md
  80. 66 0
      plugins/claude-code/scripts/context/core/task-management/navigation.md
  81. 781 0
      plugins/claude-code/scripts/context/core/task-management/standards/enhanced-task-schema.md
  82. 42 0
      plugins/claude-code/scripts/context/core/task-management/standards/navigation.md
  83. 201 0
      plugins/claude-code/scripts/context/core/task-management/standards/task-schema.md
  84. 478 0
      plugins/claude-code/scripts/context/core/visual-development.md
  85. 136 0
      plugins/claude-code/scripts/context/core/workflows/code-review.md
  86. 96 0
      plugins/claude-code/scripts/context/core/workflows/component-planning.md
  87. 20 0
      plugins/claude-code/scripts/context/core/workflows/delegation.md
  88. 179 0
      plugins/claude-code/scripts/context/core/workflows/design-iteration-best-practices.md
  89. 91 0
      plugins/claude-code/scripts/context/core/workflows/design-iteration-overview.md
  90. 182 0
      plugins/claude-code/scripts/context/core/workflows/design-iteration-plan-file.md
  91. 153 0
      plugins/claude-code/scripts/context/core/workflows/design-iteration-plan-iterations.md
  92. 80 0
      plugins/claude-code/scripts/context/core/workflows/design-iteration-stage-animation.md
  93. 157 0
      plugins/claude-code/scripts/context/core/workflows/design-iteration-stage-implementation.md
  94. 115 0
      plugins/claude-code/scripts/context/core/workflows/design-iteration-stage-layout.md
  95. 84 0
      plugins/claude-code/scripts/context/core/workflows/design-iteration-stage-theme.md
  96. 110 0
      plugins/claude-code/scripts/context/core/workflows/design-iteration-visual-content.md
  97. 461 0
      plugins/claude-code/scripts/context/core/workflows/external-context-integration.md
  98. 406 0
      plugins/claude-code/scripts/context/core/workflows/external-context-management.md
  99. 165 0
      plugins/claude-code/scripts/context/core/workflows/external-libraries-faq.md
  100. 130 0
      plugins/claude-code/scripts/context/core/workflows/external-libraries-scenarios.md

+ 7 - 6
plugins/claude-code/.context-manifest.json

@@ -1,11 +1,12 @@
 {
   "version": "1.0.0",
+  "profile": "standard",
   "source": {
-    "repository": "github:darrenhinde/OpenAgentsControl#main",
-    "branch": null,
-    "commit": null,
-    "downloaded_at": null
+    "repository": "darrenhinde/OpenAgentsControl",
+    "branch": "main",
+    "commit": "1442740b4a776a790754c9dbde64ab7f1aa9d4e8",
+    "downloaded_at": "2026-02-23T11:37:10Z"
   },
-  "categories": [],
-  "files": {}
+  "categories": ["core","openagents-repo"],
+  "files": {"core": 86,"openagents-repo": 107}
 }

+ 6 - 0
plugins/claude-code/.oac.json.example

@@ -0,0 +1,6 @@
+{
+  "version": "1",
+  "context": {
+    "root": ".claude/context"
+  }
+}

+ 7 - 34
plugins/claude-code/agents/context-scout.md

@@ -61,7 +61,7 @@ model: haiku
 **3 steps. That's it.**
 
 1. **Understand intent** — What is the user trying to do? What context do they need?
-2. **Follow navigation** — Read `navigation.md` files from `.opencode/context/` downward. They are the map.
+2. **Follow navigation** — Read `navigation.md` files from the resolved `{context_root}` downward. They are the map.
 3. **Return ranked files** — Priority order: Critical → High → Medium. Brief summary per file.
 
 ---
@@ -70,44 +70,17 @@ model: haiku
 
 ### Step 0: Discover Context Root
 
-**Before discovering context files, find where context is stored:**
+**Follow the OAC Context Discovery Protocol exactly.**
 
-**Discovery Order**:
-1. **Check .oac config** - Try reading `.oac` file for `context.root` setting
-2. **Check .claude/context** - Claude Code default location
-3. **Check context** - Simple root-level directory
-4. **Check .opencode/context** - OpenCode/OAC default location
-5. **Check plugin context** - `plugins/claude-code/context/` (installed via /install-context)
-6. **Fallback** - If none found, report error (don't assume location)
+Read the protocol file — its path is in your session context under **OAC System Paths**:
 
-**Process**:
 ```
-# Try reading .oac config
-Read: .oac
-  → If exists, parse JSON and extract context.root
-  → If context.root is set and directory exists, use it
-
-# Try .claude/context
-Glob: .claude/context/navigation.md
-  → If exists, use .claude/context
-
-# Try context
-Glob: context/navigation.md
-  → If exists, use context
-
-# Try .opencode/context
-Glob: .opencode/context/navigation.md
-  → If exists, use .opencode/context
-
-# Try plugin context (installed via /install-context)
-Glob: plugins/claude-code/context/navigation.md
-  → If exists, use plugins/claude-code/context
-
-# If none found
-  → Return error: "No context root found. Run /install-context to download context files."
+Read: {PLUGIN_ROOT}/skills/context-discovery/context-discovery-protocol.md
 ```
 
-**Output**: Context root path (e.g., `.claude/context`, `context`, or `.opencode/context`)
+Execute the protocol (Steps 1–4) and return the resolved `context_root`, `source`, and `write_oac_json` flag to the main agent.
+
+**You cannot write `.oac.json` yourself (read-only agent).** If the protocol says `write_oac_json: true`, include that signal in your response so the main agent can create the file.
 
 ---
 

+ 2 - 2
plugins/claude-code/commands/brainstorm.md

@@ -1,6 +1,6 @@
 ---
-description: "You MUST use this before any creative work — creating features, building components, adding functionality, or modifying behavior."
+description: "Use before implementing anything — discovers context and proposes a plan for approval before writing code."
 disable-model-invocation: true
 ---
 
-Invoke the oac:brainstorming skill and follow it exactly as presented to you
+Invoke the oac:approach skill and follow it exactly as presented to you

+ 1 - 1
plugins/claude-code/commands/debug.md

@@ -3,4 +3,4 @@ description: "Use when encountering any bug, test failure, or unexpected behavio
 disable-model-invocation: true
 ---
 
-Invoke the oac:systematic-debugging skill and follow it exactly as presented to you
+Invoke the oac:debugger skill and follow it exactly as presented to you

+ 3 - 104
plugins/claude-code/commands/install-context.md

@@ -1,110 +1,9 @@
 ---
 name: install-context
-description: Install OpenAgents Control context files from registry with interactive profile selection
-argument-hint: [--profile=<profile>] [--force] [--dry-run] [--verbose]
+description: Install OpenAgents Control context files
+argument-hint: [--profile=<profile>] [--force] [--dry-run]
 ---
 
-# Install Context Command
-
 $ARGUMENTS
 
-## Overview
-
-Install context files from the OpenAgents Control registry with interactive profile selection.
-
-**Available profiles**: essential, standard, extended, specialized, all
-
-**Options**:
-- `--profile=<profile>` - Install specific profile (skips interactive selection)
-- `--force` - Force reinstall even if already installed
-- `--dry-run` - Preview what would be installed without installing
-- `--verbose` - Show detailed installation progress
-- `--categories=<ids>` - Install specific context components (comma-separated)
-
----
-
-## Usage
-
-### Interactive Mode (Recommended)
-
-```
-/install-context
-```
-
-This will:
-1. Check current installation status
-2. Ask which profile to install
-3. Confirm before proceeding
-4. Run installation
-5. Verify files
-6. Offer cleanup options
-
-### Direct Mode (With Options)
-
-```
-# Install essential profile
-/install-context --profile=essential
-
-# Force reinstall standard profile
-/install-context --profile=standard --force
-
-# Preview extended profile
-/install-context --profile=extended --dry-run
-
-# Install with verbose output
-/install-context --profile=standard --verbose
-
-# Install specific components
-/install-context --categories=core-standards,openagents-repo
-```
-
----
-
-## How It Works
-
-This command invokes the `install-context` skill which:
-
-1. **Checks current installation** - Shows what's already installed (if any)
-2. **Asks for profile** - Interactive selection or uses `--profile` option
-3. **Confirms installation** - Shows summary and asks for confirmation
-4. **Runs TypeScript installer** - Executes `scripts/install-context.ts`
-5. **Verifies installation** - Checks files exist and manifest is created
-6. **Offers cleanup** - Asks about cleaning up temporary files
-
----
-
-## Profile Descriptions
-
-**essential** (Recommended for getting started)
-- Minimal components for basic functionality
-- ~4 components, ~30 seconds download
-- Includes: core patterns, project context, navigation
-
-**standard** (Recommended for most users)
-- Standard components for typical use
-- ~12 components, ~2 minutes download
-- Includes: essential + development workflows + common patterns
-
-**extended** (For advanced features)
-- Extended components for advanced features
-- ~30 components, ~5 minutes download
-- Includes: standard + specialized domains + advanced patterns
-
-**specialized** (For specific domains)
-- Specialized components for specific domains
-- ~50 components, ~10 minutes download
-- Includes: extended + domain-specific contexts (UI, data, product, etc.)
-
-**all** (Complete installation)
-- All available context components
-- ~191 components, ~20 minutes download
-- Includes: Everything in the registry
-
----
-
-## Examples
-
-### Example 1: First-time Installation
-
-```
-User: /install-context
+Use the `context-setup` skill to guide through installing context files for this project.

+ 19 - 9
plugins/claude-code/commands/oac-status.md

@@ -1,15 +1,25 @@
 ---
-name: oac:status
+name: oac-status
 description: Show OAC plugin status, installed context, and available skills
 ---
 
-Show the current OAC plugin status by running:
+Show the current OAC plugin status.
 
-!ls -la .opencode/context/ 2>/dev/null && echo "Context installed" || echo "No context installed — run /install-context"
-!cat .context-manifest.json 2>/dev/null | head -20 || echo "No manifest found"
+Run:
+```bash
+echo "=== Context Installation ===" && \
+  cat "${CLAUDE_PLUGIN_ROOT}/.context-manifest.json" 2>/dev/null | grep -E '"profile"|"downloaded_at"|"version"' || echo "Not installed — run /install-context" && \
+  echo "" && \
+  echo "=== Context Root ===" && \
+  cat .oac.json 2>/dev/null || echo "No .oac.json — context root not pinned" && \
+  echo "" && \
+  echo "=== Context Files ===" && \
+  ls "${CLAUDE_PLUGIN_ROOT}/context/" 2>/dev/null | wc -l | xargs -I{} echo "{} component directories installed"
+```
 
-Then report:
-- Plugin version: 1.0.0
-- Context status (installed/not installed)
-- Available skills: brainstorming, context-discovery, systematic-debugging, verification-before-completion, task-breakdown, code-execution, test-generation, code-review, external-scout, parallel-execution
-- Available subagents: context-scout, task-manager, coder-agent, test-engineer, code-reviewer, context-manager, external-scout
+Then report in plain language:
+- **Plugin version:** 1.0.0
+- **Context status:** installed profile + component count, or "not installed"
+- **Context root:** path from `.oac.json`, or "not pinned (run /install-context)"
+- **Available skills:** install-context, context-discovery, approach, debugger, verification-before-completion, task-breakdown, code-execution, test-generation, code-review, external-research, parallel-execution
+- **Available subagents:** context-scout, task-manager, coder-agent, test-engineer, code-reviewer, external-scout

+ 1 - 2
plugins/claude-code/hooks/hooks.json

@@ -1,5 +1,4 @@
 {
-  "description": "OAC session initialization — injects workflow context on session start",
   "hooks": {
     "SessionStart": [
       {
@@ -15,4 +14,4 @@
       }
     ]
   }
-}
+}

+ 0 - 0
plugins/claude-code/hooks/run-hook.cmd


+ 9 - 2
plugins/claude-code/hooks/session-start.sh

@@ -11,6 +11,7 @@ SKILL_FILE="${PLUGIN_ROOT}/skills/using-oac/SKILL.md"
 # Read using-oac content
 using_oac_content=$(cat "${SKILL_FILE}" 2>&1 || echo "Error reading using-oac skill")
 
+
 # Escape string for JSON embedding
 # SECURITY: Prevents command injection attacks from malicious SKILL.md files
 escape_for_json() {
@@ -49,14 +50,20 @@ fi
 # Build warning message for first-time users
 warning_message=""
 if [[ ! -f "${PLUGIN_ROOT}/.context-manifest.json" ]] && [[ ! -f "$(pwd)/.context-manifest.json" ]]; then
-    warning_message="\n\n<important-reminder>IN YOUR FIRST REPLY AFTER SEEING THIS MESSAGE YOU MUST TELL THE USER:👋 **Welcome to OpenAgents Control!** To get started, run /install-context to download context files. Then use /brainstorm before building anything.</important-reminder>"
+    warning_message="\n\n<important-reminder>IN YOUR FIRST REPLY AFTER SEEING THIS MESSAGE YOU MUST TELL THE USER: **No context files found.** Invoke the install-context skill now to set up context for this project — it will check your project type and recommend the right profile. Say: \"I notice you don't have context files set up. Let me get that sorted for you.\" Then immediately run the install-context skill.</important-reminder>"
 fi
 
 warning_escaped=$(escape_for_json "$warning_message")
 skill_catalogue_escaped=$(escape_for_json "$skill_catalogue")
 
+# Build OAC system paths block
+PROTOCOL_PATH="${PLUGIN_ROOT}/skills/context-discovery/context-discovery-protocol.md"
+plugin_root_escaped=$(escape_for_json "$PLUGIN_ROOT")
+protocol_path_escaped=$(escape_for_json "$PROTOCOL_PATH")
+OAC_SYSTEM_PATHS="## OAC System Paths\n- Plugin Root: ${plugin_root_escaped}\n- Context Discovery Protocol: ${protocol_path_escaped}"
+
 # Build context string
-OAC_CONTEXT="<EXTREMELY_IMPORTANT>\nYou have OAC (OpenAgents Control) superpowers.\n\n**Below is the full content of your 'oac:using-oac' skill — your introduction to using OAC skills. For all other skills, use the 'Skill' tool:**\n\n${using_oac_escaped}\n\n## Available OAC Skills (invoke with the Skill tool):\n${skill_catalogue_escaped}\n\n${warning_escaped}\n</EXTREMELY_IMPORTANT>"
+OAC_CONTEXT="<EXTREMELY_IMPORTANT>\nYou have OAC (OpenAgents Control).\n\n**Below is the full content of your 'oac:using-oac' skill — your introduction to using OAC skills. For all other skills, use the 'Skill' tool:**\n\n${using_oac_escaped}\n\n## Available OAC Skills (invoke with the Skill tool):\n${skill_catalogue_escaped}\n\n${OAC_SYSTEM_PATHS}\n\n${warning_escaped}\n</EXTREMELY_IMPORTANT>"
 
 # Output dual-format JSON for cross-tool compatibility
 # - additionalContext: Claude Code (hookSpecificOutput)

+ 40 - 0
plugins/claude-code/scripts/.context-manifest.json

@@ -0,0 +1,40 @@
+{
+  "version": "1.0.0",
+  "profile": "essential",
+  "source": {
+    "repository": "darrenhinde/OpenAgentsControl",
+    "branch": "main",
+    "commit": "5f4991633f5349385859a08da76c8b33f3a033e1",
+    "downloaded_at": "2026-02-16T12:20:32.201Z"
+  },
+  "context": [
+    {
+      "id": "essential-patterns",
+      "name": "Essential Patterns",
+      "path": ".opencode/context/core/essential-patterns.md",
+      "local_path": "/Users/darrenhinde/Documents/GitHub/MYBUSINESS/OpenAgentsControl/plugins/claude-code/scripts/context/core/essential-patterns.md",
+      "category": "essential"
+    },
+    {
+      "id": "project-context",
+      "name": "Project Context",
+      "path": ".opencode/context/project/project-context.md",
+      "local_path": "/Users/darrenhinde/Documents/GitHub/MYBUSINESS/OpenAgentsControl/plugins/claude-code/scripts/context/project/project-context.md",
+      "category": "essential"
+    },
+    {
+      "id": "context-paths-config",
+      "name": "Context Paths Configuration",
+      "path": ".opencode/context/core/config/paths.json",
+      "local_path": "/Users/darrenhinde/Documents/GitHub/MYBUSINESS/OpenAgentsControl/plugins/claude-code/scripts/context/core/config/paths.json",
+      "category": "essential"
+    },
+    {
+      "id": "root-navigation",
+      "name": "Root Navigation",
+      "path": ".opencode/context/navigation.md",
+      "local_path": "/Users/darrenhinde/Documents/GitHub/MYBUSINESS/OpenAgentsControl/plugins/claude-code/scripts/context/navigation.md",
+      "category": "essential"
+    }
+  ]
+}

+ 3795 - 0
plugins/claude-code/scripts/context/CODEBASE_STANDARDS.md

@@ -0,0 +1,3795 @@
+<!-- Context: core/standards | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# OpenCode Codebase Standards
+
+**Complete Reference Guide**  
+_Last Updated: Feb 2026_  
+_Analyzed: 206+ TypeScript files across `packages/opencode/src/`_
+
+---
+
+## Table of Contents
+
+1. [Function Definition Standards](#1-function-definition-standards)
+2. [Class Usage Standards](#2-class-usage-standards)
+3. [Array Handling Standards](#3-array-handling-standards)
+4. [Variable & Destructuring Standards](#4-variable--destructuring-standards)
+5. [Control Flow Standards](#5-control-flow-standards)
+6. [Async & Concurrency Standards](#6-async--concurrency-standards)
+7. [Race Condition Prevention](#7-race-condition-prevention)
+8. [AI System Integration Standards](#8-ai-system-integration-standards)
+9. [Service Architecture Standards](#9-service-architecture-standards)
+10. [State Management Standards](#10-state-management-standards)
+11. [Event Bus Standards](#11-event-bus-standards)
+12. [Configuration Management Standards](#12-configuration-management-standards)
+13. [Storage & Persistence Standards](#13-storage--persistence-standards)
+14. [Error Handling Standards](#14-error-handling-standards)
+15. [Type System Standards](#15-type-system-standards)
+16. [Import Organization Standards](#16-import-organization-standards)
+17. [Naming Conventions](#17-naming-conventions)
+18. [Testing Standards](#18-testing-standards)
+19. [Documentation Standards](#19-documentation-standards)
+20. [Schema Definition Standards](#20-schema-definition-standards)
+21. [Dependency Management Standards](#21-dependency-management-standards)
+22. [Build & Development Standards](#22-build--development-standards)
+23. [Performance Standards](#23-performance-standards)
+24. [Security Standards](#24-security-standards)
+
+---
+
+## 1. Function Definition Standards
+
+### 1.1 Naming Convention
+
+**Rule: Prefer single-word function names**
+
+**Compliance: 95%+**
+
+```typescript
+// ✅ GOOD - Single-word names
+export const create = fn(...)
+export const fork = fn(...)
+export const touch = fn(...)
+export const get = fn(...)
+export const share = fn(...)
+export async function stream(input: StreamInput) {...}
+export async function work<T>(concurrency, items, fn) {...}
+
+// ✅ ACCEPTABLE - Multi-word only when necessary
+export function isDefaultTitle(title: string) {...}      // Boolean predicate
+export function assertNotBusy(sessionID: string) {...}   // Assertion pattern
+export async function createNext(input) {...}            // Version disambiguation
+export async function resolvePromptParts(template) {...} // Complex operation needs clarity
+
+// ❌ AVOID - Unnecessary multi-word names
+function prepareJournal(dir: string) {}  // Use: journal()
+function getUserData(id: string) {}      // Use: user()
+function processFileContent(path) {}     // Use: process()
+```
+
+**File References:**
+
+- `packages/opencode/src/session/index.ts` - Lines 140, 200, 206
+- `packages/opencode/src/session/llm.ts` - Line 59
+- `packages/opencode/src/util/queue.ts` - Lines 1-32
+
+### 1.2 Function Definition Patterns
+
+#### Pattern A: Zod-Validated Functions (Primary Pattern)
+
+```typescript
+// packages/opencode/src/util/fn.ts - The fn() wrapper
+export function fn<T extends z.ZodType, Result>(schema: T, cb: (input: z.infer<T>) => Result) {
+  const result = (input: z.infer<T>) => {
+    const parsed = schema.parse(input) // Validates input
+    return cb(parsed)
+  }
+  result.force = (input: z.infer<T>) => cb(input) // Skip validation
+  result.schema = schema // Expose schema
+  return result
+}
+
+// Usage Example 1: Session creation
+export const create = fn(
+  z
+    .object({
+      parentID: Identifier.schema("session").optional(),
+      title: z.string().optional(),
+      permission: Info.shape.permission,
+    })
+    .optional(),
+  async (input) => {
+    return createNext({
+      parentID: input?.parentID,
+      title: input?.title,
+      permission: input?.permission ?? "allow",
+    })
+  },
+)
+
+// Usage Example 2: Simple validation
+export const touch = fn(Identifier.schema("session"), async (sessionID) => {
+  await update(sessionID, (draft) => {
+    draft.time.updated = Date.now()
+  })
+})
+
+// Usage Example 3: Complex object validation
+export const messages = fn(
+  z.object({
+    sessionID: Identifier.schema("session"),
+    limit: z.number().optional(),
+  }),
+  async (input) => {
+    const result = [] as MessageV2.WithParts[]
+    for await (const msg of MessageV2.stream(input.sessionID)) {
+      if (input.limit && result.length >= input.limit) break
+      result.push(msg)
+    }
+    result.reverse()
+    return result
+  },
+)
+```
+
+**File References:**
+
+- `packages/opencode/src/util/fn.ts` - Lines 1-12
+- `packages/opencode/src/session/index.ts` - Lines 140-202
+
+#### Pattern B: Namespace Organization (Preferred over Classes)
+
+```typescript
+// packages/opencode/src/session/index.ts
+export namespace Session {
+  const log = Log.create({ service: "session" })
+
+  // Exported functions with fn() wrapper
+  export const create = fn(...)
+  export const fork = fn(...)
+  export const touch = fn(...)
+  export const messages = fn(...)
+
+  // Async functions without wrapper
+  export async function createNext(input) {...}
+  export async function update(id, editor, options) {...}
+
+  // Type definitions
+  export type Info = z.infer<typeof Info>
+  export const Info = z.object({...})
+
+  // Events
+  export const Event = {
+    Created: BusEvent.define("session.created", z.object({info: Info})),
+    Updated: BusEvent.define("session.updated", z.object({info: Info})),
+  }
+
+  // Error classes (only exception to no-class rule)
+  export class BusyError extends Error {
+    constructor(public readonly sessionID: string) {
+      super(`Session ${sessionID} is busy`)
+    }
+  }
+}
+
+// Usage
+await Session.create({ title: "New Session" })
+await Session.touch(sessionID)
+const msgs = await Session.messages({ sessionID, limit: 10 })
+```
+
+**File References:**
+
+- `packages/opencode/src/session/index.ts` - Lines 26-518
+- `packages/opencode/src/tool/tool.ts` - Lines 1-90
+- `packages/opencode/src/session/processor.ts` - Lines 19-416
+
+#### Pattern C: Inline vs. Extraction Rule
+
+**Rule: Inline when used once, extract when composable/reusable**
+
+```typescript
+// ✅ GOOD - Inline when value used once
+const journal = await Bun.file(path.join(dir, "journal.json")).json()
+const [language, cfg] = await Promise.all([Provider.getLanguage(input.model), Config.get()])
+
+// ❌ BAD - Unnecessary intermediate variable
+const journalPath = path.join(dir, "journal.json")
+const journalFile = Bun.file(journalPath)
+const journal = await journalFile.json()
+
+// ✅ GOOD - Extract when reusable across multiple call sites
+async function resolveTools(input: Pick<StreamInput, "tools" | "agent" | "user">) {
+  const disabled = PermissionNext.disabled(Object.keys(input.tools), input.agent.permission)
+  for (const tool of Object.keys(input.tools)) {
+    if (input.user.tools?.[tool] === false || disabled.has(tool)) {
+      delete input.tools[tool]
+    }
+  }
+  return input.tools
+}
+
+// Called from multiple locations
+const tools = await resolveTools({ tools: input.tools, agent, user })
+
+// ✅ GOOD - Extract when logic is complex and improves readability
+function shouldUseCopilotResponsesApi(modelID: string): boolean {
+  const match = /^gpt-(\d+)/.exec(modelID)
+  if (!match) return false
+  return Number(match[1]) >= 5 && !modelID.startsWith("gpt-5-mini")
+}
+```
+
+**File References:**
+
+- `packages/opencode/src/session/llm.ts` - Lines 59, 268-276
+- `packages/opencode/src/provider/provider.ts` - Lines 46-56
+
+### 1.3 Function Composition Patterns
+
+```typescript
+// ✅ GOOD - Functional composition with pipes
+const filtered = agents
+  .filter((a) => a.mode !== "primary")
+  .filter((a) => PermissionNext.evaluate("task", a.name, caller.permission).action !== "deny")
+  .map((a) => a.name)
+
+// ✅ GOOD - Async composition with Promise.all
+const [results, metadata] = await Promise.all([processItems(items), fetchMetadata(id)])
+
+// ✅ GOOD - Higher-order functions
+export function withLock<T>(filepath: string, fn: () => Promise<T>): Promise<T> {
+  return Lock.write(filepath).then(async (lock) => {
+    try {
+      return await fn()
+    } finally {
+      lock[Symbol.dispose]()
+    }
+  })
+}
+```
+
+---
+
+## 2. Class Usage Standards
+
+### 2.1 Avoid Classes (Except Specific Patterns)
+
+**Finding: Only 5 classes in 206 files**
+
+**Rule: Use namespaces + functions instead of classes**
+
+```typescript
+// ❌ AVOID - Class-based organization
+class SessionManager {
+  private sessions: Map<string, Session> = new Map()
+
+  create(input: CreateInput) {
+    const session = { id: generateId(), ...input }
+    this.sessions.set(session.id, session)
+    return session
+  }
+
+  update(id: string, data: Partial<Session>) {
+    const session = this.sessions.get(id)
+    if (!session) throw new Error("Not found")
+    Object.assign(session, data)
+    return session
+  }
+}
+
+// ✅ PREFER - Namespace-based organization
+export namespace Session {
+  const state = Instance.state(async () => ({
+    sessions: new Map<string, Info>()
+  }))
+
+  export const create = fn(
+    CreateInput.schema,
+    async (input) => {
+      const session = { id: Identifier.ascending("session"), ...input }
+      state().sessions.set(session.id, session)
+      return session
+    }
+  )
+
+  export const update = fn(
+    z.object({ id: z.string(), data: z.record(z.unknown()) }),
+    async (input) => {
+      const session = state().sessions.get(input.id)
+      if (!session) throw NotFoundError.create({...})
+      Object.assign(session, input.data)
+      return session
+    }
+  )
+}
+```
+
+### 2.2 Allowed Class Use Cases
+
+#### Use Case 1: Error Types
+
+```typescript
+// ✅ GOOD - Custom error classes
+export class BusyError extends Error {
+  constructor(public readonly sessionID: string) {
+    super(`Session ${sessionID} is busy`)
+  }
+}
+
+// Usage
+throw new BusyError(sessionID)
+
+// Catching
+try {
+  await operation()
+} catch (error) {
+  if (error instanceof BusyError) {
+    // Handle busy state
+  }
+}
+```
+
+**File Reference:** `packages/opencode/src/session/index.ts:494`
+
+#### Use Case 2: Protocol Implementations
+
+```typescript
+// ✅ GOOD - Implementing external interfaces
+export class OpenAICompatibleChatLanguageModel implements LanguageModelV2 {
+  readonly specificationVersion = "v2"
+  readonly provider: string
+  readonly modelId: string
+
+  constructor(modelId: string, settings: ModelSettings) {
+    this.modelId = modelId
+    this.provider = settings.provider
+  }
+
+  async doGenerate(options: GenerateOptions): Promise<GenerateResult> {
+    // Implementation required by interface
+  }
+
+  async doStream(options: StreamOptions): AsyncIterableIterator<StreamPart> {
+    // Implementation required by interface
+  }
+}
+
+// ✅ GOOD - OAuth protocol implementation
+export class McpOAuthProvider implements OAuthClientProvider {
+  async getAccessToken(): Promise<string> {
+    // OAuth flow implementation
+  }
+}
+```
+
+**File References:**
+
+- `packages/opencode/src/provider/sdk/*` - Lines 53, 131
+- `packages/opencode/src/mcp/oauth-provider.ts:26`
+
+#### Use Case 3: Async Iterators
+
+```typescript
+// ✅ GOOD - AsyncIterable implementation
+export class AsyncQueue<T> implements AsyncIterable<T> {
+  private queue: T[] = []
+  private resolvers: ((value: T) => void)[] = []
+
+  push(item: T) {
+    const resolve = this.resolvers.shift()
+    if (resolve) {
+      resolve(item)
+    } else {
+      this.queue.push(item)
+    }
+  }
+
+  async next(): Promise<T> {
+    if (this.queue.length > 0) {
+      return this.queue.shift()!
+    }
+    return new Promise((resolve) => {
+      this.resolvers.push(resolve)
+    })
+  }
+
+  async *[Symbol.asyncIterator]() {
+    while (true) {
+      yield await this.next()
+    }
+  }
+}
+
+// Usage
+const queue = new AsyncQueue<Message>()
+queue.push(message)
+
+for await (const msg of queue) {
+  console.log(msg)
+}
+```
+
+**File Reference:** `packages/opencode/src/util/queue.ts:1-19`
+
+#### Use Case 4: Complex Stateful Managers
+
+```typescript
+// ✅ ACCEPTABLE - When managing complex state machines
+export class ACPSessionManager {
+  private sessions: Map<string, ACPSession>
+  private connections: Map<string, WebSocket>
+
+  // Complex lifecycle management
+  async createSession(id: string) {...}
+  async handleMessage(id: string, msg: Message) {...}
+  async closeSession(id: string) {...}
+
+  // State machine logic
+  private transition(from: State, to: State) {...}
+}
+```
+
+**File Reference:** `packages/opencode/src/acp/session.ts:8`
+
+---
+
+## 3. Array Handling Standards
+
+### 3.1 Functional Methods (85% of operations)
+
+**Rule: Prefer map/filter/flatMap over for-loops**
+
+```typescript
+// ✅ GOOD - Functional chain with type inference
+const files = messages
+  .flatMap((x) => x.parts)
+  .filter((x): x is Patch => x.type === "patch") // Type guard maintains inference
+  .flatMap((x) => x.files)
+  .map((x) => path.relative(Instance.worktree, x))
+
+// ✅ GOOD - Parallel async operations
+const results = await Promise.all(
+  toolCalls.map(async (call) => {
+    return executeCall(call)
+  }),
+)
+
+// ✅ GOOD - Reduce for aggregation
+const totalAdditions = diffs.reduce((sum, x) => sum + x.additions, 0)
+
+// ✅ GOOD - Filter with type guards
+const agents = await Agent.list().then((x) => x.filter((a): a is Agent & { mode: "secondary" } => a.mode !== "primary"))
+
+// ✅ GOOD - Unique values
+const uniqueNames = Array.from(new Set(items.map((x) => x.name)))
+
+// ✅ GOOD - Sorting
+const sorted = items.toSorted((a, b) => a.timestamp - b.timestamp)
+```
+
+**File References:**
+
+- `packages/opencode/src/tool/batch.ts` - Lines 41, 56, 80, 170
+- `packages/opencode/src/session/prompt.ts` - Lines 192-200
+- `packages/opencode/src/session/summary.ts` - Lines 96-109
+
+### 3.2 For-Loops (15%, only when necessary)
+
+**Rule: Use for-loops only for:**
+
+1. Algorithm complexity (DP, graph traversal)
+2. Early exit requirements
+3. Sequential side effects
+4. Performance-critical iteration
+
+#### Pattern 1: Algorithm Complexity
+
+```typescript
+// ✅ GOOD - Dynamic programming (LCS algorithm)
+// packages/opencode/src/tool/edit.ts:175-176
+function lcs(a: string[], b: string[]): number[][] {
+  const dp: number[][] = Array(a.length + 1)
+    .fill(0)
+    .map(() => Array(b.length + 1).fill(0))
+
+  for (let i = 1; i <= a.length; i++) {
+    for (let j = 1; j <= b.length; j++) {
+      if (a[i - 1] === b[j - 1]) {
+        dp[i][j] = dp[i - 1][j - 1] + 1
+      } else {
+        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1])
+      }
+    }
+  }
+
+  return dp
+}
+```
+
+#### Pattern 2: Early Exit
+
+```typescript
+// ✅ GOOD - Break on condition
+// packages/opencode/src/session/revert.ts:31-40
+const patches = []
+for (const msg of all) {
+  if (msg.info.id === revert.messageID) break
+  for (const part of msg.parts) {
+    if (part.type === "patch") {
+      patches.push(part)
+    }
+  }
+}
+
+// ✅ GOOD - Find first match
+for (const file of files) {
+  if (await Filesystem.exists(file)) {
+    return file
+  }
+}
+```
+
+#### Pattern 3: Sequential Side Effects
+
+```typescript
+// ✅ GOOD - Sequential mutations
+for (const key of Object.keys(input.tools)) {
+  if (input.user.tools?.[key] === false || disabled.has(key)) {
+    delete input.tools[key]
+  }
+}
+
+// ✅ GOOD - Streaming output
+for (const line of lines) {
+  await stream.write(line)
+}
+```
+
+**File Reference:** `packages/opencode/src/tool/grep.ts:77`
+
+#### Pattern 4: Performance Critical
+
+```typescript
+// ✅ GOOD - Low-level iteration for performance
+for (let i = 0; i < buffer.length; i++) {
+  result += buffer[i] * multiplier
+}
+
+// Note: Profile before optimizing - functional methods are often fast enough
+```
+
+### 3.3 Type Guards on Filter
+
+**Rule: Use type guards to maintain type inference downstream**
+
+```typescript
+// ✅ GOOD - Type guard preserves type information
+const patches = messages.flatMap((msg) => msg.parts).filter((part): part is PatchPart => part.type === "patch")
+// patches is now PatchPart[], not Part[]
+
+// ❌ BAD - Loses type information
+const patches = messages.flatMap((msg) => msg.parts).filter((part) => part.type === "patch")
+// patches is still Part[], requires casting later
+
+// ✅ GOOD - Multiple type guards
+const validAgents = agents
+  .filter((a): a is Agent => a !== undefined)
+  .filter((a): a is Agent & { mode: "secondary" } => a.mode !== "primary")
+```
+
+**File Reference:** `packages/opencode/src/tool/task.ts:24,29`
+
+---
+
+## 4. Variable & Destructuring Standards
+
+### 4.1 Variable Declaration
+
+**Rule: Prefer `const` over `let`**
+
+```typescript
+// ✅ GOOD - Immutable with ternary
+const foo = condition ? 1 : 2
+const result = await (isValid ? processValid() : processInvalid())
+
+// ❌ BAD - Reassignment
+let foo
+if (condition) {
+  foo = 1
+} else {
+  foo = 2
+}
+
+// ✅ GOOD - Early return instead of reassignment
+function getValue(condition: boolean) {
+  if (condition) return 1
+  return 2
+}
+
+// ✅ ACCEPTABLE - let when mutation is necessary
+let accumulator = 0
+for (const item of items) {
+  accumulator += item.value
+}
+```
+
+**File Reference:** `AGENTS.md:56-68`
+
+### 4.2 Destructuring
+
+**Rule: Avoid unnecessary destructuring, preserve context with dot notation**
+
+```typescript
+// ✅ GOOD - Preserve context
+function process(session: Session) {
+  log.info("processing", { id: session.id, title: session.title })
+  return {
+    id: session.id,
+    status: session.status,
+    owner: session.owner
+  }
+}
+
+// ❌ BAD - Loses context, harder to read
+function process(session: Session) {
+  const { id, title, status, owner } = session
+  log.info("processing", { id, title })
+  return { id, status, owner }
+}
+
+// ✅ ACCEPTABLE - Destructuring when improving readability
+function renderUser({ name, email, avatar }: User) {
+  return `<div>${name} (${email})</div>`
+}
+
+// ✅ ACCEPTABLE - Destructuring array returns
+const [language, cfg, provider] = await Promise.all([...])
+```
+
+**File Reference:** `AGENTS.md:43-54`
+
+### 4.3 Variable Naming
+
+**Rule: Concise single-word names when descriptive**
+
+```typescript
+// ✅ GOOD
+const session = await Session.get(id)
+const user = await Auth.current()
+const messages = await Session.messages({ sessionID })
+
+// ❌ BAD - Unnecessary verbosity
+const currentSession = await Session.get(id)
+const currentlyAuthenticatedUser = await Auth.current()
+const sessionMessagesList = await Session.messages({ sessionID })
+
+// ✅ GOOD - Multi-word when single word is ambiguous
+const sessionID = params.id
+const userAgent = req.headers["user-agent"]
+const maxRetries = config.retries
+```
+
+---
+
+## 5. Control Flow Standards
+
+### 5.1 Early Returns
+
+**Rule: Avoid `else` statements, use early returns**
+
+```typescript
+// ✅ GOOD - Early returns
+function getStatus(session: Session) {
+  if (!session) return "not_found"
+  if (session.busy) return "busy"
+  if (session.error) return "error"
+  return "ready"
+}
+
+async function process(id: string) {
+  const session = await Session.get(id)
+  if (!session) return { error: "Not found" }
+
+  const result = await execute(session)
+  if (!result.success) return { error: result.message }
+
+  return { data: result.data }
+}
+
+// ❌ BAD - Else statements
+function getStatus(session: Session) {
+  if (!session) {
+    return "not_found"
+  } else {
+    if (session.busy) {
+      return "busy"
+    } else {
+      if (session.error) {
+        return "error"
+      } else {
+        return "ready"
+      }
+    }
+  }
+}
+```
+
+**File Reference:** `AGENTS.md:70-86`
+
+### 5.2 Guard Clauses
+
+```typescript
+// ✅ GOOD - Guard clauses at function start
+async function updateSession(id: string, data: UpdateData) {
+  if (!id) throw new Error("ID required")
+  if (!data) throw new Error("Data required")
+  if (data.title && data.title.length > 100) throw new Error("Title too long")
+
+  // Main logic here
+  const session = await Session.get(id)
+  await Session.update(id, data)
+  return session
+}
+```
+
+### 5.3 Switch Statements
+
+**Rule: Use exhaustive switch with default case**
+
+```typescript
+// ✅ GOOD - Exhaustive switch for stream handling
+for await (const value of stream.fullStream) {
+  switch (value.type) {
+    case "reasoning-start":
+      reasoningMap[value.id] = { id: generateId(), type: "reasoning", text: "" }
+      break
+
+    case "reasoning-delta":
+      if (value.id in reasoningMap) {
+        reasoningMap[value.id].text += value.text
+        await Session.updatePart({ delta: value.text })
+      }
+      break
+
+    case "tool-call":
+      await Session.updatePart({ state: { status: "running" } })
+      break
+
+    case "tool-result":
+      await Session.updatePart({ state: { status: "completed" } })
+      break
+
+    default:
+      const _exhaustive: never = value
+      throw new Error(`Unhandled type: ${(value as any).type}`)
+  }
+}
+```
+
+**File Reference:** `packages/opencode/src/session/processor.ts:53-346`
+
+---
+
+## 6. Async & Concurrency Standards
+
+### 6.1 Parallel Execution (Default Pattern)
+
+**Rule: Use `Promise.all` for independent operations**
+
+```typescript
+// ✅ GOOD - Parallel independent operations
+const [language, cfg, provider, auth] = await Promise.all([
+  Provider.getLanguage(input.model),
+  Config.get(),
+  Provider.getProvider(input.model.providerID),
+  Auth.get(input.model.providerID),
+])
+
+// ✅ GOOD - Parallel array processing
+const results = await Promise.all(
+  items.map(async (item) => {
+    return processItem(item)
+  }),
+)
+
+// ❌ BAD - Sequential when independent
+const language = await Provider.getLanguage(input.model)
+const cfg = await Config.get() // Could run in parallel!
+const provider = await Provider.getProvider(input.model.providerID)
+const auth = await Auth.get(input.model.providerID)
+```
+
+**File Reference:** `packages/opencode/src/session/llm.ts:59`
+
+### 6.2 Sequential Operations
+
+**Rule: Chain when operations depend on previous results**
+
+```typescript
+// ✅ GOOD - Sequential dependency chain
+const session = await Session.create({ title: "New" })
+const message = await Session.addMessage(session.id, { content: "Hello" })
+const response = await LLM.stream({ sessionID: session.id, messageID: message.id })
+
+// ✅ GOOD - Promise chain for clarity
+const result = await Session.create({ title: "New" })
+  .then((session) => Session.addMessage(session.id, { content: "Hello" }))
+  .then((message) => LLM.stream({ messageID: message.id }))
+```
+
+### 6.3 Error Handling in Async
+
+**Rule: Prefer `.catch()` over try/catch when possible**
+
+```typescript
+// ✅ GOOD - Catch at call site
+const result = await operation().catch((error) => {
+  log.error("Operation failed", { error })
+  return defaultValue
+})
+
+// ✅ GOOD - Promise.all with error handling
+const results = await Promise.all(
+  items.map(async (item) => {
+    return processItem(item).catch((error) => {
+      log.error("Item failed", { item, error })
+      return null
+    })
+  }),
+)
+
+// ✅ ACCEPTABLE - try/catch for multiple operations
+try {
+  const session = await Session.create(input)
+  await Session.addMessage(session.id, message)
+  await EventBus.publish(Session.Event.Created, { session })
+  return session
+} catch (error) {
+  log.error("Session creation failed", { error })
+  throw error
+}
+
+// ❌ AVOID - try/catch for single operation
+try {
+  const result = await operation()
+  return result
+} catch (error) {
+  log.error(error)
+  throw error
+}
+// Better:
+const result = await operation().catch((error) => {
+  log.error(error)
+  throw error
+})
+```
+
+### 6.4 Concurrent Worker Pattern
+
+```typescript
+// ✅ GOOD - Controlled concurrency
+export async function work<T>(concurrency: number, items: T[], fn: (item: T) => Promise<void>) {
+  const pending = [...items]
+
+  await Promise.all(
+    Array.from({ length: concurrency }, async () => {
+      while (true) {
+        const item = pending.pop()
+        if (item === undefined) return
+        await fn(item)
+      }
+    }),
+  )
+}
+
+// Usage
+await work(3, files, async (file) => {
+  await processFile(file)
+})
+```
+
+**File Reference:** `packages/opencode/src/util/queue.ts:21-32`
+
+---
+
+## 7. Race Condition Prevention
+
+### 7.1 Reader-Writer Lock (Storage Operations)
+
+```typescript
+// packages/opencode/src/util/lock.ts
+export namespace Lock {
+  const locks = new Map<
+    string,
+    {
+      readers: number
+      writer: boolean
+      waitingReaders: (() => void)[]
+      waitingWriters: (() => void)[]
+    }
+  >()
+
+  export async function read(key: string): Promise<Disposable> {
+    const lock = get(key)
+    return new Promise((resolve) => {
+      // Writers get priority
+      if (!lock.writer && lock.waitingWriters.length === 0) {
+        lock.readers++
+        resolve({
+          [Symbol.dispose]: () => {
+            lock.readers--
+            process(key)
+          },
+        })
+      } else {
+        lock.waitingReaders.push(() => {
+          lock.readers++
+          resolve({
+            [Symbol.dispose]: () => {
+              lock.readers--
+              process(key)
+            },
+          })
+        })
+      }
+    })
+  }
+
+  export async function write(key: string): Promise<Disposable> {
+    const lock = get(key)
+    return new Promise((resolve) => {
+      if (!lock.writer && lock.readers === 0) {
+        lock.writer = true
+        resolve({
+          [Symbol.dispose]: () => {
+            lock.writer = false
+            process(key)
+          },
+        })
+      } else {
+        lock.waitingWriters.push(() => {
+          lock.writer = true
+          resolve({
+            [Symbol.dispose]: () => {
+              lock.writer = false
+              process(key)
+            },
+          })
+        })
+      }
+    })
+  }
+}
+
+// Usage with disposable pattern
+export async function read<T>(target: string): Promise<T> {
+  using _ = await Lock.read(target) // Auto-releases on scope exit
+  const file = Bun.file(target)
+  if (!(await file.exists())) {
+    throw NotFoundError.create({ message: `File not found: ${target}` })
+  }
+  return file.json()
+}
+
+export async function write(target: string, data: any): Promise<void> {
+  using _ = await Lock.write(target) // Auto-releases on scope exit
+  const dir = path.dirname(target)
+  await fs.mkdir(dir, { recursive: true })
+  await Bun.write(target, JSON.stringify(data, null, 2))
+}
+```
+
+**File References:**
+
+- `packages/opencode/src/util/lock.ts` - Lines 1-99
+- `packages/opencode/src/storage/storage.ts` - Lines 173, 183, 195
+
+### 7.2 File-Level Lock (Edit Operations)
+
+```typescript
+// packages/opencode/src/file/time.ts
+export async function withLock<T>(filepath: string, fn: () => Promise<T>): Promise<T> {
+  const current = state()
+  const currentLock = current.locks.get(filepath) ?? Promise.resolve()
+
+  let release: () => void = () => {}
+  const nextLock = new Promise<void>((resolve) => {
+    release = resolve
+  })
+
+  const chained = currentLock.then(() => nextLock)
+  current.locks.set(filepath, chained)
+
+  await currentLock // Wait for previous lock
+
+  try {
+    return await fn()
+  } finally {
+    release()
+    if (current.locks.get(filepath) === chained) {
+      current.locks.delete(filepath)
+    }
+  }
+}
+
+// Usage: Atomic read-modify-write
+await FileTime.withLock(filePath, async () => {
+  const contentOld = await Bun.file(filePath).text()
+  const contentNew = replace(contentOld, params.oldString, params.newString)
+  await Bun.write(filePath, contentNew)
+  await FileTime.touch(filePath)
+})
+```
+
+**File References:**
+
+- `packages/opencode/src/file/time.ts` - Lines 35-53
+- `packages/opencode/src/tool/edit.ts` - Line 50
+
+### 7.3 Mutex Pattern
+
+```typescript
+// ✅ GOOD - Simple mutex for critical sections
+const mutexes = new Map<string, Promise<void>>()
+
+async function withMutex<T>(key: string, fn: () => Promise<T>): Promise<T> {
+  const current = mutexes.get(key) ?? Promise.resolve()
+
+  let release: () => void
+  const next = new Promise<void>((resolve) => {
+    release = resolve
+  })
+  mutexes.set(key, next)
+
+  await current
+
+  try {
+    return await fn()
+  } finally {
+    release!()
+    if (mutexes.get(key) === next) {
+      mutexes.delete(key)
+    }
+  }
+}
+
+// Usage
+await withMutex(`session:${sessionID}`, async () => {
+  // Critical section - only one execution at a time
+  const session = await Session.get(sessionID)
+  session.busy = true
+  await Session.save(session)
+})
+```
+
+### 7.4 Debouncing & Throttling
+
+```typescript
+// ✅ GOOD - Debounce for file watching
+function debounce<T extends (...args: any[]) => any>(fn: T, delay: number): (...args: Parameters<T>) => void {
+  let timer: Timer | undefined
+
+  return (...args: Parameters<T>) => {
+    if (timer) clearTimeout(timer)
+    timer = setTimeout(() => {
+      fn(...args)
+      timer = undefined
+    }, delay)
+  }
+}
+
+// Usage in file watcher
+const debouncedUpdate = debounce((file: string) => {
+  Bus.publish(FileWatcher.Event.Updated, { file })
+}, 100)
+
+watcher.on("change", (file) => {
+  debouncedUpdate(file)
+})
+```
+
+---
+
+## 8. AI System Integration Standards
+
+### 8.1 Message Context Management
+
+```typescript
+// packages/opencode/src/session/message-v2.ts
+
+export type Part = TextPart | FilePart | PatchPart | ToolCallPart | ToolResultPart | ReasoningPart
+
+export interface WithParts {
+  info: Info
+  parts: Part[]
+}
+
+// Convert internal message format to LLM format
+export function toModelMessages(input: WithParts[], model: Provider.Model): ModelMessage[] {
+  return input.flatMap((msg): ModelMessage[] => {
+    if (msg.info.role === "user") {
+      return [
+        {
+          role: "user",
+          content: msg.parts.map((part) => {
+            if (part.type === "text") {
+              return { type: "text", text: part.text }
+            }
+            if (part.type === "file") {
+              return {
+                type: "file",
+                data: part.data,
+                mimeType: part.mimeType,
+              }
+            }
+            if (part.type === "patch") {
+              return {
+                type: "text",
+                text: formatPatch(part),
+              }
+            }
+            // ... handle other types
+          }),
+        },
+      ]
+    }
+
+    if (msg.info.role === "assistant") {
+      return [
+        {
+          role: "assistant",
+          content: msg.parts
+            .filter((p) => p.type === "text" || p.type === "reasoning")
+            .map((p) => ({ type: "text", text: p.text })),
+        },
+      ]
+    }
+
+    // Handle tool results...
+    return []
+  })
+}
+```
+
+**File Reference:** `packages/opencode/src/session/message-v2.ts:438-500`
+
+### 8.2 System Prompt Construction
+
+```typescript
+// packages/opencode/src/session/llm.ts
+
+export async function stream(input: StreamInput) {
+  const system: string[] = []
+
+  // Part 1: Base system prompt (cached)
+  const header = [
+    // Agent prompt OR provider prompt
+    ...(input.agent.prompt ? [input.agent.prompt] : isCodex ? [] : SystemPrompt.provider(input.model)),
+    // Custom prompt from request
+    ...input.system,
+    // Custom prompt from user config
+    ...(input.user.system ? [input.user.system] : []),
+  ]
+    .filter(Boolean)
+    .join("\n")
+
+  system.push(header)
+
+  // Part 2: Dynamic context (not cached)
+  const dynamicContext = [
+    `Working directory: ${Instance.directory}`,
+    `Current date: ${new Date().toISOString()}`,
+    // ... other dynamic info
+  ].join("\n")
+
+  system.push(dynamicContext)
+
+  // Allow plugins to transform system prompt
+  const original = clone(system)
+  await Plugin.trigger(
+    "experimental.chat.system.transform",
+    {
+      model: input.model,
+      agent: input.agent,
+    },
+    { system },
+  )
+
+  // Optimize for prompt caching: maintain 2-part structure if header unchanged
+  if (system.length > 2 && system[0] === header) {
+    const rest = system.slice(1)
+    system.length = 0
+    system.push(header, rest.join("\n"))
+  }
+
+  // Convert to LLM messages
+  const messages = [
+    ...system.map((text) => ({ role: "system", content: text })),
+    ...toModelMessages(input.messages, input.model),
+  ]
+
+  return language.doStream({
+    model: input.model.id,
+    messages,
+    tools: await resolveTools(input),
+  })
+}
+```
+
+**File Reference:** `packages/opencode/src/session/llm.ts:67-97`
+
+### 8.3 Tool Definition & Execution
+
+```typescript
+// packages/opencode/src/tool/tool.ts
+
+export namespace Tool {
+  export interface Info<Parameters = any, Metadata = any> {
+    id: string
+    title: string
+    description: string
+    parameters: z.ZodType<Parameters>
+    metadata?: Metadata
+
+    execute(args: Parameters, context: Context): Promise<ExecuteResult>
+  }
+
+  export interface Context {
+    sessionID: string
+    messageID: string
+    agent: string
+    abort: AbortSignal
+    messages: () => Promise<MessageV2.WithParts[]>
+    metadata: <T>(key: string, value: T) => Promise<void>
+    ask: <T>(question: Question<T>) => Promise<T>
+  }
+
+  export type ExecuteResult = {
+    output?: string
+    title?: string
+    metadata?: Record<string, unknown>
+  }
+
+  export function define<Parameters, Result>(
+    id: string,
+    init: {
+      title: string
+      description: string
+      parameters: z.ZodType<Parameters>
+      execute: (args: Parameters, context: Context) => Promise<ExecuteResult>
+    },
+  ): Info<Parameters> {
+    return {
+      id,
+      ...init,
+    }
+  }
+}
+
+// Usage: Define a tool
+export const ReadTool = Tool.define("read", {
+  title: "Read File",
+  description: "Read contents of a file from the filesystem",
+  parameters: z.object({
+    filePath: z.string().describe("Absolute path to file"),
+    offset: z.number().optional().describe("Line number to start reading"),
+    limit: z.number().optional().describe("Number of lines to read"),
+  }),
+
+  async execute(args, context) {
+    await context.ask({
+      type: "permission",
+      message: `Read file ${args.filePath}?`,
+      actions: ["allow", "deny"],
+    })
+
+    const content = await Bun.file(args.filePath).text()
+    const lines = content.split("\n")
+
+    const start = args.offset ?? 0
+    const end = args.limit ? start + args.limit : lines.length
+    const selected = lines.slice(start, end)
+
+    return {
+      output: selected.join("\n"),
+      title: `Read ${path.basename(args.filePath)}`,
+      metadata: {
+        lineCount: selected.length,
+        filePath: args.filePath,
+      },
+    }
+  },
+})
+
+// Register tool
+await ToolRegistry.register(ReadTool)
+
+// Tool execution in session
+const tools = await ToolRegistry.tools({ agent: input.agent })
+
+const toolMap = tools.reduce(
+  (acc, tool) => {
+    acc[tool.id] = vercelAiTool({
+      description: tool.description,
+      parameters: zodToJsonSchema(tool.parameters),
+      execute: async (args) => {
+        const result = await tool.execute(args, {
+          sessionID: input.sessionID,
+          messageID: input.messageID,
+          agent: input.agent.name,
+          abort: input.abort,
+          messages: () => Session.messages({ sessionID: input.sessionID }),
+          metadata: async (key, value) => {
+            await Session.updatePart({
+              messageID: input.messageID,
+              metadata: { [key]: value },
+            })
+          },
+          ask: async (question) => {
+            return new Promise((resolve) => {
+              Bus.publish(Session.Event.Question, {
+                sessionID: input.sessionID,
+                question,
+                respond: resolve,
+              })
+            })
+          },
+        })
+
+        return result.output
+      },
+    })
+    return acc
+  },
+  {} as Record<string, any>,
+)
+```
+
+**File References:**
+
+- `packages/opencode/src/tool/tool.ts` - Lines 1-90
+- `packages/opencode/src/session/prompt.ts` - Lines 711-748
+
+### 8.4 Streaming Handling
+
+```typescript
+// packages/opencode/src/session/processor.ts
+
+export function create(input: CreateInput) {
+  const reasoningMap: Record<string, ReasoningPart> = {}
+  const toolcalls: Record<string, ToolCallPart> = {}
+
+  return {
+    async process() {
+      const stream = await LLM.stream({
+        sessionID: input.sessionID,
+        messageID: input.messageID,
+        model: input.model,
+        messages: input.messages,
+        tools: input.tools,
+        abort: input.abort,
+      })
+
+      // Handle stream events
+      for await (const value of stream.fullStream) {
+        input.abort.throwIfAborted()
+
+        switch (value.type) {
+          case "reasoning-start":
+            reasoningMap[value.id] = {
+              id: Identifier.ascending("part"),
+              type: "reasoning",
+              text: "",
+              time: { start: Date.now() },
+            }
+            await Session.addPart({
+              messageID: input.messageID,
+              part: reasoningMap[value.id],
+            })
+            break
+
+          case "reasoning-delta":
+            if (value.id in reasoningMap) {
+              const part = reasoningMap[value.id]
+              part.text += value.text
+              await Session.updatePart({
+                messageID: input.messageID,
+                partID: part.id,
+                delta: value.text,
+              })
+            }
+            break
+
+          case "reasoning-finish":
+            if (value.id in reasoningMap) {
+              const part = reasoningMap[value.id]
+              part.time.end = Date.now()
+              await Session.updatePart({
+                messageID: input.messageID,
+                partID: part.id,
+                part,
+              })
+            }
+            break
+
+          case "text-delta":
+            // Handle text streaming...
+            break
+
+          case "tool-call":
+            const toolPart: ToolCallPart = {
+              id: Identifier.ascending("part"),
+              type: "tool-call",
+              toolCallID: value.toolCallId,
+              toolName: value.toolName,
+              state: {
+                status: "running",
+                input: value.args,
+                time: { start: Date.now() },
+              },
+            }
+            toolcalls[value.toolCallId] = toolPart
+            await Session.addPart({
+              messageID: input.messageID,
+              part: toolPart,
+            })
+            break
+
+          case "tool-result":
+            const match = toolcalls[value.toolCallId]
+            if (match) {
+              match.state = {
+                status: "completed",
+                output: value.result,
+                time: {
+                  start: match.state.time.start,
+                  end: Date.now(),
+                },
+              }
+              await Session.updatePart({
+                messageID: input.messageID,
+                partID: match.id,
+                part: match,
+              })
+            }
+            break
+
+          case "error":
+            await Session.updateMessage({
+              messageID: input.messageID,
+              error: {
+                message: value.error.message,
+                code: value.error.code,
+              },
+            })
+            throw value.error
+
+          case "finish":
+            await Session.updateMessage({
+              messageID: input.messageID,
+              tokens: value.usage,
+              time: { end: Date.now() },
+            })
+            break
+
+          default:
+            // Exhaustiveness check
+            const _exhaustive: never = value
+            throw new Error(`Unhandled stream type: ${(value as any).type}`)
+        }
+      }
+    },
+  }
+}
+```
+
+**File Reference:** `packages/opencode/src/session/processor.ts:53-346`
+
+### 8.5 Context Compaction
+
+```typescript
+// packages/opencode/src/session/compaction.ts
+
+export async function isOverflow(input: {
+  tokens: MessageV2.Assistant["tokens"]
+  model: Provider.Model
+}): Promise<boolean> {
+  const limit = input.model.limit.context
+
+  const total = input.tokens.input + input.tokens.output + input.tokens.cache.read + input.tokens.cache.write
+
+  const threshold = limit * 0.75 // Trigger at 75% capacity
+
+  return total > threshold
+}
+
+export async function compact(sessionID: string) {
+  const messages = await Session.messages({ sessionID })
+  const model = await Session.getModel(sessionID)
+
+  // Find oldest non-system messages
+  const candidates = messages.filter((m) => m.info.role !== "system")
+
+  if (candidates.length <= 2) {
+    // Keep at least 2 messages for context
+    return
+  }
+
+  // Remove oldest message
+  const toRemove = candidates[0]
+  await Session.deleteMessage(toRemove.info.id)
+
+  // Add summary if necessary
+  const summary = await generateSummary(toRemove)
+  await Session.addSystemMessage(sessionID, {
+    content: `Previous context (summarized): ${summary}`,
+  })
+
+  log.info("compacted session", {
+    sessionID,
+    removedMessageID: toRemove.info.id,
+    remainingMessages: messages.length - 1,
+  })
+}
+
+// Check after each assistant response
+await Session.onMessageComplete(async (messageID) => {
+  const message = await Session.getMessage(messageID)
+  const model = await Session.getModel(message.sessionID)
+
+  if (await isOverflow({ tokens: message.tokens, model })) {
+    await compact(message.sessionID)
+  }
+})
+```
+
+**File References:**
+
+- `packages/opencode/src/session/compaction.ts` - Lines 30-48
+- `packages/opencode/src/session/processor.ts` - Lines 282-284
+
+---
+
+## 9. Service Architecture Standards
+
+### 9.1 Core Services Overview
+
+| Service                 | Location                   | Pattern                | Responsibility              |
+| ----------------------- | -------------------------- | ---------------------- | --------------------------- |
+| **Session Management**  | `src/session/`             | Namespace + State      | AI conversation lifecycle   |
+| **File Watching**       | `src/file/watcher.ts`      | Chokidar + Debounce    | Filesystem change detection |
+| **LSP Integration**     | `src/lsp/`                 | Multi-client manager   | Language server protocol    |
+| **MCP**                 | `src/mcp/`                 | Multi-transport client | Model Context Protocol      |
+| **Terminal/PTY**        | `src/server/routes/pty.ts` | WebSocket-based        | Shell session management    |
+| **Event Bus**           | `src/bus/`                 | Pub/sub pattern        | Cross-service communication |
+| **Storage**             | `src/storage/`             | Lock-based persistence | JSON file storage           |
+| **Provider Management** | `src/provider/`            | Lazy-loaded SDKs       | LLM provider abstraction    |
+| **Config Management**   | `src/config/`              | Layered merge          | Multi-level configuration   |
+| **Scheduler**           | `src/scheduler/`           | Interval-based         | Background job execution    |
+
+### 9.2 Service Implementation Template
+
+```typescript
+// Service template following codebase patterns
+
+import { Log } from "../util/log"
+import { Instance } from "../project/instance"
+import { BusEvent } from "../bus/event"
+import z from "zod"
+
+export namespace MyService {
+  const log = Log.create({ service: "my-service" })
+
+  // 1. Type definitions
+  export type Info = z.infer<typeof Info>
+  export const Info = z.object({
+    id: z.string(),
+    status: z.enum(["idle", "active", "error"]),
+    created: z.number(),
+  })
+
+  // 2. Per-instance state
+  const state = Instance.state(
+    async () => {
+      log.info("initializing service")
+
+      return {
+        items: new Map<string, Info>(),
+        timers: new Map<string, Timer>(),
+        clients: [] as Client[],
+      }
+    },
+    async (state) => {
+      log.info("disposing service")
+
+      // Cleanup resources
+      await Promise.all([
+        ...state.clients.map((c) => c.close()),
+        ...Array.from(state.timers.values()).map((t) => clearInterval(t)),
+      ])
+
+      state.items.clear()
+    },
+  )
+
+  // 3. Event definitions
+  export const Event = {
+    Created: BusEvent.define(
+      "my-service.created",
+      z.object({
+        info: Info,
+      }),
+    ),
+    Updated: BusEvent.define(
+      "my-service.updated",
+      z.object({
+        info: Info,
+      }),
+    ),
+    Deleted: BusEvent.define(
+      "my-service.deleted",
+      z.object({
+        id: z.string(),
+      }),
+    ),
+  }
+
+  // 4. Public API with fn() wrapper
+  export const create = fn(
+    z
+      .object({
+        id: z.string().optional(),
+        data: z.record(z.unknown()).optional(),
+      })
+      .optional(),
+    async (input) => {
+      const id = input?.id ?? Identifier.ascending("my-service")
+
+      const info: Info = {
+        id,
+        status: "idle",
+        created: Date.now(),
+      }
+
+      state().items.set(id, info)
+      await Bus.publish(Event.Created, { info })
+
+      log.info("created", { id })
+      return info
+    },
+  )
+
+  export const get = fn(z.string(), async (id) => {
+    const item = state().items.get(id)
+    if (!item) {
+      throw NotFoundError.create({ message: `Item ${id} not found` })
+    }
+    return item
+  })
+
+  export const list = fn(
+    z
+      .object({
+        status: z.enum(["idle", "active", "error"]).optional(),
+      })
+      .optional(),
+    async (input) => {
+      const items = Array.from(state().items.values())
+
+      if (input?.status) {
+        return items.filter((item) => item.status === input.status)
+      }
+
+      return items
+    },
+  )
+
+  // 5. Internal functions (not exported)
+  async function cleanup(id: string) {
+    const timer = state().timers.get(id)
+    if (timer) {
+      clearInterval(timer)
+      state().timers.delete(id)
+    }
+  }
+}
+```
+
+**File References:**
+
+- `packages/opencode/src/session/index.ts` - Complete example
+- `packages/opencode/src/mcp/index.ts` - Multi-client manager
+- `packages/opencode/src/lsp/index.ts` - Lazy spawning
+
+---
+
+## 10. State Management Standards
+
+### 10.1 Per-Instance State Isolation
+
+**Rule: All state must be isolated per working directory**
+
+```typescript
+// packages/opencode/src/project/instance.ts
+
+export namespace Instance {
+  // Current working directory
+  export let directory = process.cwd()
+
+  // Git worktree root
+  export let worktree = directory
+
+  // Project ID
+  export let id = "unknown"
+
+  // Create state scoped to current instance
+  export function state<S>(
+    init: () => S | Promise<S>,
+    dispose?: (state: Awaited<S>) => Promise<void>,
+  ): () => Awaited<S> {
+    return State.create(
+      () => Instance.directory, // Key by directory
+      init,
+      dispose,
+    )
+  }
+}
+
+// packages/opencode/src/project/state.ts
+
+const recordsByKey = new Map<string, Map<Function, Entry>>()
+
+interface Entry {
+  state: any
+  dispose?: (state: any) => Promise<void>
+}
+
+export function create<S>(
+  root: () => string,
+  init: () => S | Promise<S>,
+  dispose?: (state: Awaited<S>) => Promise<void>,
+): () => Awaited<S> {
+  return () => {
+    const key = root()
+
+    // Get or create entries for this key
+    let entries = recordsByKey.get(key)
+    if (!entries) {
+      entries = new Map<Function, Entry>()
+      recordsByKey.set(key, entries)
+    }
+
+    // Get or initialize state
+    const exists = entries.get(init)
+    if (exists) {
+      return exists.state as Awaited<S>
+    }
+
+    const state = init()
+    entries.set(init, { state, dispose })
+
+    return state as Awaited<S>
+  }
+}
+
+// Dispose all state for a key
+export async function dispose(key: string) {
+  const entries = recordsByKey.get(key)
+  if (!entries) return
+
+  await Promise.all(
+    Array.from(entries.values()).map(async (entry) => {
+      if (entry.dispose) {
+        const state = await entry.state
+        await entry.dispose(state)
+      }
+    }),
+  )
+
+  recordsByKey.delete(key)
+}
+```
+
+**File References:**
+
+- `packages/opencode/src/project/instance.ts` - Lines 66-68
+- `packages/opencode/src/project/state.ts` - Lines 12-29
+
+### 10.2 State Initialization Pattern
+
+```typescript
+// ✅ GOOD - Lazy initialization with disposal
+const state = Instance.state(
+  async () => {
+    log.info("initializing LSP clients")
+
+    const cfg = await Config.get()
+    const servers: Record<string, LSPServer.Info> = {}
+    const clients: LSPClient.Info[] = []
+
+    // Initialize servers
+    for (const [id, server] of Object.entries(LSPServer)) {
+      if (cfg.lsp?.[id]?.enabled !== false) {
+        servers[id] = server
+      }
+    }
+
+    return {
+      servers,
+      clients,
+      broken: new Set<string>(),
+      spawning: new Map<string, Promise<LSPClient.Info | undefined>>(),
+    }
+  },
+  async (state) => {
+    log.info("disposing LSP clients")
+
+    // Cleanup all clients
+    await Promise.all(
+      state.clients.map(async (client) => {
+        try {
+          await client.shutdown()
+        } catch (error) {
+          log.error("failed to shutdown client", { client: client.id, error })
+        }
+      }),
+    )
+  },
+)
+
+// Access state
+const lspState = state()
+lspState.clients.push(newClient)
+```
+
+### 10.3 Global State (Rare)
+
+**Rule: Avoid global state, use per-instance state instead**
+
+```typescript
+// ❌ AVOID - Global mutable state
+const sessions = new Map<string, Session>()
+
+export function addSession(session: Session) {
+  sessions.set(session.id, session)
+}
+
+// ✅ PREFER - Per-instance state
+const state = Instance.state(async () => ({
+  sessions: new Map<string, Session>(),
+}))
+
+export function addSession(session: Session) {
+  state().sessions.set(session.id, session)
+}
+
+// ✅ ACCEPTABLE - Truly global state (user config, auth tokens)
+export namespace Global {
+  export namespace Path {
+    export const home = os.homedir()
+    export const config = path.join(home, ".config", "opencode")
+    export const data = path.join(home, ".local", "share", "opencode")
+    export const cache = path.join(home, ".cache", "opencode")
+  }
+}
+```
+
+---
+
+## 11. Event Bus Standards
+
+### 11.1 Event Definition
+
+```typescript
+// packages/opencode/src/bus/event.ts
+
+export namespace BusEvent {
+  export interface Definition<Properties extends z.ZodType = any> {
+    type: string
+    properties: Properties
+  }
+
+  export function define<Properties extends z.ZodType>(type: string, properties: Properties): Definition<Properties> {
+    return { type, properties }
+  }
+}
+
+// Usage: Define events for a service
+export namespace Session {
+  export const Event = {
+    Created: BusEvent.define("session.created", z.object({ info: Info })),
+
+    Updated: BusEvent.define("session.updated", z.object({ info: Info, changes: z.record(z.unknown()) })),
+
+    Deleted: BusEvent.define("session.deleted", z.object({ id: z.string() })),
+
+    Diff: BusEvent.define(
+      "session.diff",
+      z.object({
+        sessionID: z.string(),
+        messageID: z.string(),
+        diff: z.object({
+          file: z.string(),
+          additions: z.number(),
+          deletions: z.number(),
+        }),
+      }),
+    ),
+
+    Error: BusEvent.define(
+      "session.error",
+      z.object({
+        sessionID: z.string(),
+        error: z.object({
+          message: z.string(),
+          code: z.string().optional(),
+        }),
+      }),
+    ),
+
+    Question: BusEvent.define(
+      "session.question",
+      z.object({
+        sessionID: z.string(),
+        question: z.object({
+          type: z.string(),
+          message: z.string(),
+          options: z.array(z.unknown()),
+        }),
+        respond: z.function(),
+      }),
+    ),
+  }
+}
+```
+
+### 11.2 Publishing Events
+
+```typescript
+// packages/opencode/src/bus/index.ts
+
+export namespace Bus {
+  const state = Instance.state(async () => ({
+    subscriptions: new Map<string, Set<Handler>>(),
+  }))
+
+  type Handler = (payload: EventPayload) => void | Promise<void>
+
+  interface EventPayload {
+    type: string
+    properties: any
+  }
+
+  export async function publish<Definition extends BusEvent.Definition>(
+    def: Definition,
+    properties: z.output<Definition["properties"]>,
+  ): Promise<void> {
+    const payload: EventPayload = {
+      type: def.type,
+      properties,
+    }
+
+    const pending: Promise<void>[] = []
+
+    // Notify specific subscribers
+    const specific = state().subscriptions.get(def.type)
+    if (specific) {
+      for (const handler of specific) {
+        pending.push(Promise.resolve(handler(payload)))
+      }
+    }
+
+    // Notify wildcard subscribers
+    const wildcard = state().subscriptions.get("*")
+    if (wildcard) {
+      for (const handler of wildcard) {
+        pending.push(Promise.resolve(handler(payload)))
+      }
+    }
+
+    // Also publish to global bus (for cross-instance communication)
+    GlobalBus.emit("event", {
+      directory: Instance.directory,
+      payload,
+    })
+
+    await Promise.all(pending)
+  }
+}
+
+// Usage: Publish an event
+await Bus.publish(Session.Event.Created, {
+  info: {
+    id: "session-123",
+    title: "New Session",
+    created: Date.now(),
+  },
+})
+
+await Bus.publish(Session.Event.Updated, {
+  info: updatedSession,
+  changes: { title: "Updated Title" },
+})
+```
+
+**File Reference:** `packages/opencode/src/bus/index.ts:41-64`
+
+### 11.3 Subscribing to Events
+
+```typescript
+// packages/opencode/src/bus/index.ts
+
+export namespace Bus {
+  export function subscribe<Definition extends BusEvent.Definition>(
+    def: Definition | "*",
+    handler: (payload: { type: string; properties: z.output<Definition["properties"]> }) => void | Promise<void>,
+  ): Disposable {
+    const key = typeof def === "string" ? def : def.type
+
+    let subs = state().subscriptions.get(key)
+    if (!subs) {
+      subs = new Set()
+      state().subscriptions.set(key, subs)
+    }
+
+    subs.add(handler)
+
+    return {
+      [Symbol.dispose]: () => {
+        subs?.delete(handler)
+        if (subs?.size === 0) {
+          state().subscriptions.delete(key)
+        }
+      },
+    }
+  }
+}
+
+// Usage: Subscribe to specific events
+const subscription = Bus.subscribe(Session.Event.Created, async (event) => {
+  log.info("session created", { id: event.properties.info.id })
+  await notifyUser(`New session: ${event.properties.info.title}`)
+})
+
+// Unsubscribe
+subscription[Symbol.dispose]()
+
+// Or use disposable pattern
+{
+  using sub = Bus.subscribe(Session.Event.Updated, handleUpdate)
+
+  // Automatically unsubscribes when scope exits
+}
+
+// Subscribe to all events
+Bus.subscribe("*", (event) => {
+  log.debug("event", { type: event.type, properties: event.properties })
+})
+```
+
+### 11.4 Event-Driven Communication Pattern
+
+```typescript
+// Service A: Publish events
+export namespace FileWatcher {
+  export const Event = {
+    Updated: BusEvent.define(
+      "file.updated",
+      z.object({
+        file: z.string(),
+        event: z.enum(["add", "change", "unlink"]),
+      }),
+    ),
+  }
+
+  async function watch(directory: string) {
+    const watcher = chokidar.watch(directory)
+
+    watcher.on("change", async (file) => {
+      await Bus.publish(Event.Updated, {
+        file,
+        event: "change",
+      })
+    })
+  }
+}
+
+// Service B: React to events
+export namespace LSP {
+  export async function initialize() {
+    // Subscribe to file changes
+    Bus.subscribe(FileWatcher.Event.Updated, async (event) => {
+      if (event.properties.event === "change") {
+        await notifyClientsOfChange(event.properties.file)
+      }
+    })
+  }
+
+  async function notifyClientsOfChange(file: string) {
+    const clients = state().clients.filter((c) => c.watchesFile(file))
+    await Promise.all(clients.map((c) => c.didChangeTextDocument({ uri: file })))
+  }
+}
+
+// Service C: Also react to same events
+export namespace Session {
+  export async function initialize() {
+    Bus.subscribe(FileWatcher.Event.Updated, async (event) => {
+      // Invalidate cached file contents
+      await invalidateFileCache(event.properties.file)
+    })
+  }
+}
+```
+
+---
+
+## 12. Configuration Management Standards
+
+### 12.1 Configuration Precedence
+
+**Order (Low → High priority):**
+
+1. **Remote `.well-known/opencode`** - Organization defaults
+2. **Global config** - `~/.config/opencode/opencode.json{,c}`
+3. **Custom config** - `OPENCODE_CONFIG` env var path
+4. **Project config** - `opencode.json{,c}` in project
+5. **`.opencode` directories** - `.opencode/opencode.json{,c}`
+6. **Inline config** - `OPENCODE_CONFIG_CONTENT` env var
+7. **Managed config** - Enterprise `/etc/opencode` (highest priority)
+
+```typescript
+// packages/opencode/src/config/config.ts
+
+export namespace Config {
+  export const state = Instance.state(async () => {
+    let result: Info = {}
+
+    // 1. Remote organization config
+    const auth = await Auth.all()
+    for (const [key, value] of Object.entries(auth)) {
+      if (value.type === "wellknown") {
+        const response = await fetch(`${key}/.well-known/opencode`)
+        const wellknown = await response.json()
+        result = mergeConfigConcatArrays(result, wellknown.config ?? {})
+      }
+    }
+
+    // 2. Global user config
+    result = mergeConfigConcatArrays(result, await global())
+
+    // 3. Custom config path
+    if (Flag.OPENCODE_CONFIG) {
+      result = mergeConfigConcatArrays(result, await loadFile(Flag.OPENCODE_CONFIG))
+    }
+
+    // 4. Project config (if not disabled)
+    if (!Flag.OPENCODE_DISABLE_PROJECT_CONFIG) {
+      for (const file of ["opencode.jsonc", "opencode.json"]) {
+        const found = await Filesystem.findUp(file, Instance.directory, Instance.worktree)
+        for (const resolved of found.toReversed()) {
+          result = mergeConfigConcatArrays(result, await loadFile(resolved))
+        }
+      }
+    }
+
+    // 5. .opencode directories
+    const directories = [
+      Global.Path.config,
+      ...(!Flag.OPENCODE_DISABLE_PROJECT_CONFIG
+        ? await Array.fromAsync(
+            Filesystem.up({
+              targets: [".opencode"],
+              start: Instance.directory,
+              stop: Instance.worktree,
+            }),
+          )
+        : []),
+      // Always scan user home ~/.opencode/
+      ...(await Array.fromAsync(
+        Filesystem.up({
+          targets: [".opencode"],
+          start: Global.Path.home,
+          stop: Global.Path.home,
+        }),
+      )),
+    ]
+
+    for (const dir of unique(directories)) {
+      for (const file of ["opencode.jsonc", "opencode.json"]) {
+        const configPath = path.join(dir, file)
+        if (await Filesystem.exists(configPath)) {
+          result = mergeConfigConcatArrays(result, await loadFile(configPath))
+        }
+      }
+    }
+
+    // 6. Inline config
+    if (Flag.OPENCODE_CONFIG_CONTENT) {
+      result = mergeConfigConcatArrays(result, await load(Flag.OPENCODE_CONFIG_CONTENT, "inline"))
+    }
+
+    // 7. Managed config (enterprise, highest priority)
+    const managedPath = path.join(managedConfigDir, "opencode.json")
+    if (await Filesystem.exists(managedPath)) {
+      result = mergeConfigConcatArrays(result, await loadFile(managedPath))
+    }
+
+    return result
+  })
+
+  export const get = fn(z.void(), async () => state())
+}
+```
+
+**File Reference:** `packages/opencode/src/config/config.ts:62-150`
+
+### 12.2 Configuration Merge Strategy
+
+```typescript
+// packages/opencode/src/config/config.ts
+
+function mergeConfigConcatArrays(target: Info, source: Info): Info {
+  // Deep merge objects
+  const merged = mergeDeep(target, source)
+
+  // Special handling: Concatenate arrays instead of replacing
+  if (target.plugin && source.plugin) {
+    merged.plugin = Array.from(new Set([...target.plugin, ...source.plugin]))
+  }
+
+  if (target.instructions && source.instructions) {
+    merged.instructions = Array.from(new Set([...target.instructions, ...source.instructions]))
+  }
+
+  return merged
+}
+
+// Example:
+// Base config:    { plugin: ["a", "b"], model: { id: "gpt-4" } }
+// Override config: { plugin: ["b", "c"], model: { temperature: 0.7 } }
+// Result:         { plugin: ["a", "b", "c"], model: { id: "gpt-4", temperature: 0.7 } }
+```
+
+**File Reference:** `packages/opencode/src/config/config.ts:51-60`
+
+### 12.3 Configuration Schema
+
+```typescript
+export namespace Config {
+  export type Info = z.infer<typeof Info>
+  export const Info = z.object({
+    // Model configuration
+    model: z
+      .object({
+        id: z.string().optional(),
+        providerID: z.string().optional(),
+        temperature: z.number().optional(),
+        maxTokens: z.number().optional(),
+      })
+      .optional(),
+
+    // Providers
+    providers: z
+      .record(
+        z.object({
+          apiKey: z.string().optional(),
+          baseURL: z.string().optional(),
+          enabled: z.boolean().optional(),
+        }),
+      )
+      .optional(),
+
+    // Plugins
+    plugin: z.array(z.string()).optional(),
+
+    // Instructions (system prompts)
+    instructions: z.array(z.string()).optional(),
+
+    // Agents
+    agent: z
+      .record(
+        z.object({
+          mode: z.enum(["primary", "secondary"]).optional(),
+          prompt: z.string().optional(),
+          permission: z.string().optional(),
+        }),
+      )
+      .optional(),
+
+    // LSP servers
+    lsp: z
+      .record(
+        z.object({
+          enabled: z.boolean().optional(),
+          command: z.string().optional(),
+          args: z.array(z.string()).optional(),
+        }),
+      )
+      .optional(),
+
+    // MCP servers
+    mcp: z
+      .record(
+        z.union([
+          z.object({
+            command: z.string(),
+            args: z.array(z.string()).optional(),
+            env: z.record(z.string()).optional(),
+            enabled: z.boolean().optional(),
+          }),
+          z.object({
+            url: z.string(),
+            transport: z.literal("sse"),
+            enabled: z.boolean().optional(),
+          }),
+        ]),
+      )
+      .optional(),
+
+    // Formatters
+    formatter: z
+      .record(
+        z.object({
+          command: z.string(),
+          args: z.array(z.string()).optional(),
+        }),
+      )
+      .optional(),
+  })
+}
+```
+
+### 12.4 Configuration File Loading
+
+```typescript
+export namespace Config {
+  async function loadFile(filepath: string): Promise<Info> {
+    if (!(await Filesystem.exists(filepath))) {
+      return {}
+    }
+
+    const content = await Bun.file(filepath).text()
+    return load(content, filepath)
+  }
+
+  async function load(content: string, source: string): Promise<Info> {
+    try {
+      // Parse JSONC (JSON with comments)
+      const parsed = parseJsonc(content)
+
+      // Validate against schema
+      const validated = Info.parse(parsed)
+
+      return validated
+    } catch (error) {
+      if (error instanceof z.ZodError) {
+        log.error("config validation failed", {
+          source,
+          errors: error.errors,
+        })
+        throw new Error(`Invalid config at ${source}: ${error.errors[0].message}`)
+      }
+
+      throw error
+    }
+  }
+}
+```
+
+---
+
+## 13. Storage & Persistence Standards
+
+### 13.1 Storage Operations
+
+```typescript
+// packages/opencode/src/storage/storage.ts
+
+export namespace Storage {
+  const log = Log.create({ service: "storage" })
+
+  export const NotFoundError = NamedError.create("NotFoundError", z.object({ message: z.string() }))
+
+  // Read with lock
+  export async function read<T>(target: string): Promise<T> {
+    using _ = await Lock.read(target)
+
+    const file = Bun.file(target)
+    if (!(await file.exists())) {
+      throw NotFoundError.create({
+        message: `File not found: ${target}`,
+      })
+    }
+
+    return file.json()
+  }
+
+  // Write with lock
+  export async function write(target: string, data: any): Promise<void> {
+    using _ = await Lock.write(target)
+
+    const dir = path.dirname(target)
+    await fs.mkdir(dir, { recursive: true })
+
+    await Bun.write(target, JSON.stringify(data, null, 2))
+  }
+
+  // Update (read-modify-write)
+  export async function update<T>(target: string, editor: (draft: T) => void | Promise<void>): Promise<T> {
+    using _ = await Lock.write(target)
+
+    const data = await read<T>(target)
+    await editor(data)
+    await write(target, data)
+
+    return data
+  }
+
+  // Delete
+  export async function remove(target: string): Promise<void> {
+    using _ = await Lock.write(target)
+
+    if (await Filesystem.exists(target)) {
+      await fs.rm(target, { recursive: true })
+    }
+  }
+
+  // List files matching pattern
+  export async function list(directory: string, pattern: string): Promise<string[]> {
+    using _ = await Lock.read(directory)
+
+    const files: string[] = []
+    for await (const file of new Bun.Glob(pattern).scan({ cwd: directory })) {
+      files.push(path.join(directory, file))
+    }
+
+    return files
+  }
+}
+```
+
+**File Reference:** `packages/opencode/src/storage/storage.ts:1-200`
+
+### 13.2 Storage Paths
+
+```typescript
+export namespace Storage {
+  export function path(...segments: string[]): string {
+    return path.join(Global.Path.data, ...segments)
+  }
+
+  // Session storage
+  export namespace Session {
+    export function info(sessionID: string): string {
+      return Storage.path("session", sessionID, "info.json")
+    }
+
+    export function messages(sessionID: string): string {
+      return Storage.path("session", sessionID, "messages")
+    }
+
+    export function message(sessionID: string, messageID: string): string {
+      return Storage.path("session", sessionID, "messages", `${messageID}.json`)
+    }
+  }
+
+  // Project storage
+  export namespace Project {
+    export function info(projectID: string): string {
+      return Storage.path("project", `${projectID}.json`)
+    }
+
+    export function list(): Promise<string[]> {
+      return Storage.list(Storage.path("project"), "*.json")
+    }
+  }
+
+  // Cache storage
+  export namespace Cache {
+    export function file(key: string): string {
+      return Storage.path("cache", `${key}.json`)
+    }
+  }
+}
+```
+
+### 13.3 Migration Pattern
+
+```typescript
+export namespace Storage {
+  type Migration = (dir: string) => Promise<void>
+
+  const MIGRATIONS: Migration[] = [
+    // Migration 1: Rename old directories
+    async (dir) => {
+      const oldPath = path.join(dir, "old-structure")
+      const newPath = path.join(dir, "new-structure")
+
+      if (await Filesystem.exists(oldPath)) {
+        await fs.rename(oldPath, newPath)
+        log.info("migrated directory structure")
+      }
+    },
+
+    // Migration 2: Transform data format
+    async (dir) => {
+      const files = await Storage.list(path.join(dir, "sessions"), "*.json")
+
+      for (const file of files) {
+        const data = await Storage.read<any>(file)
+
+        // Add new field
+        if (!data.version) {
+          data.version = 2
+          data.migrated = Date.now()
+          await Storage.write(file, data)
+        }
+      }
+
+      log.info("migrated session data", { count: files.length })
+    },
+
+    // Migration 3: Consolidate files
+    async (dir) => {
+      const oldDir = path.join(dir, "old")
+      const newFile = path.join(dir, "consolidated.json")
+
+      if (await Filesystem.exists(oldDir)) {
+        const files = await Storage.list(oldDir, "*.json")
+        const consolidated = await Promise.all(files.map((f) => Storage.read(f)))
+
+        await Storage.write(newFile, consolidated)
+        await fs.rm(oldDir, { recursive: true })
+
+        log.info("consolidated files", { count: files.length })
+      }
+    },
+  ]
+
+  export async function migrate(): Promise<void> {
+    const dataDir = Global.Path.data
+    const versionFile = path.join(dataDir, ".version")
+
+    let currentVersion = 0
+    if (await Filesystem.exists(versionFile)) {
+      currentVersion = Number(await Bun.file(versionFile).text())
+    }
+
+    const targetVersion = MIGRATIONS.length
+
+    if (currentVersion >= targetVersion) {
+      log.debug("storage up to date", { version: currentVersion })
+      return
+    }
+
+    log.info("migrating storage", {
+      from: currentVersion,
+      to: targetVersion,
+    })
+
+    // Run pending migrations
+    for (let i = currentVersion; i < targetVersion; i++) {
+      log.info(`running migration ${i + 1}/${targetVersion}`)
+      await MIGRATIONS[i](dataDir)
+    }
+
+    // Update version
+    await Bun.write(versionFile, String(targetVersion))
+
+    log.info("migration complete", { version: targetVersion })
+  }
+}
+```
+
+**File Reference:** `packages/opencode/src/storage/storage.ts:24-100`
+
+---
+
+## 14. Error Handling Standards
+
+### 14.1 Named Errors (Preferred)
+
+```typescript
+// packages/opencode/src/util/error.ts
+
+import { NamedError } from "@opencode-ai/util/error"
+import z from "zod"
+
+// Define typed errors
+export const NotFoundError = NamedError.create(
+  "NotFoundError",
+  z.object({
+    message: z.string(),
+    resource: z.string().optional(),
+    id: z.string().optional(),
+  }),
+)
+
+export const ValidationError = NamedError.create(
+  "ValidationError",
+  z.object({
+    message: z.string(),
+    field: z.string().optional(),
+    expected: z.string().optional(),
+    received: z.string().optional(),
+  }),
+)
+
+export const PermissionError = NamedError.create(
+  "PermissionError",
+  z.object({
+    message: z.string(),
+    action: z.string(),
+    resource: z.string(),
+  }),
+)
+
+// Usage: Throw typed error
+throw NotFoundError.create({
+  message: "Session not found",
+  resource: "session",
+  id: sessionID,
+})
+
+// Usage: Catch and check type
+try {
+  await operation()
+} catch (error) {
+  if (NotFoundError.is(error)) {
+    log.warn("resource not found", {
+      resource: error.data.resource,
+      id: error.data.id,
+    })
+    return null
+  }
+
+  if (PermissionError.is(error)) {
+    log.error("permission denied", {
+      action: error.data.action,
+      resource: error.data.resource,
+    })
+    throw error
+  }
+
+  // Unknown error
+  log.error("unexpected error", { error })
+  throw error
+}
+```
+
+**File Reference:** `packages/opencode/src/storage/storage.ts:17-22`
+
+### 14.2 Custom Error Classes (When Needed)
+
+```typescript
+// ✅ GOOD - Error with additional context
+export class BusyError extends Error {
+  constructor(public readonly sessionID: string) {
+    super(`Session ${sessionID} is busy`)
+    this.name = "BusyError"
+  }
+}
+
+// Usage
+throw new BusyError(sessionID)
+
+// Catching
+try {
+  await process(sessionID)
+} catch (error) {
+  if (error instanceof BusyError) {
+    log.info("session busy, retrying", { sessionID: error.sessionID })
+    await retry()
+  }
+}
+```
+
+**File Reference:** `packages/opencode/src/session/index.ts:494`
+
+### 14.3 Result Pattern (for Tools)
+
+```typescript
+// ✅ GOOD - Never throw in tool execution
+export const ReadTool = Tool.define("read", {
+  async execute(args, context) {
+    try {
+      const content = await Bun.file(args.filePath).text()
+
+      return {
+        output: content,
+        title: `Read ${path.basename(args.filePath)}`,
+      }
+    } catch (error) {
+      return {
+        output: `Error reading file: ${error.message}`,
+        title: "Read Failed",
+        metadata: {
+          error: true,
+          message: error.message,
+        },
+      }
+    }
+  },
+})
+
+// ✅ GOOD - Result type for fallible operations
+export type Result<T, E = Error> = { success: true; value: T } | { success: false; error: E }
+
+export async function operation(): Promise<Result<Data>> {
+  try {
+    const data = await fetchData()
+    return { success: true, value: data }
+  } catch (error) {
+    return { success: false, error }
+  }
+}
+
+// Usage
+const result = await operation()
+if (result.success) {
+  console.log(result.value)
+} else {
+  log.error("operation failed", { error: result.error })
+}
+```
+
+### 14.4 Error Context
+
+```typescript
+// ✅ GOOD - Rich error context
+class OperationError extends Error {
+  constructor(
+    message: string,
+    public readonly context: {
+      operation: string
+      input: unknown
+      timestamp: number
+      sessionID?: string
+    }
+  ) {
+    super(message)
+    this.name = "OperationError"
+  }
+}
+
+// Usage
+try {
+  await processData(input)
+} catch (error) {
+  throw new OperationError(
+    "Failed to process data",
+    {
+      operation: "processData",
+      input,
+      timestamp: Date.now(),
+      sessionID: context.sessionID
+    }
+  )
+}
+
+// Logging with context
+catch (error) {
+  if (error instanceof OperationError) {
+    log.error("operation failed", {
+      operation: error.context.operation,
+      sessionID: error.context.sessionID,
+      error: error.message
+    })
+  }
+}
+```
+
+---
+
+## 15. Type System Standards
+
+### 15.1 Zod Schemas (Primary)
+
+**Rule: Use Zod for runtime validation, derive TypeScript types from schemas**
+
+```typescript
+// ✅ GOOD - Schema-first approach
+export namespace Session {
+  export const Info = z.object({
+    id: z.string(),
+    title: z.string(),
+    projectID: z.string(),
+    modelID: z.string().optional(),
+    permission: z.enum(["allow", "ask", "deny"]),
+    time: z.object({
+      created: z.number(),
+      updated: z.number(),
+    }),
+  })
+
+  // Derive TypeScript type from schema
+  export type Info = z.infer<typeof Info>
+
+  // Use in functions
+  export const create = fn(Info.pick({ title: true, projectID: true }).partial(), async (input): Promise<Info> => {
+    // Implementation
+  })
+}
+
+// ❌ BAD - Type-first approach (no runtime validation)
+export interface SessionInfo {
+  id: string
+  title: string
+  projectID: string
+}
+
+export function create(input: Partial<SessionInfo>): SessionInfo {
+  // No validation! Runtime errors possible
+}
+```
+
+### 15.2 Type Inference
+
+**Rule: Rely on type inference, avoid explicit annotations**
+
+```typescript
+// ✅ GOOD - Let TypeScript infer
+const session = await Session.create({ title: "New" })
+const messages = session.messages.filter((m) => m.role === "user")
+const ids = messages.map((m) => m.id)
+
+// ❌ BAD - Unnecessary annotations
+const session: Session.Info = await Session.create({ title: "New" })
+const messages: Message[] = session.messages.filter((m) => m.role === "user")
+const ids: string[] = messages.map((m) => m.id)
+
+// ✅ ACCEPTABLE - Annotation for clarity in complex scenarios
+const messages: Message[] = await fetchMessages().then((msgs): Message[] => {
+  return msgs.filter((m) => m.deleted !== true)
+})
+```
+
+**File Reference:** `AGENTS.md:15`
+
+### 15.3 Avoid `any`
+
+```typescript
+// ❌ BAD
+function process(data: any) {
+  return data.value.toString()
+}
+
+// ✅ GOOD - Use unknown and validate
+function process(data: unknown) {
+  if (typeof data !== "object" || data === null) {
+    throw new Error("Expected object")
+  }
+
+  if (!("value" in data)) {
+    throw new Error("Missing value property")
+  }
+
+  return String(data.value)
+}
+
+// ✅ BEST - Use Zod schema
+const DataSchema = z.object({
+  value: z.union([z.string(), z.number()]),
+})
+
+function process(data: unknown) {
+  const validated = DataSchema.parse(data)
+  return String(validated.value)
+}
+```
+
+**File Reference:** `AGENTS.md:12`
+
+### 15.4 Type Guards
+
+```typescript
+// ✅ GOOD - Type guards for narrowing
+function isMessage(value: unknown): value is Message {
+  return typeof value === "object" && value !== null && "id" in value && "role" in value && typeof value.id === "string"
+}
+
+// Usage
+if (isMessage(data)) {
+  console.log(data.id) // TypeScript knows data is Message
+}
+
+// ✅ GOOD - Type guards in filter
+const messages = items.filter((item): item is Message => isMessage(item)).map((msg) => msg.id)
+
+// ✅ GOOD - Discriminated unions
+type Part =
+  | { type: "text"; text: string }
+  | { type: "file"; data: Buffer; mimeType: string }
+  | { type: "patch"; files: string[]; diff: string }
+
+function handle(part: Part) {
+  switch (part.type) {
+    case "text":
+      console.log(part.text) // TypeScript knows: text part
+      break
+    case "file":
+      console.log(part.mimeType) // TypeScript knows: file part
+      break
+    case "patch":
+      console.log(part.files) // TypeScript knows: patch part
+      break
+    default:
+      const _exhaustive: never = part
+      throw new Error("Unhandled part type")
+  }
+}
+```
+
+---
+
+## 16. Import Organization Standards
+
+### 16.1 Import Order
+
+```typescript
+// 1. Zod and validation libraries
+import z from "zod"
+
+// 2. Node.js built-ins
+import path from "path"
+import fs from "fs/promises"
+import os from "os"
+
+// 3. External packages (alphabetical)
+import { mergeDeep, sortBy, unique } from "remeda"
+import chokidar from "chokidar"
+import fuzzysort from "fuzzysort"
+
+// 4. Internal packages (@opencode-ai/*)
+import { NamedError } from "@opencode-ai/util/error"
+
+// 5. Project utilities (../util/*)
+import { Log } from "../util/log"
+import { Lock } from "../util/lock"
+import { fn } from "../util/fn"
+
+// 6. Project services (../<service>/*)
+import { Config } from "../config/config"
+import { Storage } from "../storage/storage"
+import { Bus } from "../bus"
+
+// 7. Relative imports (same directory)
+import { Session } from "./session"
+import { MessageV2 } from "./message-v2"
+```
+
+### 16.2 Import Style
+
+```typescript
+// ✅ GOOD - Named imports
+import { create, update, get } from "./session"
+import { Log, type LogOptions } from "./util/log"
+
+// ❌ AVOID - Default imports (except for external packages)
+import session from "./session"
+
+// ✅ GOOD - Namespace imports for large APIs
+import * as Session from "./session"
+
+// ✅ GOOD - Type-only imports
+import type { Session } from "./session"
+import { type Config, loadConfig } from "./config"
+```
+
+### 16.3 Circular Dependency Prevention
+
+```typescript
+// ❌ BAD - Circular dependency
+// file-a.ts
+import { funcB } from "./file-b"
+export function funcA() {
+  return funcB()
+}
+
+// file-b.ts
+import { funcA } from "./file-a"
+export function funcB() {
+  return funcA()
+}
+
+// ✅ GOOD - Extract shared code
+// shared.ts
+export function shared() {
+  return 42
+}
+
+// file-a.ts
+import { shared } from "./shared"
+export function funcA() {
+  return shared()
+}
+
+// file-b.ts
+import { shared } from "./shared"
+export function funcB() {
+  return shared()
+}
+```
+
+---
+
+## 17. Naming Conventions
+
+### 17.1 Functions & Variables
+
+```typescript
+// ✅ camelCase for functions and variables
+const sessionID = "abc123"
+const userAgent = "opencode/1.0"
+const maxRetries = 3
+
+async function processMessage(messageID: string) {}
+async function createSession() {}
+```
+
+### 17.2 Types & Interfaces
+
+```typescript
+// ✅ PascalCase for types, interfaces, and classes
+type SessionInfo = {
+  id: string
+  title: string
+}
+
+interface Message {
+  id: string
+  content: string
+}
+
+class BusyError extends Error {}
+
+namespace Session {
+  export type Info = z.infer<typeof Info>
+}
+```
+
+### 17.3 Constants
+
+```typescript
+// ✅ SCREAMING_SNAKE_CASE for true constants
+const MAX_RETRY_ATTEMPTS = 3
+const DEFAULT_TIMEOUT = 5000
+const API_BASE_URL = "https://api.example.com"
+
+// ✅ camelCase for configuration values
+const maxRetries = config.retries ?? 3
+const defaultModel = config.model?.id ?? "gpt-4"
+```
+
+### 17.4 Namespaces
+
+```typescript
+// ✅ PascalCase for namespaces
+export namespace Session {}
+export namespace Storage {}
+export namespace FileWatcher {}
+```
+
+### 17.5 Files
+
+```typescript
+// ✅ kebab-case for files
+// session-manager.ts
+// message-processor.ts
+// file-watcher.ts
+
+// ✅ Single word when possible
+// session.ts
+// storage.ts
+// config.ts
+```
+
+---
+
+## 18. Testing Standards
+
+### 18.1 Principles
+
+1. **Avoid mocks** - Test actual implementation
+2. **No logic duplication** - Don't reimplement logic in tests
+3. **Use Bun test runner** - `bun test`
+
+**File Reference:** `AGENTS.md:108-111`
+
+### 18.2 Test Structure
+
+```typescript
+// packages/opencode/src/addons/serialize.test.ts
+
+import { expect, test, describe } from "bun:test"
+import { serialize, deserialize } from "./serialize"
+
+describe("serialize", () => {
+  test("preserves Date objects", () => {
+    const input = { date: new Date("2024-01-01") }
+    const serialized = serialize(input)
+    const deserialized = deserialize(serialized)
+
+    expect(deserialized.date).toBeInstanceOf(Date)
+    expect(deserialized.date.toISOString()).toBe("2024-01-01T00:00:00.000Z")
+  })
+
+  test("preserves Set objects", () => {
+    const input = { set: new Set([1, 2, 3]) }
+    const serialized = serialize(input)
+    const deserialized = deserialize(serialized)
+
+    expect(deserialized.set).toBeInstanceOf(Set)
+    expect(Array.from(deserialized.set)).toEqual([1, 2, 3])
+  })
+
+  test("handles nested structures", () => {
+    const input = {
+      map: new Map([["key", { date: new Date("2024-01-01") }]]),
+      array: [new Set([1, 2])],
+    }
+    const serialized = serialize(input)
+    const deserialized = deserialize(serialized)
+
+    expect(deserialized.map).toBeInstanceOf(Map)
+    expect(deserialized.map.get("key")?.date).toBeInstanceOf(Date)
+    expect(deserialized.array[0]).toBeInstanceOf(Set)
+  })
+})
+```
+
+**File Reference:** `packages/opencode/src/addons/serialize.test.ts`
+
+### 18.3 Test Commands
+
+```bash
+# Run all tests
+bun test
+
+# Run specific test file
+bun test src/util/queue.test.ts
+
+# Run tests matching pattern
+bun test --test-name-pattern "serialize"
+
+# Watch mode
+bun test --watch
+
+# Coverage
+bun test --coverage
+```
+
+**File Reference:** `packages/opencode/AGENTS.md` - Build/Test Commands
+
+### 18.4 Integration Tests
+
+```typescript
+import { test, expect, beforeAll, afterAll } from "bun:test"
+import { Session } from "./session"
+import { Storage } from "./storage"
+
+let sessionID: string
+
+beforeAll(async () => {
+  // Setup: Create test session
+  const session = await Session.create({ title: "Test Session" })
+  sessionID = session.id
+})
+
+afterAll(async () => {
+  // Cleanup: Delete test session
+  await Session.delete(sessionID)
+})
+
+test("create and retrieve session", async () => {
+  const session = await Session.get(sessionID)
+
+  expect(session).toBeDefined()
+  expect(session.id).toBe(sessionID)
+  expect(session.title).toBe("Test Session")
+})
+
+test("update session", async () => {
+  await Session.update(sessionID, { title: "Updated" })
+
+  const session = await Session.get(sessionID)
+  expect(session.title).toBe("Updated")
+})
+```
+
+---
+
+## 19. Documentation Standards
+
+### 19.1 Code Comments
+
+**Rule: Comment WHY, not WHAT**
+
+```typescript
+// ✅ GOOD - Explains why
+// Cache header separately to enable 2-part prompt caching
+if (system.length > 2 && system[0] === header) {
+  system.length = 0
+  system.push(header, rest.join("\n"))
+}
+
+// Prevent race condition: lock before checking existence
+using _ = await Lock.write(filepath)
+if (await Filesystem.exists(filepath)) {
+  await fs.rm(filepath)
+}
+
+// ❌ BAD - States the obvious
+// Push the item to the array
+items.push(item)
+
+// Set the title property
+session.title = "New Title"
+```
+
+### 19.2 JSDoc (For Exported APIs)
+
+````typescript
+/**
+ * Execute a function with a file lock to prevent concurrent access.
+ *
+ * The lock is automatically released when the function completes or throws.
+ * Locks are queued and processed in order.
+ *
+ * @param filepath - Absolute path to the file to lock
+ * @param fn - Function to execute while holding the lock
+ * @returns The result of the function
+ *
+ * @example
+ * ```typescript
+ * await withLock("/path/to/file", async () => {
+ *   const content = await Bun.file("/path/to/file").text()
+ *   await Bun.write("/path/to/file", content + "\n")
+ * })
+ * ```
+ */
+export async function withLock<T>(filepath: string, fn: () => Promise<T>): Promise<T>
+````
+
+### 19.3 README Structure
+
+```markdown
+# Package Name
+
+Brief description of what this package does.
+
+## Installation
+
+\`\`\`bash
+bun install @opencode-ai/package-name
+\`\`\`
+
+## Usage
+
+\`\`\`typescript
+import { feature } from "@opencode-ai/package-name"
+
+await feature()
+\`\`\`
+
+## API
+
+### `function(param: Type): ReturnType`
+
+Description of function.
+
+**Parameters:**
+
+- `param` - Description of parameter
+
+**Returns:** Description of return value
+
+**Example:**
+\`\`\`typescript
+const result = await function(param)
+\`\`\`
+
+## Development
+
+\`\`\`bash
+bun install
+bun test
+\`\`\`
+```
+
+---
+
+## 20. Schema Definition Standards
+
+### 20.1 Drizzle Schema (Database)
+
+**Rule: Use snake_case for field names to match SQL conventions**
+
+```typescript
+// ✅ GOOD - snake_case fields
+const sessionTable = sqliteTable("session", {
+  id: text().primaryKey(),
+  project_id: text().notNull(),
+  created_at: integer().notNull(),
+  updated_at: integer().notNull(),
+})
+
+// ❌ BAD - camelCase requires explicit column names
+const sessionTable = sqliteTable("session", {
+  id: text("id").primaryKey(),
+  projectID: text("project_id").notNull(),
+  createdAt: integer("created_at").notNull(),
+  updatedAt: integer("updated_at").notNull(),
+})
+```
+
+**File Reference:** `AGENTS.md:88-106`
+
+### 20.2 Zod Schema
+
+```typescript
+// ✅ GOOD - Consistent field naming
+export const SessionInfo = z.object({
+  id: z.string(),
+  projectID: z.string(), // camelCase for TypeScript
+  title: z.string(),
+  permission: z.enum(["allow", "ask", "deny"]),
+  time: z.object({
+    created: z.number(),
+    updated: z.number(),
+  }),
+})
+
+// ✅ GOOD - Schema composition
+export const CreateSessionInput = SessionInfo.pick({
+  title: true,
+  projectID: true,
+}).partial()
+
+export const UpdateSessionInput = SessionInfo.partial().required({
+  id: true,
+})
+
+// ✅ GOOD - Schema extension
+export const SessionWithMessages = SessionInfo.extend({
+  messages: z.array(MessageInfo),
+})
+```
+
+---
+
+## 21. Dependency Management Standards
+
+### 21.1 Bun Runtime Preference
+
+**Rule: Use Bun APIs when available**
+
+```typescript
+// ✅ GOOD - Bun APIs
+const content = await Bun.file(filepath).text()
+await Bun.write(filepath, content)
+const json = await Bun.file(filepath).json()
+
+const proc = Bun.spawn(["ls", "-la"], {
+  cwd: directory,
+  stdout: "pipe",
+})
+
+// ❌ AVOID - Node.js fs when Bun alternative exists
+import fs from "fs/promises"
+const content = await fs.readFile(filepath, "utf-8")
+await fs.writeFile(filepath, content)
+```
+
+**File Reference:** `AGENTS.md:14`
+
+### 21.2 Package Installation
+
+```bash
+# Add dependency
+bun add package-name
+
+# Add dev dependency
+bun add -d package-name
+
+# Add workspace dependency
+bun add @opencode-ai/other-package
+```
+
+### 21.3 Version Management
+
+```json
+// package.json
+{
+  "dependencies": {
+    "zod": "^3.22.4", // Allow patch and minor updates
+    "remeda": "1.30.0", // Pin exact version for critical deps
+    "@ai-sdk/anthropic": "^0.0.39"
+  },
+  "devDependencies": {
+    "@types/node": "^20.10.0",
+    "typescript": "^5.3.3"
+  }
+}
+```
+
+---
+
+## 22. Build & Development Standards
+
+### 22.1 Development Commands
+
+```bash
+# Install dependencies
+bun install
+
+# Run in development (TUI)
+bun dev                       # Run in packages/opencode
+bun dev <directory>           # Run in specific directory
+bun dev .                     # Run in repo root
+
+# Run API server
+bun dev serve                 # Start on port 4096
+bun dev serve --port 8080     # Custom port
+
+# Run web UI (requires server running)
+bun dev web                   # Start server + open web UI
+bun run --cwd packages/app dev  # Just web UI
+
+# Run desktop app
+bun run --cwd packages/desktop tauri dev
+
+# Type checking
+bun run typecheck
+
+# Run tests
+bun test
+bun test path/to/test.ts
+
+# Build standalone executable
+./packages/opencode/script/build.ts --single
+
+# Regenerate SDK (after server changes)
+./script/generate.ts
+```
+
+**File Reference:** `CONTRIBUTING.md:30-150`
+
+### 22.2 Project Structure
+
+```
+opencode/
+├── packages/
+│   ├── opencode/           # Core business logic & CLI
+│   │   ├── src/
+│   │   │   ├── session/    # Session management
+│   │   │   ├── tool/       # Tool implementations
+│   │   │   ├── agent/      # Agent system
+│   │   │   ├── mcp/        # Model Context Protocol
+│   │   │   ├── lsp/        # Language Server Protocol
+│   │   │   ├── file/       # File operations
+│   │   │   ├── config/     # Configuration
+│   │   │   ├── provider/   # LLM providers
+│   │   │   ├── server/     # HTTP/WebSocket server
+│   │   │   └── cli/cmd/tui/  # Terminal UI (SolidJS)
+│   │   └── script/
+│   │       └── build.ts    # Build script
+│   ├── app/                # Web UI (SolidJS)
+│   ├── desktop/            # Native app (Tauri)
+│   ├── sdk/js/             # TypeScript SDK
+│   ├── plugin/             # Plugin system
+│   └── console/            # Web console
+├── script/
+│   ├── generate.ts         # Generate SDK
+│   └── format.ts           # Format code
+├── AGENTS.md               # Agent guidelines
+├── CONTRIBUTING.md         # Contribution guide
+└── CODEBASE_STANDARDS.md   # This document
+```
+
+### 22.3 Build Output
+
+```bash
+# Single build creates:
+packages/opencode/dist/opencode-darwin-arm64/
+├── bin/
+│   └── opencode           # Executable
+├── node_modules/          # Bundled dependencies
+└── package.json
+
+# Run built executable:
+./packages/opencode/dist/opencode-darwin-arm64/bin/opencode
+```
+
+---
+
+## 23. Performance Standards
+
+### 23.1 Lazy Initialization
+
+```typescript
+// ✅ GOOD - Lazy state initialization
+const state = Instance.state(async () => {
+  // Only initialize when first accessed
+  const config = await Config.get()
+  return { config, clients: [] }
+})
+
+// Access only when needed
+if (needsClient) {
+  const client = state().clients[0]
+}
+
+// ✅ GOOD - Lazy loading of heavy dependencies
+const lazyModule = lazy(async () => {
+  return import("./heavy-module")
+})
+
+// Load only when needed
+const module = await lazyModule()
+```
+
+### 23.2 Caching
+
+```typescript
+// ✅ GOOD - Cache expensive operations
+const cache = new Map<string, Data>()
+
+async function getData(id: string): Promise<Data> {
+  const cached = cache.get(id)
+  if (cached) return cached
+
+  const data = await fetchData(id)
+  cache.set(id, data)
+  return data
+}
+
+// ✅ GOOD - Time-based cache invalidation
+const cache = new Map<string, { data: Data; expires: number }>()
+
+async function getData(id: string): Promise<Data> {
+  const cached = cache.get(id)
+  if (cached && Date.now() < cached.expires) {
+    return cached.data
+  }
+
+  const data = await fetchData(id)
+  cache.set(id, {
+    data,
+    expires: Date.now() + 60_000, // 1 minute
+  })
+  return data
+}
+```
+
+### 23.3 Debouncing
+
+```typescript
+// ✅ GOOD - Debounce high-frequency events
+function debounce<T extends (...args: any[]) => any>(fn: T, delay: number): (...args: Parameters<T>) => void {
+  let timer: Timer | undefined
+
+  return (...args: Parameters<T>) => {
+    if (timer) clearTimeout(timer)
+    timer = setTimeout(() => {
+      fn(...args)
+      timer = undefined
+    }, delay)
+  }
+}
+
+// Usage
+const debouncedSave = debounce(async (content: string) => {
+  await save(content)
+}, 500)
+
+// Only saves after 500ms of inactivity
+input.on("change", (content) => {
+  debouncedSave(content)
+})
+```
+
+### 23.4 Streaming
+
+```typescript
+// ✅ GOOD - Stream large responses
+export async function* streamMessages(sessionID: string) {
+  const files = await Storage.list(Storage.path("messages", sessionID), "*.json")
+
+  for (const file of files) {
+    const message = await Storage.read<Message>(file)
+    yield message
+  }
+}
+
+// Usage
+for await (const message of streamMessages(sessionID)) {
+  process(message)
+}
+```
+
+---
+
+## 24. Security Standards
+
+### 24.1 Input Validation
+
+```typescript
+// ✅ GOOD - Validate all external input
+export const handleRequest = fn(
+  z.object({
+    sessionID: z.string().regex(/^session-[a-z0-9]{10}$/),
+    content: z.string().max(100_000),
+    metadata: z.record(z.unknown()).optional(),
+  }),
+  async (input) => {
+    // Input is validated, safe to use
+    return process(input)
+  },
+)
+
+// ✅ GOOD - Validate file paths
+function validatePath(filepath: string) {
+  const normalized = path.normalize(filepath)
+  const absolute = path.resolve(normalized)
+
+  // Prevent directory traversal
+  if (!absolute.startsWith(Instance.worktree)) {
+    throw new Error("Path outside worktree")
+  }
+
+  return absolute
+}
+```
+
+### 24.2 Permission Checks
+
+```typescript
+// ✅ GOOD - Check permissions before sensitive operations
+async function readFile(filepath: string, context: Context) {
+  // Validate path
+  const safe = validatePath(filepath)
+
+  // Check permission
+  const permission = await PermissionNext.evaluate("read", safe, context.agent.permission)
+
+  if (permission.action === "deny") {
+    throw PermissionError.create({
+      message: "Permission denied",
+      action: "read",
+      resource: safe,
+    })
+  }
+
+  if (permission.action === "ask") {
+    const allowed = await context.ask({
+      type: "permission",
+      message: `Read file ${path.basename(safe)}?`,
+      actions: ["allow", "deny"],
+    })
+
+    if (!allowed) {
+      throw PermissionError.create({
+        message: "User denied permission",
+        action: "read",
+        resource: safe,
+      })
+    }
+  }
+
+  // Permission granted, perform operation
+  return Bun.file(safe).text()
+}
+```
+
+### 24.3 Secrets Management
+
+```typescript
+// ✅ GOOD - Load secrets from environment
+export namespace Auth {
+  export async function get(providerID: string): Promise<string | undefined> {
+    const key = `OPENCODE_${providerID.toUpperCase()}_API_KEY`
+    return process.env[key]
+  }
+}
+
+// ❌ AVOID - Hardcoded secrets
+const API_KEY = "sk-abc123..."
+
+// ❌ AVOID - Logging secrets
+log.info("api key", { key: apiKey })
+
+// ✅ GOOD - Redact secrets in logs
+log.info("api request", { key: apiKey.slice(0, 8) + "..." })
+```
+
+### 24.4 Command Injection Prevention
+
+```typescript
+// ❌ BAD - Command injection vulnerability
+const output = await $`ls ${userInput}`.text()
+
+// ✅ GOOD - Use array syntax (prevents injection)
+const proc = Bun.spawn(["ls", userInput], {
+  stdout: "pipe",
+})
+const output = await new Response(proc.stdout).text()
+
+// ✅ GOOD - Validate input
+const sanitized = userInput.replace(/[^a-zA-Z0-9_-]/g, "")
+const proc = Bun.spawn(["ls", sanitized])
+```
+
+---
+
+## Summary: Key Principles
+
+1. **Single-word function names** unless multi-word necessary (95%+ adherence)
+2. **Namespaces over classes** for code organization (only 5 classes in 206 files)
+3. **Functional array methods** over for-loops (85/15 split)
+4. **Parallel execution by default** via `Promise.all`
+5. **Lock mechanisms** prevent race conditions (reader-writer locks, file locks)
+6. **Per-instance state isolation** for multi-project support
+7. **Event-driven architecture** via pub/sub bus
+8. **Zod validation** for all inputs via `fn()` wrapper
+9. **Disposable resources** with `using` keyword for automatic cleanup
+10. **Bun runtime preference** for file I/O and process spawning
+11. **Inline values once, extract when reusable**
+12. **Named errors** over throw strings
+13. **Avoid mocks in tests**, test actual implementation
+14. **Layered config** with clear precedence (7 levels)
+15. **Graceful disposal** for all stateful services
+16. **Prefer `const` over `let`** - use ternaries instead of reassignment
+17. **Avoid `else` statements** - use early returns
+18. **Avoid destructuring** - preserve context with dot notation
+19. **Type inference** - avoid explicit annotations unless necessary
+20. **Avoid `any` type** - use `unknown` with validation
+21. **Comment WHY, not WHAT** - explain reasoning, not obvious operations
+22. **Schema-first approach** - define Zod schemas, derive TS types
+23. **Reader-writer locks** for concurrent access
+24. **System prompt caching** - maintain 2-part structure for efficiency
+25. **Context compaction** at 75% token threshold
+
+---
+
+## File References Quick Index
+
+### Core Patterns
+
+- **Function wrapper**: `packages/opencode/src/util/fn.ts`
+- **State management**: `packages/opencode/src/project/state.ts`
+- **Instance isolation**: `packages/opencode/src/project/instance.ts`
+- **Event bus**: `packages/opencode/src/bus/index.ts`
+- **Locks**: `packages/opencode/src/util/lock.ts`
+- **Async queue**: `packages/opencode/src/util/queue.ts`
+
+### Services
+
+- **Session**: `packages/opencode/src/session/index.ts`
+- **LLM streaming**: `packages/opencode/src/session/llm.ts`
+- **Processor**: `packages/opencode/src/session/processor.ts`
+- **Messages**: `packages/opencode/src/session/message-v2.ts`
+- **LSP**: `packages/opencode/src/lsp/index.ts`
+- **MCP**: `packages/opencode/src/mcp/index.ts`
+- **Storage**: `packages/opencode/src/storage/storage.ts`
+- **Config**: `packages/opencode/src/config/config.ts`
+- **Provider**: `packages/opencode/src/provider/provider.ts`
+
+### Tools
+
+- **Tool definition**: `packages/opencode/src/tool/tool.ts`
+- **Edit**: `packages/opencode/src/tool/edit.ts`
+- **Batch**: `packages/opencode/src/tool/batch.ts`
+- **Grep**: `packages/opencode/src/tool/grep.ts`
+
+### Documentation
+
+- **Style guide**: `AGENTS.md`
+- **Contributing**: `CONTRIBUTING.md`
+- **This document**: `CODEBASE_STANDARDS.md`
+
+---
+
+**End of Standards Document**

+ 37 - 0
plugins/claude-code/scripts/context/content-creation/examples/navigation.md

@@ -0,0 +1,37 @@
+<!-- Context: content-creation/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Content Examples Navigation
+
+Real-world content examples demonstrating effective techniques and formats.
+
+---
+
+## Status
+
+**Currently empty** - Placeholder for future content examples.
+
+---
+
+## Planned Content
+
+Future examples will include:
+- High-performing blog posts
+- Effective video scripts
+- Engaging social media posts
+- Successful email campaigns
+- Compelling landing page copy
+- Effective hooks and openings
+- Before/after content improvements
+
+---
+
+## Usage
+
+When examples are added, they will demonstrate:
+- Application of copywriting frameworks
+- Effective hooks and storytelling
+- Format-specific best practices
+- Audience targeting techniques
+- Content repurposing strategies
+
+Check back later for real-world examples to learn from.

+ 441 - 0
plugins/claude-code/scripts/context/content-creation/formats/audio-content.md

@@ -0,0 +1,441 @@
+<!-- Context: content-creation/audio-content | Priority: low | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Audio Content Guidelines
+
+Best practices for creating engaging audio content: podcasts, voice content, audio ads, and audiobooks.
+
+---
+
+## Podcast Episode Structure
+
+### Standard Podcast Flow
+
+**1. Cold Open (0-30 seconds)**
+- Hook with the most interesting moment
+- Tease what's coming
+- Create curiosity
+
+**2. Intro (30-60 seconds)**
+- Welcome and show intro
+- Episode topic overview
+- Guest introduction (if applicable)
+- Sponsor message (if applicable)
+
+**3. Main Content (Bulk of episode)**
+- Deliver on the promise
+- Conversational flow
+- Stories and examples
+- Varied pacing
+
+**4. Outro (1-2 minutes)**
+- Recap key points
+- Thank guest (if applicable)
+- Call-to-action
+- Preview next episode
+- Sponsor message (if applicable)
+
+---
+
+### Episode Length Guidelines
+
+**Short-form (5-15 minutes)**:
+- Daily shows
+- Quick tips
+- News and updates
+- Solo commentary
+
+**Medium-form (20-45 minutes)**:
+- Interview shows
+- Educational content
+- Most versatile length
+- Commute-friendly
+
+**Long-form (60+ minutes)**:
+- Deep-dive interviews
+- Roundtable discussions
+- Storytelling
+- Niche audiences
+
+---
+
+## Audio Script Writing
+
+### Script vs. Outline
+
+**Fully Scripted**:
+- Precise messaging required
+- Ads and sponsor reads
+- Introductions and outros
+- Educational content
+
+**Outline Only**:
+- Conversational feel
+- Interview shows
+- Discussion podcasts
+- Natural flow preferred
+
+**Hybrid**:
+- Scripted intro/outro
+- Outlined main content
+- Scripted key points
+- Flexible delivery
+
+---
+
+### Writing for the Ear
+
+**Conversational Language**:
+- Write how you speak
+- Use contractions
+- Short sentences
+- Active voice
+
+**Avoid**:
+- Complex sentences
+- Jargon without explanation
+- Long lists (hard to follow)
+- Dense information dumps
+
+**Include**:
+- Verbal signposts ("First...", "Next...", "Finally...")
+- Transitions between topics
+- Recaps of key points
+- Rhetorical questions
+
+---
+
+## Voice Content Best Practices
+
+### Vocal Delivery
+
+**Pacing**:
+- Vary speed for emphasis
+- Slow down for important points
+- Speed up for energy
+- Pause for impact
+
+**Tone**:
+- Match content (serious, playful, educational)
+- Vary tone to maintain interest
+- Authentic and natural
+- Energy appropriate to topic
+
+**Emphasis**:
+- Stress key words
+- Use volume variation
+- Pitch changes for interest
+- Avoid monotone
+
+---
+
+### Audio Quality
+
+**Recording Environment**:
+- Quiet space (no background noise)
+- Soft surfaces (reduce echo)
+- Consistent location
+- Close to microphone (6-12 inches)
+
+**Equipment**:
+- Decent microphone (USB or XLR)
+- Pop filter (reduce plosives)
+- Headphones (monitor audio)
+- Audio interface (if using XLR)
+
+**Post-Production**:
+- Remove long pauses and filler words
+- Normalize audio levels
+- EQ for clarity
+- Compression for consistency
+- Noise reduction if needed
+
+---
+
+## Audio Ad Formats
+
+### Ad Types
+
+**Pre-Roll (Beginning)**:
+- 15-30 seconds
+- Quick and punchy
+- Set expectations
+
+**Mid-Roll (Middle)**:
+- 60-90 seconds
+- Natural break in content
+- Most valuable placement
+
+**Post-Roll (End)**:
+- 15-30 seconds
+- Bonus for engaged listeners
+- Less valuable
+
+---
+
+### Ad Script Structure
+
+**Host-Read Ad**:
+1. Transition ("Speaking of [topic]...")
+2. Personal endorsement
+3. Product/service benefits
+4. Call-to-action
+5. Promo code/link
+6. Transition back to content
+
+**Produced Ad**:
+1. Hook (attention-grabbing)
+2. Problem identification
+3. Solution (product/service)
+4. Benefits
+5. Call-to-action
+6. Memorable tagline
+
+---
+
+### Ad Best Practices
+
+**Authenticity**:
+- Only promote products you use
+- Personal stories work best
+- Genuine enthusiasm
+- Honest about limitations
+
+**Integration**:
+- Natural transitions
+- Relevant to content
+- Not jarring or disruptive
+- Consistent placement
+
+**Clarity**:
+- Clear call-to-action
+- Easy-to-remember URL or code
+- Repeat key information
+- Spell out if needed
+
+---
+
+## Interview Preparation
+
+### Pre-Interview
+
+**Research**:
+- Guest background
+- Previous interviews
+- Recent work/projects
+- Unique angles
+
+**Question Preparation**:
+- 10-15 questions prepared
+- Mix of types (open-ended, specific, personal)
+- Logical flow
+- Follow-up questions ready
+
+**Logistics**:
+- Recording platform confirmed
+- Time zone verified
+- Tech test scheduled
+- Backup plan ready
+
+---
+
+### During Interview
+
+**Active Listening**:
+- Don't just read questions
+- Follow interesting threads
+- Ask follow-up questions
+- Let guest finish thoughts
+
+**Pacing**:
+- Allow pauses (don't fill every silence)
+- Vary question types
+- Build to interesting topics
+- Save best for last (or tease early)
+
+**Energy**:
+- Match guest's energy
+- Show genuine interest
+- React authentically
+- Create comfortable atmosphere
+
+---
+
+## Audio Storytelling Techniques
+
+### Story Structure
+
+**Three-Act Structure**:
+1. Setup (introduce characters, situation)
+2. Conflict (problem, challenge, tension)
+3. Resolution (outcome, lesson, transformation)
+
+**In Media Res**:
+- Start in the middle of action
+- Hook with interesting moment
+- Flash back to setup
+- Return to resolution
+
+---
+
+### Audio-Specific Techniques
+
+**Sound Design**:
+- Ambient sound for atmosphere
+- Sound effects for emphasis
+- Music for emotional tone
+- Silence for impact
+
+**Pacing**:
+- Vary speed of narration
+- Use pauses strategically
+- Build tension with pacing
+- Release with resolution
+
+**Voice**:
+- Character voices (if applicable)
+- Emotional delivery
+- Intimate vs. dramatic
+- First-person for connection
+
+---
+
+## Podcast Content Ideas
+
+### Interview Show Ideas
+
+**Expert Interviews**:
+- Industry leaders
+- Authors and creators
+- Practitioners and specialists
+- Rising stars
+
+**Story-Based Interviews**:
+- Transformation stories
+- Failure and comeback stories
+- Behind-the-scenes
+- Day-in-the-life
+
+---
+
+### Solo Show Ideas
+
+**Educational**:
+- How-to episodes
+- Framework breakdowns
+- Tool reviews
+- Myth-busting
+
+**Commentary**:
+- Industry news analysis
+- Trend discussions
+- Hot takes
+- Q&A episodes
+
+**Personal**:
+- Lessons learned
+- Experiments and results
+- Behind-the-scenes
+- Reflections
+
+---
+
+### Series Ideas
+
+**Seasonal**:
+- Multi-episode story arc
+- Theme-based seasons
+- Limited series
+- Documentary-style
+
+**Recurring**:
+- Weekly roundups
+- Monthly deep-dives
+- Quarterly reviews
+- Annual retrospectives
+
+---
+
+## Audio Content Checklist
+
+### Pre-Recording
+
+- [ ] Script or outline prepared
+- [ ] Recording environment quiet
+- [ ] Equipment tested
+- [ ] Backup recording method ready
+- [ ] Water nearby (hydration)
+
+### Recording
+
+- [ ] Consistent distance from mic
+- [ ] Energy and enthusiasm present
+- [ ] Clear enunciation
+- [ ] Varied pacing and tone
+- [ ] Minimal filler words
+
+### Post-Production
+
+- [ ] Intro/outro music added
+- [ ] Audio levels normalized
+- [ ] Long pauses removed
+- [ ] Filler words edited (if excessive)
+- [ ] Noise reduction applied
+- [ ] Metadata added (title, description, artwork)
+
+### Publishing
+
+- [ ] Episode title optimized
+- [ ] Show notes written
+- [ ] Timestamps included
+- [ ] Links and resources added
+- [ ] Artwork uploaded
+- [ ] Scheduled for optimal time
+
+---
+
+## Common Audio Content Mistakes
+
+### ❌ Poor Audio Quality
+Background noise, echo, inconsistent levels.
+
+### ✅ Clean Audio
+Quiet environment, good mic, proper editing.
+
+---
+
+### ❌ Monotone Delivery
+Same pace and tone throughout.
+
+### ✅ Varied Delivery
+Pacing, tone, and energy variation.
+
+---
+
+### ❌ No Structure
+Rambling without clear direction.
+
+### ✅ Clear Structure
+Intro, main content, outro with logical flow.
+
+---
+
+### ❌ Too Much Filler
+Excessive "um," "uh," "like," "you know."
+
+### ✅ Clean Delivery
+Minimal filler words, edited if excessive.
+
+---
+
+## Usage
+
+Apply these guidelines when creating:
+- Podcast episodes
+- Audio ads
+- Voice-over content
+- Audiobook narration
+- Voice notes
+- Audio courses
+- Meditation/guided content
+
+**Remember**: Audio is intimate. Speak directly to one person, not a crowd. Create a conversation, not a lecture.

+ 341 - 0
plugins/claude-code/scripts/context/content-creation/formats/image-content.md

@@ -0,0 +1,341 @@
+<!-- Context: content-creation/image-content | Priority: low | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Image Content Guidelines
+
+Best practices for creating visual content: social media graphics, infographics, thumbnails, and visual quotes.
+
+---
+
+## Visual Hierarchy Principles
+
+### Core Principles
+
+**1. Contrast**
+- High contrast for readability
+- Dark text on light background (or vice versa)
+- Color contrast for emphasis
+- Size contrast for importance
+
+**2. Alignment**
+- Everything should align to something
+- Creates order and professionalism
+- Use grids for consistency
+
+**3. Proximity**
+- Related elements close together
+- Unrelated elements separated
+- Creates visual grouping
+
+**4. Repetition**
+- Consistent colors, fonts, styles
+- Builds brand recognition
+- Creates cohesive look
+
+**5. White Space**
+- Don't fill every pixel
+- Gives eyes room to rest
+- Emphasizes important elements
+
+---
+
+## Text Overlay Best Practices
+
+### Typography Rules
+
+**Font Selection**:
+- Maximum 2 fonts per image
+- Pair serif + sans-serif OR two sans-serif
+- Ensure readability at small sizes
+- Avoid overly decorative fonts
+
+**Text Hierarchy**:
+- Main message: Largest, boldest
+- Supporting text: Medium size
+- Attribution/details: Smallest
+
+**Readability**:
+- Minimum 24pt font for social media
+- High contrast with background
+- Add background overlay if needed
+- Test at thumbnail size
+
+---
+
+### Text Placement
+
+**Safe Zones**:
+- Avoid edges (platform crops)
+- Center or rule-of-thirds placement
+- Leave breathing room around text
+- Consider profile picture overlap (Instagram)
+
+**Text Length**:
+- Social graphics: 3-7 words max
+- Infographics: Concise bullet points
+- Quotes: Full quote okay if readable
+
+---
+
+## Social Media Image Specs
+
+### Platform Dimensions
+
+**Instagram**:
+- Feed post: 1080 x 1080px (square)
+- Story: 1080 x 1920px (9:16)
+- Reels cover: 1080 x 1920px (9:16)
+- Carousel: 1080 x 1080px (square)
+
+**Twitter/X**:
+- Single image: 1200 x 675px (16:9)
+- Multiple images: 1200 x 600px
+
+**LinkedIn**:
+- Feed post: 1200 x 1200px (square)
+- Article header: 1200 x 627px
+
+**Facebook**:
+- Feed post: 1200 x 630px
+- Story: 1080 x 1920px (9:16)
+
+**Pinterest**:
+- Standard pin: 1000 x 1500px (2:3)
+- Square pin: 1000 x 1000px
+
+**YouTube**:
+- Thumbnail: 1280 x 720px (16:9)
+- Minimum width: 640px
+
+---
+
+## Infographic Structure
+
+### Infographic Types
+
+**Statistical Infographic**:
+- Lead with key statistic
+- Supporting data points
+- Visual data representation (charts, graphs)
+- Source attribution
+
+**Process Infographic**:
+- Step-by-step flow
+- Numbered or arrowed progression
+- Icons for each step
+- Clear beginning and end
+
+**Comparison Infographic**:
+- Side-by-side layout
+- Clear labels
+- Visual differentiation
+- Pros/cons or before/after
+
+**List Infographic**:
+- Numbered or bulleted items
+- Icon for each point
+- Brief explanation per item
+- Scannable format
+
+---
+
+### Infographic Best Practices
+
+**Layout**:
+- Clear visual flow (top to bottom or left to right)
+- Logical grouping of information
+- Consistent spacing
+- Visual hierarchy (most important = largest)
+
+**Data Visualization**:
+- Choose appropriate chart type
+- Label clearly
+- Use color meaningfully
+- Keep it simple
+
+**Branding**:
+- Logo placement (subtle, not distracting)
+- Consistent color palette
+- Brand fonts
+- URL or handle
+
+---
+
+## Visual Content Ideas
+
+### Social Media Graphics
+
+**Quote Graphics**:
+- Inspirational quotes
+- Tips and advice
+- Statistics
+- Testimonials
+
+**Announcement Graphics**:
+- New product/service
+- Event promotion
+- Milestone celebration
+- Behind-the-scenes
+
+**Educational Graphics**:
+- Tips and tricks
+- How-to steps
+- Checklists
+- Frameworks
+
+**Engagement Graphics**:
+- Questions
+- Polls (Instagram stories)
+- Fill-in-the-blank
+- This or that
+
+---
+
+### Infographic Ideas
+
+**Data-Driven**:
+- Industry statistics
+- Survey results
+- Trend analysis
+- Comparison data
+
+**Educational**:
+- Process explanations
+- Timeline of events
+- Anatomy/breakdown
+- Glossary of terms
+
+**Actionable**:
+- Step-by-step guides
+- Checklists
+- Decision trees
+- Frameworks
+
+---
+
+## Brand Consistency in Visuals
+
+### Brand Elements to Maintain
+
+**Color Palette**:
+- Primary colors (2-3)
+- Secondary colors (2-3)
+- Accent color (1)
+- Consistent usage across all graphics
+
+**Typography**:
+- Headline font
+- Body font
+- Consistent sizing and spacing
+
+**Visual Style**:
+- Photography style (bright, moody, minimal)
+- Illustration style (flat, 3D, hand-drawn)
+- Icon style (line, filled, outlined)
+- Filter/editing style
+
+**Logo Usage**:
+- Consistent placement
+- Appropriate size (visible but not dominant)
+- Correct version (color, white, black)
+
+---
+
+## Design Tools
+
+### Beginner-Friendly
+
+**Canva**:
+- Templates for all platforms
+- Drag-and-drop interface
+- Brand kit feature
+- Free and pro versions
+
+**Adobe Express**:
+- Quick graphics
+- Templates
+- Adobe integration
+
+---
+
+### Advanced
+
+**Adobe Photoshop**:
+- Full control
+- Advanced editing
+- Professional output
+
+**Adobe Illustrator**:
+- Vector graphics
+- Scalable designs
+- Infographics
+
+**Figma**:
+- Collaborative design
+- Web-based
+- Component libraries
+
+---
+
+## Image Content Checklist
+
+Before publishing, verify:
+
+- [ ] Correct dimensions for platform
+- [ ] Text is readable at thumbnail size
+- [ ] High contrast for readability
+- [ ] Brand colors and fonts used
+- [ ] Logo included (if appropriate)
+- [ ] No spelling errors
+- [ ] Aligned and balanced layout
+- [ ] Exported at correct resolution
+- [ ] File size optimized
+- [ ] Accessible (alt text ready)
+
+---
+
+## Common Image Content Mistakes
+
+### ❌ Too Much Text
+Cramming paragraphs onto an image.
+
+### ✅ Concise Message
+3-7 words for social graphics, scannable for infographics.
+
+---
+
+### ❌ Low Contrast
+Text hard to read against background.
+
+### ✅ High Contrast
+Clear, readable text with background overlay if needed.
+
+---
+
+### ❌ Inconsistent Branding
+Different colors, fonts, styles each time.
+
+### ✅ Brand Consistency
+Same colors, fonts, and style across all graphics.
+
+---
+
+### ❌ Wrong Dimensions
+Image cropped awkwardly by platform.
+
+### ✅ Platform-Specific Sizing
+Correct dimensions for each platform.
+
+---
+
+## Usage
+
+Apply these guidelines when creating:
+- Social media graphics
+- Infographics
+- Thumbnails
+- Visual quotes
+- Announcement graphics
+- Educational visuals
+- Brand assets
+
+**Remember**: Visual content should be scannable in 3 seconds. If the message isn't immediately clear, simplify.

+ 73 - 0
plugins/claude-code/scripts/context/content-creation/formats/navigation.md

@@ -0,0 +1,73 @@
+<!-- Context: content-creation/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Content Formats Navigation
+
+Format-specific guidance for creating content across different mediums.
+
+---
+
+## Available Files
+
+### written-content.md
+Guidelines for written content (articles, blogs, posts, newsletters).
+
+**Topics**:
+- Article structure and flow
+- Blog post best practices
+- Social media post formats
+- Newsletter structure
+- SEO considerations
+- Readability optimization
+
+**Use for**: Articles, blog posts, social media, newsletters, long-form content
+
+---
+
+### video-content.md
+Guidelines for video content creation (scripts, ideas, formats).
+
+**Topics**:
+- Video script structure
+- Hook and retention strategies
+- Video content ideas by platform (YouTube, TikTok, Instagram)
+- Thumbnail and title optimization
+- Call-to-action placement
+- Video series planning
+
+**Use for**: YouTube videos, short-form video, video ads, tutorials
+
+---
+
+### image-content.md
+Guidelines for visual content creation (graphics, infographics, social images).
+
+**Topics**:
+- Visual hierarchy principles
+- Text overlay best practices
+- Infographic structure
+- Social media image specs
+- Visual content ideas
+- Brand consistency in visuals
+
+**Use for**: Social media graphics, infographics, thumbnails, visual quotes
+
+---
+
+### audio-content.md
+Guidelines for audio content (podcasts, voice content, audio ads).
+
+**Topics**:
+- Podcast episode structure
+- Audio script writing
+- Voice content best practices
+- Audio ad formats
+- Interview preparation
+- Audio storytelling techniques
+
+**Use for**: Podcasts, audio ads, voice content, audiobooks
+
+---
+
+## Usage
+
+Load the relevant format file when creating content for that specific medium to ensure format-appropriate structure, style, and optimization.

+ 476 - 0
plugins/claude-code/scripts/context/content-creation/formats/video-content.md

@@ -0,0 +1,476 @@
+<!-- Context: content-creation/video-content | Priority: low | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Video Content Guidelines
+
+Best practices for creating engaging video content across platforms: YouTube, TikTok, Instagram Reels, and video ads.
+
+---
+
+## Video Script Structure
+
+### Standard Video Flow
+
+**1. Hook (First 3 seconds)**
+- Visual hook (movement, text, face)
+- Verbal hook (compelling statement)
+- Pattern interrupt (unexpected element)
+
+**2. Promise (3-10 seconds)**
+- What they'll learn/get
+- Why it matters
+- Build anticipation
+
+**3. Content Delivery (Main Body)**
+- Deliver on the promise
+- Keep pace moving
+- Use visual variety
+
+**4. Call-to-Action (Last 5-10 seconds)**
+- Clear next step
+- Like, comment, subscribe
+- Link to related content
+
+---
+
+## Hook and Retention Strategies
+
+### First 3 Seconds Are Critical
+
+**Visual Hooks**:
+- Fast movement or action
+- Text overlay with bold claim
+- Close-up of face (emotion)
+- Unexpected visual
+- Before/after comparison
+
+**Verbal Hooks**:
+- Surprising statement
+- Bold claim
+- Question that resonates
+- Tease the payoff
+- Personal story opening
+
+**Pattern Interrupts**:
+- Sudden sound effect
+- Jump cut
+- Visual effect
+- Unexpected statement
+- Format change
+
+---
+
+### Retention Techniques Throughout
+
+**Pacing**:
+- Cut dead air ruthlessly
+- Change camera angle every 3-5 seconds
+- Vary shot types (close-up, medium, wide)
+- Use B-roll to illustrate points
+
+**Open Loops**:
+- Promise information later
+- "More on that in a minute..."
+- "Wait until you see what happens next..."
+- Build anticipation
+
+**Visual Variety**:
+- Text overlays for key points
+- Graphics and animations
+- B-roll footage
+- Screen recordings
+- Multiple camera angles
+
+**Verbal Engagement**:
+- Direct address ("You might be thinking...")
+- Questions to audience
+- Acknowledge objections
+- Personal asides
+- Humor and personality
+
+---
+
+## Platform-Specific Guidelines
+
+### YouTube
+
+**Video Length**:
+- Short-form (< 60 seconds): Quick tips, teasers
+- Mid-form (3-8 minutes): Tutorials, how-tos
+- Long-form (10-20+ minutes): Deep dives, vlogs
+
+**Structure**:
+- Hook (0-3 seconds)
+- Intro/Promise (3-15 seconds)
+- Content (main body)
+- Recap (optional)
+- CTA (end screen)
+
+**Optimization**:
+- Thumbnail: High contrast, clear text, expressive face
+- Title: Keyword-rich, compelling, 60 characters
+- Description: First 2 lines visible, include keywords
+- Tags: Relevant keywords and phrases
+- End screen: Subscribe + related videos
+
+**Best Practices**:
+- First 30 seconds determine retention
+- Pattern interrupt every 30-60 seconds
+- Use chapters for longer videos
+- Pin comment to drive engagement
+- Respond to comments quickly
+
+---
+
+### TikTok
+
+**Video Length**:
+- Optimal: 15-30 seconds
+- Can go up to 10 minutes
+- Shorter often performs better
+
+**Structure**:
+- Hook (first frame + first second)
+- Quick delivery (no fluff)
+- Payoff/punchline
+- Loop-friendly ending (optional)
+
+**Optimization**:
+- Captions: Auto-captions or manual
+- Sounds: Trending audio increases reach
+- Hashtags: Mix trending + niche (3-5 total)
+- Text overlay: Key points, emphasis
+- Posting time: Test your audience
+
+**Best Practices**:
+- Vertical format (9:16)
+- Fast-paced editing
+- Trend participation
+- Authentic, raw feel
+- Strong first frame (thumbnail)
+- Loop-friendly for rewatches
+
+---
+
+### Instagram Reels
+
+**Video Length**:
+- Optimal: 7-15 seconds
+- Can go up to 90 seconds
+- Shorter often performs better
+
+**Structure**:
+- Hook (first frame)
+- Quick value delivery
+- Clear payoff
+- CTA in caption
+
+**Optimization**:
+- Cover image: Choose compelling frame
+- Caption: Hook in first line
+- Hashtags: 3-5 relevant
+- Audio: Trending or original
+- Location tag: Increases reach
+
+**Best Practices**:
+- Vertical format (9:16)
+- Text overlays for sound-off viewing
+- Trending audio when relevant
+- High-quality visuals
+- Consistent posting schedule
+- Engage with comments quickly
+
+---
+
+### YouTube Shorts
+
+**Video Length**:
+- Maximum: 60 seconds
+- Optimal: 15-30 seconds
+
+**Structure**:
+- Immediate hook
+- Fast-paced content
+- Clear payoff
+- Loop-friendly
+
+**Optimization**:
+- Vertical format (9:16)
+- #Shorts in title or description
+- Compelling first frame
+- Text overlays
+- Trending topics
+
+**Best Practices**:
+- Repurpose TikTok/Reels content
+- Fast cuts and pacing
+- Clear, simple message
+- Strong visual hook
+- No watermarks from other platforms
+
+---
+
+## Video Content Ideas by Platform
+
+### YouTube Ideas
+
+**Educational**:
+- How-to tutorials
+- Explainer videos
+- Course-style series
+- Tool reviews
+- Case studies
+
+**Entertainment**:
+- Vlogs
+- Challenges
+- Reactions
+- Storytelling
+- Behind-the-scenes
+
+**Hybrid**:
+- "Day in the life" with lessons
+- Q&A with teaching moments
+- Mistakes and lessons learned
+
+---
+
+### Short-Form Ideas (TikTok/Reels/Shorts)
+
+**Quick Tips**:
+- One tip per video
+- Before/after demonstrations
+- Common mistakes
+- Quick wins
+
+**Trends**:
+- Trending audio with your twist
+- Challenge participation
+- Duets and stitches
+- Trending formats
+
+**Storytelling**:
+- Quick personal stories
+- Client success stories
+- Failure stories with lessons
+- "Things I wish I knew"
+
+**List Format**:
+- "3 ways to..."
+- "5 signs that..."
+- "Top mistakes in..."
+- Countdown format
+
+---
+
+## Thumbnail and Title Optimization
+
+### Thumbnail Best Practices
+
+**Visual Elements**:
+- High contrast colors
+- Clear, readable text (3-5 words max)
+- Expressive face (if applicable)
+- Bright, well-lit
+- Consistent branding
+
+**Text on Thumbnail**:
+- Large, bold font
+- High contrast with background
+- Complement title (don't repeat)
+- Create curiosity
+
+**Composition**:
+- Rule of thirds
+- Clear focal point
+- Not cluttered
+- Recognizable at small size
+
+---
+
+### Title Formulas
+
+**How-To**:
+- "How to [Result] in [Timeframe]"
+- "How to [Result] Without [Common Obstacle]"
+- "How I [Achieved Result]"
+
+**List**:
+- "[Number] Ways to [Result]"
+- "[Number] [Things] That [Result]"
+- "I Tried [Number] [Things]. Here's What Worked."
+
+**Curiosity**:
+- "The [Thing] Nobody Tells You About [Topic]"
+- "Why [Common Belief] Is Wrong"
+- "What [Event] Taught Me About [Topic]"
+
+**Result-Focused**:
+- "[Result] in [Timeframe]: Full Guide"
+- "From [Starting Point] to [End Point]"
+- "[Result] Without [Expected Requirement]"
+
+---
+
+## Call-to-Action Placement
+
+### When to Include CTAs
+
+**Early CTA (First 30 seconds)**:
+- "If you're new here, subscribe for..."
+- "Drop a comment if you've experienced..."
+- Sets expectation for engagement
+
+**Mid-Roll CTA**:
+- "If you're finding this helpful, hit like"
+- "Comment below with your thoughts"
+- Natural break in content
+
+**End CTA**:
+- "Subscribe for more content like this"
+- "Check out this related video"
+- "Link in description for..."
+
+---
+
+### CTA Best Practices
+
+**Be Specific**:
+❌ "Let me know what you think"
+✅ "Comment 'YES' if you want more content like this"
+
+**Give a Reason**:
+❌ "Subscribe to my channel"
+✅ "Subscribe so you don't miss the next video in this series"
+
+**Make it Easy**:
+❌ "Check out all my links"
+✅ "Link in bio for the free template"
+
+---
+
+## Video Series Planning
+
+### Series Formats
+
+**Educational Series**:
+- Multi-part tutorial
+- Course-style progression
+- Topic deep-dives
+- Tool mastery series
+
+**Recurring Content**:
+- Weekly tips
+- Monthly reviews
+- Q&A sessions
+- Behind-the-scenes
+
+**Challenge Series**:
+- 30-day challenge
+- Experiment documentation
+- Transformation journey
+
+---
+
+### Series Benefits
+
+**Audience Retention**:
+- Viewers return for next episode
+- Builds anticipation
+- Creates habit
+
+**Content Planning**:
+- Easier to batch create
+- Consistent posting schedule
+- Clear content calendar
+
+**Authority Building**:
+- Demonstrates expertise depth
+- Comprehensive coverage
+- Positions as go-to resource
+
+---
+
+## Video Production Checklist
+
+### Pre-Production
+
+- [ ] Script or outline prepared
+- [ ] Hook and CTA planned
+- [ ] Location and lighting checked
+- [ ] Equipment ready (camera, mic, lights)
+- [ ] B-roll list (if needed)
+
+### Production
+
+- [ ] Strong hook in first 3 seconds
+- [ ] Clear audio (no background noise)
+- [ ] Good lighting (face well-lit)
+- [ ] Stable footage (tripod or stabilization)
+- [ ] Multiple takes of key sections
+
+### Post-Production
+
+- [ ] Tight editing (cut dead air)
+- [ ] Text overlays for key points
+- [ ] B-roll inserted where relevant
+- [ ] Music/sound effects (if appropriate)
+- [ ] Color correction (if needed)
+- [ ] Captions/subtitles added
+
+### Publishing
+
+- [ ] Compelling thumbnail created
+- [ ] Optimized title (keywords + curiosity)
+- [ ] Description with keywords and links
+- [ ] Relevant tags/hashtags
+- [ ] End screen/cards added (YouTube)
+- [ ] Scheduled for optimal time
+
+---
+
+## Common Video Content Mistakes
+
+### ❌ Slow Start
+Taking 10+ seconds to get to the point.
+
+### ✅ Immediate Hook
+Value or intrigue in first 3 seconds.
+
+---
+
+### ❌ Talking Head Only
+Static shot with no visual variety.
+
+### ✅ Visual Variety
+B-roll, text overlays, multiple angles.
+
+---
+
+### ❌ Poor Audio
+Background noise, echo, inconsistent levels.
+
+### ✅ Clean Audio
+Clear voice, minimal background noise, consistent levels.
+
+---
+
+### ❌ No Clear CTA
+Video ends without telling viewers what to do.
+
+### ✅ Clear Next Step
+Specific action for viewers to take.
+
+---
+
+## Usage
+
+Apply these guidelines when creating:
+- YouTube videos (short and long-form)
+- TikTok content
+- Instagram Reels
+- YouTube Shorts
+- Video ads
+- Course content
+- Social media video
+
+**Remember**: The first 3 seconds determine if someone watches. The first 30 seconds determine if they stay. Optimize ruthlessly for both.

+ 409 - 0
plugins/claude-code/scripts/context/content-creation/formats/written-content.md

@@ -0,0 +1,409 @@
+<!-- Context: content-creation/written-content | Priority: low | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Written Content Guidelines
+
+Best practices for creating effective written content across formats: articles, blog posts, social media, newsletters, and long-form content.
+
+---
+
+## Article Structure
+
+### Standard Article Flow
+
+**1. Hook (First 50 words)**
+- Grab attention immediately
+- Promise clear value
+- Create curiosity
+
+**2. Problem/Context (100-200 words)**
+- Establish the problem or topic
+- Show why it matters
+- Build relevance
+
+**3. Main Content (Body)**
+- Deliver on the promise
+- Use clear structure (subheadings, lists)
+- Include examples and data
+
+**4. Conclusion (50-100 words)**
+- Summarize key points
+- Reinforce main takeaway
+- Clear call-to-action
+
+---
+
+## Blog Post Best Practices
+
+### Formatting for Readability
+
+**Short paragraphs**:
+- 1-3 sentences max
+- White space improves scanning
+- Mobile-friendly
+
+**Subheadings every 200-300 words**:
+- Break up long sections
+- Enable skimming
+- Improve SEO
+
+**Bullet points and lists**:
+- Easy to scan
+- Highlight key points
+- Increase engagement
+
+**Bold key phrases**:
+- Draw attention to important points
+- Help skimmers find value
+- Don't overuse (2-3 per section max)
+
+---
+
+### Blog Post Length Guidelines
+
+**Short-form (300-600 words)**:
+- Quick tips
+- News and updates
+- Opinion pieces
+- Social media-friendly
+
+**Medium-form (800-1500 words)**:
+- How-to guides
+- List posts
+- Case studies
+- Most versatile length
+
+**Long-form (2000+ words)**:
+- Comprehensive guides
+- In-depth tutorials
+- Research-backed content
+- SEO pillar content
+
+---
+
+### Blog Post Templates
+
+**How-To Post**:
+1. Hook with the problem
+2. Why this solution works
+3. Step-by-step instructions
+4. Common mistakes to avoid
+5. Next steps
+
+**List Post**:
+1. Hook with promise (X ways to Y)
+2. Brief intro
+3. Each item with explanation
+4. Summary of key points
+5. Call-to-action
+
+**Case Study**:
+1. Hook with result
+2. Starting situation
+3. Challenge/problem
+4. Solution/process
+5. Results and lessons
+6. How to apply it
+
+---
+
+## Social Media Posts
+
+### Platform-Specific Guidelines
+
+**Twitter/X**:
+- Hook in first line
+- Use line breaks for readability
+- Thread for longer content
+- End with engagement question or CTA
+
+**LinkedIn**:
+- Professional but personal tone
+- Story-driven content performs well
+- Use "see more" strategically
+- Include relevant hashtags (3-5)
+
+**Instagram**:
+- Visual-first, caption supports
+- Hook before "more" cutoff
+- Use emojis strategically
+- Hashtags in comments or end of caption
+
+**Facebook**:
+- Conversational tone
+- Questions drive engagement
+- Native video outperforms links
+- Community-focused content
+
+---
+
+### Social Post Structure
+
+**Pattern 1: Hook + Story + Lesson**
+```
+[Attention-grabbing first line]
+
+[Short story or example]
+
+[Key lesson or takeaway]
+
+[Call-to-action or question]
+```
+
+**Pattern 2: Problem + Agitation + Solution**
+```
+[Identify relatable problem]
+
+[Make it worse / show impact]
+
+[Offer solution or insight]
+
+[Next step]
+```
+
+**Pattern 3: List Format**
+```
+[Hook: X things about Y]
+
+1. [Point with brief explanation]
+2. [Point with brief explanation]
+3. [Point with brief explanation]
+
+[Closing thought or CTA]
+```
+
+---
+
+## Newsletter Structure
+
+### Email Newsletter Best Practices
+
+**Subject Line**:
+- 40-50 characters ideal
+- Create curiosity or promise value
+- Personalization when relevant
+- A/B test regularly
+
+**Preview Text**:
+- First 50-100 characters matter
+- Extend the subject line hook
+- Don't waste with "View in browser"
+
+**Opening**:
+- Personal greeting
+- Quick context or story
+- Promise what's in this email
+
+**Body**:
+- One main idea per email (or clear sections)
+- Scannable format
+- Links to full content if needed
+- Visual breaks (images, dividers)
+
+**Closing**:
+- Clear call-to-action
+- Personal sign-off
+- P.S. for secondary CTA or bonus
+
+---
+
+### Newsletter Types
+
+**Curated Newsletter**:
+- Intro with theme
+- 3-7 curated items
+- Brief commentary on each
+- Why it matters
+
+**Story Newsletter**:
+- Personal story or case study
+- Lesson or insight
+- How to apply it
+- Single clear CTA
+
+**Educational Newsletter**:
+- One main teaching point
+- Step-by-step or framework
+- Examples
+- Action item
+
+---
+
+## Long-Form Content
+
+### Long-Form Structure
+
+**Comprehensive Guide Structure**:
+1. Table of contents
+2. Introduction (why this matters)
+3. Main sections (3-7 major topics)
+4. Examples and case studies
+5. Common mistakes/FAQs
+6. Conclusion and next steps
+7. Resources and further reading
+
+---
+
+### Long-Form Best Practices
+
+**Navigation**:
+- Table of contents with jump links
+- Progress indicators
+- "Back to top" links
+- Clear section breaks
+
+**Engagement**:
+- Vary content types (text, images, examples)
+- Include interactive elements
+- Break up with quotes or callouts
+- Summarize key points in boxes
+
+**Retention**:
+- Deliver value early and often
+- Use open loops (promise info later)
+- Include surprising insights
+- Make it skimmable
+
+---
+
+## SEO Considerations
+
+### On-Page SEO Basics
+
+**Title Tag**:
+- Include target keyword
+- 50-60 characters
+- Compelling and clickable
+
+**Meta Description**:
+- 150-160 characters
+- Include keyword naturally
+- Promise clear value
+
+**Headings**:
+- H1 for main title (one per page)
+- H2 for main sections
+- H3 for subsections
+- Include keywords naturally
+
+**Internal Links**:
+- Link to related content
+- Use descriptive anchor text
+- Help readers find more value
+
+**Images**:
+- Descriptive file names
+- Alt text for accessibility and SEO
+- Compressed for speed
+
+---
+
+### Keyword Integration
+
+**Natural placement**:
+- Title and first paragraph
+- Subheadings where relevant
+- Throughout body naturally
+- Don't force or over-optimize
+
+**Semantic keywords**:
+- Related terms and phrases
+- Answer related questions
+- Cover topic comprehensively
+
+---
+
+## Readability Optimization
+
+### Readability Checklist
+
+- [ ] Grade level: 8th grade or below for general audience
+- [ ] Sentence length: Average 15-20 words
+- [ ] Paragraph length: 3 sentences or less
+- [ ] Active voice: 80%+ of sentences
+- [ ] Transition words: Connect ideas smoothly
+- [ ] Jargon: Explained or avoided
+- [ ] Examples: Concrete and relatable
+
+---
+
+### Readability Tools
+
+**Hemingway Editor**:
+- Highlights complex sentences
+- Identifies passive voice
+- Suggests simpler alternatives
+
+**Grammarly**:
+- Grammar and spelling
+- Tone detection
+- Clarity suggestions
+
+**Yoast SEO** (WordPress):
+- Readability analysis
+- SEO optimization
+- Content structure
+
+---
+
+## Content Quality Checklist
+
+Before publishing, verify:
+
+- [ ] Hook grabs attention in first 50 words
+- [ ] Clear value proposition
+- [ ] Scannable format (headings, lists, bold)
+- [ ] Short paragraphs (1-3 sentences)
+- [ ] Examples and specifics (not just theory)
+- [ ] Clear call-to-action
+- [ ] Proofread for errors
+- [ ] Links work and are relevant
+- [ ] Images optimized and have alt text
+- [ ] Mobile-friendly formatting
+
+---
+
+## Common Written Content Mistakes
+
+### ❌ Burying the Lead
+Starting with background instead of value.
+
+### ✅ Lead with Value
+Put the most important information first.
+
+---
+
+### ❌ Walls of Text
+Long paragraphs that are hard to read.
+
+### ✅ White Space
+Short paragraphs with visual breaks.
+
+---
+
+### ❌ Vague Promises
+"This will help you improve your content."
+
+### ✅ Specific Value
+"Learn the 3-second hook formula that increased my engagement 300%."
+
+---
+
+### ❌ No Clear CTA
+Ending without telling readers what to do next.
+
+### ✅ Clear Next Step
+"Try this framework on your next post and let me know how it works."
+
+---
+
+## Usage
+
+Apply these guidelines when creating:
+- Blog posts and articles
+- Social media content
+- Email newsletters
+- Landing page copy
+- Long-form guides
+- Any written content
+
+**Remember**: Write for humans first, optimize for algorithms second. Clarity and value always win.

+ 56 - 0
plugins/claude-code/scripts/context/content-creation/navigation.md

@@ -0,0 +1,56 @@
+<!-- Context: content-creation/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Content Creation Navigation
+
+Context for creating compelling content across all formats and channels.
+
+---
+
+## Structure
+
+```
+content-creation/
+├── principles/      # Core writing principles & frameworks
+├── formats/         # Format-specific guidance (written, video, image, audio)
+├── workflows/       # Content planning & production workflows
+└── examples/        # Real-world content examples
+```
+
+---
+
+## Quick Routes
+
+| Need | Path |
+|------|------|
+| **Copywriting frameworks** | `principles/copywriting-frameworks.md` |
+| **Brand voice & tone** | `principles/tone-voice.md` |
+| **Write hooks** | `principles/hooks.md` |
+| **Audience targeting** | `principles/audience-targeting.md` |
+| **Written content** | `formats/written-content.md` |
+| **Video content** | `formats/video-content.md` |
+| **Image content** | `formats/image-content.md` |
+| **Content planning** | `workflows/content-matrix.md` |
+| **Content ideas** | `workflows/content-ideas.md` |
+| **Remix content** | `workflows/remix-repurpose.md` |
+
+---
+
+## By Subcategory
+
+**principles/** - Core writing principles → `principles/navigation.md`
+**formats/** - Format-specific guidance → `formats/navigation.md`
+**workflows/** - Planning & production → `workflows/navigation.md`
+**examples/** - Real-world examples → `examples/navigation.md`
+
+---
+
+## Usage
+
+Content creation agents load these files to:
+- Apply proven copywriting frameworks
+- Maintain consistent brand voice
+- Create format-appropriate content
+- Plan and organize content production
+- Generate ideas and remix existing content
+
+Load the relevant subcategory navigation to explore available context files.

+ 372 - 0
plugins/claude-code/scripts/context/content-creation/principles/audience-targeting.md

@@ -0,0 +1,372 @@
+<!-- Context: content-creation/audience-targeting | Priority: low | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Audience Targeting
+
+Understanding and targeting specific audiences to create content that resonates and converts.
+
+---
+
+## Why Audience Targeting Matters
+
+**Generic content fails**:
+- Trying to speak to everyone means speaking to no one
+- Specific, targeted content outperforms generic content 10:1
+- Understanding your audience enables precise messaging
+
+---
+
+## Audience Research Methods
+
+### 1. Direct Conversations
+Talk to your audience directly.
+
+**Methods**:
+- Customer interviews
+- Social media DMs
+- Comment section engagement
+- Email replies
+- Community forums
+
+**Questions to ask**:
+- What's your biggest challenge with [topic]?
+- What have you tried that didn't work?
+- What would success look like for you?
+- What's holding you back?
+
+---
+
+### 2. Data Analysis
+Use data to understand behavior patterns.
+
+**Sources**:
+- Website analytics (pages visited, time spent)
+- Social media insights (engagement patterns)
+- Email metrics (open rates, click patterns)
+- Search data (what they're searching for)
+- Purchase behavior
+
+**Look for**:
+- Most engaged content topics
+- Common questions and pain points
+- Language and terminology used
+- Content format preferences
+
+---
+
+### 3. Social Listening
+Monitor conversations in your audience's spaces.
+
+**Where to listen**:
+- Reddit communities
+- Facebook groups
+- Twitter/X conversations
+- LinkedIn discussions
+- Niche forums
+- YouTube comments
+
+**What to capture**:
+- Common complaints
+- Frequently asked questions
+- Language and phrases used
+- Emotional triggers
+- Competing solutions discussed
+
+---
+
+### 4. Competitor Analysis
+Study what's working for competitors.
+
+**Analyze**:
+- Their most engaged content
+- Comment sections (what resonates)
+- Content gaps (what they're missing)
+- Audience complaints
+- Positioning and messaging
+
+---
+
+## Persona Development
+
+### Basic Persona Template
+
+**Demographics**:
+- Age range
+- Location
+- Job title/role
+- Income level
+- Education
+
+**Psychographics**:
+- Goals and aspirations
+- Fears and frustrations
+- Values and beliefs
+- Interests and hobbies
+- Information sources
+
+**Behavioral**:
+- Content consumption habits
+- Purchase decision process
+- Preferred platforms
+- Engagement patterns
+- Objections and barriers
+
+---
+
+### Persona Example: "Struggling Content Creator Sarah"
+
+**Demographics**:
+- Age: 28-35
+- Location: Urban areas
+- Role: Freelance content creator / side hustler
+- Income: $30-60k/year
+
+**Goals**:
+- Build consistent audience
+- Monetize content
+- Quit day job eventually
+
+**Frustrations**:
+- Content gets no engagement
+- Inconsistent results
+- Overwhelmed by advice
+- Limited time and resources
+
+**Fears**:
+- Wasting time on content nobody sees
+- Being too late to the game
+- Not being good enough
+- Never achieving financial freedom
+
+**Language**:
+- "I'm putting in the work but not seeing results"
+- "I don't know what I'm doing wrong"
+- "Everyone else seems to have it figured out"
+- "I just want a clear path forward"
+
+**Content preferences**:
+- Actionable, step-by-step guides
+- Real examples and case studies
+- Quick wins and fast results
+- Honest, no-BS advice
+
+---
+
+## Pain Points and Desires Mapping
+
+### Pain Points Framework
+
+**Surface-level pain**: What they say
+- "I need more followers"
+- "My content doesn't get engagement"
+
+**Deeper pain**: What they mean
+- "I feel invisible and unheard"
+- "I'm afraid I'm wasting my time"
+
+**Core pain**: What drives them
+- "I want to feel valued and successful"
+- "I need financial security and freedom"
+
+---
+
+### Desires Framework
+
+**Surface-level desire**: What they ask for
+- "I want to go viral"
+- "I want more subscribers"
+
+**Deeper desire**: What they really want
+- "I want validation and recognition"
+- "I want to build something meaningful"
+
+**Core desire**: What truly motivates them
+- "I want freedom and control over my life"
+- "I want to make an impact"
+
+---
+
+## Language and Tone Adaptation
+
+### Match Their Language
+
+**Don't say**: "Leverage synergistic content strategies"
+**Do say**: "Create content that actually works"
+
+**Don't say**: "Optimize your content funnel"
+**Do say**: "Turn readers into customers"
+
+**Don't say**: "Implement a multi-channel approach"
+**Do say**: "Post where your audience hangs out"
+
+---
+
+### Tone by Audience Sophistication
+
+**Beginner audience**:
+- Simple, jargon-free language
+- Step-by-step explanations
+- Encouraging and supportive tone
+- Lots of examples
+
+**Intermediate audience**:
+- Some industry terms (but explained)
+- Focus on optimization and improvement
+- Practical, actionable advice
+- Case studies and data
+
+**Advanced audience**:
+- Industry terminology expected
+- Nuanced, strategic insights
+- Challenge conventional thinking
+- Deep dives and analysis
+
+---
+
+### Emotional Tone Matching
+
+**Frustrated audience**:
+- Acknowledge their frustration
+- Show empathy and understanding
+- Offer hope and a clear path forward
+- Be direct and honest
+
+**Ambitious audience**:
+- Inspire and challenge
+- Show what's possible
+- Provide advanced strategies
+- Celebrate wins
+
+**Skeptical audience**:
+- Lead with proof and data
+- Address objections upfront
+- Be transparent about limitations
+- Build trust through honesty
+
+---
+
+## Audience Segmentation
+
+### Segmentation Dimensions
+
+**By awareness level**:
+- Unaware (don't know problem exists)
+- Problem-aware (know problem, not solution)
+- Solution-aware (know solutions exist)
+- Product-aware (know your solution)
+- Most aware (ready to buy)
+
+**By experience level**:
+- Beginner (just starting)
+- Intermediate (some experience)
+- Advanced (expert level)
+
+**By goal**:
+- Quick wins (want fast results)
+- Long-term growth (building for future)
+- Specific outcome (clear goal in mind)
+
+**By barrier**:
+- Time-constrained
+- Budget-constrained
+- Knowledge-constrained
+- Confidence-constrained
+
+---
+
+### Content Adaptation by Segment
+
+**For beginners**:
+- "Getting Started" guides
+- Basic concepts explained
+- Step-by-step tutorials
+- Common mistakes to avoid
+
+**For intermediate**:
+- Optimization strategies
+- Advanced techniques
+- Case studies
+- Comparison content
+
+**For advanced**:
+- Cutting-edge strategies
+- Nuanced insights
+- Industry analysis
+- Thought leadership
+
+---
+
+## Audience Targeting Checklist
+
+Before creating content, verify:
+
+- [ ] I know exactly who this is for
+- [ ] I understand their specific pain point
+- [ ] I know what outcome they want
+- [ ] I'm using language they use
+- [ ] The tone matches their emotional state
+- [ ] The content depth matches their level
+- [ ] I'm addressing their specific objections
+- [ ] The format matches their preferences
+
+---
+
+## Common Targeting Mistakes
+
+### ❌ Too Broad
+"This is for anyone who wants to grow their business."
+
+### ✅ Specific
+"This is for freelance content creators who are getting views but no engagement."
+
+---
+
+### ❌ Assuming Knowledge
+Using jargon without explanation for beginner audiences.
+
+### ✅ Meeting Them Where They Are
+Explaining concepts in their language at their level.
+
+---
+
+### ❌ Ignoring Emotional State
+Focusing only on tactics without addressing feelings.
+
+### ✅ Emotional Resonance
+Acknowledging how they feel and why it matters.
+
+---
+
+## Audience Research Template
+
+Use this template for each content piece:
+
+**Target Audience**: [Specific description]
+
+**Their Current Situation**: [Where they are now]
+
+**Their Desired Outcome**: [Where they want to be]
+
+**Their Main Pain Point**: [What's frustrating them]
+
+**Their Main Objection**: [What's holding them back]
+
+**Language They Use**: [Exact phrases and terms]
+
+**Emotional State**: [How they're feeling]
+
+**Content Depth Needed**: [Beginner/Intermediate/Advanced]
+
+**Preferred Format**: [Blog/Video/Social/Email]
+
+---
+
+## Usage
+
+Apply audience targeting to:
+- Content planning (what to create)
+- Messaging (how to say it)
+- Tone and voice (emotional resonance)
+- Format selection (where to publish)
+- Call-to-action (what to ask for)
+
+**Remember**: The more specific your audience targeting, the more your content will resonate and convert.

+ 286 - 0
plugins/claude-code/scripts/context/content-creation/principles/copywriting-frameworks.md

@@ -0,0 +1,286 @@
+<!-- Context: content-creation/copywriting-frameworks | Priority: low | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Copywriting Frameworks
+
+**Category**: content  
+**Purpose**: Proven copywriting frameworks and persuasive writing techniques  
+**Used by**: copywriter
+
+---
+
+## Overview
+
+Effective copywriting follows proven frameworks that guide readers through awareness, interest, desire, and action. This guide covers the most effective frameworks for different contexts.
+
+## Core Frameworks
+
+### 1. AIDA (Attention, Interest, Desire, Action)
+
+**Classic framework for persuasive copy**:
+
+**Attention**: Grab attention with a compelling headline
+```
+"Stop Wasting Hours on Manual Data Entry"
+```
+
+**Interest**: Build interest with relevant benefits
+```
+"Our automation tool processes 1000 entries in minutes, 
+not hours. No coding required."
+```
+
+**Desire**: Create desire by showing transformation
+```
+"Join 10,000+ businesses that saved 20 hours per week 
+and reduced errors by 95%."
+```
+
+**Action**: Clear call-to-action
+```
+"Start Your Free 14-Day Trial - No Credit Card Required"
+```
+
+### 2. PAS (Problem, Agitate, Solve)
+
+**Effective for pain-point driven copy**:
+
+**Problem**: Identify the reader's problem
+```
+"Struggling to keep your team aligned on project deadlines?"
+```
+
+**Agitate**: Amplify the pain
+```
+"Missed deadlines lead to frustrated clients, lost revenue, 
+and team burnout. Every day without a solution costs you money."
+```
+
+**Solve**: Present your solution
+```
+"ProjectSync keeps everyone on the same page with real-time 
+updates, automated reminders, and visual timelines."
+```
+
+### 3. BAB (Before, After, Bridge)
+
+**Show transformation clearly**:
+
+**Before**: Current state (pain)
+```
+"You're spending 3 hours daily answering the same customer 
+questions via email."
+```
+
+**After**: Desired state (pleasure)
+```
+"Imagine having those 3 hours back to focus on growing your 
+business while customers get instant answers 24/7."
+```
+
+**Bridge**: How to get there
+```
+"Our AI chatbot learns from your knowledge base and handles 
+80% of customer inquiries automatically."
+```
+
+### 4. FAB (Features, Advantages, Benefits)
+
+**Product-focused framework**:
+
+**Features**: What it is
+```
+"Built-in analytics dashboard with real-time reporting"
+```
+
+**Advantages**: What it does
+```
+"Track campaign performance instantly without switching tools"
+```
+
+**Benefits**: What it means for them
+```
+"Make data-driven decisions faster and increase ROI by 30%"
+```
+
+### 5. The 4 Ps (Picture, Promise, Prove, Push)
+
+**Storytelling approach**:
+
+**Picture**: Paint a vivid picture
+```
+"Picture this: It's Monday morning. Instead of drowning in 
+emails, you're reviewing last week's wins with your team."
+```
+
+**Promise**: Make a clear promise
+```
+"We'll help you reclaim 10 hours per week by automating 
+your busywork."
+```
+
+**Prove**: Back it up with evidence
+```
+"Over 5,000 teams have saved an average of 12 hours weekly. 
+Here's what they say..."
+```
+
+**Push**: Call to action
+```
+"Join them today - start your free trial now."
+```
+
+## Headline Formulas
+
+### 1. How-To Headlines
+```
+"How to [Achieve Desired Result] Without [Common Obstacle]"
+"How to Double Your Sales in 30 Days Without Paid Ads"
+```
+
+### 2. Number Headlines
+```
+"[Number] Ways to [Achieve Result]"
+"7 Proven Strategies to Boost Email Open Rates"
+```
+
+### 3. Question Headlines
+```
+"Are You Making These [Number] [Mistakes]?"
+"Are You Making These 5 SEO Mistakes?"
+```
+
+### 4. Negative Headlines
+```
+"Stop [Doing Wrong Thing] and Start [Doing Right Thing]"
+"Stop Guessing and Start Growing with Data-Driven Marketing"
+```
+
+### 5. Benefit-Driven Headlines
+```
+"[Achieve Result] in [Timeframe] with [Solution]"
+"Launch Your Online Store in 24 Hours with Shopify"
+```
+
+## Emotional Triggers
+
+### 1. Fear of Missing Out (FOMO)
+```
+"Limited spots available - only 10 left"
+"Offer ends tonight at midnight"
+"Join 50,000 early adopters"
+```
+
+### 2. Social Proof
+```
+"Trusted by Fortune 500 companies"
+"4.9/5 stars from 10,000+ reviews"
+"As featured in Forbes, TechCrunch, and Wired"
+```
+
+### 3. Authority
+```
+"Recommended by industry experts"
+"Developed by former Google engineers"
+"Award-winning customer support"
+```
+
+### 4. Reciprocity
+```
+"Free 30-day trial - no credit card required"
+"Download our free guide"
+"Get instant access to our resource library"
+```
+
+### 5. Scarcity
+```
+"Only 5 seats left for this cohort"
+"Flash sale - 24 hours only"
+"Limited edition - won't be restocked"
+```
+
+## Writing Techniques
+
+### 1. Power Words
+
+**Action words**:
+- Discover, Unlock, Transform, Boost, Accelerate
+- Proven, Guaranteed, Exclusive, Limited, Secret
+
+**Emotional words**:
+- Amazing, Incredible, Stunning, Revolutionary
+- Effortless, Simple, Easy, Quick, Instant
+
+### 2. Sensory Language
+
+**Engage the senses**:
+```
+Instead of: "Good coffee"
+Write: "Rich, aromatic coffee with notes of dark chocolate"
+
+Instead of: "Fast software"
+Write: "Lightning-fast software that responds instantly"
+```
+
+### 3. Specificity
+
+**Be concrete, not vague**:
+```
+Vague: "Save money"
+Specific: "Save $1,247 per year"
+
+Vague: "Many customers"
+Specific: "12,847 customers in 47 countries"
+```
+
+### 4. Active Voice
+
+**Use active, not passive**:
+```
+Passive: "Your data is protected by encryption"
+Active: "We encrypt your data with military-grade security"
+```
+
+## Best Practices
+
+1. **Know your audience** - Write for one specific person
+2. **Focus on benefits, not features** - What's in it for them?
+3. **Use simple language** - Write at 8th-grade reading level
+4. **Create urgency** - Give readers a reason to act now
+5. **Tell stories** - Stories are memorable and persuasive
+6. **Use social proof** - Testimonials, case studies, numbers
+7. **Remove friction** - Make it easy to take action
+8. **Test everything** - A/B test headlines, CTAs, copy
+9. **Edit ruthlessly** - Cut unnecessary words
+10. **Read it aloud** - Does it sound natural?
+
+## Anti-Patterns
+
+- ❌ **Jargon and buzzwords** - Confuses readers
+- ❌ **Passive voice** - Weakens your message
+- ❌ **Vague claims** - "Best in class" without proof
+- ❌ **Too many CTAs** - Confuses and dilutes action
+- ❌ **Focusing on features** - Readers care about benefits
+- ❌ **Long paragraphs** - Hard to scan and read
+- ❌ **No clear value proposition** - Why should they care?
+- ❌ **Ignoring objections** - Address concerns proactively
+
+## Copy Checklist
+
+Before publishing, ask:
+- [ ] Does the headline grab attention?
+- [ ] Is the value proposition clear in 5 seconds?
+- [ ] Are benefits emphasized over features?
+- [ ] Is there social proof or credibility?
+- [ ] Is there a clear, compelling CTA?
+- [ ] Have I addressed objections?
+- [ ] Is the copy scannable (headers, bullets, short paragraphs)?
+- [ ] Does it pass the "so what?" test?
+- [ ] Is it free of jargon and complex language?
+- [ ] Have I created urgency or scarcity?
+
+## References
+
+- Breakthrough Advertising by Eugene Schwartz
+- The Copywriter's Handbook by Robert Bly
+- Influence by Robert Cialdini
+- Made to Stick by Chip & Dan Heath

+ 242 - 0
plugins/claude-code/scripts/context/content-creation/principles/hooks.md

@@ -0,0 +1,242 @@
+<!-- Context: content-creation/hooks | Priority: low | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Writing Compelling Hooks
+
+Techniques for creating attention-grabbing openings that make people want to keep reading, watching, or listening.
+
+---
+
+## Why Hooks Matter
+
+**First 3 seconds are critical**:
+- 80% of people decide to continue or leave within 3 seconds
+- Hooks determine whether your content gets consumed or ignored
+- Strong hooks increase engagement, shares, and conversions
+
+---
+
+## Hook Types
+
+### 1. Question Hook
+Ask a question that resonates with your audience's pain points or desires.
+
+**Examples**:
+- "Ever wonder why some content goes viral while yours gets ignored?"
+- "What if I told you there's a better way to write hooks?"
+- "Are you making these 3 fatal mistakes in your content?"
+
+**Best for**: Blog posts, emails, social media
+
+---
+
+### 2. Statistic Hook
+Lead with a surprising or compelling statistic.
+
+**Examples**:
+- "95% of content gets zero engagement. Here's why."
+- "The average person scrolls past 300 posts per day. Here's how to stop them."
+- "I analyzed 10,000 viral posts. Here's what they all had in common."
+
+**Best for**: Data-driven content, credibility building
+
+---
+
+### 3. Story Hook
+Start with a relatable story or scenario.
+
+**Examples**:
+- "I spent 6 months creating content that nobody read. Then I changed one thing..."
+- "Picture this: You hit publish on your best work yet. Crickets."
+- "Three years ago, I was exactly where you are now..."
+
+**Best for**: Personal content, case studies, testimonials
+
+---
+
+### 4. Bold Claim Hook
+Make a provocative or counterintuitive statement.
+
+**Examples**:
+- "Everything you know about content marketing is wrong."
+- "You don't need more content. You need better hooks."
+- "The secret to viral content has nothing to do with quality."
+
+**Best for**: Thought leadership, contrarian takes, attention-grabbing
+
+---
+
+### 5. Problem-Agitation Hook
+Identify a problem and agitate it before offering a solution.
+
+**Examples**:
+- "Your content is invisible. Not because it's bad, but because nobody sees it."
+- "You're working twice as hard and getting half the results. Sound familiar?"
+- "Every day you wait, your competitors are stealing your audience."
+
+**Best for**: Sales copy, problem-solution content
+
+---
+
+### 6. Curiosity Gap Hook
+Create intrigue by hinting at valuable information without revealing it.
+
+**Examples**:
+- "The one thing nobody tells you about content creation..."
+- "I discovered something that changed everything. Here's what happened."
+- "There's a hidden pattern in all viral content. Once you see it, you can't unsee it."
+
+**Best for**: Clickable content, social media, email subject lines
+
+---
+
+## First Sentence Formulas
+
+### Formula 1: Problem + Promise
+"[Problem] is killing your results. Here's how to fix it."
+
+### Formula 2: Surprising Fact + Explanation
+"[Surprising fact]. Here's why it matters."
+
+### Formula 3: Personal Story + Lesson
+"I [did something]. Here's what I learned."
+
+### Formula 4: Question + Answer Preview
+"[Question]? The answer might surprise you."
+
+### Formula 5: Bold Statement + Proof
+"[Bold claim]. Here's the data to prove it."
+
+---
+
+## Opening Patterns by Format
+
+### Blog Posts
+- Start with a question or statistic
+- Use 1-2 sentence paragraphs for easy scanning
+- Promise value in the first 50 words
+
+### Videos
+- Visual hook in first 3 seconds (movement, text, face)
+- Verbal hook in first 5 seconds
+- Pattern interrupt (unexpected sound, visual, statement)
+
+### Social Media Posts
+- Hook in first line (before "see more")
+- Use line breaks to create curiosity
+- Emoji or formatting to stand out
+
+### Emails
+- Subject line = hook
+- First sentence reinforces the hook
+- Preview text extends the curiosity
+
+### Podcasts
+- Tease the most valuable insight upfront
+- Use a story or surprising fact
+- Promise a clear takeaway
+
+---
+
+## Attention Retention Techniques
+
+### Open Loops
+Create questions or promises early that you answer later.
+
+**Example**: "I'll share the exact framework at the end, but first..."
+
+### Pattern Interrupts
+Break expected patterns to recapture attention.
+
+**Examples**:
+- Sudden format change
+- Unexpected question
+- Contrarian statement
+- Personal aside
+
+### Value Stacking
+Continuously promise and deliver value throughout.
+
+**Example**: "Not only will you learn X, but I'll also show you Y and Z."
+
+### Micro-Commitments
+Get small agreements that lead to continued engagement.
+
+**Example**: "If you've ever felt this way, keep reading..."
+
+---
+
+## Hook Testing Checklist
+
+Before publishing, ask:
+
+- [ ] Does it grab attention in the first 3 seconds?
+- [ ] Does it create curiosity or promise value?
+- [ ] Is it relevant to my target audience?
+- [ ] Does it align with the content that follows?
+- [ ] Would I stop scrolling for this?
+- [ ] Is it specific rather than generic?
+- [ ] Does it trigger an emotional response?
+
+---
+
+## Common Hook Mistakes
+
+### ❌ Too Generic
+"In this post, I'll talk about content creation."
+
+### ✅ Specific and Compelling
+"The 3-second rule that determines if your content lives or dies."
+
+---
+
+### ❌ Burying the Lead
+Starting with background info instead of the hook.
+
+### ✅ Lead with Value
+Put the most compelling information first.
+
+---
+
+### ❌ Overpromising
+Making claims you can't deliver on.
+
+### ✅ Honest Value
+Promise what you can actually deliver.
+
+---
+
+## Hook Templates
+
+### For How-To Content
+- "How to [achieve desired outcome] without [common obstacle]"
+- "The [number]-step process to [desired result]"
+- "[Desired outcome] in [timeframe]: Here's how"
+
+### For List Content
+- "[Number] [things] that [result]"
+- "I tried [number] [things]. Here's what worked."
+- "The only [number] [things] you need to [result]"
+
+### For Case Studies
+- "How I [achieved result] in [timeframe]"
+- "From [starting point] to [end point]: The full story"
+- "[Result] without [expected requirement]: Here's how"
+
+### For Opinion/Thought Leadership
+- "Why [common belief] is wrong"
+- "The truth about [topic] nobody talks about"
+- "[Controversial take] and why it matters"
+
+---
+
+## Usage
+
+Apply these hook techniques to:
+- Blog post openings
+- Video intros
+- Social media posts
+- Email subject lines and openings
+- Podcast intros
+- Landing page headlines
+
+**Remember**: The hook's job is to get people to consume the next sentence, not to tell the whole story.

+ 72 - 0
plugins/claude-code/scripts/context/content-creation/principles/navigation.md

@@ -0,0 +1,72 @@
+<!-- Context: content-creation/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Content Principles Navigation
+
+Core writing principles, frameworks, and techniques for effective content creation.
+
+---
+
+## Available Files
+
+### copywriting-frameworks.md
+Proven copywriting frameworks and persuasive writing techniques.
+
+**Topics**:
+- AIDA, PAS, BAB, FAB frameworks
+- Headline formulas
+- Emotional triggers (FOMO, social proof, authority)
+- Power words and sensory language
+- Copy checklist
+
+**Use for**: Sales copy, landing pages, email campaigns, ads
+
+---
+
+### tone-voice.md
+Maintaining consistent brand voice and adapting tone for different contexts.
+
+**Topics**:
+- Voice vs. tone distinction
+- Voice dimensions (formality, enthusiasm, expertise)
+- Tone guidelines by context (marketing, docs, errors, support)
+- Emotional tone mapping
+- Brand voice examples
+
+**Use for**: All content to maintain brand consistency
+
+---
+
+### hooks.md
+Techniques for writing compelling hooks that grab attention.
+
+**Topics**:
+- Hook types (question, statistic, story, bold claim)
+- First sentence formulas
+- Opening patterns by format
+- Attention retention techniques
+
+**Use for**: Blog posts, videos, social media, emails
+
+---
+
+### audience-targeting.md
+Understanding and targeting specific audiences effectively.
+
+**Topics**:
+- Audience research methods
+- Persona development
+- Pain points and desires mapping
+- Language and tone adaptation
+- Audience segmentation
+
+**Use for**: All content to ensure audience fit
+
+---
+
+## Usage
+
+Load these files when creating any content to ensure:
+- Persuasive, engaging writing
+- Consistent brand voice
+- Audience-appropriate messaging
+- Attention-grabbing openings

+ 348 - 0
plugins/claude-code/scripts/context/content-creation/principles/tone-voice.md

@@ -0,0 +1,348 @@
+<!-- Context: content-creation/tone-voice | Priority: low | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Tone & Voice Guidelines
+
+**Category**: content  
+**Purpose**: Maintaining consistent brand voice and adapting tone for different contexts  
+**Used by**: copywriter, technical-writer
+
+---
+
+## Overview
+
+Voice is your brand's personality - it stays consistent. Tone is how that voice adapts to different situations and audiences. This guide helps maintain consistency while being contextually appropriate.
+
+## Voice vs. Tone
+
+### Voice (Consistent)
+Your brand's personality that never changes:
+- Professional but approachable
+- Knowledgeable but not condescending
+- Confident but humble
+- Clear and direct
+
+### Tone (Adaptive)
+How voice adapts to context:
+- **Error messages**: Apologetic, helpful
+- **Success messages**: Encouraging, celebratory
+- **Marketing**: Enthusiastic, persuasive
+- **Documentation**: Clear, instructional
+- **Support**: Empathetic, solution-focused
+
+## Voice Dimensions
+
+### 1. Formality Spectrum
+
+**Formal** ←→ **Casual**
+
+**Formal**:
+```
+"We appreciate your business and look forward to serving you."
+```
+
+**Casual**:
+```
+"Thanks for choosing us! We're excited to work with you."
+```
+
+**Choose based on**:
+- Industry norms
+- Audience expectations
+- Context (legal vs. social)
+
+### 2. Enthusiasm Spectrum
+
+**Reserved** ←→ **Enthusiastic**
+
+**Reserved**:
+```
+"Your account has been created successfully."
+```
+
+**Enthusiastic**:
+```
+"Welcome aboard! Your account is ready to go! 🎉"
+```
+
+**Choose based on**:
+- Moment significance
+- User emotional state
+- Brand personality
+
+### 3. Expertise Spectrum
+
+**Educational** ←→ **Expert**
+
+**Educational**:
+```
+"Let's walk through this step by step. First, click the 
+'Settings' button in the top right corner."
+```
+
+**Expert**:
+```
+"Navigate to Settings > Advanced > API Configuration."
+```
+
+**Choose based on**:
+- User expertise level
+- Content complexity
+- Context (onboarding vs. advanced docs)
+
+## Tone Guidelines by Context
+
+### 1. Marketing Copy
+
+**Characteristics**:
+- Enthusiastic and persuasive
+- Benefit-focused
+- Action-oriented
+- Emotionally engaging
+
+**Example**:
+```
+"Transform your workflow in minutes, not months. Join 10,000+ 
+teams who've already made the switch."
+```
+
+### 2. Product Documentation
+
+**Characteristics**:
+- Clear and instructional
+- Step-by-step
+- Neutral tone
+- Technically accurate
+
+**Example**:
+```
+"To configure authentication:
+1. Navigate to Settings > Security
+2. Click 'Add Authentication Method'
+3. Select your preferred provider"
+```
+
+### 3. Error Messages
+
+**Characteristics**:
+- Apologetic but not overly so
+- Explain what happened
+- Provide clear next steps
+- Never blame the user
+
+**Bad**:
+```
+"Error: Invalid input. Try again."
+```
+
+**Good**:
+```
+"We couldn't process your request because the email format 
+isn't valid. Please check and try again."
+```
+
+### 4. Success Messages
+
+**Characteristics**:
+- Positive and encouraging
+- Confirm what happened
+- Suggest next steps
+- Celebrate wins
+
+**Example**:
+```
+"Great! Your changes have been saved. Ready to publish?"
+```
+
+### 5. Support Communication
+
+**Characteristics**:
+- Empathetic and understanding
+- Solution-focused
+- Patient and helpful
+- Personalized
+
+**Example**:
+```
+"I understand how frustrating this must be. Let's get this 
+sorted out for you. Can you tell me what you see when you 
+click the 'Export' button?"
+```
+
+### 6. Onboarding
+
+**Characteristics**:
+- Welcoming and encouraging
+- Educational without overwhelming
+- Progressive disclosure
+- Celebrate small wins
+
+**Example**:
+```
+"Welcome! Let's get you set up in 3 quick steps. 
+First, let's create your workspace."
+```
+
+## Writing Principles
+
+### 1. Be Clear and Concise
+
+**Before**:
+```
+"In order to facilitate the process of account creation, 
+it is necessary for you to provide your email address."
+```
+
+**After**:
+```
+"Enter your email to create your account."
+```
+
+### 2. Use Active Voice
+
+**Passive**:
+```
+"Your password has been reset by our system."
+```
+
+**Active**:
+```
+"We've reset your password."
+```
+
+### 3. Write for Humans
+
+**Robotic**:
+```
+"Operation completed successfully. Proceed to next step."
+```
+
+**Human**:
+```
+"All set! What would you like to do next?"
+```
+
+### 4. Be Inclusive
+
+**Exclusive**:
+```
+"Hey guys, check out our new feature!"
+```
+
+**Inclusive**:
+```
+"Check out our new feature!"
+```
+
+### 5. Avoid Jargon
+
+**Jargon-heavy**:
+```
+"Leverage our API to synergize your tech stack."
+```
+
+**Clear**:
+```
+"Connect our API to your existing tools."
+```
+
+## Emotional Tone Mapping
+
+### User Emotional State → Appropriate Tone
+
+**User is frustrated** → Empathetic, solution-focused
+```
+"I know this is frustrating. Let's fix this together."
+```
+
+**User achieved something** → Celebratory, encouraging
+```
+"Awesome work! You've completed your first project."
+```
+
+**User is confused** → Patient, educational
+```
+"No worries! Let me break this down for you."
+```
+
+**User made an error** → Helpful, non-judgmental
+```
+"Looks like there's a small issue. Here's how to fix it."
+```
+
+**User is new** → Welcoming, supportive
+```
+"Welcome! We're here to help you get started."
+```
+
+## Brand Voice Examples
+
+### Example 1: Tech Startup (Friendly, Modern)
+```
+Voice: Approachable, innovative, helpful
+Tone variations:
+- Marketing: "Build amazing things, faster"
+- Error: "Oops! Something went wrong. Let's try that again."
+- Success: "Nice! You're all set."
+```
+
+### Example 2: Enterprise SaaS (Professional, Trustworthy)
+```
+Voice: Professional, reliable, expert
+Tone variations:
+- Marketing: "Enterprise-grade security you can trust"
+- Error: "We encountered an issue. Please contact support."
+- Success: "Configuration saved successfully."
+```
+
+### Example 3: Creative Tool (Inspiring, Playful)
+```
+Voice: Creative, inspiring, fun
+Tone variations:
+- Marketing: "Unleash your creativity"
+- Error: "Hmm, that didn't work. Let's try something else!"
+- Success: "Beautiful! Your design is ready to share."
+```
+
+## Best Practices
+
+1. **Create a voice chart** - Document your brand's voice attributes
+2. **Use real examples** - Show, don't just tell
+3. **Consider context** - Adapt tone to situation
+4. **Be consistent** - Use the same voice across channels
+5. **Avoid clichés** - "Think outside the box," "game-changer"
+6. **Use contractions** - "We're" not "We are" (unless formal)
+7. **Address the user** - Use "you" and "your"
+8. **Be specific** - Concrete details over vague statements
+9. **Test with users** - Does it resonate?
+10. **Update regularly** - Voice evolves with your brand
+
+## Anti-Patterns
+
+- ❌ **Inconsistent voice** - Confuses users about your brand
+- ❌ **Overly formal** - Creates distance from users
+- ❌ **Too casual** - May seem unprofessional
+- ❌ **Jargon overload** - Excludes non-experts
+- ❌ **Passive voice** - Weakens your message
+- ❌ **Blaming users** - "You entered the wrong password"
+- ❌ **Fake enthusiasm** - "Amazing! Incredible! Awesome!" overuse
+- ❌ **Corporate speak** - "Leverage synergies to optimize"
+
+## Voice & Tone Checklist
+
+Before publishing, verify:
+- [ ] Does this sound like our brand?
+- [ ] Is the tone appropriate for the context?
+- [ ] Is it clear and easy to understand?
+- [ ] Does it use active voice?
+- [ ] Is it free of jargon?
+- [ ] Does it address the user directly?
+- [ ] Is it inclusive and respectful?
+- [ ] Does it match our voice chart?
+- [ ] Would I say this to someone in person?
+- [ ] Does it help the user accomplish their goal?
+
+## References
+
+- Nicely Said by Nicole Fenton & Kate Kiefer Lee
+- The Voice and Tone Guide by MailChimp
+- Conversational Design by Erika Hall

+ 462 - 0
plugins/claude-code/scripts/context/content-creation/workflows/audience-review.md

@@ -0,0 +1,462 @@
+<!-- Context: content-creation/workflows | Priority: medium | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Audience Review
+
+Process for reviewing content to ensure it resonates with your target audience and achieves its goals.
+
+---
+
+## Pre-Publish Review Checklist
+
+### Audience Alignment
+
+- [ ] **Target audience clearly defined**
+  - Who is this specifically for?
+  - What's their experience level?
+  - What's their current situation?
+
+- [ ] **Addresses specific pain point**
+  - What problem does this solve?
+  - Why does this matter to them?
+  - Is the pain point clearly stated?
+
+- [ ] **Delivers promised value**
+  - Does it fulfill the hook's promise?
+  - Is the value clear and actionable?
+  - Would the audience feel satisfied?
+
+- [ ] **Appropriate depth and complexity**
+  - Matches audience's knowledge level?
+  - Not too basic or too advanced?
+  - Explains necessary concepts?
+
+---
+
+### Message Clarity
+
+- [ ] **One clear main message**
+  - What's the single key takeaway?
+  - Is it stated clearly?
+  - Is it reinforced throughout?
+
+- [ ] **Logical flow and structure**
+  - Does each section connect?
+  - Are transitions smooth?
+  - Is the progression clear?
+
+- [ ] **No jargon without explanation**
+  - Technical terms explained?
+  - Acronyms spelled out?
+  - Industry language appropriate?
+
+- [ ] **Concrete examples included**
+  - Abstract concepts illustrated?
+  - Real-world applications shown?
+  - Relatable scenarios used?
+
+---
+
+### Tone and Voice
+
+- [ ] **Consistent brand voice**
+  - Matches established voice?
+  - Appropriate formality level?
+  - Personality comes through?
+
+- [ ] **Appropriate emotional tone**
+  - Matches audience's emotional state?
+  - Empathetic to their situation?
+  - Energy level appropriate?
+
+- [ ] **Language matches audience**
+  - Uses their terminology?
+  - Avoids alienating language?
+  - Culturally appropriate?
+
+---
+
+### Value Proposition
+
+- [ ] **Clear benefit stated upfront**
+  - What will they gain?
+  - Why should they care?
+  - Is it compelling?
+
+- [ ] **Actionable takeaways**
+  - Can they apply this immediately?
+  - Are steps clear and specific?
+  - Is it practical, not just theoretical?
+
+- [ ] **Unique angle or insight**
+  - What makes this different?
+  - What's the unique perspective?
+  - Why consume this vs. alternatives?
+
+---
+
+### Call-to-Action
+
+- [ ] **Clear next step**
+  - What should they do now?
+  - Is it specific and actionable?
+  - Is it easy to do?
+
+- [ ] **Appropriate to content**
+  - Matches the content topic?
+  - Logical progression?
+  - Not jarring or forced?
+
+- [ ] **Single primary CTA**
+  - One main action requested?
+  - Not overwhelming with options?
+  - Clear and prominent?
+
+---
+
+## Readability and Accessibility
+
+### Readability Checks
+
+- [ ] **Scannable format**
+  - Short paragraphs (1-3 sentences)?
+  - Subheadings every 200-300 words?
+  - Bullet points and lists used?
+  - Bold text for emphasis?
+
+- [ ] **Clear hierarchy**
+  - Heading levels logical (H1, H2, H3)?
+  - Visual hierarchy clear?
+  - Important info stands out?
+
+- [ ] **Appropriate length**
+  - Long enough to deliver value?
+  - Short enough to maintain attention?
+  - No unnecessary fluff?
+
+- [ ] **Active voice predominant**
+  - 80%+ active voice?
+  - Direct and engaging?
+  - Not passive and boring?
+
+---
+
+### Accessibility Checks
+
+- [ ] **Alt text for images**
+  - Descriptive alt text provided?
+  - Conveys image meaning?
+  - Accessible to screen readers?
+
+- [ ] **Sufficient color contrast**
+  - Text readable against background?
+  - Not relying on color alone?
+  - Accessible to colorblind users?
+
+- [ ] **Captions for video/audio**
+  - Subtitles or captions provided?
+  - Accurate transcription?
+  - Accessible to deaf/hard of hearing?
+
+- [ ] **Mobile-friendly**
+  - Readable on small screens?
+  - Images sized appropriately?
+  - No horizontal scrolling?
+
+---
+
+## Quality Assurance
+
+### Content Quality
+
+- [ ] **Factually accurate**
+  - Information verified?
+  - Sources credible?
+  - Data current?
+
+- [ ] **Original content**
+  - Not plagiarized?
+  - Unique perspective?
+  - Proper attribution if quoting?
+
+- [ ] **Complete and comprehensive**
+  - All promised points covered?
+  - No major gaps?
+  - Satisfies the topic?
+
+- [ ] **Examples and proof**
+  - Claims backed up?
+  - Examples provided?
+  - Data or case studies included?
+
+---
+
+### Technical Quality
+
+- [ ] **No spelling or grammar errors**
+  - Proofread thoroughly?
+  - Run through grammar checker?
+  - Read aloud for flow?
+
+- [ ] **Links work correctly**
+  - All links tested?
+  - Open in appropriate window?
+  - Relevant and current?
+
+- [ ] **Images optimized**
+  - File size compressed?
+  - Dimensions appropriate?
+  - Quality maintained?
+
+- [ ] **Formatting consistent**
+  - Heading styles consistent?
+  - List formatting uniform?
+  - Spacing consistent?
+
+---
+
+## Engagement Optimization
+
+### Hook and Opening
+
+- [ ] **Strong hook (first 3 seconds/50 words)**
+  - Grabs attention immediately?
+  - Creates curiosity or promises value?
+  - Relevant to target audience?
+
+- [ ] **Clear value proposition early**
+  - What they'll get stated upfront?
+  - Why they should continue?
+  - Compelling reason to engage?
+
+---
+
+### Throughout Content
+
+- [ ] **Maintains interest**
+  - Pacing appropriate?
+  - Variety in content presentation?
+  - No boring sections?
+
+- [ ] **Visual breaks**
+  - Images, graphics, or videos?
+  - White space used well?
+  - Not walls of text?
+
+- [ ] **Engagement opportunities**
+  - Questions posed?
+  - Invites interaction?
+  - Encourages comments/shares?
+
+---
+
+### Closing
+
+- [ ] **Strong conclusion**
+  - Summarizes key points?
+  - Reinforces main message?
+  - Leaves lasting impression?
+
+- [ ] **Clear CTA**
+  - Next step obvious?
+  - Easy to take action?
+  - Compelling reason to act?
+
+---
+
+## Platform-Specific Checks
+
+### Blog/Article
+
+- [ ] SEO optimized (title, meta, headings)
+- [ ] Internal links to related content
+- [ ] Featured image included
+- [ ] Table of contents (if long-form)
+- [ ] Social sharing buttons visible
+
+---
+
+### Social Media
+
+- [ ] Hook before "see more" cutoff
+- [ ] Appropriate hashtags (3-5)
+- [ ] Tagged relevant accounts
+- [ ] Correct image dimensions
+- [ ] Posting at optimal time
+
+---
+
+### Video
+
+- [ ] Compelling thumbnail
+- [ ] Hook in first 3 seconds
+- [ ] Captions/subtitles included
+- [ ] End screen with CTA
+- [ ] Optimized title and description
+
+---
+
+### Email
+
+- [ ] Subject line compelling (40-50 chars)
+- [ ] Preview text optimized
+- [ ] Mobile-friendly layout
+- [ ] Unsubscribe link included
+- [ ] Tested across email clients
+
+---
+
+### Podcast
+
+- [ ] Clean audio (no background noise)
+- [ ] Show notes written
+- [ ] Timestamps included
+- [ ] Episode artwork uploaded
+- [ ] Metadata complete
+
+---
+
+## Audience Feedback Integration
+
+### Before Publishing
+
+**Beta readers**:
+- Share with small group
+- Get feedback on clarity
+- Test assumptions
+- Identify gaps
+
+**A/B testing**:
+- Test different hooks
+- Try variations of CTA
+- Experiment with formats
+- Compare headlines
+
+---
+
+### After Publishing
+
+**Monitor engagement**:
+- Comments and questions
+- Share and save rates
+- Time on page
+- Drop-off points
+
+**Gather feedback**:
+- Ask for input
+- Survey audience
+- Read comments carefully
+- Track common questions
+
+**Iterate**:
+- Update based on feedback
+- Clarify confusing points
+- Add missing information
+- Improve weak sections
+
+---
+
+## Review Process
+
+### Self-Review (First Pass)
+
+1. **Read through completely**
+   - Don't edit yet, just read
+   - Note overall impression
+   - Identify major issues
+
+2. **Check against checklist**
+   - Go through each item
+   - Mark what needs fixing
+   - Prioritize changes
+
+3. **Make revisions**
+   - Address major issues first
+   - Then minor improvements
+   - Don't over-edit
+
+---
+
+### Peer Review (Second Pass)
+
+1. **Share with colleague or friend**
+   - Someone in target audience ideal
+   - Fresh eyes catch issues
+   - Get honest feedback
+
+2. **Ask specific questions**
+   - "Is the main point clear?"
+   - "Does the hook grab you?"
+   - "Is anything confusing?"
+   - "Would you share this?"
+
+3. **Incorporate feedback**
+   - Consider all feedback
+   - Make judgment calls
+   - Don't change everything
+
+---
+
+### Final Review (Third Pass)
+
+1. **Technical check**
+   - Spelling and grammar
+   - Links and images
+   - Formatting
+   - Platform requirements
+
+2. **Read aloud**
+   - Catches awkward phrasing
+   - Tests flow and rhythm
+   - Identifies run-on sentences
+
+3. **Final approval**
+   - Meets all checklist items?
+   - Satisfied with quality?
+   - Ready to publish?
+
+---
+
+## Common Review Mistakes
+
+### ❌ Skipping the Review
+Publishing without checking.
+
+### ✅ Systematic Review
+Following checklist every time.
+
+---
+
+### ❌ Only Self-Reviewing
+Missing issues you're blind to.
+
+### ✅ Getting Fresh Eyes
+Peer review or beta readers.
+
+---
+
+### ❌ Over-Editing
+Losing voice and authenticity.
+
+### ✅ Balanced Editing
+Improve clarity without over-polishing.
+
+---
+
+### ❌ Ignoring Audience Fit
+Focusing only on technical quality.
+
+### ✅ Audience-First Review
+Ensuring it serves the audience.
+
+---
+
+## Usage
+
+Use this review process for:
+- All content before publishing
+- Updating existing content
+- Quality assurance
+- Team content reviews
+- Client content approval
+
+**Remember**: The review process ensures your content serves your audience effectively. It's not about perfection—it's about clarity, value, and resonance.

+ 459 - 0
plugins/claude-code/scripts/context/content-creation/workflows/content-ideas.md

@@ -0,0 +1,459 @@
+<!-- Context: content-creation/workflows | Priority: medium | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Content Ideas
+
+Frameworks and techniques for generating endless content ideas and overcoming creative blocks.
+
+---
+
+## Ideation Frameworks
+
+### SCAMPER Method
+
+Apply these prompts to existing content or topics:
+
+**S - Substitute**: What can you replace?
+- "Instead of X, what if we tried Y?"
+- "How would [different industry] approach this?"
+
+**C - Combine**: What can you merge?
+- "What if we combined [topic A] with [topic B]?"
+- "How can we blend [format 1] and [format 2]?"
+
+**A - Adapt**: What can you adjust?
+- "How can we adapt [successful content] for [new audience]?"
+- "What worked in [context A] that could work in [context B]?"
+
+**M - Modify**: What can you change?
+- "What if we made this [bigger/smaller/faster/slower]?"
+- "How can we present this differently?"
+
+**P - Put to other uses**: What else could this be?
+- "Who else could benefit from this?"
+- "What other problems does this solve?"
+
+**E - Eliminate**: What can you remove?
+- "What if we simplified this to just [core element]?"
+- "What happens if we remove [common element]?"
+
+**R - Reverse**: What if we flipped it?
+- "What if we did the opposite?"
+- "What if we started with the end?"
+
+---
+
+### Mind Mapping
+
+**Process**:
+1. Write main topic in center
+2. Branch out with related subtopics
+3. Branch further with specific ideas
+4. Look for connections between branches
+5. Identify content opportunities
+
+**Example**:
+```
+                    [Content Creation]
+                           |
+        +------------------+------------------+
+        |                  |                  |
+    [Writing]          [Video]           [Social]
+        |                  |                  |
+    +---+---+          +---+---+          +---+---+
+    |       |          |       |          |       |
+  [Hooks] [SEO]    [Scripts] [Editing] [Threads] [Reels]
+```
+
+---
+
+### Question-Based Ideation
+
+**What Questions**:
+- What is [topic]?
+- What are the types of [topic]?
+- What mistakes do people make with [topic]?
+- What's the future of [topic]?
+
+**How Questions**:
+- How to [achieve result]?
+- How to [avoid problem]?
+- How to [do task] faster/better/cheaper?
+- How I [achieved result]?
+
+**Why Questions**:
+- Why [common belief] is wrong?
+- Why [topic] matters?
+- Why [approach] works better?
+- Why you should [action]?
+
+**When Questions**:
+- When to [take action]?
+- When to avoid [approach]?
+- When is the best time to [action]?
+
+**Who Questions**:
+- Who should [take action]?
+- Who is [topic] for?
+- Who are the experts in [topic]?
+
+**Where Questions**:
+- Where to [find resource]?
+- Where do [people] go wrong?
+- Where to start with [topic]?
+
+---
+
+## Content Idea Sources
+
+### 1. Audience Questions
+
+**Where to find them**:
+- Comments on your content
+- DMs and emails
+- Social media mentions
+- Q&A platforms (Quora, Reddit)
+- Community forums
+- Customer support tickets
+
+**How to use**:
+- Answer questions directly
+- Create comprehensive guides
+- Address common misconceptions
+- Bundle related questions
+
+---
+
+### 2. Trending Topics
+
+**Tools**:
+- Google Trends
+- Twitter/X trending
+- Reddit trending
+- TikTok discover page
+- YouTube trending
+- Industry news sites
+
+**Approach**:
+- Add your unique angle
+- Connect trend to your niche
+- Timely response (strike while hot)
+- Evergreen spin on trend
+
+---
+
+### 3. Competitor Content Analysis
+
+**What to analyze**:
+- Their most popular content
+- Topics they cover frequently
+- Gaps in their content
+- Comment sections (what people want)
+- Content formats they use
+
+**How to differentiate**:
+- Go deeper on the topic
+- Different angle or perspective
+- Better examples or data
+- More actionable advice
+- Different format
+
+---
+
+### 4. Your Own Experience
+
+**Content from experience**:
+- Lessons learned
+- Mistakes made
+- Experiments and results
+- Behind-the-scenes
+- Day-in-the-life
+- Tools and processes
+- Before and after
+
+**Why it works**:
+- Authentic and unique
+- Builds trust
+- Relatable
+- Proof of expertise
+
+---
+
+### 5. Keyword Research
+
+**Tools**:
+- Google Keyword Planner
+- Ahrefs
+- SEMrush
+- AnswerThePublic
+- Google autocomplete
+- "People also ask" boxes
+
+**What to look for**:
+- High volume, low competition
+- Long-tail keywords
+- Question-based keywords
+- "How to" searches
+- Comparison searches
+
+---
+
+### 6. Content Remixing
+
+**Remix strategies**:
+- Update old content with new info
+- Change the format (blog → video)
+- Different angle on same topic
+- Combine multiple pieces
+- Break down comprehensive guide
+- Expand on brief mention
+
+---
+
+## Content Idea Templates
+
+### List-Based Ideas
+
+- "[Number] ways to [achieve result]"
+- "[Number] mistakes to avoid with [topic]"
+- "[Number] tools for [task]"
+- "[Number] examples of [topic]"
+- "[Number] lessons from [experience]"
+- "Top [number] [things] for [audience]"
+
+---
+
+### How-To Ideas
+
+- "How to [achieve result] in [timeframe]"
+- "How to [task] without [common obstacle]"
+- "How to [task] like [expert/pro]"
+- "How I [achieved result]"
+- "How to get started with [topic]"
+- "How to [task] on a budget"
+
+---
+
+### Comparison Ideas
+
+- "[Option A] vs [Option B]: Which is better?"
+- "[Tool A] vs [Tool B]: Honest comparison"
+- "[Approach A] vs [Approach B]: Pros and cons"
+- "Why I switched from [A] to [B]"
+- "[Topic] then vs now"
+
+---
+
+### Problem-Solution Ideas
+
+- "Struggling with [problem]? Try this"
+- "[Problem]? Here's why it happens"
+- "The real reason you're [experiencing problem]"
+- "How to fix [problem] in [timeframe]"
+- "[Problem] solved: [solution]"
+
+---
+
+### Myth-Busting Ideas
+
+- "[Number] myths about [topic]"
+- "Why [common belief] is wrong"
+- "The truth about [topic]"
+- "Debunking [misconception]"
+- "What nobody tells you about [topic]"
+
+---
+
+### Personal Story Ideas
+
+- "How I [achieved result]"
+- "I tried [thing] for [timeframe]. Here's what happened"
+- "My biggest mistake with [topic]"
+- "What [experience] taught me about [topic]"
+- "From [starting point] to [end point]: My journey"
+
+---
+
+## Evergreen vs. Timely Content
+
+### Evergreen Content
+
+**Characteristics**:
+- Stays relevant long-term
+- Consistent traffic over time
+- Foundational topics
+- How-to guides and tutorials
+
+**Examples**:
+- "How to write a blog post"
+- "Beginner's guide to [topic]"
+- "Essential tools for [task]"
+- "Common mistakes in [topic]"
+
+**Benefits**:
+- Long-term traffic
+- Compound value
+- Less frequent updates needed
+- SEO value
+
+---
+
+### Timely Content
+
+**Characteristics**:
+- Relevant for short period
+- Spike in traffic, then drops
+- Trends and news
+- Seasonal topics
+
+**Examples**:
+- "2024 trends in [industry]"
+- "New [tool] review"
+- "What [recent event] means for [audience]"
+- "Holiday gift guide for [audience]"
+
+**Benefits**:
+- Captures immediate interest
+- Shows you're current
+- Viral potential
+- Timely engagement
+
+---
+
+### Balanced Approach
+
+**80/20 Rule**:
+- 80% evergreen (long-term value)
+- 20% timely (immediate relevance)
+
+**Why**:
+- Evergreen builds foundation
+- Timely captures attention
+- Balance sustains growth
+
+---
+
+## Overcoming Creative Blocks
+
+### When You're Stuck
+
+**Change your environment**:
+- Go for a walk
+- Work from different location
+- Take a break
+- Exercise
+
+**Consume content**:
+- Read in your niche
+- Watch videos
+- Listen to podcasts
+- Browse social media
+
+**Talk it out**:
+- Discuss with colleague
+- Explain topic to someone
+- Voice record thoughts
+- Join community discussions
+
+**Use constraints**:
+- Set a timer (10 minutes)
+- Limit to 3 ideas
+- Choose random topic
+- Use a template
+
+---
+
+### Idea Generation Habits
+
+**Daily practices**:
+- Save interesting content
+- Note questions you get
+- Track what resonates
+- Review analytics
+- Engage with audience
+
+**Weekly practices**:
+- Brainstorm session (30 min)
+- Review saved ideas
+- Analyze top content
+- Check trending topics
+- Plan next week's content
+
+**Monthly practices**:
+- Content audit
+- Competitor analysis
+- Audience survey
+- Trend research
+- Strategy review
+
+---
+
+## Content Idea Bank
+
+### Building Your Idea Bank
+
+**What to capture**:
+- Content ideas (topics, angles)
+- Headlines and hooks
+- Interesting quotes
+- Data and statistics
+- Examples and case studies
+- Questions from audience
+- Trending topics
+
+**Where to store**:
+- Note-taking app (Notion, Evernote)
+- Spreadsheet
+- Project management tool
+- Voice memos
+- Bookmarking tool
+
+**How to organize**:
+- By topic/category
+- By format
+- By priority
+- By funnel stage
+- By status (idea, in progress, published)
+
+---
+
+### Using Your Idea Bank
+
+**Regular review**:
+- Weekly: Review and prioritize
+- Monthly: Organize and clean up
+- Quarterly: Identify patterns
+
+**When planning**:
+- Pull from bank for content calendar
+- Combine related ideas
+- Prioritize based on goals
+- Schedule creation
+
+---
+
+## Content Idea Checklist
+
+Before committing to an idea, ask:
+
+- [ ] Is this relevant to my audience?
+- [ ] Can I add unique value or perspective?
+- [ ] Do I have expertise or experience with this?
+- [ ] Is there search demand or interest?
+- [ ] Can I create this with available resources?
+- [ ] Does it align with my goals?
+- [ ] Is the timing right?
+- [ ] Can I make it actionable?
+
+---
+
+## Usage
+
+Use these frameworks when:
+- Planning content calendar
+- Overcoming creative blocks
+- Brainstorming new topics
+- Expanding content coverage
+- Finding unique angles
+- Building content pipeline
+
+**Remember**: The best content ideas come from understanding your audience's needs and adding your unique perspective. Quality over quantity always wins.

+ 367 - 0
plugins/claude-code/scripts/context/content-creation/workflows/content-matrix.md

@@ -0,0 +1,367 @@
+<!-- Context: content-creation/workflows | Priority: medium | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Content Matrix
+
+Framework for organizing and planning content across topics, formats, and stages of the customer journey.
+
+---
+
+## What is a Content Matrix?
+
+A **content matrix** is a strategic planning tool that helps you:
+- Organize content by topic and format
+- Identify content gaps
+- Plan balanced content distribution
+- Align content with audience needs
+- Create content systems, not one-offs
+
+---
+
+## Basic Content Matrix Structure
+
+### Two-Dimensional Matrix
+
+**Axis 1: Topics/Themes**
+- Core topics you cover
+- Pillar content areas
+- Audience interests
+
+**Axis 2: Content Formats**
+- Blog posts
+- Videos
+- Social media
+- Newsletters
+- Podcasts
+
+**Example**:
+
+| Topic | Blog Post | Video | Social Post | Newsletter | Podcast |
+|-------|-----------|-------|-------------|------------|---------|
+| Topic A | ✅ | ✅ | ✅ | ⬜ | ⬜ |
+| Topic B | ✅ | ⬜ | ✅ | ✅ | ⬜ |
+| Topic C | ⬜ | ✅ | ✅ | ⬜ | ✅ |
+
+---
+
+## Advanced Content Matrix
+
+### Three-Dimensional Matrix
+
+**Axis 1: Topics**
+**Axis 2: Formats**
+**Axis 3: Funnel Stage**
+
+**Funnel Stages**:
+- Awareness (top of funnel)
+- Consideration (middle of funnel)
+- Decision (bottom of funnel)
+- Retention (existing customers)
+
+---
+
+### Example: Advanced Matrix
+
+**Topic: Content Creation**
+
+| Format | Awareness | Consideration | Decision | Retention |
+|--------|-----------|---------------|----------|-----------|
+| **Blog** | "What is content marketing?" | "5 content strategies that work" | "Our content service vs. DIY" | "Advanced content techniques" |
+| **Video** | "Content creation 101" | "How we create content" | "Client success stories" | "Exclusive tips for clients" |
+| **Social** | Quick tips | Framework breakdowns | Testimonials | Community highlights |
+| **Email** | Welcome series | Educational series | Case studies | Product updates |
+
+---
+
+## Topic Clustering
+
+### Pillar Content Strategy
+
+**Pillar Content** (Comprehensive, SEO-focused):
+- Long-form guide (2000+ words)
+- Covers topic comprehensively
+- Target high-volume keywords
+- Hub for related content
+
+**Cluster Content** (Supporting, specific):
+- Shorter, focused pieces
+- Target long-tail keywords
+- Link back to pillar
+- Dive deep into subtopics
+
+---
+
+### Example: Pillar + Cluster
+
+**Pillar**: "The Complete Guide to Content Marketing"
+
+**Clusters**:
+- "How to Write Blog Posts That Rank"
+- "Video Content Strategy for Beginners"
+- "Social Media Content Calendar Template"
+- "Email Newsletter Best Practices"
+- "Content Repurposing Framework"
+
+Each cluster links to the pillar, and pillar links to all clusters.
+
+---
+
+## Format Distribution
+
+### Balanced Content Mix
+
+**Educational (40%)**:
+- How-to guides
+- Tutorials
+- Frameworks
+- Best practices
+
+**Inspirational (30%)**:
+- Success stories
+- Case studies
+- Behind-the-scenes
+- Personal stories
+
+**Promotional (20%)**:
+- Product/service features
+- Testimonials
+- Offers and announcements
+- Comparisons
+
+**Entertaining (10%)**:
+- Humor
+- Trends and memes
+- Personality-driven
+- Community content
+
+---
+
+### Platform-Specific Distribution
+
+**Blog**:
+- Educational deep-dives
+- SEO-focused content
+- Comprehensive guides
+
+**Video**:
+- Tutorials and demos
+- Behind-the-scenes
+- Personality-driven content
+
+**Social Media**:
+- Quick tips
+- Engagement content
+- Trending topics
+- Community building
+
+**Email**:
+- Curated content
+- Exclusive insights
+- Personal stories
+- Direct offers
+
+**Podcast**:
+- Long-form discussions
+- Interviews
+- Deep-dive topics
+- Storytelling
+
+---
+
+## Content Calendar Planning
+
+### Monthly Planning Template
+
+**Week 1: Educational**
+- Blog: How-to guide
+- Video: Tutorial
+- Social: Tips series
+- Email: Educational newsletter
+
+**Week 2: Inspirational**
+- Blog: Case study
+- Video: Success story
+- Social: Behind-the-scenes
+- Email: Personal story
+
+**Week 3: Promotional**
+- Blog: Product feature breakdown
+- Video: Demo or testimonial
+- Social: Offer announcement
+- Email: Product spotlight
+
+**Week 4: Community**
+- Blog: Q&A or roundup
+- Video: Community highlights
+- Social: User-generated content
+- Email: Community newsletter
+
+---
+
+### Content Batching
+
+**Batch by Type**:
+- Film all videos in one day
+- Write multiple blog posts in one session
+- Create social graphics in batches
+- Record podcast episodes in bulk
+
+**Benefits**:
+- Efficiency (setup once)
+- Consistency (same style/quality)
+- Reduced decision fatigue
+- Buffer for busy periods
+
+---
+
+## Content Gap Analysis
+
+### Identifying Gaps
+
+**Topic Gaps**:
+- What topics haven't you covered?
+- What questions do you get repeatedly?
+- What are competitors covering that you're not?
+- What's trending in your industry?
+
+**Format Gaps**:
+- Are you only creating one format?
+- Which formats does your audience prefer?
+- Where are you underutilizing platforms?
+
+**Funnel Gaps**:
+- Too much awareness content, not enough decision content?
+- Missing retention content for existing customers?
+- No consideration content to nurture leads?
+
+---
+
+### Gap Analysis Process
+
+1. **Audit existing content**
+   - List all content by topic and format
+   - Identify what's performing well
+   - Note what's missing
+
+2. **Analyze audience needs**
+   - Review questions and comments
+   - Check search data
+   - Survey your audience
+
+3. **Map to matrix**
+   - Fill in existing content
+   - Identify empty cells
+   - Prioritize gaps to fill
+
+4. **Create action plan**
+   - Prioritize high-impact gaps
+   - Schedule content creation
+   - Assign resources
+
+---
+
+## Pillar Content Strategy
+
+### Creating Pillar Content
+
+**Characteristics**:
+- Comprehensive (2000+ words)
+- Evergreen (stays relevant)
+- SEO-optimized
+- Regularly updated
+- Hub for related content
+
+**Structure**:
+- Table of contents
+- Multiple sections
+- Examples and case studies
+- Internal links to clusters
+- Clear CTAs
+
+---
+
+### Cluster Content Strategy
+
+**Characteristics**:
+- Focused on specific subtopic
+- 800-1500 words
+- Long-tail keyword targeting
+- Links to pillar
+- Easier to rank
+
+**Benefits**:
+- Builds topical authority
+- Captures long-tail traffic
+- Supports pillar content
+- Easier to create
+
+---
+
+## Content Repurposing Matrix
+
+### One Piece → Many Formats
+
+**Start with**: Long-form blog post or video
+
+**Repurpose into**:
+- Social media posts (pull quotes, tips)
+- Email newsletter (summary + link)
+- Infographic (key points visualized)
+- Podcast episode (discuss the topic)
+- Short-form video (key takeaways)
+- Carousel post (step-by-step)
+- Thread (Twitter/X breakdown)
+
+---
+
+### Repurposing Strategy
+
+**Pillar Content** → Multiple Formats:
+1. Write comprehensive blog post
+2. Record video covering same topic
+3. Extract quotes for social media
+4. Create infographic of key points
+5. Discuss in podcast episode
+6. Send newsletter with summary
+7. Create short-form videos from clips
+
+**Result**: One topic, 7+ pieces of content
+
+---
+
+## Content Matrix Templates
+
+### Simple Matrix Template
+
+```
+| Topic | Blog | Video | Social | Email | Status |
+|-------|------|-------|--------|-------|--------|
+| [Topic 1] | [ ] | [ ] | [ ] | [ ] | Planning |
+| [Topic 2] | [✓] | [ ] | [✓] | [ ] | In Progress |
+| [Topic 3] | [✓] | [✓] | [✓] | [✓] | Complete |
+```
+
+---
+
+### Advanced Matrix Template
+
+```
+| Topic | Format | Funnel Stage | Keyword | Due Date | Status |
+|-------|--------|--------------|---------|----------|--------|
+| [Topic] | Blog | Awareness | [keyword] | [date] | [ ] |
+| [Topic] | Video | Consideration | [keyword] | [date] | [ ] |
+| [Topic] | Social | Decision | - | [date] | [ ] |
+```
+
+---
+
+## Usage
+
+Use the content matrix for:
+- Strategic content planning
+- Identifying content gaps
+- Balancing content types
+- Organizing content production
+- Tracking content coverage
+- Planning content repurposing
+
+**Remember**: The matrix is a planning tool, not a rigid constraint. Adapt based on what works for your audience and goals.

+ 78 - 0
plugins/claude-code/scripts/context/content-creation/workflows/navigation.md

@@ -0,0 +1,78 @@
+<!-- Context: content-creation/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Content Workflows Navigation
+
+Content planning, ideation, and production workflows.
+
+---
+
+## Available Files
+
+### content-matrix.md
+Content planning matrix for organizing content across topics and formats.
+
+**Topics**:
+- Content matrix structure
+- Topic clustering
+- Format distribution
+- Content calendar planning
+- Pillar content strategy
+- Content gap analysis
+
+**Use for**: Content strategy, planning content calendars, organizing content themes
+
+---
+
+### content-ideas.md
+Frameworks and techniques for generating content ideas.
+
+**Topics**:
+- Ideation frameworks (SCAMPER, mind mapping, etc.)
+- Content idea sources
+- Trending topic research
+- Audience question mining
+- Competitor content analysis
+- Evergreen vs. timely content
+
+**Use for**: Brainstorming content, overcoming creative blocks, content planning
+
+---
+
+### audience-review.md
+Process for reviewing content for audience fit and effectiveness.
+
+**Topics**:
+- Audience alignment checklist
+- Message clarity assessment
+- Tone and voice verification
+- Value proposition check
+- Call-to-action effectiveness
+- Readability and accessibility
+
+**Use for**: Content review, quality assurance, pre-publish checks
+
+---
+
+### remix-repurpose.md
+Strategies for remixing and repurposing existing content.
+
+**Topics**:
+- Content atomization (breaking down pillar content)
+- Format transformation (blog → video → social posts)
+- Update and refresh strategies
+- Cross-platform adaptation
+- Content series creation
+- Evergreen content maintenance
+
+**Use for**: Maximizing content ROI, content repurposing, content updates
+
+---
+
+## Usage
+
+Load these workflow files when:
+- Planning content strategy
+- Generating new content ideas
+- Reviewing content before publishing
+- Repurposing existing content
+- Organizing content production

+ 522 - 0
plugins/claude-code/scripts/context/content-creation/workflows/remix-repurpose.md

@@ -0,0 +1,522 @@
+<!-- Context: content-creation/workflows | Priority: medium | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Content Remix and Repurposing
+
+Strategies for maximizing content ROI by transforming existing content into multiple formats and reaching new audiences.
+
+---
+
+## Why Repurpose Content?
+
+**Benefits**:
+- **Efficiency**: Create once, use many times
+- **Reach**: Different audiences prefer different formats
+- **Reinforcement**: Repetition increases retention
+- **SEO**: More content = more ranking opportunities
+- **Longevity**: Extend content lifespan
+
+**ROI**: One piece of pillar content can become 20+ pieces across formats.
+
+---
+
+## Content Atomization
+
+### Breaking Down Pillar Content
+
+**Pillar Content** (2000+ word blog post or 30+ min video):
+
+**Can become**:
+- 10-15 social media posts (key points)
+- 5-7 short-form videos (TikTok/Reels)
+- 3-5 email newsletters (sections)
+- 1 infographic (visual summary)
+- 1 podcast episode (audio discussion)
+- 1 carousel post (step-by-step)
+- 1 Twitter/X thread (breakdown)
+- 5-10 quote graphics (pull quotes)
+
+---
+
+### Atomization Process
+
+1. **Identify key points**
+   - Main takeaways
+   - Actionable tips
+   - Interesting statistics
+   - Compelling quotes
+   - Examples and stories
+
+2. **Extract standalone pieces**
+   - Each point becomes content
+   - Add context if needed
+   - Make self-contained
+
+3. **Adapt for each platform**
+   - Format appropriately
+   - Adjust length
+   - Optimize for platform
+
+4. **Link back to original**
+   - Drive traffic to pillar
+   - Build authority
+   - Create content ecosystem
+
+---
+
+## Format Transformation
+
+### Blog Post → Other Formats
+
+**Blog Post → Video**:
+- Use blog as script outline
+- Add visual demonstrations
+- Include on-screen text for key points
+- Film yourself explaining concepts
+
+**Blog Post → Podcast**:
+- Discuss the topic conversationally
+- Expand with additional insights
+- Interview someone about the topic
+- Add personal stories
+
+**Blog Post → Infographic**:
+- Extract key statistics and points
+- Visualize data and processes
+- Create scannable format
+- Design for sharing
+
+**Blog Post → Social Posts**:
+- Pull out individual tips
+- Create quote graphics
+- Share key statistics
+- Tease with hook + link
+
+**Blog Post → Email Series**:
+- Break into multiple emails
+- One section per email
+- Add personal commentary
+- Include CTAs
+
+---
+
+### Video → Other Formats
+
+**Video → Blog Post**:
+- Transcribe video
+- Edit for readability
+- Add images/screenshots
+- Optimize for SEO
+
+**Video → Short-Form Videos**:
+- Extract best moments
+- Create standalone clips
+- Add captions
+- Optimize for platform (TikTok, Reels, Shorts)
+
+**Video → Social Posts**:
+- Pull quotes from video
+- Create quote graphics
+- Share key frames
+- Tease with clip + link
+
+**Video → Podcast**:
+- Extract audio
+- Add intro/outro
+- Edit for audio-only
+- Publish as episode
+
+**Video → Carousel**:
+- Screenshot key moments
+- Add text overlays
+- Create step-by-step
+- Post on Instagram/LinkedIn
+
+---
+
+### Podcast → Other Formats
+
+**Podcast → Blog Post**:
+- Transcribe episode
+- Edit and structure
+- Add headings and formatting
+- Include embedded player
+
+**Podcast → Video**:
+- Add visual element (waveform, images)
+- Create video version
+- Upload to YouTube
+- Add chapters
+
+**Podcast → Social Posts**:
+- Pull interesting quotes
+- Create audiograms
+- Share key insights
+- Tease episode
+
+**Podcast → Email**:
+- Summarize key points
+- Include interesting moments
+- Link to full episode
+- Add show notes
+
+---
+
+## Cross-Platform Adaptation
+
+### Platform-Specific Optimization
+
+**LinkedIn**:
+- Professional tone
+- Industry insights
+- Longer-form posts
+- Document posts (carousels)
+
+**Twitter/X**:
+- Concise threads
+- Quick tips
+- Engaging questions
+- Link to full content
+
+**Instagram**:
+- Visual-first
+- Carousel posts
+- Reels for video
+- Stories for behind-the-scenes
+
+**TikTok**:
+- Short, punchy videos
+- Trending audio
+- Hook in first second
+- Educational or entertaining
+
+**YouTube**:
+- Longer-form video
+- Comprehensive coverage
+- SEO-optimized
+- Playlist organization
+
+**Email**:
+- Personal tone
+- Exclusive insights
+- Direct CTAs
+- Curated content
+
+---
+
+## Update and Refresh Strategies
+
+### When to Update Content
+
+**Triggers**:
+- Content is 12+ months old
+- Information is outdated
+- New data available
+- Ranking has dropped
+- Topic is trending again
+- New examples available
+
+---
+
+### How to Update Content
+
+**Minor Updates**:
+- Update statistics and data
+- Add recent examples
+- Fix broken links
+- Refresh images
+- Update date stamp
+
+**Major Updates**:
+- Rewrite sections
+- Add new sections
+- Restructure for clarity
+- Expand with new insights
+- Improve SEO optimization
+
+**Complete Refresh**:
+- Rewrite from scratch
+- New angle or perspective
+- Current best practices
+- Updated examples
+- New format
+
+---
+
+### Republishing Strategy
+
+**After updating**:
+- Change publish date (or add "Updated: [date]")
+- Announce the update on social media
+- Email subscribers about refresh
+- Resubmit to search engines
+- Share as "new" content
+
+---
+
+## Content Series Creation
+
+### Turning One Topic into a Series
+
+**Blog Series**:
+- Part 1: Introduction and overview
+- Part 2: Deep dive into aspect A
+- Part 3: Deep dive into aspect B
+- Part 4: Advanced techniques
+- Part 5: Case studies and examples
+
+**Video Series**:
+- Episode 1: The basics
+- Episode 2: Step-by-step tutorial
+- Episode 3: Common mistakes
+- Episode 4: Advanced tips
+- Episode 5: Q&A
+
+**Email Course**:
+- Day 1: Welcome and overview
+- Day 2: Foundation concepts
+- Day 3: Implementation
+- Day 4: Optimization
+- Day 5: Next steps
+
+---
+
+### Series Benefits
+
+**For audience**:
+- Comprehensive coverage
+- Logical progression
+- Easier to follow
+- Builds anticipation
+
+**For creator**:
+- Easier to plan
+- Batch creation
+- Consistent posting
+- Authority building
+
+---
+
+## Evergreen Content Maintenance
+
+### Evergreen Content Strategy
+
+**Characteristics**:
+- Timeless topics
+- Foundational concepts
+- How-to guides
+- Best practices
+
+**Maintenance schedule**:
+- Review quarterly
+- Update annually
+- Refresh examples
+- Add new insights
+
+---
+
+### Evergreen Repurposing
+
+**Regular resharing**:
+- Share on social media quarterly
+- Include in email newsletters
+- Reference in new content
+- Update and republish
+
+**Seasonal angles**:
+- "New year" version
+- "Summer" edition
+- "Back to school" spin
+- Holiday tie-in
+
+---
+
+## Content Repurposing Workflows
+
+### Workflow 1: Pillar → Atomized
+
+1. **Create pillar content** (blog post or video)
+2. **Extract key points** (10-15 takeaways)
+3. **Create social posts** (one per key point)
+4. **Design infographic** (visual summary)
+5. **Record podcast** (discuss the topic)
+6. **Create short videos** (key takeaways)
+7. **Write email series** (break into parts)
+8. **Schedule distribution** (spread over weeks)
+
+---
+
+### Workflow 2: Format Transformation
+
+1. **Start with one format** (e.g., video)
+2. **Transcribe to text** (blog post)
+3. **Extract audio** (podcast episode)
+4. **Create clips** (short-form videos)
+5. **Design graphics** (quote cards)
+6. **Write social posts** (teasers)
+7. **Compile email** (summary + links)
+
+---
+
+### Workflow 3: Update and Refresh
+
+1. **Audit existing content** (identify top performers)
+2. **Check for outdated info** (stats, examples, links)
+3. **Update content** (refresh information)
+4. **Improve SEO** (optimize further)
+5. **Republish** (new date or "updated" note)
+6. **Promote again** (social, email)
+7. **Monitor performance** (track improvements)
+
+---
+
+## Repurposing Calendar
+
+### Monthly Repurposing Plan
+
+**Week 1: Create Pillar**
+- Publish comprehensive blog post or video
+- Optimize for SEO
+- Promote on main channels
+
+**Week 2: Atomize**
+- Extract key points
+- Create social posts
+- Design graphics
+- Schedule distribution
+
+**Week 3: Transform**
+- Convert to different format
+- Create short-form content
+- Write email newsletter
+- Publish across platforms
+
+**Week 4: Refresh**
+- Update old content
+- Republish refreshed piece
+- Promote updated content
+- Plan next month
+
+---
+
+## Repurposing Tools
+
+### Content Creation
+
+**Transcription**:
+- Otter.ai
+- Descript
+- Rev.com
+
+**Video Editing**:
+- Descript (video + transcription)
+- Kapwing
+- Adobe Premiere
+
+**Graphic Design**:
+- Canva
+- Adobe Express
+- Figma
+
+**Social Media**:
+- Buffer
+- Hootsuite
+- Later
+
+---
+
+### Content Management
+
+**Organization**:
+- Notion (content database)
+- Airtable (content tracker)
+- Trello (workflow management)
+
+**Scheduling**:
+- Buffer (social scheduling)
+- ConvertKit (email automation)
+- YouTube Studio (video scheduling)
+
+---
+
+## Repurposing Checklist
+
+Before repurposing, verify:
+
+- [ ] Original content performed well
+- [ ] Content is still relevant
+- [ ] New format suits the content
+- [ ] Platform is appropriate
+- [ ] Adapted for platform (not just copy-paste)
+- [ ] Links back to original
+- [ ] Optimized for new format
+- [ ] Scheduled strategically
+- [ ] Tracked for performance
+
+---
+
+## Common Repurposing Mistakes
+
+### ❌ Copy-Paste Without Adaptation
+Posting same content across platforms without optimization.
+
+### ✅ Platform-Specific Adaptation
+Tailoring content for each platform's audience and format.
+
+---
+
+### ❌ Repurposing Low-Performing Content
+Wasting time on content that didn't resonate.
+
+### ✅ Repurposing Winners
+Focusing on proven, high-performing content.
+
+---
+
+### ❌ No Link Back to Original
+Missing opportunity to drive traffic.
+
+### ✅ Strategic Linking
+Always linking back to pillar content.
+
+---
+
+### ❌ Overwhelming Audience
+Posting too much repurposed content at once.
+
+### ✅ Strategic Distribution
+Spreading repurposed content over time.
+
+---
+
+## Repurposing ROI
+
+### Measuring Success
+
+**Metrics to track**:
+- Total pieces created from one pillar
+- Traffic to original content
+- Engagement across formats
+- Time saved vs. creating new
+- Reach across platforms
+
+**Example ROI**:
+- 1 pillar blog post (4 hours)
+- → 15 social posts (2 hours)
+- → 1 infographic (1 hour)
+- → 1 podcast episode (2 hours)
+- → 5 short videos (2 hours)
+- **Total**: 20+ pieces in 11 hours vs. 80+ hours creating from scratch
+
+---
+
+## Usage
+
+Apply repurposing strategies to:
+- Maximize content ROI
+- Reach different audiences
+- Maintain consistent posting
+- Extend content lifespan
+- Build content ecosystem
+- Save time and resources
+
+**Remember**: Repurposing isn't lazy—it's strategic. Your audience consumes content differently across platforms. Meet them where they are with the format they prefer.

+ 39 - 0
plugins/claude-code/scripts/context/core/config/navigation.md

@@ -0,0 +1,39 @@
+<!-- Context: core/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Core Configuration
+
+**Purpose**: Configuration standards and patterns for the context system
+
+---
+
+## Structure
+
+```
+core/config/
+├── navigation.md (this file)
+└── [configuration files]
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **View configuration** | `../config/` |
+| **Core standards** | `../standards/navigation.md` |
+| **System guides** | `../system/navigation.md` |
+
+---
+
+## By Type
+
+**Configuration Files** → Settings and configuration patterns for the context system
+
+---
+
+## Related Context
+
+- **Core Standards** → `../standards/navigation.md`
+- **Core System** → `../system/navigation.md`
+- **Core Navigation** → `../navigation.md`

+ 7 - 0
plugins/claude-code/scripts/context/core/config/paths.json

@@ -0,0 +1,7 @@
+{
+  "description": "Additional context file paths - agents load this via @ reference for dynamic pathing",
+  "paths": {
+    "local": ".opencode/context",
+    "global": "~/.config/opencode/context"
+  }
+}

+ 450 - 0
plugins/claude-code/scripts/context/core/context-system.md

@@ -0,0 +1,450 @@
+<!-- Context: core/context-system | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Context System
+
+**Purpose**: Minimal, concern-based knowledge organization for AI agents
+
+**Last Updated**: 2026-01-08
+
+---
+
+## Core Principles
+
+### 1. Minimal Viable Information (MVI)
+Extract only core concepts (1-3 sentences), key points (3-5 bullets), minimal example, and reference link. 
+**Goal**: Scannable in <30 seconds. Reference full docs, don't duplicate them.
+
+### 2. Concern-Based Structure
+Organize by **what you're doing** (concern), then by **how you're doing it** (approach/tech):
+
+**Two organizational patterns**:
+
+#### Pattern A: Function-Based (for repository-specific context)
+```
+category/
+├── navigation.md
+├── concepts/              # What it is
+├── examples/              # Working code
+├── guides/                # How to do it
+├── lookup/                # Quick reference
+└── errors/                # Common issues
+```
+
+**Use when**: Content is repository-specific (e.g., `openagents-repo/`)
+
+#### Pattern B: Concern-Based (for development context)
+```
+category/
+├── navigation.md
+├── {concern}/             # Organize by what you're doing
+│   ├── navigation.md
+│   ├── {approach}/        # Then by approach/tech
+│   │   ├── navigation.md
+│   │   └── {files}.md
+```
+
+**Use when**: Content spans multiple technologies (e.g., `development/`)
+
+**Examples**:
+- `development/backend/api-patterns/` - Concern: backend, Approach: API patterns
+- `development/backend/nodejs/` - Concern: backend, Tech: Node.js
+- `development/frontend/react/` - Concern: frontend, Tech: React
+
+### 3. Token-Efficient Navigation
+Every category/subcategory has `navigation.md` with:
+- **ASCII tree** for quick structure scan (~50 tokens)
+- **Quick routes table** for common tasks (~100 tokens)
+- **By concern/type** sections (~50 tokens)
+- **Total**: ~200-300 tokens per navigation file
+
+**Why**: Faster loading, less cost, quicker AI decisions
+
+### 4. Specialized Navigation Files
+For cross-cutting concerns, create specialized navigation:
+- `development/ui-navigation.md` - Spans frontend/ + ui/
+- `development/backend-navigation.md` - Covers APIs, auth, middleware
+- `development/fullstack-navigation.md` - Common tech stacks
+
+**Why**: Real workflows don't fit neat categories
+
+### 5. Self-Describing Filenames
+Filenames should tell you what's inside:
+- ❌ `code.md` → ✅ `code-quality.md`
+- ❌ `tests.md` → ✅ `test-coverage.md`
+- ❌ `review.md` → ✅ `code-review.md`
+
+**Why**: No need to open files to understand content
+
+### 6. Knowledge Harvesting
+Extract valuable context from AI summaries/overviews, then delete them. Workspace stays clean, knowledge persists.
+
+### 5. Technology Context Organization
+
+**Purpose**: Ensure consistent placement of new technologies (frameworks, libraries, tools) to maintain discoverability.
+
+**Frameworks vs Architectural Layers**:
+
+- **Full-Stack Frameworks** (e.g., Tanstack Start, Next.js): Add under `development/frameworks/{tech}/`. These are "meta-frameworks" that span multiple layers.
+- **Specialized Concerns** (e.g., AI, Data): Add under `development/{concern}/{tech}/`.
+- **Layer-Specific Tech** (e.g., React, Node.js): Add under `development/{frontend|backend}/{tech}/`.
+
+**Decision Process**:
+1. Is it a full-stack framework? → `development/frameworks/`
+2. Is it a specialized domain (AI, Data)? → `development/{domain}/`
+3. Is it layer-specific? → `development/{frontend|backend}/`
+
+---
+
+## Directory Patterns
+
+### Pattern A: Function-Based (Repository-Specific)
+
+**Use for**: Repository-specific context (e.g., `openagents-repo/`)
+
+```
+.opencode/context/{category}/
+├── navigation.md              # Fast, token-efficient navigation
+├── quick-start.md             # Optional: 2-minute orientation
+│
+├── core-concepts/             # Foundational concepts (optional)
+│   ├── navigation.md
+│   └── {concept}.md
+│
+├── concepts/                  # What it is
+│   ├── navigation.md
+│   └── {concept}.md
+│
+├── examples/                  # Working code
+│   ├── navigation.md
+│   └── {example}.md
+│
+├── guides/                    # How to do it
+│   ├── navigation.md
+│   └── {guide}.md
+│
+├── lookup/                    # Quick reference
+│   ├── navigation.md
+│   └── {lookup}.md
+│
+└── errors/                    # Common issues
+    ├── navigation.md
+    └── {error}.md
+```
+
+---
+
+### Pattern B: Concern-Based (Development Context)
+
+**Use for**: Multi-technology development context (e.g., `development/`)
+
+```
+.opencode/context/{category}/
+├── navigation.md                       # Main navigation
+├── {concern}-navigation.md             # Specialized navigation (optional)
+│
+├── principles/                         # Universal principles (optional)
+│   ├── navigation.md
+│   └── {principle}.md
+│
+├── {concern}/                          # Organize by concern
+│   ├── navigation.md
+│   │
+│   ├── {approach}/                     # Then by approach
+│   │   ├── navigation.md
+│   │   └── {pattern}.md
+│   │
+│   └── {tech}/                         # Or by tech
+│       ├── navigation.md
+│       └── {pattern}.md
+```
+
+**Example**:
+```
+development/
+├── navigation.md
+├── ui-navigation.md                    # Specialized
+├── backend-navigation.md               # Specialized
+├── fullstack-navigation.md             # Specialized
+│
+├── principles/                         # Universal
+│   ├── clean-code.md
+│   └── api-design.md
+│
+├── frontend/                           # Concern
+│   ├── react/                          # Tech
+│   │   ├── hooks-patterns.md
+│   │   └── tanstack/                   # Sub-tech
+│   │       ├── query-patterns.md
+│   │       └── router-patterns.md
+│   └── vue/                            # Tech
+│
+├── backend/                            # Concern
+│   ├── api-patterns/                   # Approach
+│   │   ├── rest-design.md
+│   │   └── graphql-design.md
+│   ├── nodejs/                         # Tech
+│   └── authentication/                 # Functional concern
+│
+└── data/                               # Concern
+    ├── sql-patterns/                   # Approach
+    └── orm-patterns/                   # Approach
+```
+
+---
+
+## Navigation File Format
+
+### Token-Efficient Template
+
+```markdown
+# {Category} Navigation
+
+**Purpose**: [1 sentence]
+
+---
+
+## Structure
+
+```
+{category}/
+├── navigation.md
+├── {subcategory}/
+│   ├── navigation.md
+│   └── {files}.md
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **{Task 1}** | `{path}` |
+| **{Task 2}** | `{path}` |
+
+---
+
+## By {Concern/Type}
+
+**{Section 1}** → {description}
+**{Section 2}** → {description}
+```
+
+**Target**: 200-300 tokens
+
+---
+
+## Organizing Principles
+
+### 1. Core Standards (Universal)
+
+Location: `.opencode/context/core/standards/`
+
+**Purpose**: Universal standards that apply to ALL development
+
+**Content**:
+- Code quality principles (all languages)
+- Test coverage standards
+- Documentation standards
+- Security patterns
+- Code analysis approaches
+
+**Used by**: All agents, all projects
+
+**Effect on other categories**: 
+- Other categories can reference these standards
+- Users can edit core standards to affect context flow globally
+- Development-specific standards go in `development/principles/`
+
+---
+
+### 2. Development Principles vs Core Standards
+
+| Location | Scope | Examples |
+|----------|-------|----------|
+| `core/standards/` | **Universal** (all projects, all languages) | Code quality, testing, docs, security |
+| `development/principles/` | **Development-specific** (software engineering) | Clean code, API design, error handling |
+
+**Both exist**: Core standards are universal, development principles are domain-specific
+
+---
+
+### 3. Data Context Location
+
+**Decision**: Data patterns live in `development/data/` (not top-level)
+
+**Rationale**: Data layer is part of development workflow
+
+**Structure**:
+```
+development/data/
+├── navigation.md
+├── sql-patterns/
+├── nosql-patterns/
+└── orm-patterns/
+```
+
+**Top-level `data/` category**: Reserved for data engineering/analytics (different concern)
+
+---
+
+### 4. Specialized Navigation Strategy
+
+**Full-stack navigation includes**:
+- Quick routes (table format)
+- Common stack patterns (MERN, T3, etc.)
+
+**Example**:
+```markdown
+## Quick Routes
+| Task | Path |
+|------|------|
+| **Frontend** | `ui-navigation.md` |
+
+## Common Stacks
+
+### MERN Stack
+Frontend: development/frontend/react/
+Backend:  development/backend/nodejs/
+Data:     development/data/nosql-patterns/mongodb.md
+```
+
+---
+
+## Operations
+
+### Harvest (`/context harvest`)
+
+**Purpose**: Extract knowledge from summary files → permanent context, then clean up.
+
+**Process**:
+1. Scan for patterns: `*OVERVIEW.md`, `*SUMMARY.md`, `SESSION-*.md`, `CONTEXT-*.md`
+2. Analyze content:
+   - Design decisions → `concepts/`
+   - Solutions/patterns → `examples/`
+   - Workflows → `guides/`
+   - Errors encountered → `errors/`
+   - Reference data → `lookup/`
+3. Present approval UI (letter-based: `A B C` or `all`)
+4. Extract + minimize (apply MVI)
+5. Archive/delete summaries
+6. Report results
+
+---
+
+### Extract (`/context extract`)
+
+**Purpose**: Extract context from docs/code/URLs.
+
+**Process**:
+1. Read source
+2. Extract core concepts (1-3 sentences each)
+3. Find minimal examples
+4. Identify workflows (numbered steps)
+5. Build lookup tables
+6. Capture errors/gotchas
+7. Create references
+
+**Output**: Follow MVI template
+
+---
+
+### Organize (`/context organize`)
+
+**Purpose**: Restructure existing files into appropriate pattern.
+
+**Process**:
+1. Scan category
+2. Determine pattern (function-based or concern-based)
+3. Create missing directories
+4. Move/refactor files
+5. Update navigation.md
+6. Fix references
+
+---
+
+### Update (`/context update`)
+
+**Purpose**: Update context when APIs/frameworks change.
+
+**Process**:
+1. Identify what changed
+2. Find affected files
+3. Update concepts, examples, guides, lookups
+4. Add migration notes to errors/
+5. Validate references
+
+---
+
+## File Naming Conventions
+
+### Navigation Files
+- `navigation.md` - Main navigation for category/subcategory
+- `{domain}-navigation.md` - Specialized cross-cutting navigation
+
+### Content Files
+- Use descriptive names: `code-quality.md` not `code.md`
+- Include type when helpful: `rest-design.md`, `jwt-patterns.md`
+- Use kebab-case: `scroll-linked-animations.md`
+
+---
+
+## Extraction Rules
+
+### ✅ Extract:
+- Core concepts (minimal)
+- Essential patterns
+- Step-by-step workflows
+- Critical errors
+- Quick reference data
+- Links to detailed docs
+
+### ❌ Don't Extract:
+- Verbose explanations
+- Complete API docs
+- Implementation details
+- Historical context
+- Marketing content
+- Duplicate info
+
+---
+
+## Success Criteria
+
+✅ **Minimal** - Core info only, <200 lines per file
+✅ **Navigable** - navigation.md at every level
+✅ **Organized** - Appropriate pattern (function-based or concern-based)
+✅ **Token-efficient** - Navigation files ~200-300 tokens
+✅ **Self-describing** - Filenames tell you what's inside
+✅ **Referenceable** - Links to full docs
+✅ **Searchable** - Easy to find via navigation
+✅ **Maintainable** - Easy to update
+
+---
+
+## Related Documentation
+
+- `context-system/guides/navigation-design.md` - How to create navigation files
+- `context-system/guides/organizing-context.md` - How to choose organizational pattern
+- `context-system/examples/navigation-examples.md` - Good navigation examples
+- `context-system/standards/templates.md` - File templates
+
+---
+
+## Quick Commands
+
+```bash
+/context                      # Quick scan, suggest actions
+/context harvest              # Clean up summaries → permanent context
+/context extract {source}     # From docs/code/URLs
+/context organize {category}  # Restructure flat files → function folders
+/context update {what}        # When APIs/frameworks change
+/context migrate              # Move global project-intelligence → local project
+/context create {category}    # Create new context category
+/context error {error}        # Add recurring error to knowledge base
+/context compact {file}       # Minimize verbose file to MVI format
+/context map [category]       # View context structure
+/context validate             # Check integrity, references, sizes
+```
+
+**All operations show a preview of what will be created/moved/deleted before asking for approval.**

+ 87 - 0
plugins/claude-code/scripts/context/core/context-system/CHANGELOG.md

@@ -0,0 +1,87 @@
+<!-- Context: core/CHANGELOG | Priority: low | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Context System Changelog
+
+**Purpose**: Track major changes to the context system
+
+---
+
+## 2026-01-08: Navigation System Redesign
+
+### Major Changes
+
+1. **Renamed README.md → navigation.md**
+   - More descriptive filename
+   - Better discoverability
+   - Self-describing purpose
+
+2. **Added Concern-Based Organization Pattern**
+   - Pattern A: Function-Based (repository-specific)
+   - Pattern B: Concern-Based (multi-technology)
+   - Hybrid approach supported
+
+3. **Token-Efficient Navigation**
+   - Target: 200-300 tokens per navigation file
+   - ASCII trees for structure
+   - Tables for quick routes
+   - Concise descriptions (3-5 words)
+
+4. **Specialized Navigation Files**
+   - Cross-cutting concerns (e.g., `ui-navigation.md`)
+   - Task-focused routes
+   - Workflow-oriented
+
+5. **Self-Describing Filenames**
+   - `code.md` → `code-quality.md`
+   - `tests.md` → `test-coverage.md`
+   - `review.md` → `code-review.md`
+
+### New Documentation
+
+**Created**:
+- `guides/navigation-design.md` - How to create navigation files
+- `guides/organizing-context.md` - How to choose organizational pattern
+- `examples/navigation-examples.md` - Real-world examples
+
+**Updated**:
+- `context-system.md` - Added concern-based pattern, navigation principles
+- `standards/templates.md` - Added navigation templates
+
+### Organizational Decisions
+
+1. **Core Standards (Universal)**
+   - Location: `core/standards/`
+   - Scope: All projects, all languages
+   - Users can edit to affect global context flow
+
+2. **Development Principles (Domain-Specific)**
+   - Location: `development/principles/`
+   - Scope: Software engineering
+   - Both core standards and dev principles exist
+
+3. **Data Context**
+   - Location: `development/data/` (not top-level)
+   - Rationale: Data layer is part of development workflow
+
+4. **Specialized Navigation**
+   - Includes quick routes + common patterns
+   - Example: `fullstack-navigation.md` shows MERN, T3 stacks
+
+### Migration Path
+
+**Phase 0**: ✅ Update context system documentation (DONE)
+**Phase 1**: Rename navigation files, update core/
+**Phase 2**: Restructure development/ category
+**Phase 3**: Organize New-context-to-sort/
+**Phase 4**: Update all references
+
+---
+
+## Previous Changes
+
+### 2026-01-06: Initial Context System
+
+- Established MVI principle
+- Created function-based structure
+- Added file templates
+- Defined operations (harvest, extract, organize, update)

+ 493 - 0
plugins/claude-code/scripts/context/core/context-system/examples/navigation-examples.md

@@ -0,0 +1,493 @@
+<!-- Context: core/navigation-examples | Priority: high | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Examples: Navigation Files
+
+**Purpose**: Real-world examples of good navigation files
+
+**Last Updated**: 2026-01-08
+
+---
+
+## Example 1: Category Navigation (Function-Based)
+
+**File**: `openagents-repo/navigation.md`
+
+**Pattern**: Function-Based (repository-specific)
+
+**Token count**: ~250 tokens
+
+```markdown
+# OpenAgents Control Repository Navigation
+
+**Purpose**: Navigate OpenAgents Control repository context
+
+---
+
+## Structure
+
+```
+openagents-repo/
+├── navigation.md
+├── quick-start.md
+│
+├── core-concepts/
+│   ├── agent-architecture.md
+│   ├── eval-framework.md
+│   └── registry-system.md
+│
+├── guides/
+│   ├── adding-agent.md
+│   ├── testing-agent.md
+│   └── debugging-issues.md
+│
+├── lookup/
+│   ├── commands.md
+│   └── file-locations.md
+│
+└── errors/
+    └── tool-permission-errors.md
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **New here** | `quick-start.md` |
+| **Add agent** | `guides/adding-agent.md` |
+| **Test agent** | `guides/testing-agent.md` |
+| **Debug issue** | `guides/debugging-issues.md` |
+| **Find files** | `lookup/file-locations.md` |
+| **Fix error** | `errors/tool-permission-errors.md` |
+
+---
+
+## By Type
+
+**Core Concepts** → Foundational understanding (agents, evals, registry)
+**Guides** → Step-by-step workflows
+**Lookup** → Quick reference tables
+**Errors** → Troubleshooting
+```
+
+**Why this works**:
+- ✅ Token-efficient (~250 tokens)
+- ✅ ASCII tree shows structure
+- ✅ Quick routes for common tasks
+- ✅ Organized by information type
+
+---
+
+## Example 2: Category Navigation (Concern-Based)
+
+**File**: `development/navigation.md`
+
+**Pattern**: Concern-Based (multi-technology)
+
+**Token count**: ~280 tokens
+
+```markdown
+# Development Navigation
+
+**Purpose**: Software development across all stacks
+
+---
+
+## Structure
+
+```
+development/
+├── navigation.md
+├── ui-navigation.md           # Specialized
+├── backend-navigation.md      # Specialized
+│
+├── principles/
+│   ├── clean-code.md
+│   └── api-design.md
+│
+├── frontend/
+│   ├── react/
+│   └── vue/
+│
+├── backend/
+│   ├── api-patterns/
+│   ├── nodejs/
+│   └── authentication/
+│
+└── data/
+    ├── sql-patterns/
+    └── orm-patterns/
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **UI/Frontend** | `ui-navigation.md` |
+| **Backend/API** | `backend-navigation.md` |
+| **Clean code** | `principles/clean-code.md` |
+| **API design** | `principles/api-design.md` |
+
+---
+
+## By Concern
+
+**Principles** → Universal development practices
+**Frontend** → React, Vue, state management
+**Backend** → APIs, Node.js, Python, auth
+**Data** → SQL, NoSQL, ORMs
+```
+
+**Why this works**:
+- ✅ Token-efficient (~280 tokens)
+- ✅ Shows specialized navigation files
+- ✅ Organized by concern (frontend, backend, data)
+- ✅ Points to specialized navigation for complex workflows
+
+---
+
+## Example 3: Specialized Navigation
+
+**File**: `development/ui-navigation.md`
+
+**Pattern**: Cross-cutting (spans multiple categories)
+
+**Token count**: ~270 tokens
+
+```markdown
+# UI Development Navigation
+
+**Scope**: Frontend code + visual design
+
+---
+
+## Structure
+
+```
+Frontend Code (development/frontend/):
+├── react/
+│   ├── hooks-patterns.md
+│   ├── component-architecture.md
+│   └── tanstack/
+│       ├── query-patterns.md
+│       └── router-patterns.md
+└── vue/
+
+Visual Design (ui/web/):
+├── animation-patterns.md
+├── ui-styling-standards.md
+└── design-systems.md
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **React patterns** | `frontend/react/hooks-patterns.md` |
+| **TanStack Query** | `frontend/react/tanstack/query-patterns.md` |
+| **Animations** | `../../ui/web/animation-patterns.md` |
+| **Styling** | `../../ui/web/ui-styling-standards.md` |
+
+---
+
+## By Framework
+
+**React** → `frontend/react/`
+**Vue** → `frontend/vue/`
+**TanStack** → `frontend/react/tanstack/`
+
+## By Concern
+
+**Code patterns** → `development/frontend/`
+**Visual design** → `ui/web/`
+```
+
+**Why this works**:
+- ✅ Token-efficient (~270 tokens)
+- ✅ Spans multiple categories (development/ + ui/)
+- ✅ Task-focused (UI development)
+- ✅ Shows both code and design paths
+
+---
+
+## Example 4: Subcategory Navigation
+
+**File**: `development/backend/navigation.md`
+
+**Pattern**: Concern-based subcategory
+
+**Token count**: ~240 tokens
+
+```markdown
+# Backend Development Navigation
+
+**Scope**: Server-side, APIs, databases, auth
+
+---
+
+## Structure
+
+```
+backend/
+├── navigation.md
+│
+├── api-patterns/
+│   ├── rest-design.md
+│   ├── graphql-design.md
+│   └── grpc-patterns.md
+│
+├── nodejs/
+│   ├── express-patterns.md
+│   └── fastify-patterns.md
+│
+├── python/
+│   └── fastapi-patterns.md
+│
+└── authentication/
+    ├── jwt-patterns.md
+    └── oauth-patterns.md
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **REST API** | `api-patterns/rest-design.md` |
+| **GraphQL** | `api-patterns/graphql-design.md` |
+| **Node.js** | `nodejs/express-patterns.md` |
+| **Auth (JWT)** | `authentication/jwt-patterns.md` |
+
+---
+
+## By Approach
+
+**REST** → `api-patterns/rest-design.md`
+**GraphQL** → `api-patterns/graphql-design.md`
+
+## By Language
+
+**Node.js** → `nodejs/`
+**Python** → `python/`
+```
+
+**Why this works**:
+- ✅ Token-efficient (~240 tokens)
+- ✅ Organized by approach first (REST, GraphQL)
+- ✅ Then by tech (Node.js, Python)
+- ✅ Functional concerns separate (authentication/)
+
+---
+
+## Example 5: Full-Stack Navigation
+
+**File**: `development/fullstack-navigation.md`
+
+**Pattern**: Workflow-focused
+
+**Token count**: ~300 tokens
+
+```markdown
+# Full-Stack Development Navigation
+
+**Scope**: End-to-end application development
+
+---
+
+## Common Stacks
+
+### MERN (MongoDB, Express, React, Node)
+```
+Frontend: development/frontend/react/
+Backend:  development/backend/nodejs/express-patterns.md
+Data:     development/data/nosql-patterns/mongodb.md
+API:      development/backend/api-patterns/rest-design.md
+```
+
+### T3 Stack (Next.js, tRPC, Prisma, Tailwind)
+```
+Frontend: development/frontend/react/ + ui/web/ui-styling-standards.md
+Backend:  development/backend/nodejs/ + api-patterns/trpc-patterns.md
+Data:     development/data/orm-patterns/prisma.md
+```
+
+---
+
+## Quick Routes
+
+| Layer | Navigate To |
+|-------|-------------|
+| **Frontend** | `ui-navigation.md` |
+| **Backend** | `backend-navigation.md` |
+| **Data** | `data/navigation.md` |
+
+---
+
+## Common Workflows
+
+**New API endpoint**:
+1. `principles/api-design.md` (principles)
+2. `backend/api-patterns/rest-design.md` (approach)
+3. `backend/nodejs/express-patterns.md` (implementation)
+
+**New React feature**:
+1. `frontend/react/component-architecture.md` (structure)
+2. `frontend/react/hooks-patterns.md` (logic)
+3. `ui/web/ui-styling-standards.md` (styling)
+```
+
+**Why this works**:
+- ✅ Token-efficient (~300 tokens)
+- ✅ Shows common tech stacks
+- ✅ Workflow-focused (how to build features)
+- ✅ Points to layer-specific navigation
+
+---
+
+## Example 6: Minimal Navigation
+
+**File**: `content/navigation.md`
+
+**Pattern**: Simple category (few files)
+
+**Token count**: ~150 tokens
+
+```markdown
+# Content Navigation
+
+**Purpose**: Copywriting and content creation
+
+---
+
+## Structure
+
+```
+content/
+├── navigation.md
+├── copywriting-frameworks.md
+└── tone-voice.md
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **Write copy** | `copywriting-frameworks.md` |
+| **Set tone** | `tone-voice.md` |
+
+---
+
+## Files
+
+**copywriting-frameworks.md** → AIDA, PAS, persuasive writing
+**tone-voice.md** → Brand voice, tone guidelines
+```
+
+**Why this works**:
+- ✅ Token-efficient (~150 tokens)
+- ✅ Simple structure (only 2 files)
+- ✅ No unnecessary complexity
+- ✅ Clear and scannable
+
+---
+
+## Anti-Patterns (What NOT to Do)
+
+### ❌ Too Verbose
+
+```markdown
+# Development Navigation
+
+**Purpose**: This comprehensive navigation file is designed to help you navigate the extensive collection of software development patterns, standards, and best practices that we have carefully curated across all technology stacks including frontend frameworks like React and Vue, backend technologies such as Node.js and Python, database systems both SQL and NoSQL, and infrastructure tools for deployment and operations.
+
+## Introduction
+
+The development category represents a significant portion of our context system...
+
+[Continues for 800+ tokens]
+```
+
+**Problems**:
+- ❌ 800+ tokens (should be 200-300)
+- ❌ Verbose explanations (should be concise)
+- ❌ Hard to scan (should use tables/trees)
+
+---
+
+### ❌ Missing Structure
+
+```markdown
+# Development Navigation
+
+Here are the files:
+- clean-code.md
+- api-design.md
+- react-patterns.md
+- express-patterns.md
+```
+
+**Problems**:
+- ❌ No ASCII tree (hard to see hierarchy)
+- ❌ No quick routes (hard to find tasks)
+- ❌ No organization (just a list)
+
+---
+
+### ❌ Too Detailed
+
+```markdown
+# Development Navigation
+
+## React Patterns
+
+### Hooks
+React hooks allow you to use state and lifecycle features in functional components. The most common hooks are:
+
+1. useState - For managing component state
+   - Syntax: const [state, setState] = useState(initialValue)
+   - Example: const [count, setCount] = useState(0)
+   
+2. useEffect - For side effects
+   [... continues with full documentation]
+```
+
+**Problems**:
+- ❌ Contains file contents (should just point to files)
+- ❌ Duplicates information (should reference, not repeat)
+- ❌ Too detailed (navigation, not documentation)
+
+---
+
+## Key Takeaways
+
+### ✅ Good Navigation Files
+
+1. **Token-efficient** (200-300 tokens)
+2. **Scannable** (ASCII trees, tables)
+3. **Task-focused** (quick routes)
+4. **Organized** (by concern/type)
+5. **Concise** (3-5 word descriptions)
+
+### ❌ Bad Navigation Files
+
+1. **Verbose** (500+ tokens)
+2. **Hard to scan** (paragraphs)
+3. **Unfocused** (no clear routes)
+4. **Unorganized** (just lists)
+5. **Detailed** (duplicates content)
+
+---
+
+## Related
+
+- `../guides/navigation-design.md` - How to create navigation files
+- `../guides/organizing-context.md` - How to choose organizational pattern
+- `../standards/mvi.md` - Minimal Viable Information principle

+ 39 - 0
plugins/claude-code/scripts/context/core/context-system/examples/navigation.md

@@ -0,0 +1,39 @@
+<!-- Context: core/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Context System Examples
+
+**Purpose**: Example navigation files and context patterns
+
+---
+
+## Structure
+
+```
+examples/
+├── navigation.md (this file)
+└── navigation-examples.md
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **View navigation examples** | `navigation-examples.md` |
+| **Learn navigation design** | `../guides/navigation-design-basics.md` |
+| **Use templates** | `../guides/navigation-templates.md` |
+
+---
+
+## By Type
+
+**Examples** → Working examples of navigation files
+
+---
+
+## Related Context
+
+- **Context System** → `../navigation.md`
+- **Guides** → `../guides/navigation.md`
+- **Standards** → `../standards/navigation.md`

+ 122 - 0
plugins/claude-code/scripts/context/core/context-system/guides/compact.md

@@ -0,0 +1,122 @@
+<!-- Context: core/compact | Priority: high | Version: 1.1 | Updated: 2026-02-15 -->
+
+# Context Compaction (Minimization)
+
+**Purpose**: Compress verbose content into minimal viable information
+
+**Last Updated**: 2026-02-15
+
+---
+
+## Core Idea
+
+Transform verbose explanations → core concepts following MVI principle.
+
+**Formula**: Verbose Content → Core Concept (1-3 sentences) → Key Points (3-5 bullets) → Minimal Example (<10 lines) → Reference Link → Compact File
+
+---
+
+## 5 Compression Techniques
+
+### 1. Extract Core Concept
+**From**: Paragraphs → **To**: 1-3 sentences  
+**Rule**: If you can't explain it in 3 sentences, simplify further.
+
+### 2. Bulletize Key Points
+**From**: Long paragraphs → **To**: 3-5 bullet points  
+**Rule**: Each bullet = one key fact. No sub-bullets.
+
+### 3. Minimize Examples
+**From**: Full implementations → **To**: Smallest working example (<10 lines)  
+**Rule**: Show the simplest case. Link to full examples.
+
+### 4. Replace Repetition with References
+**From**: Same info repeated → **To**: Define once, reference with links  
+**Rule**: Say it once in concepts/, reference everywhere else.
+
+### 5. Convert Prose to Tables
+**From**: Paragraphs listing things → **To**: Scannable tables  
+**Rule**: If listing >3 items, use a table or bullets.
+
+---
+
+## Compaction Checklist
+
+- [ ] Core concept is 1-3 sentences?
+- [ ] Key points are 3-5 bullets (no sub-bullets)?
+- [ ] Example is <10 lines of code?
+- [ ] No repeated explanations?
+- [ ] Reference link added for deep dive?
+- [ ] File is under line limit?
+- [ ] Can be scanned in <30 seconds?
+
+---
+
+## Common Bloat Patterns to Remove
+
+| Bloat Type | ❌ Avoid | ✅ Use Instead |
+|------------|---------|---------------|
+| Over-Explaining | "This is important because it allows you to manage state in a more efficient way..." | "Manages state efficiently" |
+| Historical Context | "Before React 16.8, we used class components..." | Skip history unless critical |
+| Multiple Examples | Example 1, 2, 3, 4... | ONE simple example + link |
+| Implementation Details | "The internal implementation uses a fiber architecture..." | Skip internals, show usage |
+
+---
+
+## Target Line Counts
+
+| File Type | Target | Max |
+|-----------|--------|-----|
+| Concept | 40-60 | 100 |
+| Example | 30-50 | 80 |
+| Guide | 60-100 | 150 |
+| Lookup | 20-40 | 100 |
+| Error | 50-80 | 150 |
+
+**Philosophy**: If you hit max lines, split into multiple files or reference external docs.
+
+---
+
+## The 30-Second Rule
+
+<rule id="thirty_second_rule" enforcement="strict">
+  Every context file must be scannable in <30 seconds.
+</rule>
+
+**Test**: Can someone unfamiliar explain it back in 30 seconds?
+
+---
+
+## Quick Example
+
+**Before (150 lines)**: Long authentication system explanation with edge cases, examples, etc.
+
+**After (45 lines)**:
+```markdown
+# Concept: Authentication
+
+**Core Idea**: JWT-based stateless auth. Token in httpOnly cookie, verified on every request.
+
+**Key Points**:
+- Token has userId + role claims
+- Expires in 1 hour (refresh token for renewal)
+- Stored in httpOnly cookie (XSS protection)
+- Verified via middleware on protected routes
+
+**Quick Example**:
+```js
+const token = jwt.sign({ userId: 123 }, SECRET, { expiresIn: '1h' })
+res.cookie('auth', token, { httpOnly: true })
+```
+
+**Reference**: https://docs.company.com/auth
+**Related**: examples/jwt-auth.md, errors/auth-errors.md
+```
+
+---
+
+## Related
+
+- mvi.md - MVI principle
+- harvest.md - When to compact
+- templates.md - Standard formats

+ 173 - 0
plugins/claude-code/scripts/context/core/context-system/guides/creation.md

@@ -0,0 +1,173 @@
+<!-- Context: core/creation | Priority: high | Version: 1.1 | Updated: 2026-02-15 -->
+
+# Context File Creation Standards
+
+**Purpose**: Ensure all context files follow the same format and structure
+
+**Last Updated**: 2026-02-15
+
+---
+
+## Critical Rules
+
+<critical_rules priority="absolute" enforcement="strict">
+  <rule id="size_limit">Files MUST be under line limits (see below)</rule>
+  <rule id="mvi_required">All files MUST follow MVI principle</rule>
+  <rule id="function_placement">Files MUST be in correct folder</rule>
+  <rule id="navigation_update">MUST update navigation.md when creating files</rule>
+</critical_rules>
+
+---
+
+## Creation Workflow
+
+### 1. Determine Function
+Ask: Is this a concept, example, guide, lookup, or error?  
+→ Place in correct folder
+
+### 2. Apply Template
+Use standard template for file type (see templates.md)
+
+### 3. Apply MVI
+- Core: 1-3 sentences
+- Key points: 3-5 bullets
+- Example: <10 lines
+- Reference: Link to docs
+
+### 4. Validate Size
+Ensure file under limit. If not, split or reference external.
+
+### 5. Add Cross-References
+Link to related concepts/, examples/, guides/, errors/
+
+### 6. Update Navigation
+Add entry to navigation.md in parent directory
+
+---
+
+## File Naming Conventions
+
+| Type | Format | Example |
+|------|--------|---------|
+| Concept | `{concept-name}.md` | `authentication.md` |
+| Example | `{example-name}.md` | `jwt-example.md` |
+| Guide | `{action-name}.md` | `creating-agents.md` |
+| Lookup | `{reference-name}.md` | `commands.md` |
+| Error | `{error-category}.md` | `auth-errors.md` |
+
+**Rules**:
+- Use kebab-case (lowercase with hyphens)
+- Be descriptive but concise
+- Avoid redundant category in name (not `concept-authentication.md`)
+
+---
+
+## Standard Metadata (Frontmatter)
+
+```html
+<!-- Context: {path} | Priority: {level} | Version: {X.Y} | Updated: {YYYY-MM-DD} -->
+```
+
+**Priority levels**: critical, high, medium, low
+
+**When to use**:
+- critical: Core system files, always needed
+- high: Frequently referenced, important patterns
+- medium: Useful but not essential
+- low: Nice-to-have, rarely needed
+
+---
+
+## File Size Limits
+
+| File Type | Max Lines |
+|-----------|-----------|
+| Concept | 100 |
+| Example | 80 |
+| Guide | 150 |
+| Lookup | 100 |
+| Error | 150 |
+
+**Enforcement**: Strict. If over limit, split into multiple files or reference external docs.
+
+---
+
+## Cross-Reference Guidelines
+
+**Format**: `See {type}/{filename}.md for {what}`
+
+**Examples**:
+- `See concepts/authentication.md for JWT details`
+- `See examples/jwt-example.md for working code`
+- `See errors/auth-errors.md for troubleshooting`
+
+**Best practices**:
+- Link to related concepts
+- Link to examples from guides
+- Link to errors from guides
+- Create bidirectional links when relevant
+
+---
+
+## Navigation Update Process
+
+When creating a file, update parent `navigation.md`:
+
+```markdown
+| File | Description | Priority |
+|------|-------------|----------|
+| new-file.md | Brief description | high |
+```
+
+**Keep navigation**:
+- Alphabetical within priority groups
+- Grouped by priority (critical → high → medium → low)
+- Descriptions <10 words
+
+---
+
+## Validation Before Commit
+
+- [ ] File under line limit?
+- [ ] MVI format applied?
+- [ ] Frontmatter added?
+- [ ] In correct folder?
+- [ ] Navigation.md updated?
+- [ ] Cross-references added?
+- [ ] Can be scanned in <30 seconds?
+
+---
+
+## Common Creation Mistakes
+
+| Mistake | Fix |
+|---------|-----|
+| File too long | Split into multiple files or compress |
+| Missing frontmatter | Add HTML comment at top |
+| Wrong folder | Move to correct function folder |
+| No cross-references | Add links to related files |
+| Verbose explanations | Apply MVI compression |
+| Missing from navigation | Update navigation.md |
+
+---
+
+## Template Selection
+
+| File Type | Template | Use When |
+|-----------|----------|----------|
+| Concept | Concept template | Explaining what something is |
+| Example | Example template | Showing working code |
+| Guide | Guide template | Step-by-step instructions |
+| Lookup | Lookup template | Quick reference data |
+| Error | Error template | Troubleshooting issues |
+
+See templates.md for full templates.
+
+---
+
+## Related
+
+- templates.md - File templates
+- mvi.md - MVI principle
+- compact.md - Compression techniques
+- structure.md - Directory structure

+ 133 - 0
plugins/claude-code/scripts/context/core/context-system/guides/navigation-design-basics.md

@@ -0,0 +1,133 @@
+<!-- Context: core/navigation-design-basics | Priority: high | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Guide: Designing Navigation Files
+
+**Purpose**: How to create token-efficient, scannable navigation files
+
+---
+
+## Prerequisites
+
+- Understand MVI principle (`context-system/standards/mvi.md`)
+- Know your category's organizational pattern
+- Have content files already created
+
+**Estimated time**: 15-20 min per navigation file
+
+---
+
+## Core Principles
+
+### 1. Token Efficiency
+**Goal**: 200-300 tokens per navigation file
+
+**How**:
+- Use ASCII trees (not verbose descriptions)
+- Use tables (not paragraphs)
+- Be concise (not comprehensive)
+
+### 2. Scannable Structure
+**Goal**: AI can find what it needs in <5 seconds
+
+**Format**:
+1. **Structure** (ASCII tree) - See what exists
+2. **Quick Routes** (table) - Jump to common tasks
+3. **By Concern/Type** (sections) - Browse by category
+
+### 3. Self-Contained
+**Include**: ✅ Paths | ✅ Brief descriptions (3-5 words) | ✅ When to use
+**Exclude**: ❌ File contents | ❌ Detailed explanations | ❌ Duplicates
+
+---
+
+## Steps
+
+### 1. Determine Navigation Type
+
+| Type | Path | Purpose |
+|------|------|---------|
+| Category-level | `{category}/navigation.md` | Overview of category |
+| Subcategory-level | `{category}/{sub}/navigation.md` | Files in subcategory |
+| Specialized | `{category}/{domain}-navigation.md` | Cross-cutting (e.g., ui-navigation.md) |
+
+### 2. Create Structure Section
+
+```markdown
+## Structure
+
+```
+openagents-repo/
+├── navigation.md
+├── quick-start.md
+├── concepts/
+│   └── subagent-testing-modes.md
+├── guides/
+│   ├── adding-agent.md
+│   └── testing-agent.md
+└── lookup/
+    └── commands.md
+```
+```
+
+**Token count**: ~50-100 tokens
+
+### 3. Create Quick Routes Table
+
+```markdown
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **Add agent** | `guides/adding-agent.md` |
+| **Test agent** | `guides/testing-agent.md` |
+| **Find files** | `lookup/file-locations.md` |
+```
+
+**Guidelines**: Use **bold** for tasks | Relative paths | 5-10 common tasks
+
+### 4. Create By Concern/Type Sections
+
+```markdown
+## By Type
+
+**Concepts** → Core ideas and principles
+**Guides** → Step-by-step workflows
+**Lookup** → Quick reference tables
+**Errors** → Troubleshooting
+```
+
+### 5. Add Related Context (Optional)
+
+```markdown
+## Related Context
+
+- **Core Standards** → `../core/standards/navigation.md`
+```
+
+### 6. Validate Token Count
+
+**Target**: 200-300 tokens
+
+```bash
+wc -w navigation.md  # Multiply by 1.3 for token estimate
+```
+
+---
+
+## Verification Checklist
+
+- [ ] Token count 200-300?
+- [ ] ASCII tree included?
+- [ ] Quick routes table?
+- [ ] By concern/type section?
+- [ ] Relative paths?
+- [ ] Descriptions 3-5 words?
+- [ ] No duplicate information?
+
+---
+
+## Related
+
+- `navigation-templates.md` - Ready-to-use templates
+- `../standards/mvi.md` - MVI principle
+- `../examples/navigation-examples.md` - More examples

+ 185 - 0
plugins/claude-code/scripts/context/core/context-system/guides/navigation-templates.md

@@ -0,0 +1,185 @@
+<!-- Context: core/navigation-templates | Priority: high | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Navigation File Templates
+
+**Purpose**: Ready-to-use templates for navigation files
+
+---
+
+## Category Navigation Template
+
+```markdown
+# {Category} Navigation
+
+**Purpose**: [1 sentence]
+
+---
+
+## Structure
+
+```
+{category}/
+├── navigation.md
+├── {subcategory}/
+│   ├── navigation.md
+│   └── {files}.md
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **{Task 1}** | `{path}` |
+| **{Task 2}** | `{path}` |
+| **{Task 3}** | `{path}` |
+
+---
+
+## By {Concern/Type}
+
+**{Section 1}** → {description}
+**{Section 2}** → {description}
+**{Section 3}** → {description}
+
+---
+
+## Related Context
+
+- **{Category}** → `../{category}/navigation.md`
+```
+
+**Token count**: ~200-250 tokens
+
+---
+
+## Specialized Navigation Template
+
+```markdown
+# {Domain} Navigation
+
+**Scope**: [What this covers]
+
+---
+
+## Structure
+
+```
+{Relevant directories across multiple categories}
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **{Task 1}** | `{path}` |
+| **{Task 2}** | `{path}` |
+
+---
+
+## By {Framework/Approach}
+
+**{Tech 1}** → `{path}`
+**{Tech 2}** → `{path}`
+
+---
+
+## Common Workflows
+
+**{Workflow 1}**:
+1. `{file1}` ({purpose})
+2. `{file2}` ({purpose})
+```
+
+**Token count**: ~250-300 tokens
+
+---
+
+## Good Example (Token-Efficient)
+
+```markdown
+# Development Navigation
+
+**Purpose**: Software development across all stacks
+
+---
+
+## Structure
+
+```
+development/
+├── navigation.md
+├── ui-navigation.md
+├── principles/
+├── frontend/
+├── backend/
+└── data/
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **UI/Frontend** | `ui-navigation.md` |
+| **Backend/API** | `backend-navigation.md` |
+| **Clean code** | `principles/clean-code.md` |
+
+---
+
+## By Concern
+
+**Principles** → Universal practices
+**Frontend** → React, Vue, state
+**Backend** → APIs, Node, auth
+**Data** → SQL, NoSQL, ORMs
+```
+
+**Token count**: ~180 tokens ✅
+
+---
+
+## Bad Example (Too Verbose)
+
+```markdown
+# Development Navigation
+
+**Purpose**: This navigation file helps you find software development 
+patterns, standards, and best practices across all technology stacks 
+including frontend, backend, databases, and infrastructure.
+
+---
+
+## Introduction
+
+The development category contains comprehensive guides and patterns 
+for building modern applications. Whether you're working on frontend 
+user interfaces, backend APIs, database integrations...
+
+[... continues for 500+ tokens]
+```
+
+**Token count**: 500+ tokens ❌
+
+---
+
+## Troubleshooting
+
+| Issue | Solution |
+|-------|----------|
+| Too many tokens | Remove verbose descriptions, shorten entries |
+| Hard to scan | Use tables instead of paragraphs |
+| Missing files | Add to structure and quick routes |
+| Unclear paths | Use relative paths, add brief descriptions |
+
+---
+
+## Related
+
+- `navigation-design-basics.md` - Core principles and steps
+- `../standards/mvi.md` - MVI principle
+- `../examples/navigation-examples.md` - More examples

+ 50 - 0
plugins/claude-code/scripts/context/core/context-system/guides/navigation.md

@@ -0,0 +1,50 @@
+<!-- Context: core/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Context System Guides
+
+**Purpose**: Step-by-step guides for working with the context system
+
+---
+
+## Structure
+
+```
+guides/
+├── navigation.md (this file)
+├── compact.md
+├── creation.md
+├── navigation-design-basics.md
+├── navigation-templates.md
+├── organizing-context.md
+└── workflows.md
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **Create context files** | `creation.md` |
+| **Design navigation** | `navigation-design-basics.md` |
+| **Use templates** | `navigation-templates.md` |
+| **Organize context** | `organizing-context.md` |
+| **Compact files** | `compact.md` |
+| **Context workflows** | `workflows.md` |
+
+---
+
+## By Type
+
+**Creation** → How to create new context files  
+**Navigation** → How to design navigation files  
+**Organization** → How to organize context structure  
+**Maintenance** → How to maintain and compact files
+
+---
+
+## Related Context
+
+- **Context System** → `../navigation.md`
+- **Operations** → `../operations/navigation.md`
+- **Standards** → `../standards/navigation.md`

+ 152 - 0
plugins/claude-code/scripts/context/core/context-system/guides/organizing-context.md

@@ -0,0 +1,152 @@
+<!-- Context: core/organizing-context | Priority: high | Version: 1.1 | Updated: 2026-02-15 -->
+
+# Guide: Organizing Context by Concern
+
+**Purpose**: How to choose and apply the right organizational pattern
+
+**Last Updated**: 2026-02-15
+
+---
+
+## Two Organizational Patterns
+
+### Pattern A: Function-Based
+**Use for**: Repository-specific context
+
+**Structure**: Organize by what the information does
+```
+{repo}/
+├── concepts/     # What it is
+├── examples/     # Working code
+├── guides/       # How to do it
+├── lookup/       # Quick reference
+└── errors/       # Troubleshooting
+```
+
+**Example**: `openagents-repo/`
+
+---
+
+### Pattern B: Concern-Based
+**Use for**: Multi-technology development context
+
+**Structure**: Organize by what you're doing (concern), then how (approach/tech)
+```
+{concern}/
+├── {approach}/   # How you're doing it
+└── {tech}/       # What you're using
+```
+
+**Example**: `development/frontend/react/`, `ui/web/design/`
+
+---
+
+## Decision Tree
+
+| Question | Answer | Use Pattern |
+|----------|--------|-------------|
+| Is this repository-specific? | YES | **Pattern A** (Function-Based) |
+| Does content span multiple technologies? | YES | **Pattern B** (Concern-Based) |
+| Single domain/technology? | YES | **Pattern A** (Function-Based) |
+
+---
+
+## Quick Steps to Organize
+
+### 1. Audit Existing Content
+- List all files
+- Identify natural groupings
+- Note overlaps/duplicates
+
+### 2. Choose Pattern
+- Use decision tree above
+- Consider future growth
+- Check existing patterns in `.opencode/context/`
+
+### 3. Create Directory Structure
+```bash
+mkdir -p {category}/{subcategory}
+```
+
+### 4. Move Files
+- Move files to new structure
+- Keep filenames descriptive
+- Follow naming conventions
+
+### 5. Create Navigation Files
+- Add `navigation.md` to each directory
+- Follow navigation template (see navigation-templates.md)
+- Keep to 200-300 tokens
+
+### 6. Update References
+- Update links in moved files
+- Update parent navigation.md
+- Test navigation paths
+
+---
+
+## Pattern Examples
+
+### Function-Based (openagents-repo/)
+```
+openagents-repo/
+├── concepts/agents.md
+├── examples/subagent-example.md
+├── guides/creating-agents.md
+├── lookup/commands.md
+└── errors/tool-errors.md
+```
+
+### Concern-Based (development/)
+```
+development/
+├── frontend/
+│   ├── react/
+│   └── vue/
+├── backend/
+│   ├── node/
+│   └── python/
+└── data/
+    └── postgres/
+```
+
+### Hybrid (ui/)
+```
+ui/
+├── web/
+│   ├── design/
+│   ├── animation/
+│   └── react-patterns.md
+└── terminal/
+    └── cli-design.md
+```
+
+---
+
+## Verification Checklist
+
+- [ ] Every directory has navigation.md?
+- [ ] Navigation files follow template?
+- [ ] All files have frontmatter?
+- [ ] Links updated and working?
+- [ ] Pattern is consistent?
+- [ ] Files under line limits?
+
+---
+
+## Troubleshooting
+
+| Issue | Solution |
+|-------|----------|
+| File fits multiple categories | Choose primary purpose, reference from others |
+| Too many files in one directory | Create subcategories |
+| Unclear hierarchy | Use concern-based pattern |
+| Navigation too complex | Simplify structure, use specialized navigation |
+
+---
+
+## Related
+
+- structure.md - Directory structure standards
+- navigation-templates.md - Navigation file templates
+- creation.md - Creating new context files

+ 573 - 0
plugins/claude-code/scripts/context/core/context-system/guides/workflows.md

@@ -0,0 +1,573 @@
+<!-- Context: core/workflows | Priority: high | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Context Operation Workflows
+
+**Purpose**: Detailed interactive workflows for all context operations
+
+**Last Updated**: 2026-01-06
+
+---
+
+## Extract Workflow (Interactive)
+
+### Stage 1: Read Source
+```
+/context extract from https://react.dev/hooks
+  ↓
+Agent: "Reading source (8,500 lines)...
+Analyzing content for extractable items..."
+```
+
+### Stage 2: Analyze & Categorize
+```
+Agent: "Analysis complete.
+
+Found 12 core concepts:
+  - useState (state management)
+  - useEffect (side effects)
+  - useContext (context consumption)
+  ... (9 more)
+
+Found 8 common errors:
+  - Hooks called conditionally
+  - Hooks in loops
+  - Hooks outside components
+  ... (5 more)
+
+Found 3 workflows:
+  - Setting up custom hooks
+  - Debugging hook issues
+  - Testing components with hooks"
+```
+
+### Stage 3: Select Category (APPROVAL REQUIRED)
+```
+Agent: "Which category should this go in?
+  [1] development/
+  [2] core/
+  [3] Create new category: ___
+
+Select items to extract:
+  Concepts:
+    ✓ [A] useState
+    ✓ [B] useEffect
+    ✓ [C] useContext
+    ... [D-L] (9 more)
+  
+  Errors:
+    ✓ [M] Hooks called conditionally
+    ✓ [N] Hooks in loops
+    ... [O-T] (6 more)
+  
+  Guides:
+    ✓ [U] Setting up custom hooks
+    ✓ [V] Debugging hook issues
+    ✓ [W] Testing components
+
+Type items (A B M or 'all') + category (1/2/3):"
+
+User: "all 1"
+```
+
+### Stage 4: Preview (APPROVAL REQUIRED)
+```
+Agent: "Would create in development/:
+
+  concepts/use-state.md (45 lines)
+  concepts/use-effect.md (52 lines)
+  concepts/use-context.md (38 lines)
+  ... (9 more concept files)
+  
+  errors/react-hooks-errors.md (124 lines)
+    - 8 errors grouped in one file
+  
+  guides/custom-hooks.md (87 lines)
+  guides/debugging-hooks.md (65 lines)
+  guides/testing-hooks.md (72 lines)
+
+Total: 15 files, ~850 lines
+
+Preview specific file? (type filename or 'skip')
+Approve? (yes/no/preview):"
+
+User: "preview use-state.md"
+
+Agent: [Shows first 30 lines of use-state.md]
+
+User: "yes"
+```
+
+### Stage 5-7: Create, Update, Report
+```
+Agent: "Creating files...
+✅ Extracted 20 items into development/
+📄 Created 15 files
+📊 Updated development/README.md
+
+Files created:
+  - development/concepts/ (12 files)
+  - development/errors/react-hooks-errors.md
+  - development/guides/ (3 files)"
+```
+
+---
+
+## Organize Workflow (Interactive)
+
+### Stage 1-2: Scan & Categorize
+```
+/context organize development/
+  ↓
+Agent: "Scanning development/ (23 files, flat structure)...
+
+Categorizing by function..."
+```
+
+### Stage 3: Resolve Conflicts (APPROVAL REQUIRED)
+```
+Agent: "Categorization plan:
+
+Clear categorization (18 files):
+  concepts/ (8 files):
+    ✓ authentication.md → concepts/authentication.md
+    ✓ state-management.md → concepts/state-management.md
+    ✓ caching.md → concepts/caching.md
+    ... (5 more)
+  
+  examples/ (5 files):
+    ✓ jwt-example.md → examples/jwt-example.md
+    ✓ hooks-example.md → examples/hooks-example.md
+    ... (3 more)
+  
+  guides/ (5 files):
+    ✓ setting-up-auth.md → guides/setting-up-auth.md
+    ... (4 more)
+
+Ambiguous files (5 - need your input):
+  
+  [?] api-design.md (contains concepts AND step-by-step guide)
+      Content: Explains REST principles (concept) + how to design endpoints (guide)
+      → [A] Split into:
+            concepts/api-design.md (REST principles)
+            guides/api-design-guide.md (how to design)
+      → [B] Keep as concepts/api-design.md (primary: concepts)
+      → [C] Keep as guides/api-design.md (primary: guide)
+  
+  [?] error-handling.md (contains guide AND error examples)
+      Content: How to handle errors (guide) + common error patterns (errors)
+      → [D] Split into:
+            guides/error-handling.md (how to handle)
+            errors/common-errors.md (error patterns)
+      → [E] Keep as guides/error-handling.md
+      → [F] Keep as errors/error-handling.md
+  
+  [?] testing-patterns.md (contains concepts AND examples)
+      → [G] Split into concepts/ + examples/
+      → [H] Keep as concepts/testing-patterns.md
+      → [I] Keep as examples/testing-patterns.md
+
+Conflicts (2):
+  
+  [!] authentication.md → concepts/auth.md
+      Target concepts/auth.md already exists (120 lines)
+      → [J] Merge authentication.md into existing auth.md
+      → [K] Rename to concepts/authentication-v2.md
+      → [L] Skip (keep flat)
+  
+  [!] jwt-example.md → examples/jwt.md
+      Target examples/jwt.md already exists (65 lines)
+      → [M] Merge jwt-example.md into existing jwt.md
+      → [N] Rename to examples/jwt-example-v2.md
+      → [O] Skip (keep flat)
+
+Select resolutions (A D G J M or 'auto' for AI suggestions):"
+
+User: "A D G J M"
+```
+
+### Stage 4: Preview (APPROVAL REQUIRED)
+```
+Agent: "Preview of changes:
+
+CREATE directories:
+  development/concepts/
+  development/examples/
+  development/guides/
+  development/lookup/
+  development/errors/
+
+MOVE files (18):
+  authentication.md → concepts/authentication.md
+  state-management.md → concepts/state-management.md
+  ... (16 more)
+
+SPLIT files (3):
+  api-design.md →
+    concepts/api-design.md (concepts section)
+    guides/api-design-guide.md (guide section)
+  
+  error-handling.md →
+    guides/error-handling.md (guide section)
+    errors/common-errors.md (error examples)
+  
+  testing-patterns.md →
+    concepts/testing-patterns.md (concepts)
+    examples/testing-examples.md (examples)
+
+MERGE files (2):
+  authentication.md → concepts/auth.md (merge content)
+  jwt-example.md → examples/jwt.md (merge content)
+
+UPDATE:
+  development/README.md (create navigation tables)
+  Fix 47 internal references
+
+Dry-run? (yes/no/show-diff):"
+
+User: "dry-run"
+
+Agent: [Simulates changes without executing, shows what would happen]
+
+User: "yes"
+```
+
+### Stage 5-8: Backup, Execute, Update, Report
+```
+Agent: "Creating backup...
+💾 Backup: .tmp/backup/organize-development-2026-01-06-143022/
+
+Executing changes...
+✅ Organized 23 files into function folders
+📁 Created 5 new folders
+🔀 Split 3 ambiguous files
+🔗 Fixed 47 references
+📊 Updated development/README.md
+
+Rollback available at: .tmp/backup/organize-development-2026-01-06-143022/"
+```
+
+---
+
+## Update Workflow (Interactive)
+
+### Stage 1: Identify Changes (APPROVAL REQUIRED)
+```
+/context update for Next.js 15
+  ↓
+Agent: "What changed in Next.js 15?
+  [A] API changes
+  [B] Deprecations
+  [C] New features
+  [D] Breaking changes
+  [E] Other (describe)
+
+Select all that apply (A B C D or describe):"
+
+User: "A C D"
+
+Agent: "Please describe the changes:
+  API changes: ___
+  New features: ___
+  Breaking changes: ___"
+
+User: "API changes: App router is now default
+New features: New metadata API, Server Actions stable
+Breaking changes: Pages router requires explicit opt-in"
+```
+
+### Stage 2: Find Affected Files
+```
+Agent: "Searching for files referencing Next.js...
+
+Found 5 files with 17 references:
+  📄 concepts/routing.md (3 references, 145 lines)
+  📄 examples/app-router-example.md (7 references, 78 lines)
+  📄 guides/setting-up-nextjs.md (2 references, 132 lines)
+  📄 errors/nextjs-errors.md (1 reference, 98 lines)
+  📄 lookup/nextjs-commands.md (4 references, 54 lines)
+
+Total impact: 17 references across 5 files"
+```
+
+### Stage 3: Preview Changes (APPROVAL REQUIRED)
+```
+Agent: "Proposed updates:
+
+━━━ concepts/routing.md ━━━
+
+Line 15:
+  - App router is optional (use pages/ or app/ directory)
+  + App router is now default in Next.js 15 (pages/ still supported with opt-in)
+
+Line 42:
+  + ## Metadata API (New in v15)
+  + 
+  + Next.js 15 introduces new metadata API for SEO optimization.
+  + Replaces Head component with metadata exports.
+
+Line 87:
+  - **Reference**: https://nextjs.org/docs/app
+  + **Reference**: https://nextjs.org/docs/15/app
+
+━━━ examples/app-router-example.md ━━━
+
+Line 8:
+  - // Optional: use app router
+  + // Default in Next.js 15+
+
+Line 23:
+  + // New: Metadata API
+  + export const metadata = {
+  +   title: 'My App',
+  +   description: 'App description'
+  + }
+
+━━━ guides/setting-up-nextjs.md ━━━
+
+Line 45:
+  - 3. Choose router: pages/ or app/
+  + 3. App router is default (use --pages flag for pages router)
+
+━━━ errors/nextjs-errors.md ━━━
+
+Line 67:
+  + ## Migration: Next.js 14 → 15
+  + 
+  + **Breaking Changes**:
+  + - App router is now default
+  + - Pages router requires explicit opt-in
+  + 
+  + **Migration Steps**:
+  + 1. Update to Next.js 15: `npm install next@15`
+  + 2. For pages router: Add `pages: true` to next.config.js
+  + 3. Update metadata: Replace Head with metadata exports
+  + 
+  + **Reference**: https://nextjs.org/docs/15/upgrade-guide
+
+━━━ lookup/nextjs-commands.md ━━━
+
+Line 12:
+  - npx create-next-app@latest
+  + npx create-next-app@latest  # App router default
+  + npx create-next-app@latest --pages  # Pages router
+
+Preview next file? (yes/no/show-all)
+Approve changes? (yes/no/edit):"
+
+User: "edit"
+
+Agent: "Line-by-line approval mode.
+
+concepts/routing.md - Line 15 change?
+  - App router is optional (use pages/ or app/ directory)
+  + App router is now default in Next.js 15 (pages/ still supported with opt-in)
+
+Approve? (yes/no/modify):"
+
+User: "yes"
+
+[... continues for each change ...]
+```
+
+### Stage 4-8: Backup, Update, Add Migration, Validate, Report
+```
+Agent: "Creating backup...
+💾 Backup: .tmp/backup/update-nextjs-2026-01-06-143530/
+
+Updating files...
+✅ Updated 5 files
+📝 Modified 17 references
+🔄 Added migration notes to errors/nextjs-errors.md
+🔗 Validated all references (0 broken links)
+
+Summary of changes:
+  - concepts/routing.md: 3 updates (145 → 162 lines)
+  - examples/app-router-example.md: 4 updates (78 → 89 lines)
+  - guides/setting-up-nextjs.md: 1 update (132 → 133 lines)
+  - errors/nextjs-errors.md: Added migration section (98 → 125 lines)
+  - lookup/nextjs-commands.md: 2 updates (54 → 56 lines)
+
+All files still under 200 line limit ✓
+
+Rollback available at: .tmp/backup/update-nextjs-2026-01-06-143530/"
+```
+
+---
+
+## Error Workflow (Interactive)
+
+### Stage 1: Search Existing
+```
+/context error for "Cannot read property 'map' of undefined"
+  ↓
+Agent: "Searching existing errors for similar issues...
+
+Found 1 similar error:
+  📄 development/errors/react-errors.md (Line 45)
+     ## Error: Cannot read property 'X' of undefined
+     Covers: General undefined property access in React
+     Frequency: common
+
+Found 2 related errors:
+  📄 development/errors/react-errors.md
+     ## Error: Cannot read property 'length' of undefined
+     ## Error: Undefined is not an object"
+```
+
+### Stage 2: Check Duplication (APPROVAL REQUIRED)
+```
+Agent: "Options:
+  [A] Add as new error to react-errors.md
+      (Specific case: 'map' on undefined array)
+  
+  [B] Update existing 'Cannot read property X' error
+      (Add 'map' as common example)
+  
+  [C] Skip (already covered sufficiently)
+
+Which framework/category?
+  [1] React (react-errors.md)
+  [2] JavaScript (js-errors.md)
+  [3] General (common-errors.md)
+  [4] Create new: ___
+
+Select option + category (e.g., 'B 1'):"
+
+User: "B 1"
+```
+
+### Stage 3: Preview (APPROVAL REQUIRED)
+```
+Agent: "Would update development/errors/react-errors.md:
+
+Current (Line 45):
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+## Error: Cannot read property 'X' of undefined
+
+**Symptom**:
+```
+TypeError: Cannot read property 'X' of undefined
+```
+
+**Cause**: Attempting to access property on undefined/null object.
+
+**Solution**:
+1. Add null check before accessing property
+2. Use optional chaining (?.)
+3. Provide default value
+
+**Code**:
+```jsx
+// ❌ Before
+const value = obj.property
+
+// ✅ After
+const value = obj?.property ?? 'default'
+```
+
+**Prevention**: Always validate data exists before accessing
+**Frequency**: common
+**Reference**: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_access_property
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+
+Proposed update:
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+## Error: Cannot read property 'X' of undefined
+
+**Symptom**:
+```
+TypeError: Cannot read property 'X' of undefined
+TypeError: Cannot read property 'map' of undefined  ← NEW
+TypeError: Cannot read property 'length' of undefined  ← NEW
+```
+
+**Cause**: Attempting to access property on undefined/null object.
+Common with array methods (map, filter) when data hasn't loaded.  ← NEW
+
+**Solution**:
+1. Add null check before accessing property
+2. Use optional chaining (?.)
+3. Provide default value (especially for arrays)  ← UPDATED
+
+**Code**:
+```jsx
+// ❌ Before
+const value = obj.property
+const items = data.map(item => item.name)  ← NEW
+
+// ✅ After
+const value = obj?.property ?? 'default'
+const items = (data || []).map(item => item.name)  ← NEW
+// Or with optional chaining:
+const items = data?.map(item => item.name) ?? []  ← NEW
+```
+
+**Prevention**: Always validate data exists before accessing.
+For arrays, provide empty array default.  ← UPDATED
+
+**Frequency**: common
+**Reference**: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cant_access_property
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+
+File size: 98 lines → 105 lines (under 150 limit ✓)
+
+Approve? (yes/no/edit):"
+
+User: "yes"
+```
+
+### Stage 4-6: Add, Update, Report
+```
+Agent: "Updating development/errors/react-errors.md...
+
+✅ Updated error in development/errors/react-errors.md
+🔗 Cross-referenced with 2 related errors
+📊 File size: 105 lines (under 150 limit)
+
+Changes:
+  - Added 'map' and 'length' to symptom examples
+  - Updated cause to mention array methods
+  - Added array-specific code examples
+  - Updated prevention guidance"
+```
+
+---
+
+## Common Patterns
+
+### Approval Gates
+All operations with `enforce="@critical_rules.approval_gate"` MUST:
+1. Show clear preview of what will happen
+2. Wait for explicit user input
+3. Provide options (yes/no/edit/preview/dry-run)
+4. Never proceed without confirmation
+
+### Conflict Resolution
+When conflicts detected:
+1. Present all options clearly
+2. Use letter-based selection (A/B/C)
+3. Show impact of each option
+4. Allow user to choose resolution
+
+### Previews
+All previews should show:
+1. What will be created/modified/deleted
+2. File sizes (before → after)
+3. Line-by-line diffs for updates
+4. Validation status (under limits, no broken links)
+
+### Backups
+Operations that modify files MUST:
+1. Create backup before changes
+2. Store in `.tmp/backup/{operation}-{topic}-{timestamp}/`
+3. Report backup location
+4. Keep backups for rollback
+
+---
+
+## Related
+
+- context.md - Main command interface
+- harvest.md - Harvest workflow details
+- mvi-principle.md - What to extract
+- compact.md - How to minimize

+ 53 - 0
plugins/claude-code/scripts/context/core/context-system/navigation.md

@@ -0,0 +1,53 @@
+<!-- Context: core/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Context System
+
+**Purpose**: Documentation for the context system architecture and operations
+
+---
+
+## Structure
+
+```
+core/context-system/
+├── navigation.md (this file)
+├── examples/
+│   └── navigation.md
+├── guides/
+│   └── navigation.md
+├── operations/
+│   └── navigation.md
+├── standards/
+│   └── navigation.md
+└── [overview files]
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **Understand context system** | `../context-system.md` |
+| **Operations & procedures** | `operations/navigation.md` |
+| **Implementation guides** | `guides/navigation.md` |
+| **Standards & templates** | `standards/navigation.md` |
+| **Examples** | `examples/navigation.md` |
+| **Migrate global → local** | `operations/migrate.md` |
+
+---
+
+## By Type
+
+**Examples** → Working examples of navigation files  
+**Guides** → Step-by-step guides for working with context  
+**Operations** → How to operate and maintain the context system  
+**Standards** → Templates and standards for context files
+
+---
+
+## Related Context
+
+- **Core Navigation** → `../navigation.md`
+- **Core Standards** → `../standards/navigation.md`
+- **Core System** → `../system/navigation.md`

+ 275 - 0
plugins/claude-code/scripts/context/core/context-system/operations/error.md

@@ -0,0 +1,275 @@
+<!-- Context: core/error | Priority: medium | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Error Operation
+
+**Purpose**: Add recurring errors to knowledge base with deduplication
+
+**Last Updated**: 2026-01-06
+
+---
+
+## When to Use
+
+- Encountered same error multiple times
+- Want to document solution for team
+- Building error knowledge base
+- Preventing repeated debugging
+
+---
+
+## 6-Stage Workflow
+
+### Stage 1: Search Existing
+**Action**: Search for similar/related errors
+
+**Process**:
+1. Search error message across all errors/ files
+2. Find similar errors (fuzzy matching)
+3. Find related errors (same category)
+
+**Format**:
+```
+Searching for: "Cannot read property 'map' of undefined"
+
+Found 1 similar error:
+  📄 development/errors/react-errors.md (Line 45)
+     ## Error: Cannot read property 'X' of undefined
+     Covers: General undefined property access
+     Frequency: common
+
+Found 2 related errors:
+  📄 development/errors/react-errors.md
+     ## Error: Cannot read property 'length' of undefined
+     ## Error: Undefined is not an object
+```
+
+---
+
+### Stage 2: Check Duplication (APPROVAL REQUIRED)
+**Action**: Present deduplication options
+
+**Format**:
+```
+Options:
+  [A] Add as new error to react-errors.md
+      (Specific case: 'map' on undefined array)
+  
+  [B] Update existing 'Cannot read property X' error
+      (Add 'map' as common example)
+  
+  [C] Skip (already covered sufficiently)
+
+Which framework/category?
+  [1] React (react-errors.md)
+  [2] JavaScript (js-errors.md)
+  [3] General (common-errors.md)
+  [4] Create new: ___
+
+Select option + category (e.g., 'B 1'):
+```
+
+**Validation**: MUST wait for user input
+
+---
+
+### Stage 3: Preview (APPROVAL REQUIRED)
+**Action**: Show full error entry before adding
+
+**Format**:
+```
+Would update development/errors/react-errors.md:
+
+Current (Line 45):
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+## Error: Cannot read property 'X' of undefined
+
+**Symptom**:
+```
+TypeError: Cannot read property 'X' of undefined
+```
+
+**Cause**: Attempting to access property on undefined/null object.
+
+**Solution**:
+1. Add null check
+2. Use optional chaining (?.)
+3. Provide default value
+
+**Code**:
+```jsx
+// ❌ Before
+const value = obj.property
+
+// ✅ After
+const value = obj?.property ?? 'default'
+```
+
+**Prevention**: Always validate data exists
+**Frequency**: common
+**Reference**: [Link]
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+
+Proposed update:
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+## Error: Cannot read property 'X' of undefined
+
+**Symptom**:
+```
+TypeError: Cannot read property 'X' of undefined
+TypeError: Cannot read property 'map' of undefined  ← NEW
+TypeError: Cannot read property 'length' of undefined  ← NEW
+```
+
+**Cause**: Attempting to access property on undefined/null object.
+Common with array methods (map, filter) when data hasn't loaded.  ← NEW
+
+**Solution**:
+1. Add null check
+2. Use optional chaining (?.)
+3. Provide default value (especially for arrays)  ← UPDATED
+
+**Code**:
+```jsx
+// ❌ Before
+const value = obj.property
+const items = data.map(item => item.name)  ← NEW
+
+// ✅ After
+const value = obj?.property ?? 'default'
+const items = (data || []).map(item => item.name)  ← NEW
+```
+
+**Prevention**: Always validate data exists. For arrays, provide empty array default.  ← UPDATED
+**Frequency**: common
+**Reference**: [Link]
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+
+File size: 98 lines → 105 lines (under 150 limit ✓)
+
+Approve? (yes/no/edit):
+```
+
+**Edit mode**: Allow modification before adding
+
+**Validation**: MUST get approval before proceeding
+
+---
+
+### Stage 4: Add/Update
+**Action**: Add or update error entry
+
+**Process**:
+1. Add/update error in target file
+2. Follow error template format
+3. Maintain file size <150 lines
+4. Update "Last Updated" date
+
+**Template Format**:
+```markdown
+## Error: {Name}
+
+**Symptom**: [Error message]
+**Cause**: [Why - 1-2 sentences]
+**Solution**: [Steps]
+**Code**: [Before/After example]
+**Prevention**: [How to avoid]
+**Frequency**: common/occasional/rare
+**Reference**: [Link]
+```
+
+---
+
+### Stage 5: Update Navigation
+**Action**: Update README.md and add cross-references
+
+**Process**:
+1. Update README.md if new file created
+2. Add cross-references to related errors
+3. Link from related concepts/examples
+
+---
+
+### Stage 6: Report
+**Action**: Show results
+
+**Format**:
+```
+✅ Added error to {category}/errors/{file}.md
+🔗 Cross-referenced with X related errors
+📊 Updated README.md (if needed)
+
+Changes:
+  - Updated existing error entry
+  - Added 'map' and 'length' examples
+  - File size: 105 lines (under 150 limit)
+```
+
+---
+
+## Deduplication Strategy
+
+### Similar Errors
+Same root cause, different manifestations
+→ **Update existing** to include new examples
+
+### Related Errors
+Different causes, same category
+→ **Cross-reference** between errors
+
+### Duplicate Errors
+Exact same error already documented
+→ **Skip** (already covered)
+
+### New Errors
+Unique error not yet documented
+→ **Add as new** error entry
+
+---
+
+## Error Grouping
+
+Group errors by framework/topic in single file:
+- `react-errors.md` - All React errors
+- `nextjs-errors.md` - All Next.js errors
+- `auth-errors.md` - All authentication errors
+
+**Don't create**: One file per error (too granular)
+
+---
+
+## Examples
+
+### Add New Error
+```bash
+/context error for "hooks can only be called inside components"
+```
+
+### Add Common Error
+```bash
+/context error for "Cannot read property 'map' of undefined"
+```
+
+### Add Framework Error
+```bash
+/context error for "Hydration failed in Next.js"
+```
+
+---
+
+## Success Criteria
+
+- [ ] Searched for similar errors?
+- [ ] Deduplication options presented?
+- [ ] Preview shown?
+- [ ] User approved?
+- [ ] Error follows template format?
+- [ ] File size <150 lines?
+- [ ] Cross-references added?
+- [ ] README.md updated (if new file)?
+
+---
+
+## Related
+
+- standards/templates.md - Error template format
+- guides/workflows.md - Interactive examples

+ 202 - 0
plugins/claude-code/scripts/context/core/context-system/operations/extract.md

@@ -0,0 +1,202 @@
+<!-- Context: core/extract | Priority: medium | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Extract Operation
+
+**Purpose**: Extract context from docs, code, or URLs into organized context files
+
+**Last Updated**: 2026-01-06
+
+---
+
+## When to Use
+
+- Extracting from documentation (React docs, API docs, etc.)
+- Extracting from codebase (patterns, conventions)
+- Extracting from URLs (blog posts, guides)
+- Creating initial context for new topics
+
+---
+
+## 7-Stage Workflow
+
+### Stage 1: Read Source
+```
+/context extract from https://react.dev/hooks
+  ↓
+Agent: "Reading source (8,500 lines)...
+Analyzing content for extractable items..."
+```
+
+**Action**: Read and analyze source material
+
+---
+
+### Stage 2: Analyze & Categorize
+**Action**: Extract and categorize content by function
+
+**Categorization**:
+- Design decisions → `concepts/`
+- Working code → `examples/`
+- Step-by-step workflows → `guides/`
+- Reference data (commands, paths) → `lookup/`
+- Errors/gotchas → `errors/`
+
+**Output**: List of extractable items with previews
+
+---
+
+### Stage 3: Select Category (APPROVAL REQUIRED)
+**Action**: User chooses target category and items
+
+**Format**:
+```
+Found 12 extractable items from {source}:
+
+Concepts (8):
+  ✓ [A] useState - State management hook
+  ✓ [B] useEffect - Side effects hook
+  ... (6 more)
+
+Errors (4):
+  ✓ [I] Hooks called conditionally
+  ✓ [J] Hooks in loops
+  ... (2 more)
+
+Which category?
+  [1] development/
+  [2] core/
+  [3] Create new category: ___
+
+Select items (A B I or 'all') + category (1/2/3):
+```
+
+**Validation**: MUST wait for user input before proceeding
+
+---
+
+### Stage 4: Preview (APPROVAL REQUIRED)
+**Action**: Show what will be created, check for conflicts
+
+**Format**:
+```
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+Extraction Plan: development/
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+
+CREATE (new files):
+  concepts/use-state.md (45 lines)
+  concepts/use-effect.md (52 lines)
+  concepts/use-context.md (38 lines)
+  ... (6 more)
+  guides/custom-hooks.md (87 lines)
+  guides/debugging-hooks.md (65 lines)
+
+ADD TO (existing files):
+  errors/react-hooks-errors.md (98 → 124 lines)
+    + 4 new error entries
+
+⚠️  CONFLICT (file already exists):
+  concepts/use-memo.md already exists (42 lines)
+    Options:
+      [A] Skip — keep existing file
+      [B] Overwrite — replace with extracted version
+      [C] Merge — add new content to existing file (42 → 58 lines)
+    Choose [A/B/C]: _
+
+NAVIGATION UPDATE:
+  development/navigation.md
+    + 9 new entries in Concepts table
+    + 2 new entries in Guides table
+    + 1 updated entry in Errors table
+
+Total: 12 files, ~650 lines
+
+Preview content? (type filename, 'all' for batch, or 'skip')
+Approve? [y/n/edit]: _
+```
+
+**If user types 'all'**: Show first 10 lines of each file in sequence
+**If user types filename**: Show full content of that file
+**If user types 'skip'**: Proceed to approval
+
+**Validation**: MUST get approval before proceeding
+
+---
+
+### Stage 5: Create
+**Action**: Create files in function folders
+
+**Process**:
+1. Apply MVI format (1-3 sentences, 3-5 key points, minimal example)
+2. Create files in correct function folders
+3. Ensure all files <200 lines
+4. Add cross-references
+
+**Enforcement**: `@critical_rules.mvi_strict` + `@critical_rules.function_structure`
+
+---
+
+### Stage 6: Update Navigation (preview included in Stage 4)
+**Action**: Update navigation.md and add cross-references
+
+**Process**:
+1. Update category navigation.md with new files (as previewed in Stage 4)
+2. Add priority levels (critical/high/medium/low)
+3. Add cross-references between related files
+4. Update "Last Updated" dates
+
+---
+
+### Stage 7: Report
+**Action**: Show comprehensive results
+
+**Format**:
+```
+✅ Extracted X items into {category}
+📄 Created Y files
+📊 Updated {category}/README.md
+
+Files created:
+  - {category}/concepts/ (N files)
+  - {category}/examples/ (N files)
+  - {category}/errors/ (N files)
+```
+
+---
+
+## Examples
+
+### Extract from URL
+```bash
+/context extract from https://react.dev/hooks
+```
+
+### Extract from Local Docs
+```bash
+/context extract from docs/api.md
+/context extract from docs/architecture/
+```
+
+### Extract from Code
+```bash
+/context extract from src/utils/
+```
+
+---
+
+## Success Criteria
+
+- [ ] All files <200 lines?
+- [ ] MVI format applied (1-3 sentences, 3-5 points, example, reference)?
+- [ ] Files in correct function folders?
+- [ ] README.md updated?
+- [ ] Cross-references added?
+- [ ] User approved before creation?
+
+---
+
+## Related
+
+- standards/mvi.md - What to extract
+- guides/compact.md - How to minimize
+- guides/workflows.md - Interactive examples

+ 342 - 0
plugins/claude-code/scripts/context/core/context-system/operations/harvest.md

@@ -0,0 +1,342 @@
+<!-- Context: core/harvest | Priority: medium | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Context Harvest Operation
+
+**Purpose**: Extract knowledge from AI summaries → permanent context, then clean workspace
+
+**Last Updated**: 2026-01-06
+
+---
+
+## Core Problem
+
+AI agents create summary files (OVERVIEW.md, SESSION-*.md, SUMMARY.md) that contain valuable knowledge but clutter the workspace. These files "plague" the codebase.
+
+**Solution**: Harvest the knowledge → permanent context, then delete the summaries.
+
+---
+
+## Auto-Detection Patterns
+
+<rule id="summary_patterns" enforcement="strict">
+  Harvest automatically detects these patterns:
+  
+  Filename patterns:
+  - *OVERVIEW.md
+  - *SUMMARY.md
+  - SESSION-*.md
+  - CONTEXT-*.md
+  - *NOTES.md
+  
+  Location patterns:
+  - Files in .tmp/ directory
+  - Files with "Summary", "Overview", "Session" in title
+  - Files >2KB in root directory (likely summaries)
+</rule>
+
+---
+
+## 6-Stage Workflow
+
+<workflow id="harvest" enforce="@critical_rules">
+  
+### Stage 1: Scan
+**Action**: Find all summary files in workspace
+
+**Process**:
+1. Search for auto-detection patterns
+2. Check .tmp/ directory
+3. List files with sizes
+4. Sort by modification date (newest first)
+
+**Output**: List of candidate files
+
+**Example**:
+```
+Found 3 summary documents:
+1. CONTEXT-SYSTEM-OVERVIEW.md (4.2 KB, modified 1 hour ago)
+2. SESSION-auth-work.md (1.8 KB, modified today)
+3. .tmp/IMPLEMENTATION-NOTES.md (800 bytes, modified today)
+```
+
+---
+
+### Stage 2: Analyze
+**Action**: Categorize content by function
+
+**Mapping Rules**:
+| Content Type | Target Folder | How to Identify |
+|--------------|---------------|-----------------|
+| Design decisions | `concepts/` | "We decided to...", "Architecture", "Pattern" |
+| Solutions/patterns | `examples/` | Code snippets, "Here's how we..." |
+| Workflows | `guides/` | Numbered steps, "How to...", "Setup" |
+| Errors encountered | `errors/` | Error messages, "Fixed issue", "Gotcha" |
+| Reference data | `lookup/` | Tables, lists, paths, commands |
+
+**Process**:
+1. Read each file
+2. Identify valuable sections (skip planning/conversation)
+3. Categorize by function
+4. Determine target file path
+5. Generate preview (first 60 chars)
+
+**Output**: Categorized items with letter IDs
+
+---
+
+### Stage 3: Approve (CRITICAL)
+**Action**: Present approval UI with letter-based selection
+
+<rule id="approval_gate" enforcement="strict">
+  ALWAYS show approval UI before extracting/deleting.
+  NEVER auto-harvest without user confirmation.
+</rule>
+
+**Format**:
+```
+### CONTEXT-SYSTEM-OVERVIEW.md (4.2 KB)
+
+✓ [A] Design: Function-based context organization
+    → Would add to: core/concepts/context-organization.md
+    Preview: "Organize by function (concepts/, examples/...)..."
+
+✓ [B] Pattern: Minimal Viable Information
+    → Would add to: core/concepts/mvi-principle.md
+    Preview: "Extract core only (1-3 sentences), 3-5 key points..."
+
+✓ [C] Workflow: Harvesting summary documents
+    → Would create: core/guides/harvesting.md
+    Preview: "Scan for summaries → Extract → Approve → Delete"
+
+✗ [D] Skip: Planning discussion notes (temporary knowledge)
+
+---
+
+### SESSION-auth-work.md (1.8 KB)
+
+✓ [E] Error: JWT token expiration not handled
+    → Would add to: development/errors/auth-errors.md
+    Preview: "Symptom: 401 after 1 hour. Cause: No refresh flow..."
+
+✓ [F] Example: JWT refresh token implementation
+    → Would create: development/examples/jwt-refresh.md
+    Preview: "Store refresh token → Check expiry → Request new..."
+
+---
+
+### .tmp/IMPLEMENTATION-NOTES.md (800 bytes)
+
+✗ [G] Skip: Duplicate info (already in development/concepts/api-design.md)
+
+---
+
+**Quick options**:
+- Type 'A B C E F' - Approve specific items
+- Type 'all' - Approve all ✓ items (A B C E F)
+- Type 'none' - Skip harvesting, delete files anyway
+- Type 'cancel' - Keep files, don't harvest
+```
+
+**Validation**:
+- MUST wait for user input
+- MUST not proceed without approval
+- If user types 'cancel', stop immediately
+
+**Output**: List of approved items
+
+---
+
+### Stage 4: Extract
+**Action**: Extract and minimize approved items
+
+<rule id="extraction" enforce="@mvi_principle">
+  Apply MVI to all extracted content:
+  - Core concept: 1-3 sentences
+  - Key points: 3-5 bullets
+  - Minimal example: <10 lines
+  - Reference link: to original source
+  - Files: <200 lines each
+</rule>
+
+**Process**:
+1. For each approved item:
+   - Extract core content
+   - Apply MVI minimization (see compact.md)
+   - Generate preview of final content
+2. Show extraction preview (APPROVAL REQUIRED):
+
+```
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+Extraction Preview
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+
+[A] → core/concepts/context-organization.md (CREATE, 45 lines)
+┌─────────────────────────────────────────────────────────┐
+│ # Concept: Context Organization                         │
+│                                                         │
+│ **Purpose**: Function-based knowledge organization      │
+│                                                         │
+│ ## Core Concept                                         │
+│ Organize context by function: concepts/, examples/...   │
+│ ...                                                     │
+└─────────────────────────────────────────────────────────┘
+
+[E] → development/errors/auth-errors.md (ADD to existing, 98 → 112 lines)
+┌─────────────────────────────────────────────────────────┐
+│ + ## Error: JWT Token Expiration Not Handled             │
+│ +                                                       │
+│ + **Symptom**: 401 after 1 hour                         │
+│ + **Cause**: No refresh token flow                      │
+│ + ...                                                   │
+└─────────────────────────────────────────────────────────┘
+
+... ({remaining_count} more items)
+
+Show all? [y/n] | Approve extraction? [y/n/edit]: _
+```
+
+3. On approval:
+   - Write files to disk
+   - Add cross-references
+   - Update navigation.md maps
+
+**Output**: List of created/updated files
+
+---
+
+### Stage 5: Cleanup (APPROVAL REQUIRED)
+**Action**: Archive or delete source summary files
+
+```
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+Cleanup: Source Files
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+
+Successfully harvested from:
+  CONTEXT-SYSTEM-OVERVIEW.md (4.2 KB)
+  SESSION-auth-work.md (1.8 KB)
+
+Skipped (no valuable content):
+  .tmp/IMPLEMENTATION-NOTES.md (800 bytes)
+
+How should we handle these source files?
+
+  1. Archive (safe) — move to .tmp/archive/harvested/{date}/
+     → Can restore later if needed
+
+  2. Delete — permanently remove harvested files
+     → Frees disk space, no undo
+
+  3. Keep — leave source files in place
+     → No cleanup, files remain where they are
+
+Choose [1/2/3] (default: 1): _
+```
+
+<rule id="cleanup_safety" enforcement="strict">
+  ONLY cleanup files that had content successfully harvested.
+  If extraction failed, keep the original file.
+</rule>
+
+**Output**: Cleanup report
+
+---
+
+### Stage 6: Report
+**Action**: Show comprehensive results summary
+
+**Format**:
+```
+✅ Harvested 5 items into permanent context:
+   - Added to core/concepts/context-organization.md
+   - Added to core/concepts/mvi-principle.md
+   - Created core/guides/harvesting.md
+   - Added to development/errors/auth-errors.md
+   - Created development/examples/jwt-refresh.md
+
+🗑️ Cleaned up workspace:
+   - Archived: CONTEXT-SYSTEM-OVERVIEW.md → .tmp/archive/harvested/2026-01-06/
+   - Archived: SESSION-auth-work.md → .tmp/archive/harvested/2026-01-06/
+   - Deleted: .tmp/IMPLEMENTATION-NOTES.md (no valuable content)
+
+📊 Updated navigation maps:
+   - .opencode/context/core/navigation.md
+   - .opencode/context/development/navigation.md
+
+💾 Disk space freed: 6.8 KB
+```
+
+</workflow>
+
+---
+
+## Usage Examples
+
+### Scan entire workspace
+```bash
+/context harvest
+```
+
+### Scan specific directory
+```bash
+/context harvest .tmp/
+/context harvest docs/sessions/
+```
+
+### Harvest specific file
+```bash
+/context harvest OVERVIEW.md
+/context harvest SESSION-2026-01-06.md
+```
+
+---
+
+## Smart Content Detection
+
+### ✅ Extract (Valuable Knowledge)
+- Design decisions ("We chose X because...")
+- Patterns that worked ("This pattern solved...")
+- Errors encountered + solutions
+- API changes ("Updated from v1 to v2...")
+- Performance findings ("Optimization reduced...")
+- Core concepts explained
+
+### ❌ Skip (Temporary/Noise)
+- Planning discussion ("Should we...?", "Maybe try...")
+- Conversational notes ("I think...", "We talked about...")
+- Duplicate info (already in context)
+- TODO lists (move to task system instead)
+- Timestamps and session metadata
+
+---
+
+## Safety Features
+
+1. **Approval gate** - Never auto-delete without confirmation
+2. **Archive by default** - Move to .tmp/archive/, not permanent delete
+3. **Validation** - Check file sizes, structure before committing
+4. **Rollback** - Can restore from archive if needed
+5. **Dry run** - Show what would happen before doing it
+
+---
+
+## Success Criteria
+
+After harvest operation:
+
+- [ ] Valuable knowledge extracted to permanent context?
+- [ ] All extracted files <200 lines?
+- [ ] Files in correct function folders?
+- [ ] navigation.md navigation updated?
+- [ ] Summary files archived/deleted?
+- [ ] Workspace cleaner than before?
+- [ ] No knowledge lost?
+
+---
+
+## Related
+
+- compact.md - How to minimize extracted content
+- mvi-principle.md - What to extract
+- structure.md - Where files go
+- creation.md - File creation rules

+ 223 - 0
plugins/claude-code/scripts/context/core/context-system/operations/migrate.md

@@ -0,0 +1,223 @@
+<!-- Context: core/migrate | Priority: medium | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Context Migrate Operation
+
+**Purpose**: Copy context files from global (`~/.config/opencode/context/`) to local (`.opencode/context/`) so they're project-specific and git-committed.
+
+**Last Updated**: 2026-02-06
+
+---
+
+## Core Problem
+
+Users who installed OAC globally have project-intelligence files at `~/.config/opencode/context/project-intelligence/`. These files are project-specific patterns but aren't committed to git or shared with the team.
+
+**Solution**: Migrate project-intelligence from global → local, so patterns are version-controlled and team-shared.
+
+---
+
+## 4-Stage Workflow
+
+<workflow id="migrate" enforce="@critical_rules">
+
+### Stage 1: Detect Sources
+
+Scan for context files in the global config directory:
+
+```
+Scanning global context...
+
+Global location: ~/.config/opencode/context/
+
+Found:
+  project-intelligence/
+    technical-domain.md (1.2 KB, Version: 1.3)
+    navigation.md (800 bytes, Version: 1.0)
+    business-domain.md (1.5 KB, Version: 1.1)
+
+Local location: .opencode/context/
+
+Status: No local project-intelligence/ found
+```
+
+**If no global context found:**
+```
+No global context found at ~/.config/opencode/context/
+
+Nothing to migrate. Use /add-context to create project intelligence.
+```
+→ Exit
+
+**If no global project-intelligence found (but other global context exists):**
+```
+Global context found at ~/.config/opencode/context/ but no project-intelligence/ directory.
+
+Only project-intelligence files are migrated (project-specific patterns).
+Core standards stay in global (they're universal, not project-specific).
+
+Nothing to migrate. Use /add-context to create project intelligence.
+```
+→ Exit
+
+---
+
+### Stage 2: Check for Conflicts
+
+If local `.opencode/context/project-intelligence/` already exists:
+
+```
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+Conflict: Local project-intelligence already exists
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+
+Global files:                              Local files:
+  technical-domain.md                        technical-domain.md
+    Version: 1.3, Updated: 2026-01-15         Version: 1.0, Updated: 2026-02-01
+  navigation.md                              navigation.md
+    Version: 1.0, Updated: 2026-01-10         Version: 1.0, Updated: 2026-02-01
+  business-domain.md                         (not present locally)
+    Version: 1.1, Updated: 2026-01-12
+
+Options:
+  1. Skip existing — only copy files that don't exist locally
+     → Will copy: business-domain.md
+     → Will skip: technical-domain.md, navigation.md (local kept)
+
+  2. Overwrite all — replace local with global versions
+     → Will overwrite: technical-domain.md, navigation.md
+     → Will copy: business-domain.md
+     → Local backup created first
+
+  3. Cancel
+
+Choose [1/2/3]: _
+```
+
+**If user chooses 2 (Overwrite), show content diff first:**
+```
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+Diff: technical-domain.md
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+
+Local (current):                    Global (incoming):
+  Version: 1.0                        Version: 1.3
+  Tech Stack: Next.js 14              Tech Stack: Next.js 15  ← different
+  API: basic validation                API: Zod validation     ← different
+  Component: same                      Component: same
+  Naming: same                         Naming: same
+
+Show full diff? [y/n]: _
+
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+
+Backup local files to .tmp/backup/migrate-{timestamp}/ before overwriting?
+[y/n] (default: y): _
+```
+
+If no conflicts → proceed directly to Stage 3.
+
+---
+
+### Stage 3: Approval & Copy
+
+```
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+Migration Plan
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+
+Will copy from: ~/.config/opencode/context/project-intelligence/
+Will copy to:   .opencode/context/project-intelligence/
+
+Files to copy:
+  ✓ technical-domain.md (1.2 KB)
+  ✓ navigation.md (800 bytes)
+  ✓ business-domain.md (1.5 KB)
+
+After migration:
+  → Local files committed to git = team gets your patterns
+  → Agents load local (overrides global)
+  → Global files remain as fallback for other projects
+
+Proceed? [y/n]: _
+```
+
+**Actions on approval:**
+1. Create `.opencode/context/project-intelligence/` if it doesn't exist
+2. Copy each file from global → local
+3. Validate copied files (frontmatter, MVI compliance)
+
+---
+
+### Stage 4: Cleanup & Confirmation
+
+```
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+Migration Complete
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+
+Copied 3 files to .opencode/context/project-intelligence/
+
+  ✓ technical-domain.md
+  ✓ navigation.md
+  ✓ business-domain.md
+
+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
+
+Clean up global project-intelligence?
+
+The global files are no longer needed for THIS project (local takes priority).
+Keeping them means they still apply as fallback to other projects.
+
+  1. Keep global files (safe default)
+  2. Remove global project-intelligence/ (only affects this user)
+
+Choose [1/2] (default: 1): _
+```
+
+**If user chooses 2 (Remove):**
+- Delete `~/.config/opencode/context/project-intelligence/` only
+- Do NOT touch `~/.config/opencode/context/core/` or any other global context
+
+</workflow>
+
+---
+
+## What Gets Migrated
+
+| Migrated (project-specific) | NOT Migrated (universal) |
+|---|---|
+| `project-intelligence/` | `core/standards/` |
+| `project-intelligence/technical-domain.md` | `core/context-system/` |
+| `project-intelligence/business-domain.md` | `core/workflows/` |
+| `project-intelligence/navigation.md` | `core/guides/` |
+| `project-intelligence/decisions-log.md` | Any other `core/` files |
+| `project-intelligence/living-notes.md` | |
+
+**Rationale**: Project intelligence is project-specific (YOUR tech stack, YOUR patterns). Core standards are universal (code quality, documentation standards) and should stay global.
+
+---
+
+## Error Handling
+
+**Permission denied:**
+```
+Error: Cannot write to .opencode/context/project-intelligence/
+Check directory permissions and try again.
+```
+
+**Global path not found:**
+```
+No global OpenCode config found at ~/.config/opencode/
+
+If you installed to a custom location, set OPENCODE_INSTALL_DIR:
+  export OPENCODE_INSTALL_DIR=/your/custom/path
+  /context migrate
+```
+
+---
+
+## Related
+
+- `/add-context` — Create new project intelligence (interactive wizard)
+- `/context harvest` — Extract knowledge from summaries
+- Context path resolution: `.opencode/context/core/system/context-paths.md`

+ 50 - 0
plugins/claude-code/scripts/context/core/context-system/operations/navigation.md

@@ -0,0 +1,50 @@
+<!-- Context: core/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Context System Operations
+
+**Purpose**: Operational procedures for maintaining the context system
+
+---
+
+## Structure
+
+```
+operations/
+├── navigation.md (this file)
+├── error.md
+├── extract.md
+├── harvest.md
+├── migrate.md
+├── organize.md
+└── update.md
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **Extract context** | `extract.md` |
+| **Harvest summaries** | `harvest.md` |
+| **Organize files** | `organize.md` |
+| **Update context** | `update.md` |
+| **Migrate context** | `migrate.md` |
+| **Add errors** | `error.md` |
+
+---
+
+## By Type
+
+**Extraction** → Extract context from sources  
+**Harvesting** → Clean up and harvest summaries  
+**Organization** → Restructure context files  
+**Maintenance** → Update and migrate context
+
+---
+
+## Related Context
+
+- **Context System** → `../navigation.md`
+- **Guides** → `../guides/navigation.md`
+- **Standards** → `../standards/navigation.md`

+ 224 - 0
plugins/claude-code/scripts/context/core/context-system/operations/organize.md

@@ -0,0 +1,224 @@
+<!-- Context: core/organize | Priority: medium | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Organize Operation
+
+**Purpose**: Restructure flat context files into function-based folder structure
+
+**Last Updated**: 2026-01-06
+
+---
+
+## When to Use
+
+- Migrating from flat structure to function-based
+- Cleaning up disorganized context directories
+- Splitting ambiguous files into proper categories
+- Resolving duplicate/conflicting files
+
+---
+
+## 8-Stage Workflow
+
+### Stage 1: Scan
+**Action**: Scan category for all files and detect structure
+
+**Output**: List of files with current structure type (flat vs organized)
+
+---
+
+### Stage 2: Categorize
+**Action**: Categorize each file by function
+
+**Categorization Rules**:
+- Explains concept? → `concepts/`
+- Shows working code? → `examples/`
+- Step-by-step instructions? → `guides/`
+- Reference data (tables, commands)? → `lookup/`
+- Errors/issues? → `errors/`
+
+**Output**: Categorization plan with flagged ambiguous files
+
+---
+
+### Stage 3: Resolve Conflicts (APPROVAL REQUIRED)
+**Action**: Present categorization plan and handle conflicts
+
+**Format**:
+```
+Organizing {category}/ (23 files, flat structure)
+
+Clear categorization (18 files):
+  concepts/ (8):
+    ✓ authentication.md → concepts/authentication.md
+  
+  examples/ (5):
+    ✓ jwt-example.md → examples/jwt-example.md
+
+Ambiguous files (5 - need your input):
+  
+  [?] api-design.md (contains concepts AND steps)
+      → [A] Split: concepts/api-design.md + guides/api-design-guide.md
+      → [B] Keep as concepts/api-design.md
+      → [C] Keep as guides/api-design.md
+
+Conflicts (2):
+  
+  [!] authentication.md → concepts/auth.md
+      Target already exists (120 lines)
+      → [J] Merge into existing
+      → [K] Rename to concepts/authentication-v2.md
+      → [L] Skip (keep flat)
+
+Select resolutions (A J or 'auto'):
+```
+
+**Validation**: MUST wait for user input
+
+---
+
+### Stage 4: Preview (APPROVAL REQUIRED)
+**Action**: Show preview of all changes
+
+**Format**:
+```
+Preview changes:
+
+CREATE directories:
+  {category}/concepts/
+  {category}/examples/
+  {category}/guides/
+  {category}/lookup/
+  {category}/errors/
+
+MOVE files (18):
+  authentication.md → concepts/authentication.md
+  ... (17 more)
+
+SPLIT files (3):
+  api-design.md → concepts/api-design.md + guides/api-design-guide.md
+
+MERGE files (2):
+  authentication.md → concepts/auth.md (merge content)
+
+UPDATE:
+  {category}/README.md
+  Fix 47 internal references
+
+Dry-run? (yes/no/show-diff):
+```
+
+**Dry-run**: Simulates changes without executing
+
+**Validation**: MUST get approval before proceeding
+
+---
+
+### Stage 5: Backup
+**Action**: Create backup before making changes
+
+**Location**: `.tmp/backup/organize-{category}-{timestamp}/`
+
+**Purpose**: Enable rollback if needed
+
+---
+
+### Stage 6: Execute
+**Action**: Perform the reorganization
+
+**Process**:
+1. Create function folders
+2. Move files to correct locations
+3. Split ambiguous files if requested
+4. Merge conflicts if requested
+
+---
+
+### Stage 7: Update
+**Action**: Update navigation and fix references
+
+**Process**:
+1. Update README.md with navigation tables
+2. Fix all internal references to moved files
+3. Validate all links work
+4. Update "Last Updated" dates
+
+---
+
+### Stage 8: Report
+**Action**: Show comprehensive results
+
+**Format**:
+```
+✅ Organized X files into function folders
+📁 Created Y new folders
+🔀 Split Z ambiguous files
+🔗 Fixed N references
+💾 Backup: .tmp/backup/organize-{category}-{timestamp}/
+
+Rollback available if needed.
+```
+
+---
+
+## Conflict Resolution
+
+### Ambiguous Files
+File fits multiple categories (e.g., has concepts AND steps)
+
+**Options**:
+- Split into multiple files (recommended)
+- Keep in primary category
+- User decides which is primary
+
+### Duplicate Targets
+Target file already exists
+
+**Options**:
+- Merge content into existing file
+- Rename to avoid conflict (e.g., -v2)
+- Skip (keep in flat structure)
+
+### Auto-Resolution
+Agent suggests best option based on:
+- File size
+- Content analysis
+- Existing structure
+
+---
+
+## Examples
+
+### Organize Flat Directory
+```bash
+/context organize development/
+```
+
+### Dry-Run First
+```bash
+/context organize development/ --dry-run
+```
+
+### Organize Multiple
+```bash
+/context organize development/
+/context organize core/
+```
+
+---
+
+## Success Criteria
+
+- [ ] All files in function folders (not flat)?
+- [ ] Ambiguous files resolved?
+- [ ] Conflicts handled?
+- [ ] README.md created/updated?
+- [ ] All references fixed?
+- [ ] Backup created?
+- [ ] User approved changes?
+
+---
+
+## Related
+
+- standards/structure.md - Folder organization rules
+- guides/workflows.md - Interactive examples

+ 237 - 0
plugins/claude-code/scripts/context/core/context-system/operations/update.md

@@ -0,0 +1,237 @@
+<!-- Context: core/update | Priority: medium | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Update Operation
+
+**Purpose**: Update context when APIs, frameworks, or contracts change
+
+**Last Updated**: 2026-01-06
+
+---
+
+## When to Use
+
+- Framework version updates (Next.js 14 → 15)
+- API changes (breaking changes, deprecations)
+- New features added to existing topics
+- Migration guides needed
+
+---
+
+## 8-Stage Workflow
+
+### Stage 1: Identify Changes (APPROVAL REQUIRED)
+**Action**: User describes what changed
+
+**Format**:
+```
+What changed in {topic}?
+  [A] API changes
+  [B] Deprecations
+  [C] New features
+  [D] Breaking changes
+  [E] Other (describe)
+
+Select all that apply (A B C D or describe):
+```
+
+**Follow-up**: Get specific details for each selected type
+
+**Validation**: MUST get user input before proceeding
+
+---
+
+### Stage 2: Find Affected Files
+**Action**: Search for files referencing the topic
+
+**Process**:
+1. Grep for topic references across all context
+2. Count references per file
+3. Show impact analysis
+
+**Format**:
+```
+Found 5 files referencing {topic}:
+  📄 concepts/routing.md (3 references, 145 lines)
+  📄 examples/app-router-example.md (7 references, 78 lines)
+  📄 guides/setting-up-nextjs.md (2 references, 132 lines)
+  📄 errors/nextjs-errors.md (1 reference, 98 lines)
+  📄 lookup/nextjs-commands.md (4 references, 54 lines)
+
+Total impact: 17 references across 5 files
+```
+
+---
+
+### Stage 3: Preview Changes (APPROVAL REQUIRED)
+**Action**: Show line-by-line diff for each file
+
+**Format**:
+```
+Proposed updates:
+
+━━━ concepts/routing.md ━━━
+
+Line 15:
+  - App router is optional (use pages/ or app/)
+  + App router is now default in Next.js 15 (pages/ still supported)
+
+Line 42:
+  + ## Metadata API (New in v15)
+  + Next.js 15 introduces new metadata API...
+
+━━━ examples/app-router-example.md ━━━
+
+Line 8:
+  - // Optional: use app router
+  + // Default in Next.js 15+
+
+Preview next file? (yes/no/show-all)
+Approve changes? (yes/no/edit):
+```
+
+**Edit mode**: Line-by-line approval for each change
+
+**Validation**: MUST get approval before proceeding
+
+---
+
+### Stage 4: Backup
+**Action**: Create backup before updating
+
+**Location**: `.tmp/backup/update-{topic}-{timestamp}/`
+
+**Purpose**: Enable rollback if updates cause issues
+
+---
+
+### Stage 5: Update Files
+**Action**: Apply approved changes
+
+**Process**:
+1. Update concepts, examples, guides, lookups
+2. Maintain MVI format (<200 lines)
+3. Update "Last Updated" dates
+4. Preserve file structure
+
+**Enforcement**: `@critical_rules.mvi_strict`
+
+---
+
+### Stage 6: Add Migration Notes
+**Action**: Add migration guide to errors/
+
+**Format**:
+```markdown
+## Migration: {Old Version} → {New Version}
+
+**Breaking Changes**:
+- Change 1
+- Change 2
+
+**Migration Steps**:
+1. Step 1
+2. Step 2
+
+**Reference**: [Link to changelog]
+```
+
+**Location**: `{category}/errors/{topic}-errors.md`
+
+---
+
+### Stage 7: Validate
+**Action**: Check all references and links
+
+**Checks**:
+- All internal references still work
+- No broken links
+- All files still <200 lines
+- MVI format maintained
+
+---
+
+### Stage 8: Report
+**Action**: Show comprehensive results
+
+**Format**:
+```
+✅ Updated X files
+📝 Modified Y references
+🔄 Added migration notes to errors/
+💾 Backup: .tmp/backup/update-{topic}-{timestamp}/
+
+Summary of changes:
+  - concepts/routing.md: 2 updates (145 → 162 lines)
+  - examples/app-router-example.md: 4 updates (78 → 89 lines)
+  - guides/setting-up-nextjs.md: 1 update (132 → 133 lines)
+
+All files still under 200 line limit ✓
+
+Rollback available if needed.
+```
+
+---
+
+## Change Types
+
+### API Changes
+- Method signatures changed
+- Parameters added/removed
+- Return types changed
+
+### Deprecations
+- Features marked deprecated
+- Replacement APIs available
+- Timeline for removal
+
+### New Features
+- New capabilities added
+- New APIs introduced
+- New patterns available
+
+### Breaking Changes
+- Incompatible changes
+- Migration required
+- Old code won't work
+
+---
+
+## Examples
+
+### Framework Update
+```bash
+/context update for Next.js 15
+/context update for React 19
+```
+
+### API Changes
+```bash
+/context update for Stripe API v2024
+/context update for OpenAI API breaking changes
+```
+
+### Library Update
+```bash
+/context update for Tailwind CSS v4
+```
+
+---
+
+## Success Criteria
+
+- [ ] User described changes?
+- [ ] All affected files found?
+- [ ] Diff preview shown?
+- [ ] User approved changes?
+- [ ] Backup created?
+- [ ] Migration notes added?
+- [ ] All references validated?
+- [ ] All files still <200 lines?
+
+---
+
+## Related
+
+- guides/workflows.md - Interactive diff examples
+- standards/mvi.md - Maintain MVI format
+- operations/error.md - Adding migration notes

+ 145 - 0
plugins/claude-code/scripts/context/core/context-system/standards/codebase-references.md

@@ -0,0 +1,145 @@
+<!-- Context: core/codebase-references | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Codebase References
+
+**Purpose**: Link context files to actual code implementation
+
+**Last Updated**: 2026-01-27
+
+---
+
+## Core Principle
+
+<rule id="link_to_code" enforcement="critical">
+  ALL context files SHOULD include `📂 Codebase References` section linking to relevant code.
+  Use sections that apply to your context type (not all files need all sections).
+</rule>
+
+**Why**: Agents need to find actual implementation, not just read about it.
+
+---
+
+## Section Types (Use What's Relevant)
+
+### Business Domain Context
+```markdown
+**Business Logic**: (MOST IMPORTANT for business domains)
+- `src/orders/rules/validation-rules.ts` - Order validation business rules
+
+**Implementation**:
+- `src/orders/order-processor.ts` - Main order processing logic
+
+**Models/Types**:
+- `src/orders/models/order.model.ts` - Order data model
+
+**Tests**:
+- `src/orders/__tests__/processor.test.ts` - Order processing tests
+
+**Configuration**:
+- `config/orders.config.ts` - Order processing config
+```
+
+### Technical/Code Context
+```markdown
+**Implementation**: (MOST IMPORTANT for technical contexts)
+- `src/auth/jwt-handler.ts` - JWT authentication implementation
+
+**Examples**:
+- `src/auth/examples/jwt-example.ts` - Working JWT example
+
+**Types**:
+- `src/auth/types/jwt-payload.ts` - JWT payload types
+
+**Tests**:
+- `src/auth/__tests__/jwt.test.ts` - JWT tests
+```
+
+### Standards/Quality Context
+```markdown
+**Validation/Enforcement**: (MOST IMPORTANT for standards)
+- `scripts/validate-code-quality.ts` - Code quality validator
+- `eslint.config.js` - ESLint rules
+
+**Examples**:
+- `examples/good-code.ts` - Good code example
+- `examples/bad-code.ts` - Anti-pattern example
+
+**Tests**:
+- `tests/code-quality.test.ts` - Quality validation tests
+```
+
+### Operational Context
+```markdown
+**Scripts/Tools**: (MOST IMPORTANT for operations)
+- `scripts/deploy.sh` - Deployment script
+- `scripts/monitor.ts` - Monitoring setup
+
+**Configuration**:
+- `config/deployment.config.ts` - Deployment configuration
+- `.github/workflows/deploy.yml` - CI/CD workflow
+```
+
+---
+
+## Rules
+
+<rule id="path_format" enforcement="strict">
+  1. Use project-relative paths (src/..., not /Users/...)
+  2. Use forward slashes (/)
+  3. Include file extension (.ts, .js, .sh)
+  4. Brief description (3-10 words) for each file
+  5. Verify files exist (warn if not found)
+  6. Use relevant sections only (not all files need all sections)
+</rule>
+
+---
+
+## Examples
+
+**Business Context**:
+```markdown
+## 📂 Codebase References
+
+**Business Logic**:
+- `src/payments/rules/validation-rules.ts` - Card validation rules
+- `src/payments/rules/fraud-detection.ts` - Fraud detection logic
+
+**Implementation**:
+- `src/payments/payment-processor.ts` - Main payment processing
+
+**Tests**:
+- `src/payments/__tests__/processor.test.ts` - Payment tests
+```
+
+**Technical Context**:
+```markdown
+## 📂 Codebase References
+
+**Implementation**:
+- `src/auth/jwt-handler.ts` - JWT authentication
+
+**Examples**:
+- `examples/jwt-auth.ts` - Working example
+
+**Tests**:
+- `src/auth/__tests__/jwt.test.ts` - JWT tests
+```
+
+---
+
+## Validation
+
+- [ ] Has "📂 Codebase References" section?
+- [ ] Most important section for context type included?
+- [ ] Paths are project-relative?
+- [ ] Paths include extensions?
+- [ ] Each path has 3-10 word description?
+
+---
+
+## Related
+
+- frontmatter.md - Frontmatter format
+- templates.md - File templates
+- structure.md - File organization
+- templates/ - File templates with codebase references

+ 64 - 0
plugins/claude-code/scripts/context/core/context-system/standards/frontmatter.md

@@ -0,0 +1,64 @@
+# Frontmatter Format
+
+**Purpose**: HTML comment frontmatter format for all context files
+
+**Last Updated**: 2026-01-27
+
+---
+
+## Format
+
+<rule id="frontmatter_required" enforcement="strict">
+  ALL context files MUST start with:
+  
+  ```markdown
+  <!-- Context: {category}/{function} | Priority: {level} | Version: X.Y | Updated: YYYY-MM-DD -->
+  ```
+</rule>
+
+---
+
+## Components
+
+**Category/Function**: `{category}/{function}`
+- Examples: `ecommerce/concepts`, `development/examples`, `core/standards`
+- Category = domain (ecommerce, payments, development)
+- Function = file type (concepts, examples, guides, lookup, errors)
+
+**Priority**: `critical` | `high` | `medium` | `low`
+- critical: 80% of use cases (business logic, core concepts)
+- high: 15% of use cases (common workflows, examples)
+- medium: 4% of use cases (edge cases)
+- low: 1% of use cases (rare scenarios)
+
+**Version**: `X.Y` (start 1.0, increment on changes)
+
+**Updated**: `YYYY-MM-DD` (ISO 8601, must match metadata section)
+
+---
+
+## Examples
+
+```markdown
+<!-- Context: ecommerce/concepts | Priority: critical | Version: 1.0 | Updated: 2026-01-27 -->
+<!-- Context: payments/guides | Priority: high | Version: 1.2 | Updated: 2026-01-27 -->
+<!-- Context: development/examples | Priority: medium | Version: 1.0 | Updated: 2026-01-27 -->
+```
+
+---
+
+## Validation
+
+- [ ] Frontmatter is first line?
+- [ ] Format exact: `<!-- Context: ... -->`?
+- [ ] Priority is critical|high|medium|low?
+- [ ] Version is X.Y?
+- [ ] Date is YYYY-MM-DD?
+
+---
+
+## Related
+
+- structure.md - File organization
+- templates.md - File templates
+- codebase-references.md - Linking to code

+ 151 - 0
plugins/claude-code/scripts/context/core/context-system/standards/mvi.md

@@ -0,0 +1,151 @@
+<!-- Context: core/mvi | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# MVI Principle (Minimal Viable Information)
+
+**Purpose**: Extract only core concepts, not verbose explanations
+
+**Last Updated**: 2026-01-06
+
+---
+
+## Core Idea
+
+Extract the **minimum information** needed for an AI agent to understand and use a concept:
+- Core concept (1-3 sentences)
+- Key points (3-5 bullets)
+- Minimal working example
+- Reference link to full docs
+
+**Goal**: Scannable in <30 seconds. Reference full docs, don't duplicate them.
+
+---
+
+## The Formula
+
+```
+Core Concept (1-3 sentences)
+  ↓
+Key Points (3-5 bullets)
+  ↓
+Quick Example (5-10 lines)
+  ↓
+Reference Link (full docs)
+  ↓
+Related Files (cross-refs)
+```
+
+---
+
+## What to Extract ✅
+
+- **Core definitions** - What it is (1-3 sentences)
+- **Key properties** - Essential characteristics (3-5 bullets)
+- **Minimal example** - Simplest working code (5-10 lines)
+- **Common patterns** - How it's typically used (2-3 bullets)
+- **Critical gotchas** - Must-know issues (1-2 bullets)
+- **Reference links** - Where to learn more
+
+---
+
+## What to Skip ❌
+
+- **Verbose explanations** - Link to docs instead
+- **Complete API docs** - Summarize + reference
+- **Implementation details** - Show minimal example + reference
+- **Historical context** - Unless critical to understanding
+- **Marketing content** - Just the facts
+- **Duplicate information** - Say it once, reference elsewhere
+
+---
+
+## Example: JWT Authentication
+
+### ❌ Too Verbose (400+ lines)
+```markdown
+# JWT Authentication
+
+JSON Web Tokens (JWT) are an open standard (RFC 7519) that defines 
+a compact and self-contained way for securely transmitting information 
+between parties as a JSON object. This information can be verified and 
+trusted because it is digitally signed. JWTs can be signed using a 
+secret (with the HMAC algorithm) or a public/private key pair using RSA 
+or ECDSA.
+
+[... 400 more lines of explanation, examples, edge cases ...]
+```
+
+### ✅ MVI Compliant (~50 lines)
+```markdown
+# Concept: JWT Authentication
+
+**Core Idea**: Stateless authentication using JSON Web Tokens signed 
+with a secret key. Token contains user data (payload) that server can 
+trust because signature is verified.
+
+**Key Points**:
+- Token has 3 parts: header.payload.signature (Base64 encoded)
+- Server verifies signature to trust payload without database lookup
+- No session storage needed (stateless)
+- Tokens expire (include `exp` claim)
+- Store in httpOnly cookie or Authorization header
+
+**Quick Example**:
+```js
+// Sign token
+const token = jwt.sign(
+  { userId: 123, role: 'admin' }, 
+  SECRET_KEY, 
+  { expiresIn: '1h' }
+)
+
+// Verify token
+const decoded = jwt.verify(token, SECRET_KEY)
+console.log(decoded.userId) // 123
+```
+
+**Reference**: https://jwt.io/introduction
+
+**Related**: 
+- examples/jwt-auth-example.md
+- guides/implementing-jwt.md
+- errors/auth-errors.md
+```
+
+---
+
+## File Size Limits
+
+<rule id="size_limits" enforcement="strict">
+  - Concept files: max 100 lines
+  - Example files: max 80 lines
+  - Guide files: max 150 lines
+  - Lookup files: max 100 lines
+  - Error files: max 150 lines
+  - README files: max 100 lines
+</rule>
+
+**Why**: Forces brevity. If you need more, split into multiple files or reference external docs.
+
+---
+
+## Validation Checklist
+
+Before creating a context file, verify:
+
+- [ ] Core concept is 1-3 sentences?
+- [ ] Key points are 3-5 bullets?
+- [ ] Example is <10 lines of code?
+- [ ] Reference link is included?
+- [ ] File is <200 lines total?
+- [ ] Can be scanned in <30 seconds?
+
+If any answer is "no", apply more compression.
+
+---
+
+## Related
+
+- structure.md - Where files go
+- compact.md - How to minimize
+- templates.md - Standard formats
+- creation.md - File creation rules

+ 48 - 0
plugins/claude-code/scripts/context/core/context-system/standards/navigation.md

@@ -0,0 +1,48 @@
+<!-- Context: core/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Context System Standards
+
+**Purpose**: Standards and templates for context files
+
+---
+
+## Structure
+
+```
+standards/
+├── navigation.md (this file)
+├── codebase-references.md
+├── frontmatter.md
+├── mvi.md
+├── structure.md
+└── templates.md
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **MVI principle** | `mvi.md` |
+| **Frontmatter format** | `frontmatter.md` |
+| **File structure** | `structure.md` |
+| **File templates** | `templates.md` |
+| **Codebase references** | `codebase-references.md` |
+
+---
+
+## By Type
+
+**Principles** → Core principles (MVI)  
+**Formats** → File formats and frontmatter  
+**Structure** → Directory and file structure  
+**Templates** → Ready-to-use templates
+
+---
+
+## Related Context
+
+- **Context System** → `../navigation.md`
+- **Guides** → `../guides/navigation.md`
+- **Operations** → `../operations/navigation.md`

+ 240 - 0
plugins/claude-code/scripts/context/core/context-system/standards/structure.md

@@ -0,0 +1,240 @@
+<!-- Context: core/structure | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Context Structure
+
+**Purpose**: Function-based folder organization for easy discovery
+
+**Last Updated**: 2026-01-06
+
+---
+
+## Core Structure
+
+<rule id="function_structure" enforcement="strict">
+  ALWAYS organize by function (what info does), not just by topic.
+  
+  Required folders:
+  - concepts/  - Core ideas, definitions, "what is it?"
+  - examples/  - Minimal working code
+  - guides/    - Step-by-step workflows
+  - lookup/    - Quick reference tables, commands, paths
+  - errors/    - Common issues, gotchas, fixes
+</rule>
+
+```
+.opencode/context/{category}/
+├── navigation.md              # Navigation map (REQUIRED)
+├── concepts/              # What it is
+│   └── {topic}.md
+├── examples/              # Working code
+│   └── {example}.md
+├── guides/                # How to do it
+│   └── {guide}.md
+├── lookup/                # Quick reference
+│   └── {reference}.md
+└── errors/                # Common issues
+    └── {framework}.md
+```
+
+---
+
+## Folder Purposes
+
+### concepts/
+**Purpose**: Core ideas, definitions, "what is it?"
+
+**Contains**:
+- Fundamental concepts
+- Design patterns
+- Architecture decisions
+- System principles
+
+**Examples**:
+- `concepts/authentication.md`
+- `concepts/state-management.md`
+- `concepts/mvi-principle.md`
+
+---
+
+### examples/
+**Purpose**: Minimal working code examples
+
+**Contains**:
+- Code snippets that work as-is
+- Minimal reproductions
+- Common patterns in action
+
+**Examples**:
+- `examples/jwt-auth-example.md`
+- `examples/react-hooks-example.md`
+- `examples/api-call-example.md`
+
+**Rule**: Examples should be <30 lines of code, fully functional
+
+---
+
+### guides/
+**Purpose**: Step-by-step workflows, "how to do X"
+
+**Contains**:
+- Numbered procedures
+- Setup instructions
+- Implementation workflows
+- Migration guides
+
+**Examples**:
+- `guides/setting-up-auth.md`
+- `guides/deploying-api.md`
+- `guides/migrating-to-v2.md`
+
+**Rule**: Steps should be actionable (not theoretical)
+
+---
+
+### lookup/
+**Purpose**: Quick reference tables, commands, paths
+
+**Contains**:
+- Command lists
+- File locations
+- API endpoints
+- Configuration options
+- Keyboard shortcuts
+
+**Examples**:
+- `lookup/cli-commands.md`
+- `lookup/file-locations.md`
+- `lookup/api-endpoints.md`
+
+**Rule**: Must be in table/list format (scannable)
+
+---
+
+### errors/
+**Purpose**: Common errors, gotchas, edge cases
+
+**Contains**:
+- Error messages + fixes
+- Common pitfalls
+- Edge cases
+- Troubleshooting
+
+**Examples**:
+- `errors/react-errors.md`
+- `errors/nextjs-build-errors.md`
+- `errors/auth-errors.md`
+
+**Rule**: Group by framework/topic, not one file per error
+
+---
+
+## navigation.md Requirement
+
+<rule id="readme_required" enforcement="strict">
+  Every context category MUST have navigation.md at its root with:
+  1. Purpose (1-2 sentences)
+  2. Navigation tables for each function folder
+  3. Priority levels (critical/high/medium/low)
+  4. Loading strategy (what to load for common tasks)
+</rule>
+
+**Example**:
+```markdown
+# Development Context
+
+**Purpose**: Core development patterns, errors, and examples
+
+---
+
+## Quick Navigation
+
+### Concepts
+| File | Description | Priority |
+|------|-------------|----------|
+| concepts/auth.md | Authentication patterns | critical |
+
+### Examples
+| File | Description | Priority |
+|------|-------------|----------|
+| examples/jwt.md | JWT auth example | high |
+
+### Errors
+| File | Description | Priority |
+|------|-------------|----------|
+| errors/react.md | Common React errors | high |
+
+---
+
+## Loading Strategy
+
+**For auth work**: 
+1. Load concepts/auth.md
+2. Load examples/jwt.md
+3. Reference guides/setup-auth.md if needed
+```
+
+---
+
+## Categorization Rules
+
+When organizing a file, ask:
+
+| Question | Folder |
+|----------|--------|
+| Does it explain **what** something is? | `concepts/` |
+| Does it show **working code**? | `examples/` |
+| Does it explain **how to do** something? | `guides/` |
+| Is it **quick reference** data? | `lookup/` |
+| Does it document an **error/issue**? | `errors/` |
+
+---
+
+## Anti-Patterns ❌
+
+### ❌ Flat Structure
+```
+development/
+├── authentication.md
+├── jwt-example.md
+├── setting-up-auth.md
+├── auth-errors.md
+└── api-endpoints.md
+```
+**Problem**: Hard to discover. Is authentication.md a concept or guide?
+
+### ✅ Function-Based
+```
+development/
+├── navigation.md
+├── concepts/
+│   └── authentication.md
+├── examples/
+│   └── jwt-example.md
+├── guides/
+│   └── setting-up-auth.md
+├── lookup/
+│   └── api-endpoints.md
+└── errors/
+    └── auth-errors.md
+```
+**Benefit**: Instantly know file purpose by location
+
+---
+
+## Validation
+
+Before committing context structure:
+
+- [ ] All categories have navigation.md?
+- [ ] Files are in function folders (not flat)?
+- [ ] README has navigation tables?
+- [ ] Priority levels assigned?
+- [ ] Loading strategy documented?
+
+---
+
+## Related
+
+- mvi-principle.md - What to extract
+- templates.md - File formats
+- creation.md - How to create files

+ 396 - 0
plugins/claude-code/scripts/context/core/context-system/standards/templates.md

@@ -0,0 +1,396 @@
+# Context File Templates
+
+**Purpose**: Standard formats for all context file types
+
+**Last Updated**: 2026-01-06
+
+---
+
+## Template Selection
+
+| Type | Max Lines | Required Sections |
+|------|-----------|-------------------|
+| Concept | 100 | Purpose, Core Idea (1-3 sentences), Key Points (3-5), Example (<10 lines), Reference, Related |
+| Example | 80 | Purpose, Use Case, Code (10-30 lines), Explanation, Related |
+| Guide | 150 | Purpose, Prerequisites, Steps (4-7), Verification, Related |
+| Lookup | 100 | Purpose, Tables/Lists, Commands, Related |
+| Error | 150 | Purpose, Per-error: Symptom, Cause, Solution, Prevention, Reference, Related |
+| README | 100 | Purpose, Navigation tables (all 5 folders), Loading Strategy, Statistics |
+
+---
+
+## 1. Concept Template
+
+```markdown
+<!-- Context: {category}/concepts | Priority: {critical|high|medium|low} | Version: 1.0 | Updated: YYYY-MM-DD -->
+# Concept: {Name}
+
+**Purpose**: [1 sentence]
+**Last Updated**: {YYYY-MM-DD}
+
+## Core Idea
+[1-3 sentences]
+
+## Key Points
+- Point 1
+- Point 2
+- Point 3
+
+## When to Use
+- Use case 1
+- Use case 2
+
+## Quick Example
+```lang
+[<10 lines]
+```
+
+## 📂 Codebase References
+
+**Business Logic** (if business domain):
+- `path/to/rules.ts` - {3-10 word description}
+
+**Implementation**:
+- `path/to/main.ts` - {3-10 word description}
+
+**Models/Types**:
+- `path/to/model.ts` - {3-10 word description}
+
+**Tests**:
+- `path/to/test.ts` - {3-10 word description}
+
+## Deep Dive
+**Reference**: [Link or "See implementation above"]
+
+## Related
+- concepts/x.md
+- examples/y.md
+```
+
+---
+
+## 2. Example Template
+
+```markdown
+<!-- Context: {category}/examples | Priority: {high|medium} | Version: 1.0 | Updated: YYYY-MM-DD -->
+# Example: {What It Shows}
+
+**Purpose**: [1 sentence]
+**Last Updated**: {YYYY-MM-DD}
+
+## Use Case
+[2-3 sentences]
+
+## Code
+```lang
+[10-30 lines]
+```
+
+## Explanation
+1. Step 1
+2. Step 2
+3. Step 3
+
+**Key points**:
+- Detail 1
+- Detail 2
+
+## 📂 Codebase References
+
+**Full Implementation**:
+- `path/to/real-implementation.ts` - {Production version}
+
+**Related Code**:
+- `path/to/helper.ts` - {Helper utilities}
+
+**Tests**:
+- `path/to/test.ts` - {Tests demonstrating pattern}
+
+## Related
+- concepts/x.md
+```
+
+---
+
+## 3. Guide Template
+
+```markdown
+<!-- Context: {category}/guides | Priority: {critical|high|medium} | Version: 1.0 | Updated: YYYY-MM-DD -->
+# Guide: {Action}
+
+**Purpose**: [1 sentence]
+**Last Updated**: {YYYY-MM-DD}
+
+## Prerequisites
+- Requirement 1
+- Requirement 2
+
+**Estimated time**: X min
+
+## Steps
+
+### 1. {Step}
+```bash
+{command}
+```
+**Expected**: [result]
+**Implementation**: `path/to/step.ts`
+
+### 2. {Step}
+[Repeat 4-7 steps]
+
+## Verification
+```bash
+{verify command}
+```
+
+## 📂 Codebase References
+
+**Workflow Orchestration**:
+- `path/to/workflow.ts` - {Main workflow coordinator}
+
+**Business Logic** (if applicable):
+- `path/to/rules.ts` - {Process validation rules}
+
+**Integration Points**:
+- `path/to/api-client.ts` - {External integration}
+
+**Tests**:
+- `path/to/workflow.test.ts` - {End-to-end tests}
+
+## Troubleshooting
+| Issue | Solution |
+|-------|----------|
+| Problem | Fix |
+
+## Related
+- concepts/x.md
+```
+
+---
+
+## 4. Lookup Template
+
+```markdown
+<!-- Context: {category}/lookup | Priority: {high|medium} | Version: 1.0 | Updated: YYYY-MM-DD -->
+# Lookup: {Reference Type}
+
+**Purpose**: Quick reference for {desc}
+**Last Updated**: {YYYY-MM-DD}
+
+## {Section}
+| Item | Value | Desc | Code |
+|------|-------|------|------|
+| x | y | z | `path/to/file.ts` |
+
+## Commands
+```bash
+# Description
+{command}
+```
+
+## Paths
+```
+{path} - {desc}
+```
+
+## 📂 Codebase References
+
+**Validation/Enforcement**:
+- `path/to/validator.ts` - {Validation logic}
+
+**Configuration**:
+- `path/to/config.ts` - {Configuration settings}
+
+**Tests**:
+- `path/to/test.ts` - {Validation tests}
+
+## Related
+- concepts/x.md
+```
+
+---
+
+## 5. Error Template
+
+```markdown
+<!-- Context: {category}/errors | Priority: {high|medium} | Version: 1.0 | Updated: YYYY-MM-DD -->
+# Errors: {Framework}
+
+**Purpose**: Common errors for {framework}
+**Last Updated**: {YYYY-MM-DD}
+
+## Error: {Name}
+
+**Symptom**:
+```
+{error message}
+```
+
+**Cause**: [1-2 sentences]
+
+**Solution**:
+1. Step 1
+2. Step 2
+
+**Code**:
+```lang
+// ❌ Before
+{bad}
+
+// ✅ After
+{fixed}
+```
+
+**Prevention**: [how to avoid]
+**Frequency**: common/occasional/rare
+
+**Code References**:
+- Error thrown: `path/to/error-source.ts`
+- Error handler: `path/to/error-handler.ts`
+- Prevention: `path/to/validator.ts`
+
+---
+
+[Repeat for 5-10 errors]
+
+## 📂 Codebase References
+
+**Error Definitions**:
+- `path/to/error-types.ts` - {Error class definitions}
+
+**Error Handling**:
+- `path/to/error-handler.ts` - {Error handler}
+
+**Prevention Logic**:
+- `path/to/validator.ts` - {Validation preventing errors}
+
+**Tests**:
+- `path/to/error-handling.test.ts` - {Error handling tests}
+
+## Related
+- concepts/x.md
+```
+
+---
+
+## 6. Navigation Template (Replaces README.md)
+
+**Note**: Use `navigation.md` instead of `README.md` for better discoverability
+
+**Target**: 200-300 tokens
+
+```markdown
+# {Category} Navigation
+
+**Purpose**: [1 sentence]
+
+---
+
+## Structure
+
+```
+{category}/
+├── navigation.md
+├── {subcategory}/
+│   ├── navigation.md
+│   └── {files}.md
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **{Task 1}** | `{path}` |
+| **{Task 2}** | `{path}` |
+| **{Task 3}** | `{path}` |
+
+---
+
+## By {Concern/Type}
+
+**{Section 1}** → {description}
+**{Section 2}** → {description}
+**{Section 3}** → {description}
+
+---
+
+## Related Context
+
+- **{Category}** → `../{category}/navigation.md`
+```
+
+---
+
+## 7. Specialized Navigation Template
+
+**Use for**: Cross-cutting concerns (e.g., `ui-navigation.md`)
+
+**Target**: 250-300 tokens
+
+```markdown
+# {Domain} Navigation
+
+**Scope**: [What this covers]
+
+---
+
+## Structure
+
+```
+{Relevant directories across multiple categories}
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **{Task 1}** | `{path}` |
+| **{Task 2}** | `{path}` |
+
+---
+
+## By {Framework/Approach}
+
+**{Tech 1}** → `{path}`
+**{Tech 2}** → `{path}`
+
+---
+
+## Common Workflows
+
+**{Workflow 1}**:
+1. `{file1}` ({purpose})
+2. `{file2}` ({purpose})
+```
+
+---
+
+## All Templates Must Have
+
+1. Title with type prefix (# Concept:, # Example:, etc.)
+2. **Purpose** (1 sentence)
+3. **Last Updated** (YYYY-MM-DD)
+4. **Related** section (cross-references)
+
+---
+
+## Validation
+
+- [ ] Correct template for file type?
+- [ ] Has required sections?
+- [ ] Under max line limit?
+- [ ] Cross-references added?
+- [ ] Added to README.md?
+
+---
+
+## Related
+
+- creation.md - When to use each template
+- mvi-principle.md - How to fill templates
+- compact.md - How to stay under limits

+ 210 - 0
plugins/claude-code/scripts/context/core/essential-patterns.md

@@ -0,0 +1,210 @@
+<!-- Context: core/essential-patterns | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Essential Patterns - Core Development Guidelines
+
+## Quick Reference
+
+**Core Philosophy**: Modular, Functional, Maintainable
+
+**Critical Patterns**: Error Handling, Validation, Security, Logging, Pure Functions
+
+**ALWAYS**: Handle errors gracefully, validate input, use env vars for secrets, write pure functions
+
+**NEVER**: Expose sensitive info, hardcode credentials, skip input validation, mutate state
+
+**Language-agnostic**: Apply to all programming languages
+
+---
+
+## Overview
+
+This file provides essential development patterns that apply across all programming languages. For detailed standards, see:
+- `standards/code-quality.md` - Modular, functional code patterns
+- `standards/security-patterns.md` - Language-agnostic patterns
+- `standards/test-coverage.md` - Testing standards
+- `standards/documentation.md` - Documentation standards
+- `standards/code-analysis.md` - Analysis framework
+
+---
+
+## Core Philosophy
+
+**Modular**: Everything is a component - small, focused, reusable
+**Functional**: Pure functions, immutability, composition over inheritance
+**Maintainable**: Self-documenting, testable, predictable
+
+---
+
+## Critical Patterns
+
+### 1. Pure Functions
+
+**ALWAYS** write pure functions:
+- Same input = same output
+- No side effects
+- No mutation of external state
+- Predictable and testable
+
+### 2. Error Handling
+
+**ALWAYS** handle errors gracefully:
+- Catch specific errors, not generic ones
+- Log errors with context
+- Return meaningful error messages
+- Don't expose internal implementation details
+- Use language-specific error handling mechanisms (try/catch, Result, error returns)
+
+### 3. Input Validation
+
+**ALWAYS** validate input data:
+- Check for null/nil/None values
+- Validate data types
+- Validate data ranges and constraints
+- Sanitize user input
+- Return clear validation error messages
+
+### 4. Security
+
+**NEVER** expose sensitive information:
+- Don't log passwords, tokens, or API keys
+- Use environment variables for secrets
+- Sanitize all user input
+- Use parameterized queries (prevent SQL injection)
+- Validate and escape output (prevent XSS)
+
+### 5. Logging
+
+**USE** consistent logging levels:
+- **Debug**: Detailed information for debugging (development only)
+- **Info**: Important events and milestones
+- **Warning**: Potential issues that don't stop execution
+- **Error**: Failures and exceptions
+
+---
+
+## Code Structure Patterns
+
+### Modular Design
+- Single responsibility per module
+- Clear interfaces (explicit inputs/outputs)
+- Independent and composable
+- < 100 lines per component (ideally < 50)
+
+### Functional Approach
+- **Pure functions**: Same input = same output, no side effects
+- **Immutability**: Create new data, don't modify existing
+- **Composition**: Build complex from simple functions
+- **Declarative**: Describe what, not how
+
+### Component Structure
+```
+component/
+├── index.js      # Public interface
+├── core.js       # Core logic (pure functions)
+├── utils.js      # Helpers
+└── tests/        # Tests
+```
+
+---
+
+## Anti-Patterns to Avoid
+
+**Code Smells**:
+- ❌ Mutation and side effects
+- ❌ Deep nesting (> 3 levels)
+- ❌ God modules (> 200 lines)
+- ❌ Global state
+- ❌ Large functions (> 50 lines)
+- ❌ Hardcoded values
+- ❌ Tight coupling
+
+**Security Issues**:
+- ❌ Hardcoded credentials
+- ❌ Exposed sensitive data in logs
+- ❌ Unvalidated user input
+- ❌ SQL injection vulnerabilities
+- ❌ XSS vulnerabilities
+
+---
+
+## Testing Patterns
+
+**ALWAYS** write tests:
+- Unit tests for pure functions
+- Integration tests for components
+- Test edge cases and error conditions
+- Aim for > 80% coverage
+- Use descriptive test names
+
+**Test Structure**:
+```
+describe('Component', () => {
+  it('should handle valid input', () => {
+    // Arrange
+    const input = validData;
+    
+    // Act
+    const result = component(input);
+    
+    // Assert
+    expect(result).toBe(expected);
+  });
+  
+  it('should handle invalid input', () => {
+    // Test error cases
+  });
+});
+```
+
+---
+
+## Documentation Patterns
+
+**ALWAYS** document:
+- Public APIs and interfaces
+- Complex logic and algorithms
+- Non-obvious decisions
+- Usage examples
+
+**Use clear, concise language**:
+- Explain WHY, not just WHAT
+- Include examples
+- Keep it up to date
+- Use consistent formatting
+
+---
+
+## Language-Specific Implementations
+
+These patterns are language-agnostic. For language-specific implementations:
+
+**TypeScript/JavaScript**: See project context for Next.js, React, Node.js patterns
+**Python**: See project context for FastAPI, Django patterns
+**Go**: See project context for Go-specific patterns
+**Rust**: See project context for Rust-specific patterns
+
+---
+
+## Quick Checklist
+
+Before committing code, verify:
+- ✅ Pure functions (no side effects)
+- ✅ Input validation
+- ✅ Error handling
+- ✅ No hardcoded secrets
+- ✅ Tests written and passing
+- ✅ Documentation updated
+- ✅ No security vulnerabilities
+- ✅ Code is modular and maintainable
+
+---
+
+## Additional Resources
+
+For more detailed guidelines, see:
+- `standards/code-quality.md` - Comprehensive code standards
+- `standards/security-patterns.md` - Detailed pattern catalog
+- `standards/test-coverage.md` - Testing best practices
+- `standards/documentation.md` - Documentation guidelines
+- `standards/code-analysis.md` - Code analysis framework
+- `workflows/code-review.md` - Code review process

+ 39 - 0
plugins/claude-code/scripts/context/core/guides/navigation.md

@@ -0,0 +1,39 @@
+<!-- Context: core/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Core Guides
+
+**Purpose**: General guides for core system operations
+
+---
+
+## Structure
+
+```
+guides/
+├── navigation.md (this file)
+└── resuming-sessions.md
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **Resume sessions** | `resuming-sessions.md` |
+| **Context system guides** | `../context-system/guides/navigation.md` |
+| **Task management guides** | `../task-management/guides/navigation.md` |
+
+---
+
+## By Type
+
+**Session Management** → How to resume and manage sessions
+
+---
+
+## Related Context
+
+- **Core Navigation** → `../navigation.md`
+- **Context System** → `../context-system/navigation.md`
+- **Task Management** → `../task-management/navigation.md`

+ 322 - 0
plugins/claude-code/scripts/context/core/guides/resuming-sessions.md

@@ -0,0 +1,322 @@
+<!-- Context: core/guides | Priority: high | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Guide: Resuming Multi-Session Tasks
+
+**Purpose**: How to resume work from previous sessions using session context and task files
+
+**Last Updated**: 2026-02-04
+
+---
+
+## When to Use This Guide
+
+- Continuing work after a break or interruption
+- Picking up a task from another agent or developer
+- Understanding what was done in a previous session
+- Avoiding duplicate work or lost progress
+
+---
+
+## Session File Structure
+
+```
+.tmp/
+├── sessions/                      # Session context
+│   └── {YYYY-MM-DD}-{task-slug}/
+│       ├── context.md             # Full task context
+│       └── PROGRESS.md            # Progress report
+│
+└── tasks/                         # Task breakdowns
+    └── {task-slug}/
+        ├── task.json              # Main task definition
+        └── subtask_NN.json        # Individual subtasks
+```
+
+---
+
+## Quick Resume Steps
+
+### 1. Find Your Session (30 seconds)
+
+```bash
+# List recent sessions
+ls -lt .tmp/sessions/ | head -5
+
+# Most recent session
+SESSION=$(ls -t .tmp/sessions/ | head -1)
+echo "Latest session: $SESSION"
+```
+
+---
+
+### 2. Read Progress Report (2 minutes)
+
+```bash
+# View progress
+cat .tmp/sessions/$SESSION/PROGRESS.md
+```
+
+**Look for**:
+- ✅ **Completed Work** - What's already done
+- 🔥 **Next Steps** - What to do next
+- 📊 **Overall Progress** - How much is complete
+- ⚠️ **Blockers** - Any issues to resolve
+
+---
+
+### 3. Check Task Context (3 minutes)
+
+```bash
+# View full context
+cat .tmp/sessions/$SESSION/context.md
+```
+
+**Key sections**:
+- **Current Request** - What was asked for
+- **Context Files** - Standards to follow (CRITICAL)
+- **Reference Files** - Existing code to read
+- **Components** - What needs to be built
+- **Exit Criteria** - When you're done
+
+---
+
+### 4. Review Subtasks (2 minutes)
+
+```bash
+# Find task directory
+TASK_DIR=.tmp/tasks/$(basename $SESSION | cut -d'-' -f4-)
+
+# List subtasks
+ls $TASK_DIR/subtask_*.json
+
+# View next subtask
+cat $TASK_DIR/subtask_04.json  # Example
+```
+
+**Subtask format**:
+```json
+{
+  "id": "04",
+  "name": "Migrate AgentLoader",
+  "description": "Create src/core/AgentLoader.ts with load/parse functions",
+  "estimated_hours": 1.5,
+  "status": "pending",
+  "dependencies": ["02"],
+  "context_files": ["...standards to load..."],
+  "acceptance_criteria": ["...checklist..."]
+}
+```
+
+---
+
+## Resume Workflow
+
+### Option 1: Continue from Last Checkpoint
+
+```bash
+# 1. Check what's done
+grep "✅" .tmp/sessions/$SESSION/PROGRESS.md
+
+# 2. Find next task
+grep "🔥 NEXT" .tmp/sessions/$SESSION/PROGRESS.md
+
+# 3. Tell the agent
+"Continue with subtask 04 from session $SESSION"
+```
+
+---
+
+### Option 2: Jump to Specific Phase
+
+```bash
+# 1. View phase structure
+cat .tmp/tasks/$TASK_DIR/task.json | jq '.phases'
+
+# 2. Find phase tasks
+cat .tmp/tasks/$TASK_DIR/task.json | jq '.phases[1]'  # Phase 2
+
+# 3. Tell the agent
+"Start Phase 2 - Adapters from session $SESSION"
+```
+
+---
+
+### Option 3: Review and Decide
+
+```bash
+# 1. Quick status
+cat .tmp/sessions/$SESSION/PROGRESS.md | grep -A5 "Overall Progress"
+
+# 2. View completed work
+cat .tmp/sessions/$SESSION/PROGRESS.md | grep -A20 "Completed Work"
+
+# 3. Discuss with agent
+"Show me the current status of session $SESSION and suggest next steps"
+```
+
+---
+
+## Key Files to Read
+
+### context.md (ALWAYS)
+
+**Why**: Contains standards you MUST follow
+
+```markdown
+## Context Files (Standards to Follow)
+- .opencode/context/core/standards/code-quality.md - CRITICAL
+- .opencode/context/core/standards/test-coverage.md - CRITICAL
+```
+
+**Before writing any code**, load these standards!
+
+---
+
+### PROGRESS.md (RECOMMENDED)
+
+**Why**: Shows exactly what's done and what's next
+
+**Key sections**:
+- **Overall Progress** - % complete, phases
+- **Completed Work** - Files created, tasks done
+- **Next Steps** - What to do immediately
+- **Blockers** - Issues to resolve
+
+---
+
+### subtask_NN.json (WHEN NEEDED)
+
+**Why**: Detailed task definition with acceptance criteria
+
+**Use when**:
+- Starting a new subtask
+- Need to know exact requirements
+- Want to see dependencies
+
+---
+
+## Common Scenarios
+
+### Scenario 1: "I don't remember where I was"
+
+```bash
+# Quick catch-up
+cat .tmp/sessions/$SESSION/PROGRESS.md | head -50
+# Read: Overall Progress + Completed Work + Next Steps
+```
+
+**Time**: 2 minutes
+
+---
+
+### Scenario 2: "What was I supposed to build?"
+
+```bash
+# Read original request
+cat .tmp/sessions/$SESSION/context.md | grep -A20 "Current Request"
+
+# Read components
+cat .tmp/sessions/$SESSION/context.md | grep -A30 "Components"
+```
+
+**Time**: 3 minutes
+
+---
+
+### Scenario 3: "What standards should I follow?"
+
+```bash
+# Read context files list
+cat .tmp/sessions/$SESSION/context.md | grep -A15 "Context Files"
+
+# Load the standards
+cat .opencode/context/core/standards/code-quality.md
+```
+
+**Time**: 5 minutes
+
+---
+
+### Scenario 4: "How do I know when I'm done?"
+
+```bash
+# Read exit criteria
+cat .tmp/sessions/$SESSION/context.md | grep -A20 "Exit Criteria"
+```
+
+**Time**: 1 minute
+
+---
+
+## Agent Instructions
+
+When resuming a session, tell the agent:
+
+```
+"Resume session: {SESSION_ID}"
+```
+
+Or more specific:
+
+```
+"Continue with subtask 04 from session 2026-02-04-compatibility-layer-141"
+```
+
+The agent should:
+1. ✅ Read context.md for standards
+2. ✅ Read PROGRESS.md for current state
+3. ✅ Load next subtask JSON
+4. ✅ Load required context files (from subtask.context_files)
+5. ✅ Propose next steps
+6. ✅ Request approval before executing
+
+---
+
+## Session Lifecycle
+
+### Active Session
+- Created when task starts
+- Updated after each subtask completes
+- Contains live progress tracking
+
+### Completed Session
+- All subtasks marked complete
+- Exit criteria met
+- Ready for archival
+
+### Archived Session
+- Moved to `.tmp/archive/sessions/{date}/`
+- Knowledge harvested to permanent context
+- Task JSONs can be deleted
+
+---
+
+## Cleanup Checklist
+
+After completing a session:
+
+- [ ] All exit criteria met?
+- [ ] Valuable knowledge harvested to context?
+- [ ] Session files archived?
+- [ ] Task JSONs cleaned up?
+- [ ] Temporary files deleted?
+
+---
+
+## Best Practices
+
+1. **Always read context.md first** - Contains critical standards
+2. **Check PROGRESS.md before asking** - Likely has the answer
+3. **Use subtask JSONs for detailed requirements** - Not just memory
+4. **Update PROGRESS.md after each task** - Keep it current
+5. **Archive when done** - Don't clutter workspace
+
+---
+
+## Reference
+
+- **Session Template**: `.tmp/sessions/{YYYY-MM-DD}-{task-slug}/`
+- **Task Template**: `.tmp/tasks/{task-slug}/`
+- **Related**:
+  - guides/compatibility-layer-workflow.md (example session)
+  - standards/code-quality.md (what to follow)

+ 93 - 0
plugins/claude-code/scripts/context/core/navigation.md

@@ -0,0 +1,93 @@
+<!-- Context: core/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Core Context Navigation
+
+**Purpose**: Universal standards and workflows for all development
+
+---
+
+## Structure
+
+```
+core/
+├── navigation.md
+├── context-system.md
+├── essential-patterns.md
+│
+├── standards/
+│   ├── navigation.md
+│   ├── code-quality.md
+│   ├── test-coverage.md
+│   ├── documentation.md
+│   ├── security-patterns.md
+│   └── code-analysis.md
+│
+├── workflows/
+│   ├── navigation.md
+│   ├── code-review.md
+│   ├── task-delegation-basics.md
+│   ├── feature-breakdown.md
+│   ├── session-management.md
+│   └── design-iteration-overview.md
+│
+├── guides/
+│   ├── navigation.md
+│   └── resuming-sessions.md
+│
+├── task-management/
+│   ├── navigation.md
+│   ├── standards/
+│   │   └── navigation.md
+│   ├── guides/
+│   │   └── navigation.md
+│   └── lookup/
+│       └── navigation.md
+│
+├── system/
+│   └── context-guide.md
+│
+└── context-system/
+    ├── navigation.md
+    ├── examples/
+    │   └── navigation.md
+    ├── guides/
+    │   └── navigation.md
+    ├── operations/
+    │   └── navigation.md
+    └── standards/
+        └── navigation.md
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **Write code** | `standards/code-quality.md` |
+| **Write tests** | `standards/test-coverage.md` |
+| **Write docs** | `standards/documentation.md` |
+| **Security patterns** | `standards/security-patterns.md` |
+| **Review code** | `workflows/code-review.md` |
+| **Delegate task** | `workflows/task-delegation-basics.md` |
+| **Break down feature** | `workflows/feature-breakdown.md` |
+| **Resume session** | `guides/resuming-sessions.md` |
+| **Manage tasks** | `task-management/navigation.md` |
+| **Task CLI commands** | `task-management/lookup/task-commands.md` |
+| **Context system** | `context-system.md` |
+
+---
+
+## By Type
+
+**Standards** → Code quality, testing, docs, security (critical priority)
+**Workflows** → Review, delegation, task breakdown (high priority)
+**Task Management** → JSON-driven task tracking with CLI (high priority)
+**System** → Context management and guides (medium priority)
+
+---
+
+## Related Context
+
+- **Development** → `../development/navigation.md`
+- **OpenAgents Control Repo** → `../openagents-repo/navigation.md`

+ 152 - 0
plugins/claude-code/scripts/context/core/standards/code-analysis.md

@@ -0,0 +1,152 @@
+<!-- Context: standards/analysis | Priority: high | Version: 2.0 | Updated: 2025-01-21 -->
+
+# Analysis Guidelines
+
+## Quick Reference
+
+**Process**: Context → Gather → Patterns → Impact → Recommendations
+
+**Report Format**: Context, Findings, Patterns, Issues (🔴🟡🔵), Recommendations, Trade-offs, Next Steps
+
+**Be**: Thorough, Objective, Specific, Actionable
+
+**Checklist**: Context stated, Evidence gathered, Patterns identified, Issues prioritized, Recommendations specific, Trade-offs considered
+
+---
+
+## Purpose
+Framework for analyzing code, patterns, and technical issues systematically.
+
+## When to Use
+Reference this when:
+- Analyzing codebase patterns
+- Investigating bugs or issues
+- Evaluating architectural decisions
+- Assessing code quality
+- Researching solutions
+
+## Analysis Process
+
+### 1. Understand Context
+- What are we analyzing and why?
+- What's the goal or question?
+- What's the scope?
+- What constraints exist?
+
+### 2. Gather Information
+- Read relevant code / data points
+- Check documentation
+- Search for patterns
+- Review related issues
+- Examine dependencies
+
+### 3. Identify Patterns
+- What's consistent across the codebase?
+- What conventions are followed?
+- What patterns are repeated?
+- What's inconsistent or unusual?
+
+### 4. Assess Impact
+- What are the implications?
+- What are the trade-offs?
+- What could break?
+- What are the risks?
+
+### 5. Provide Recommendations
+- What should be done?
+- Why this approach?
+- What are alternatives?
+- What's the priority?
+
+## Analysis Report Format
+
+```markdown
+## Analysis: {Topic}
+
+**Context:** {What we're analyzing and why}
+
+**Findings:**
+- {Key finding 1}
+- {Key finding 2}
+- {Key finding 3}
+
+**Patterns Observed:**
+- {Pattern 1}: {Description}
+- {Pattern 2}: {Description}
+
+**Issues Identified:**
+- 🔴 Critical: {Issue requiring immediate attention}
+- 🟡 Warning: {Issue to address soon}
+- 🔵 Suggestion: {Nice-to-have improvement}
+
+**Recommendations:**
+1. {Recommendation 1} - {Why}
+2. {Recommendation 2} - {Why}
+
+**Trade-offs:**
+- {Approach A}: {Pros/Cons}
+- {Approach B}: {Pros/Cons}
+
+**Next Steps:**
+- {Action 1}
+- {Action 2}
+```
+
+## Common Analysis Types
+
+### Code Quality Analysis
+- Complexity (cyclomatic, cognitive)
+- Duplication
+- Test coverage
+- Documentation completeness
+- Naming consistency
+- Error handling patterns
+
+### Architecture Analysis
+- Module dependencies
+- Coupling and cohesion
+- Separation of concerns
+- Scalability considerations
+- Performance bottlenecks
+
+### Bug Investigation
+- Reproduce the issue
+- Identify root cause
+- Assess impact and severity
+- Propose fix with rationale
+- Consider edge cases
+
+### Pattern Discovery
+- Search for similar implementations
+- Identify common approaches
+- Document conventions
+- Note inconsistencies
+- Recommend standardization
+
+## Best Practices
+
+### Be Thorough
+- Check multiple examples
+- Consider edge cases
+- Look for exceptions
+- Verify assumptions
+
+### Be Objective
+- Base conclusions on evidence
+- Avoid assumptions
+- Consider multiple perspectives
+- Acknowledge limitations
+
+### Be Specific
+- Provide concrete examples
+- Include file names and line numbers
+- Show code snippets
+- Quantify when possible
+
+### Be Actionable
+- Clear recommendations
+- Prioritize findings
+- Explain rationale
+- Suggest next steps
+
+

+ 164 - 0
plugins/claude-code/scripts/context/core/standards/code-quality.md

@@ -0,0 +1,164 @@
+<!-- Context: standards/code | Priority: critical | Version: 2.0 | Updated: 2025-01-21 -->
+# Code Standards
+
+## Quick Reference
+
+**Core Philosophy**: Modular, Functional, Maintainable
+**Golden Rule**: If you can't easily test it, refactor it
+
+**Critical Patterns** (use these):
+- ✅ Pure functions (same input = same output, no side effects)
+- ✅ Immutability (create new data, don't modify)
+- ✅ Composition (build complex from simple)
+- ✅ Small functions (< 50 lines)
+- ✅ Explicit dependencies (dependency injection)
+
+**Anti-Patterns** (avoid these):
+- ❌ Mutation, side effects, deep nesting
+- ❌ God modules, global state, large functions
+
+---
+
+## Core Philosophy
+
+**Modular**: Everything is a component - small, focused, reusable
+**Functional**: Pure functions, immutability, composition over inheritance
+**Maintainable**: Self-documenting, testable, predictable
+
+## Principles
+
+### Modular Design
+- Single responsibility per module
+- Clear interfaces (explicit inputs/outputs)
+- Independent and composable
+- < 100 lines per component (ideally < 50)
+
+### Functional Approach
+- **Pure functions**: Same input = same output, no side effects
+- **Immutability**: Create new data, don't modify existing
+- **Composition**: Build complex from simple functions
+- **Declarative**: Describe what, not how
+
+### Component Structure
+```
+component/
+├── index.js      # Public interface
+├── core.js       # Core logic (pure functions)
+├── utils.js      # Helpers
+└── tests/        # Tests
+```
+
+## Patterns
+
+### Pure Functions
+```javascript
+// ✅ Pure
+const add = (a, b) => a + b;
+const formatUser = (user) => ({ ...user, fullName: `${user.firstName} ${user.lastName}` });
+
+// ❌ Impure (side effects)
+let total = 0;
+const addToTotal = (value) => { total += value; return total; };
+```
+
+### Immutability
+```javascript
+// ✅ Immutable
+const addItem = (items, item) => [...items, item];
+const updateUser = (user, changes) => ({ ...user, ...changes });
+
+// ❌ Mutable
+const addItem = (items, item) => { items.push(item); return items; };
+```
+
+### Composition
+```javascript
+// ✅ Compose small functions
+const processUser = pipe(validateUser, enrichUserData, saveUser);
+const isValidEmail = (email) => validateEmail(normalizeEmail(email));
+
+// ❌ Deep inheritance
+class ExtendedUserManagerWithValidation extends UserManager { }
+```
+
+### Declarative
+```javascript
+// ✅ Declarative
+const activeUsers = users.filter(u => u.isActive).map(u => u.name);
+
+// ❌ Imperative
+const names = [];
+for (let i = 0; i < users.length; i++) {
+  if (users[i].isActive) names.push(users[i].name);
+}
+```
+
+## Naming
+
+- **Files**: lowercase-with-dashes.js
+- **Functions**: verbPhrases (getUser, validateEmail)
+- **Predicates**: isValid, hasPermission, canAccess
+- **Variables**: descriptive (userCount not uc), const by default
+- **Constants**: UPPER_SNAKE_CASE
+
+## Error Handling
+
+```javascript
+// ✅ Explicit error handling
+function parseJSON(text) {
+  try {
+    return { success: true, data: JSON.parse(text) };
+  } catch (error) {
+    return { success: false, error: error.message };
+  }
+}
+
+// ✅ Validate at boundaries
+function createUser(userData) {
+  const validation = validateUserData(userData);
+  if (!validation.isValid) {
+    return { success: false, errors: validation.errors };
+  }
+  return { success: true, user: saveUser(userData) };
+}
+```
+
+## Dependency Injection
+
+```javascript
+// ✅ Dependencies explicit
+function createUserService(database, logger) {
+  return {
+    createUser: (userData) => {
+      logger.info('Creating user');
+      return database.insert('users', userData);
+    }
+  };
+}
+
+// ❌ Hidden dependencies
+import db from './database.js';
+function createUser(userData) { return db.insert('users', userData); }
+```
+
+## Anti-Patterns
+
+❌ **Mutation**: Modifying data in place
+❌ **Side effects**: console.log, API calls in pure functions
+❌ **Deep nesting**: Use early returns instead
+❌ **God modules**: Split into focused modules
+❌ **Global state**: Pass dependencies explicitly
+❌ **Large functions**: Keep < 50 lines
+
+## Best Practices
+
+✅ Pure functions whenever possible
+✅ Immutable data structures
+✅ Small, focused functions (< 50 lines)
+✅ Compose small functions into larger ones
+✅ Explicit dependencies (dependency injection)
+✅ Validate at boundaries
+✅ Self-documenting code
+✅ Test in isolation
+
+**Golden Rule**: If you can't easily test it, refactor it.

+ 164 - 0
plugins/claude-code/scripts/context/core/standards/code.md

@@ -0,0 +1,164 @@
+<!-- Context: standards/code | Priority: critical | Version: 2.0 | Updated: 2025-01-21 -->
+# Code Standards
+
+## Quick Reference
+
+**Core Philosophy**: Modular, Functional, Maintainable
+**Golden Rule**: If you can't easily test it, refactor it
+
+**Critical Patterns** (use these):
+- ✅ Pure functions (same input = same output, no side effects)
+- ✅ Immutability (create new data, don't modify)
+- ✅ Composition (build complex from simple)
+- ✅ Small functions (< 50 lines)
+- ✅ Explicit dependencies (dependency injection)
+
+**Anti-Patterns** (avoid these):
+- ❌ Mutation, side effects, deep nesting
+- ❌ God modules, global state, large functions
+
+---
+
+## Core Philosophy
+
+**Modular**: Everything is a component - small, focused, reusable
+**Functional**: Pure functions, immutability, composition over inheritance
+**Maintainable**: Self-documenting, testable, predictable
+
+## Principles
+
+### Modular Design
+- Single responsibility per module
+- Clear interfaces (explicit inputs/outputs)
+- Independent and composable
+- < 100 lines per component (ideally < 50)
+
+### Functional Approach
+- **Pure functions**: Same input = same output, no side effects
+- **Immutability**: Create new data, don't modify existing
+- **Composition**: Build complex from simple functions
+- **Declarative**: Describe what, not how
+
+### Component Structure
+```
+component/
+├── index.js      # Public interface
+├── core.js       # Core logic (pure functions)
+├── utils.js      # Helpers
+└── tests/        # Tests
+```
+
+## Patterns
+
+### Pure Functions
+```javascript
+// ✅ Pure
+const add = (a, b) => a + b;
+const formatUser = (user) => ({ ...user, fullName: `${user.firstName} ${user.lastName}` });
+
+// ❌ Impure (side effects)
+let total = 0;
+const addToTotal = (value) => { total += value; return total; };
+```
+
+### Immutability
+```javascript
+// ✅ Immutable
+const addItem = (items, item) => [...items, item];
+const updateUser = (user, changes) => ({ ...user, ...changes });
+
+// ❌ Mutable
+const addItem = (items, item) => { items.push(item); return items; };
+```
+
+### Composition
+```javascript
+// ✅ Compose small functions
+const processUser = pipe(validateUser, enrichUserData, saveUser);
+const isValidEmail = (email) => validateEmail(normalizeEmail(email));
+
+// ❌ Deep inheritance
+class ExtendedUserManagerWithValidation extends UserManager { }
+```
+
+### Declarative
+```javascript
+// ✅ Declarative
+const activeUsers = users.filter(u => u.isActive).map(u => u.name);
+
+// ❌ Imperative
+const names = [];
+for (let i = 0; i < users.length; i++) {
+  if (users[i].isActive) names.push(users[i].name);
+}
+```
+
+## Naming
+
+- **Files**: lowercase-with-dashes.js
+- **Functions**: verbPhrases (getUser, validateEmail)
+- **Predicates**: isValid, hasPermission, canAccess
+- **Variables**: descriptive (userCount not uc), const by default
+- **Constants**: UPPER_SNAKE_CASE
+
+## Error Handling
+
+```javascript
+// ✅ Explicit error handling
+function parseJSON(text) {
+  try {
+    return { success: true, data: JSON.parse(text) };
+  } catch (error) {
+    return { success: false, error: error.message };
+  }
+}
+
+// ✅ Validate at boundaries
+function createUser(userData) {
+  const validation = validateUserData(userData);
+  if (!validation.isValid) {
+    return { success: false, errors: validation.errors };
+  }
+  return { success: true, user: saveUser(userData) };
+}
+```
+
+## Dependency Injection
+
+```javascript
+// ✅ Dependencies explicit
+function createUserService(database, logger) {
+  return {
+    createUser: (userData) => {
+      logger.info('Creating user');
+      return database.insert('users', userData);
+    }
+  };
+}
+
+// ❌ Hidden dependencies
+import db from './database.js';
+function createUser(userData) { return db.insert('users', userData); }
+```
+
+## Anti-Patterns
+
+❌ **Mutation**: Modifying data in place
+❌ **Side effects**: console.log, API calls in pure functions
+❌ **Deep nesting**: Use early returns instead
+❌ **God modules**: Split into focused modules
+❌ **Global state**: Pass dependencies explicitly
+❌ **Large functions**: Keep < 50 lines
+
+## Best Practices
+
+✅ Pure functions whenever possible
+✅ Immutable data structures
+✅ Small, focused functions (< 50 lines)
+✅ Compose small functions into larger ones
+✅ Explicit dependencies (dependency injection)
+✅ Validate at boundaries
+✅ Self-documenting code
+✅ Test in isolation
+
+**Golden Rule**: If you can't easily test it, refactor it.

+ 150 - 0
plugins/claude-code/scripts/context/core/standards/docs.md

@@ -0,0 +1,150 @@
+<!-- Context: standards/docs | Priority: critical | Version: 2.0 | Updated: 2025-01-21 -->
+
+# Documentation Standards
+
+## Quick Reference
+
+**Golden Rule**: If users ask the same question twice, document it
+
+**Document** (✅ DO):
+- WHY decisions were made
+- Complex algorithms/logic
+- Public APIs, setup, common use cases
+
+**Don't Document** (❌ DON'T):
+- Obvious code (i++ doesn't need comment)
+- What code does (should be self-explanatory)
+
+**Principles**: Audience-focused, Show don't tell, Keep current
+
+---
+
+## Principles
+
+**Audience-focused**: Write for users (what/how), developers (why/when), contributors (setup/conventions)
+**Show, don't tell**: Code examples, real use cases, expected output
+**Keep current**: Update with code changes, remove outdated info, mark deprecations
+
+## README Structure
+
+```markdown
+# Project Name
+Brief description (1-2 sentences)
+
+## Features
+- Key feature 1
+- Key feature 2
+
+## Installation
+```bash
+npm install package-name
+```
+
+## Quick Start
+```javascript
+const result = doSomething();
+```
+
+## Usage
+[Detailed examples]
+
+## API Reference
+[If applicable]
+
+## Contributing
+[Link to CONTRIBUTING.md]
+
+## License
+[License type]
+```
+
+## Function Documentation
+
+```javascript
+/**
+ * Calculate total price including tax
+ * 
+ * @param {number} price - Base price
+ * @param {number} taxRate - Tax rate (0-1)
+ * @returns {number} Total with tax
+ * 
+ * @example
+ * calculateTotal(100, 0.1) // 110
+ */
+function calculateTotal(price, taxRate) {
+  return price * (1 + taxRate);
+}
+```
+
+## What to Document
+
+### ✅ DO
+- **WHY** decisions were made
+- Complex algorithms/logic
+- Non-obvious behavior
+- Public APIs
+- Setup/installation
+- Common use cases
+- Known limitations
+- Workarounds (with explanation)
+
+### ❌ DON'T
+- Obvious code (i++ doesn't need comment)
+- What code does (should be self-explanatory)
+- Redundant information
+- Outdated/incorrect info
+
+## Comments
+
+### Good
+```javascript
+// Calculate discount by tier (Bronze: 5%, Silver: 10%, Gold: 15%)
+const discount = getDiscountByTier(customer.tier);
+
+// HACK: API returns null instead of [], normalize it
+const items = response.items || [];
+
+// TODO: Use async/await when Node 18+ is minimum
+```
+
+### Bad
+```javascript
+// Increment i
+i++;
+
+// Get user
+const user = getUser();
+```
+
+## API Documentation
+
+```markdown
+### POST /api/users
+Create a new user
+
+**Request:**
+```json
+{ "name": "John", "email": "john@example.com" }
+```
+
+**Response:**
+```json
+{ "id": "123", "name": "John", "email": "john@example.com" }
+```
+
+**Errors:**
+- 400 - Invalid input
+- 409 - Email exists
+```
+
+## Best Practices
+
+✅ Explain WHY, not just WHAT
+✅ Include working examples
+✅ Show expected output
+✅ Cover error handling
+✅ Use consistent terminology
+✅ Keep structure predictable
+✅ Update when code changes
+
+**Golden Rule**: If users ask the same question twice, document it.

+ 150 - 0
plugins/claude-code/scripts/context/core/standards/documentation.md

@@ -0,0 +1,150 @@
+<!-- Context: standards/docs | Priority: critical | Version: 2.0 | Updated: 2025-01-21 -->
+
+# Documentation Standards
+
+## Quick Reference
+
+**Golden Rule**: If users ask the same question twice, document it
+
+**Document** (✅ DO):
+- WHY decisions were made
+- Complex algorithms/logic
+- Public APIs, setup, common use cases
+
+**Don't Document** (❌ DON'T):
+- Obvious code (i++ doesn't need comment)
+- What code does (should be self-explanatory)
+
+**Principles**: Audience-focused, Show don't tell, Keep current
+
+---
+
+## Principles
+
+**Audience-focused**: Write for users (what/how), developers (why/when), contributors (setup/conventions)
+**Show, don't tell**: Code examples, real use cases, expected output
+**Keep current**: Update with code changes, remove outdated info, mark deprecations
+
+## README Structure
+
+```markdown
+# Project Name
+Brief description (1-2 sentences)
+
+## Features
+- Key feature 1
+- Key feature 2
+
+## Installation
+```bash
+npm install package-name
+```
+
+## Quick Start
+```javascript
+const result = doSomething();
+```
+
+## Usage
+[Detailed examples]
+
+## API Reference
+[If applicable]
+
+## Contributing
+[Link to CONTRIBUTING.md]
+
+## License
+[License type]
+```
+
+## Function Documentation
+
+```javascript
+/**
+ * Calculate total price including tax
+ * 
+ * @param {number} price - Base price
+ * @param {number} taxRate - Tax rate (0-1)
+ * @returns {number} Total with tax
+ * 
+ * @example
+ * calculateTotal(100, 0.1) // 110
+ */
+function calculateTotal(price, taxRate) {
+  return price * (1 + taxRate);
+}
+```
+
+## What to Document
+
+### ✅ DO
+- **WHY** decisions were made
+- Complex algorithms/logic
+- Non-obvious behavior
+- Public APIs
+- Setup/installation
+- Common use cases
+- Known limitations
+- Workarounds (with explanation)
+
+### ❌ DON'T
+- Obvious code (i++ doesn't need comment)
+- What code does (should be self-explanatory)
+- Redundant information
+- Outdated/incorrect info
+
+## Comments
+
+### Good
+```javascript
+// Calculate discount by tier (Bronze: 5%, Silver: 10%, Gold: 15%)
+const discount = getDiscountByTier(customer.tier);
+
+// HACK: API returns null instead of [], normalize it
+const items = response.items || [];
+
+// TODO: Use async/await when Node 18+ is minimum
+```
+
+### Bad
+```javascript
+// Increment i
+i++;
+
+// Get user
+const user = getUser();
+```
+
+## API Documentation
+
+```markdown
+### POST /api/users
+Create a new user
+
+**Request:**
+```json
+{ "name": "John", "email": "john@example.com" }
+```
+
+**Response:**
+```json
+{ "id": "123", "name": "John", "email": "john@example.com" }
+```
+
+**Errors:**
+- 400 - Invalid input
+- 409 - Email exists
+```
+
+## Best Practices
+
+✅ Explain WHY, not just WHAT
+✅ Include working examples
+✅ Show expected output
+✅ Cover error handling
+✅ Use consistent terminology
+✅ Keep structure predictable
+✅ Update when code changes
+
+**Golden Rule**: If users ask the same question twice, document it.

+ 51 - 0
plugins/claude-code/scripts/context/core/standards/navigation.md

@@ -0,0 +1,51 @@
+<!-- Context: core/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Core Standards Navigation
+
+**Purpose**: Universal standards for all development work
+
+---
+
+## Files
+
+| File | Topic | Priority | Load When |
+|------|-------|----------|-----------|
+| `code-quality.md` | Code quality rules | ⭐⭐⭐⭐⭐ | Writing/reviewing code |
+| `test-coverage.md` | Testing standards | ⭐⭐⭐⭐⭐ | Writing tests |
+| `documentation.md` | Documentation rules | ⭐⭐⭐⭐ | Writing docs |
+| `security-patterns.md` | Security best practices | ⭐⭐⭐⭐ | Security review, patterns |
+| `project-intelligence.md` | What and why | ⭐⭐⭐⭐ | Onboarding, understanding projects |
+| `project-intelligence-management.md` | How to manage | ⭐⭐⭐ | Managing intelligence files |
+| `code-analysis.md` | Analysis approaches | ⭐⭐⭐ | Analyzing code, debugging |
+
+---
+
+## Loading Strategy
+
+**For code implementation**:
+1. Load `code-quality.md` (critical)
+2. Load `security-patterns.md` (high)
+
+**For testing**:
+1. Load `test-coverage.md` (critical)
+2. Depends on: `code-quality.md`
+
+**For documentation**:
+1. Load `documentation.md` (critical)
+
+**For code review**:
+1. Load `code-quality.md` (critical)
+2. Load `security-patterns.md` (high)
+3. Load `test-coverage.md` (high)
+
+**For project onboarding/understanding**:
+1. Load `project-intelligence.md` (high)
+2. Then load: `../../project-intelligence/` folder for full project context
+
+---
+
+## Related
+
+- **Workflows** → `../workflows/navigation.md`
+- **Development Principles** → `../../development/principles/`
+- **Project Intelligence** → `../../project-intelligence/navigation.md` (full project context)

+ 249 - 0
plugins/claude-code/scripts/context/core/standards/project-intelligence-management.md

@@ -0,0 +1,249 @@
+<!-- Context: standards/intelligence-mgmt | Priority: high | Version: 1.0 | Updated: 2025-01-12 -->
+
+# Project Intelligence Management
+
+> **What**: How to manage project intelligence files and folders.
+> **When**: Use this guide when adding, updating, or removing intelligence files.
+> **Related**: See `project-intelligence.md` for what and why.
+
+## Quick Reference
+
+| Action | Do This |
+|--------|---------|
+| Update existing file | Edit + bump frontmatter version |
+| Add new file | Create `.md` + add to navigation.md |
+| Add subfolder | Create folder + `navigation.md` + update parent nav |
+| Remove file | Rename `.deprecated.md` + archive, don't delete |
+
+---
+
+## Update Existing Files
+
+**When**:
+- Business changes → Update `business-domain.md`
+- New decision → Add to `decisions-log.md`
+- New issues → Update `living-notes.md`
+- Feature launch → Update `business-tech-bridge.md`
+- Stack changes → Update `technical-domain.md`
+
+**Process**:
+1. Edit the file
+2. Update frontmatter:
+   ```html
+   <!-- Context: {category} | Priority: {level} | Version: {X.Y} | Updated: {YYYY-MM-DD} -->
+   ```
+3. Keep under 200 lines
+4. Commit with message like: `docs: Update business-domain.md with new market focus`
+
+---
+
+## Add New Files
+
+**When**:
+- New domain area needs dedicated docs
+- Existing file exceeds 200 lines
+- Specialized context requires separation
+
+**Naming**:
+- Kebab-case: `user-research.md`, `api-docs.md`
+- Descriptive: filename tells you what's inside
+
+**Template**:
+```html
+<!-- Context: project-intelligence/{filename} | Priority: {high|medium} | Version: 1.0 | Updated: {YYYY-MM-DD} -->
+
+# File Title
+
+> One-line purpose statement
+
+## Quick Reference
+
+- **Purpose**: [What this covers]
+- **Update When**: [Triggers]
+- **Related Files**: [Links]
+
+## Content
+
+[Follow patterns from existing files]
+
+## Related Files
+
+- [File 1] - [Description]
+```
+
+**Process**:
+1. Create file in `project-intelligence/`
+2. Add frontmatter with `project-intelligence/{filename}`
+3. Follow existing file patterns
+4. Keep under 200 lines
+5. Add to `navigation.md`
+
+---
+
+## Create Subfolders
+
+**When**:
+- 5+ related files need grouping
+- Subdomain warrants separation (e.g., `api/`, `mobile/`, `integrations/`)
+- Improves navigation clarity
+
+**Structure**:
+```
+project-intelligence/
+├── navigation.md           # Root nav
+├── [new-subfolder]/        # Create this
+│   ├── navigation.md       # Subfolder nav required
+│   ├── file-1.md
+│   └── file-2.md
+```
+
+**Process**:
+1. Create folder: `mkdir project-intelligence/{name}/`
+2. Create `navigation.md` inside:
+   ```html
+   <!-- Context: project-intelligence/{name}/nav | Priority: medium | Version: 1.0 | Updated: {YYYY-MM-DD} -->
+   
+   # {Name} Navigation
+   
+   > Quick overview
+   
+   ## Files
+   
+   | File | Purpose |
+   |------|---------|
+   | `file-1.md` | [Desc] |
+   ```
+3. Add content files
+4. Update root `navigation.md` with subfolder entry
+
+**Rule**: Every subfolder MUST have `navigation.md`. Avoid nesting deeper than 2 levels (e.g., `project-intelligence/domain/subdomain/`) to prevent context fragmentation.
+
+---
+
+## Remove/Deprecate Files
+
+**When**:
+- Content moved elsewhere
+- File no longer relevant
+- Merged with another file
+
+**Process**:
+1. Rename: `filename.md` → `filename.deprecated.md`
+2. Add frontmatter:
+   ```html
+   <!-- DEPRECATED: {YYYY-MM-DD} - {Reason} -->
+   <!-- REPLACED BY: {new-file.md} -->
+   ```
+3. Add banner at top:
+   > ⚠️ **DEPRECATED**: See `new-file.md` for current info
+4. Mark as deprecated in `navigation.md`
+
+**Never Delete**:
+- Decision history (archive instead)
+- Lessons learned (move to `living-notes.md`)
+- Context that might be needed later
+
+---
+
+## Version Tracking
+
+**Frontmatter**:
+```html
+<!-- Context: {category} | Priority: {level} | Version: {MAJOR.MINOR} | Updated: {YYYY-MM-DD} -->
+```
+
+**Version Rules**:
+| Change | Version |
+|--------|---------|
+| New file | 1.0 |
+| Content addition/update | MINOR |
+| Structure change | MAJOR |
+| Typo fix | PATCH |
+
+**Date**: Always `YYYY-MM-DD`
+
+---
+
+## Quality Standards
+
+**Line Limits**:
+- Files: <200 lines
+- Sections: 3-7 per file
+
+**Required Elements**:
+- Frontmatter with all fields
+- Quick Reference section
+- Related files section
+
+**Anti-Patterns**:
+❌ Mix concerns in one file
+❌ Exceed 200 lines
+❌ Delete files (archive instead)
+❌ Skip frontmatter
+❌ Duplicate information
+
+✅ Keep focused and scannable
+✅ Archive deprecated content
+✅ Use frontmatter consistently
+✅ Link to related files
+
+---
+
+## Governance
+
+**Ownership**:
+| Area | Owner | Responsibility |
+|------|-------|----------------|
+| Business domain | Product Owner | Keep current, accurate |
+| Technical domain | Tech Lead | Keep current, accurate |
+| Decisions log | Tech Lead | Document decisions |
+| Living notes | Team | Keep active items current |
+
+**Review Cadence**:
+| Activity | Frequency |
+|----------|-----------|
+| Quick review | Per PR |
+| Full review | Quarterly |
+| Archive review | Semi-annually |
+
+---
+
+## Checklist
+
+### Add New Intelligence File
+- [ ] Follow naming convention
+- [ ] Add complete frontmatter
+- [ ] Include Quick Reference
+- [ ] Keep under 200 lines
+- [ ] Add to navigation.md
+- [ ] Link from related files
+- [ ] Version: 1.0
+
+### Update Existing File
+- [ ] Make targeted changes
+- [ ] Update version/date in frontmatter
+- [ ] Verify <200 lines
+- [ ] Update navigation if needed
+- [ ] Update related files
+
+### Create Subfolder
+- [ ] Verify warranted (5+ files)
+- [ ] Create folder with kebab-case name
+- [ ] Create `navigation.md` inside
+- [ ] Add subfolder to parent navigation
+- [ ] Create content files
+
+### Deprecate File
+- [ ] Rename with `.deprecated.md`
+- [ ] Add deprecation frontmatter
+- [ ] Add deprecation banner
+- [ ] Mark deprecated in navigation
+- [ ] Document replacement
+
+---
+
+## Related Files
+
+- **Standard**: `project-intelligence.md`
+- **Project Intelligence**: `../../project-intelligence/navigation.md`
+- **Context System**: `../context-system.md`

+ 77 - 0
plugins/claude-code/scripts/context/core/standards/project-intelligence.md

@@ -0,0 +1,77 @@
+<!-- Context: standards/intelligence | Priority: high | Version: 1.0 | Updated: 2025-01-12 -->
+
+# Project Intelligence
+
+> **What**: Living documentation that bridges business domain and technical implementation.
+> **Why**: Quick project understanding and onboarding for developers, agents, and stakeholders.
+> **Where**: `.opencode/context/project-intelligence/` (dedicated folder)
+
+## Quick Reference
+
+| What You Need | File | Description |
+|---------------|------|-------------|
+| Understand the "why" | `business-domain.md` | Problem, users, value |
+| Understand the "how" | `technical-domain.md` | Stack, architecture |
+| See the connection | `business-tech-bridge.md` | Business → technical mapping |
+| Know the context | `decisions-log.md` | Why decisions were made |
+| Current state | `living-notes.md` | Active issues, debt, questions |
+
+## Why This Exists
+
+Projects fail when:
+- Business intent is lost in code
+- Technical decisions aren't documented with context
+- New members spend weeks instead of hours understanding the project
+- Context lives only in people's heads (who leave)
+
+This ensures **business and technical domains speak the same language**.
+
+## Structure
+
+```
+.opencode/context/
+├── project-intelligence/              # Project-specific context
+│   ├── navigation.md                  # Quick overview & routes
+│   ├── business-domain.md             # Business context, problems solved
+│   ├── technical-domain.md            # Stack, architecture, decisions
+│   ├── business-tech-bridge.md        # How business needs → solutions
+│   ├── decisions-log.md               # Decisions with rationale
+│   └── living-notes.md                # Active issues, technical debt
+└── core/                              # Universal standards
+```
+
+## Onboarding Checklist
+
+For new team members or agents:
+
+- [ ] Read `navigation.md` (this file)
+- [ ] Read `business-domain.md` to understand the "why"
+- [ ] Read `technical-domain.md` to understand the "how"
+- [ ] Review `business-tech-bridge.md` to see the connection
+- [ ] Check `decisions-log.md` for context on key choices
+- [ ] Review `living-notes.md` for current state
+- [ ] Explore codebase with this context loaded
+
+## How to Keep This Alive
+
+| Trigger | Action |
+|---------|--------|
+| Business direction shifts | Update `business-domain.md` |
+| New technical decision | Add to `decisions-log.md` |
+| New issues or debt | Update `living-notes.md` |
+| Feature launch | Update `business-tech-bridge.md` |
+| Stack changes | Update `technical-domain.md` |
+
+**Full Management Guide**: See `.opencode/context/core/standards/project-intelligence-management.md`
+
+## Integration with Context System
+
+- **Lazy Loading**: Load project intelligence first when joining a project
+- **Layering**: Then load standards and specific context as needed
+- **Reference**: See `.opencode/context/core/context-system.md` for system overview
+
+## Related Files
+
+- **Management Guide**: `.opencode/context/core/standards/project-intelligence-management.md`
+- **Context System**: `.opencode/context/core/context-system.md`
+- **Standards Index**: `.opencode/context/core/standards/navigation.md`

+ 149 - 0
plugins/claude-code/scripts/context/core/standards/security-patterns.md

@@ -0,0 +1,149 @@
+<!-- Context: standards/patterns | Priority: high | Version: 2.0 | Updated: 2025-01-21 -->
+
+# Essential Patterns - Core Knowledge Base
+
+## Quick Reference
+
+**Critical Patterns**: Error Handling, Validation, Security, Logging
+
+**ALWAYS**: Handle errors gracefully, validate input, use env vars for secrets
+
+**NEVER**: Expose sensitive info, hardcode credentials, skip input validation
+
+**Language-agnostic**: Apply to all programming languages
+
+---
+
+These are language-agnostic patterns that apply to all programming languages. Language-specific implementations are loaded from context files based on project detection.
+
+## Error Handling Pattern
+
+**ALWAYS** handle errors gracefully:
+
+- Catch specific errors, not generic ones
+- Log errors with context
+- Return meaningful error messages
+- Don't expose internal implementation details
+- Use language-specific error handling mechanisms (try/catch, Result, error returns)
+
+## Validation Pattern
+
+**ALWAYS** validate input data:
+
+- Check for null/nil/None values
+- Validate data types
+- Validate data ranges and constraints
+- Sanitize user input
+- Return clear validation error messages
+
+## Logging Pattern
+
+**USE** consistent logging levels:
+
+- **Debug**: Detailed information for debugging (development only)
+- **Info**: Important events and milestones
+- **Warning**: Potential issues that don't stop execution
+- **Error**: Failures and exceptions
+
+## Security Pattern
+
+**NEVER** expose sensitive information:
+
+- Don't log passwords, tokens, or API keys
+- Don't expose internal error details to users
+- Validate and sanitize all user input
+- Use environment variables for secrets
+- Follow principle of least privilege
+
+## File System Safety Pattern
+
+**ALWAYS** validate file paths:
+
+- Prevent path traversal attacks
+- Check file permissions before operations
+- Use absolute paths when possible
+- Handle file not found errors gracefully
+- Close file handles properly
+
+## Configuration Pattern
+
+**ALWAYS** use environment variables for configuration:
+
+- Never hardcode secrets or credentials
+- Provide sensible defaults
+- Validate required configuration on startup
+- Document all configuration options
+- Use different configs for dev/staging/production
+
+## Testing Pattern
+
+**ALWAYS** write testable code:
+
+- Use dependency injection
+- Keep functions pure when possible
+- Write unit tests for business logic
+- Write integration tests for external dependencies
+- Use test fixtures and mocks appropriately
+
+## Documentation Pattern
+
+**DOCUMENT** complex logic and public APIs:
+
+- Explain the "why", not just the "what"
+- Document function parameters and return values
+- Include usage examples
+- Keep documentation up to date with code
+- Use language-specific documentation tools
+
+## Performance Pattern
+
+**AVOID** unnecessary operations:
+
+- Don't repeat expensive calculations
+- Cache results when appropriate
+- Use efficient data structures
+- Profile before optimizing
+- Consider time and space complexity
+
+## Code Organization Pattern
+
+**KEEP** code modular and focused:
+
+- Single Responsibility Principle - one function, one purpose
+- Don't Repeat Yourself (DRY)
+- Separate concerns (business logic, data access, presentation)
+- Use meaningful names for functions and variables
+- Keep functions small and focused (< 50 lines ideally)
+
+## Dependency Management
+
+**MANAGE** dependencies carefully:
+
+- Pin dependency versions for reproducibility
+- Regularly update dependencies for security
+- Minimize number of dependencies
+- Audit dependencies for security vulnerabilities
+- Document why each dependency is needed
+
+## Version Control
+
+**FOLLOW** git best practices:
+
+- Write clear, descriptive commit messages
+- Make atomic commits (one logical change per commit)
+- Use feature branches for development
+- Review code before merging
+- Keep main/master branch stable
+
+## Code Review Checklist
+
+**REVIEW** for these common issues:
+
+- Error handling is comprehensive
+- Input validation is present
+- No hardcoded secrets or credentials
+- Tests cover new functionality
+- Documentation is updated
+- Code follows project conventions
+- No obvious security vulnerabilities
+- Performance considerations addressed

+ 127 - 0
plugins/claude-code/scripts/context/core/standards/test-coverage.md

@@ -0,0 +1,127 @@
+<!-- Context: standards/tests | Priority: critical | Version: 2.0 | Updated: 2025-01-21 -->
+
+# Testing Standards
+
+## Quick Reference
+
+**Golden Rule**: If you can't test it easily, refactor it
+
+**AAA Pattern**: Arrange → Act → Assert
+
+**Test** (✅ DO):
+- Happy path, edge cases, error cases
+- Business logic, public APIs
+
+**Don't Test** (❌ DON'T):
+- Third-party libraries, framework internals
+- Simple getters/setters, private details
+
+**Coverage**: Critical (100%), High (90%+), Medium (80%+)
+
+---
+
+## Principles
+
+**Test behavior, not implementation**: Focus on what code does, not how
+**Keep tests simple**: One assertion per test, clear names, minimal setup
+**Independent tests**: No shared state, run in any order
+**Fast and reliable**: Quick execution, no flaky tests, deterministic
+
+## Test Structure (AAA Pattern)
+
+```javascript
+test('calculateTotal returns sum of item prices', () => {
+  // Arrange - Set up test data
+  const items = [{ price: 10 }, { price: 20 }, { price: 30 }];
+  
+  // Act - Execute code
+  const result = calculateTotal(items);
+  
+  // Assert - Verify result
+  expect(result).toBe(60);
+});
+```
+
+## What to Test
+
+### ✅ DO Test
+- Happy path (normal usage)
+- Edge cases (boundaries, empty, null, undefined)
+- Error cases (invalid input, failures)
+- Business logic (core functionality)
+- Public APIs (exported functions)
+
+### ❌ DON'T Test
+- Third-party libraries
+- Framework internals
+- Simple getters/setters
+- Private implementation details
+
+## Coverage Goals
+
+1. **Critical**: Business logic, data transformations (100%)
+2. **High**: Public APIs, user-facing features (90%+)
+3. **Medium**: Utilities, helpers (80%+)
+4. **Low**: Simple wrappers, configs (optional)
+
+## Testing Pure Functions
+
+```javascript
+function add(a, b) { return a + b; }
+
+test('add returns sum', () => {
+  expect(add(2, 3)).toBe(5);
+  expect(add(-1, 1)).toBe(0);
+  expect(add(0, 0)).toBe(0);
+});
+```
+
+## Testing with Dependencies
+
+```javascript
+// Testable with dependency injection
+function createUserService(database) {
+  return {
+    getUser: (id) => database.findById('users', id)
+  };
+}
+
+// Test with mock
+test('getUser retrieves from database', () => {
+  const mockDb = {
+    findById: jest.fn().mockReturnValue({ id: 1, name: 'John' })
+  };
+  
+  const service = createUserService(mockDb);
+  const user = service.getUser(1);
+  
+  expect(mockDb.findById).toHaveBeenCalledWith('users', 1);
+  expect(user).toEqual({ id: 1, name: 'John' });
+});
+```
+
+## Test Naming
+
+```javascript
+// ✅ Good: Descriptive, clear expectation
+test('calculateDiscount returns 10% off for premium users', () => {});
+test('validateEmail returns false for invalid format', () => {});
+test('createUser throws error when email exists', () => {});
+
+// ❌ Bad: Vague, unclear
+test('it works', () => {});
+test('test user', () => {});
+```
+
+## Best Practices
+
+✅ Test one thing per test
+✅ Use descriptive test names
+✅ Keep tests independent
+✅ Mock external dependencies
+✅ Test edge cases and errors
+✅ Make tests readable
+✅ Run tests frequently
+✅ Fix failing tests immediately
+
+**Golden Rule**: If you can't test it easily, refactor it.

+ 127 - 0
plugins/claude-code/scripts/context/core/standards/tests.md

@@ -0,0 +1,127 @@
+<!-- Context: standards/tests | Priority: critical | Version: 2.0 | Updated: 2025-01-21 -->
+
+# Testing Standards
+
+## Quick Reference
+
+**Golden Rule**: If you can't test it easily, refactor it
+
+**AAA Pattern**: Arrange → Act → Assert
+
+**Test** (✅ DO):
+- Happy path, edge cases, error cases
+- Business logic, public APIs
+
+**Don't Test** (❌ DON'T):
+- Third-party libraries, framework internals
+- Simple getters/setters, private details
+
+**Coverage**: Critical (100%), High (90%+), Medium (80%+)
+
+---
+
+## Principles
+
+**Test behavior, not implementation**: Focus on what code does, not how
+**Keep tests simple**: One assertion per test, clear names, minimal setup
+**Independent tests**: No shared state, run in any order
+**Fast and reliable**: Quick execution, no flaky tests, deterministic
+
+## Test Structure (AAA Pattern)
+
+```javascript
+test('calculateTotal returns sum of item prices', () => {
+  // Arrange - Set up test data
+  const items = [{ price: 10 }, { price: 20 }, { price: 30 }];
+  
+  // Act - Execute code
+  const result = calculateTotal(items);
+  
+  // Assert - Verify result
+  expect(result).toBe(60);
+});
+```
+
+## What to Test
+
+### ✅ DO Test
+- Happy path (normal usage)
+- Edge cases (boundaries, empty, null, undefined)
+- Error cases (invalid input, failures)
+- Business logic (core functionality)
+- Public APIs (exported functions)
+
+### ❌ DON'T Test
+- Third-party libraries
+- Framework internals
+- Simple getters/setters
+- Private implementation details
+
+## Coverage Goals
+
+1. **Critical**: Business logic, data transformations (100%)
+2. **High**: Public APIs, user-facing features (90%+)
+3. **Medium**: Utilities, helpers (80%+)
+4. **Low**: Simple wrappers, configs (optional)
+
+## Testing Pure Functions
+
+```javascript
+function add(a, b) { return a + b; }
+
+test('add returns sum', () => {
+  expect(add(2, 3)).toBe(5);
+  expect(add(-1, 1)).toBe(0);
+  expect(add(0, 0)).toBe(0);
+});
+```
+
+## Testing with Dependencies
+
+```javascript
+// Testable with dependency injection
+function createUserService(database) {
+  return {
+    getUser: (id) => database.findById('users', id)
+  };
+}
+
+// Test with mock
+test('getUser retrieves from database', () => {
+  const mockDb = {
+    findById: jest.fn().mockReturnValue({ id: 1, name: 'John' })
+  };
+  
+  const service = createUserService(mockDb);
+  const user = service.getUser(1);
+  
+  expect(mockDb.findById).toHaveBeenCalledWith('users', 1);
+  expect(user).toEqual({ id: 1, name: 'John' });
+});
+```
+
+## Test Naming
+
+```javascript
+// ✅ Good: Descriptive, clear expectation
+test('calculateDiscount returns 10% off for premium users', () => {});
+test('validateEmail returns false for invalid format', () => {});
+test('createUser throws error when email exists', () => {});
+
+// ❌ Bad: Vague, unclear
+test('it works', () => {});
+test('test user', () => {});
+```
+
+## Best Practices
+
+✅ Test one thing per test
+✅ Use descriptive test names
+✅ Keep tests independent
+✅ Mock external dependencies
+✅ Test edge cases and errors
+✅ Make tests readable
+✅ Run tests frequently
+✅ Fix failing tests immediately
+
+**Golden Rule**: If you can't test it easily, refactor it.

+ 192 - 0
plugins/claude-code/scripts/context/core/system/context-guide.md

@@ -0,0 +1,192 @@
+<!-- Context: core/context-guide | Priority: low | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Context System Guide
+
+## Quick Reference
+
+**Golden Rule**: Fetch context when needed, not before (lazy loading)
+
+**Key Principle**: Use context index for discovery, load specific files as needed
+
+**Index Location**: `.opencode/context/navigation.md` - Quick map of all contexts
+
+**Structure**: standards/ (quality + analysis), workflows/ (process + review), system/ (internals)
+
+**Session Location**: `.tmp/sessions/{timestamp}-{task-slug}/context.md`
+
+---
+
+## Overview
+
+Context files provide guidelines and templates for specific tasks. Use the index system for efficient discovery and lazy loading to keep prompts lean.
+
+## Context Index System
+
+**Central Index**: `.opencode/context/navigation.md` - Ultra-compact map of all contexts
+
+The index provides:
+- Quick map for common tasks (code, docs, tests, review, delegation)
+- Triggers/keywords for each context
+- Dependencies between contexts
+- Priority levels (critical, high, medium)
+
+### Available Context Files
+
+All files are in `.opencode/context/core/` with organized subfolders:
+
+### Standards (Quality Guidelines + Analysis)
+- `standards/code-quality.md` - Modular, functional code principles [critical]
+- `standards/documentation.md` - Documentation standards [critical]
+- `standards/test-coverage.md` - Testing standards [critical]
+- `standards/security-patterns.md` - Core patterns (error handling, security) [high]
+- `standards/code-analysis.md` - Analysis framework [high]
+
+### Workflows (Process Templates + Review)
+- `workflows/task-delegation-basics.md` - Delegation template [high]
+- `workflows/feature-breakdown.md` - Complex task breakdown [high]
+- `workflows/session-management.md` - Session lifecycle [medium]
+- `workflows/code-review.md` - Code review guidelines [high]
+
+## How to Use the Index
+
+**Step 1: Check Quick Map** (for common tasks)
+- Code task? → Load `standards/code-quality.md`
+- Docs task? → Load `standards/documentation.md`
+- Review task? → Load `workflows/code-review.md`
+
+**Step 2: Load Index** (for keyword matching)
+- Load `.opencode/context/navigation.md`
+- Scan triggers to find relevant contexts
+- Load specific context files as needed
+
+**Step 3: Load Dependencies**
+- Check `deps:` in index
+- Load dependent contexts for complete guidelines
+
+**Benefits:**
+- No prompt bloat (index is only ~120 tokens)
+- Fetch only what's relevant
+- Faster for simple tasks
+- Clear dependency tracking
+
+## When to Use Each File
+
+### .opencode/context/core/standards/code-quality.md
+- Writing new code
+- Modifying existing code
+- Following modular/functional patterns
+- Making architectural decisions
+
+### .opencode/context/core/standards/documentation.md
+- Writing README files
+- Creating API documentation
+- Adding code comments
+
+### .opencode/context/core/standards/test-coverage.md
+- Writing new tests
+- Running test suites
+- Debugging test failures
+
+### .opencode/context/core/standards/security-patterns.md
+- Error handling
+- Security patterns
+- Common code patterns
+
+### .opencode/context/core/standards/code-analysis.md
+- Analyzing codebase patterns
+- Investigating bugs
+- Evaluating architecture
+
+### .opencode/context/core/workflows/task-delegation-basics.md
+- Delegating to general agent
+- Creating task context
+- Multi-file coordination
+
+### .opencode/context/core/workflows/feature-breakdown.md
+- Tasks with 4+ files
+- Estimated effort >60 minutes
+- Complex dependencies
+
+### .opencode/context/core/workflows/session-management.md
+- Session lifecycle
+- Cleanup procedures
+- Session isolation
+
+### .opencode/context/core/workflows/code-review.md
+- Reviewing code
+- Conducting code audits
+- Providing PR feedback
+
+## Temporary Context (Session-Specific)
+
+When delegating, create focused task context:
+
+**Location**: `.tmp/sessions/{timestamp}-{task-slug}/context.md`
+
+**Structure**:
+```markdown
+# Task Context: {Task Name}
+
+Session ID: {id}
+Created: {timestamp}
+Status: in_progress
+
+## Current Request
+{What user asked for}
+
+## Requirements
+- {requirement 1}
+- {requirement 2}
+
+## Decisions Made
+- {decision 1}
+
+## Files to Modify/Create
+- {file 1} - {purpose}
+
+## Static Context Available
+- .opencode/context/core/standards/code-quality.md
+- .opencode/context/core/standards/test-coverage.md
+
+## Constraints/Notes
+{Important context}
+
+## Progress
+- [ ] {task 1}
+- [ ] {task 2}
+
+---
+**Instructions for Subagent:**
+{Specific instructions}
+```
+
+## Session Management
+
+### Session Structure
+```
+.tmp/sessions/{session-id}/
+├── context.md          # Task context
+├── notes.md            # Working notes
+└── artifacts/          # Generated files
+```
+
+### Session ID Format
+`{timestamp}-{random-4-chars}`
+Example: `20250119-143022-a4f2`
+
+### Cleanup
+- Ask user before deleting session files
+- Remove after task completion
+- Keep if user wants to review
+
+## Best Practices
+
+✅ Use index for context discovery
+✅ Load only relevant context files
+✅ Check dependencies in index
+✅ Create temp context when delegating
+✅ Clean up sessions after completion
+✅ Reference specific sections when possible
+✅ Keep temp context focused and concise
+
+**Golden Rule**: Fetch context when needed, not before.

+ 85 - 0
plugins/claude-code/scripts/context/core/system/context-paths.md

@@ -0,0 +1,85 @@
+<!-- Context: core/context-paths | Priority: low | Version: 1.0 | Updated: 2026-02-15 -->
+
+---
+id: context-paths
+name: Context File Path Resolution
+---
+
+# Context File Path Resolution
+
+## Resolution Order
+
+Context files are resolved in this order (later sources override earlier ones for conflicting keys):
+
+1. **Global context** (`~/.config/opencode/context/`) — user-wide defaults
+2. **Local context** (`.opencode/context/` in project root) — project-specific, highest priority
+
+This mirrors OpenCode's own config merging behavior (see [OpenCode Config Docs](https://opencode.ai/docs/config/)).
+
+## What Goes Where
+
+| Content Type | Recommended Location | Why |
+|---|---|---|
+| **Project Intelligence** (tech stack, patterns, naming) | Local `.opencode/context/project-intelligence/` | Project-specific, committed to git, shared with team |
+| **Core Standards** (code-quality, docs, tests) | Wherever OAC was installed | Universal standards, same across projects |
+| **Personal Defaults** (your preferred patterns) | Global `~/.config/opencode/context/project-intelligence/` | Personal coding style across all projects |
+
+## How Merging Works
+
+- If a file exists in **both** local and global, the **local version wins**
+- If a file exists **only** in global, it's still loaded (acts as a fallback)
+- If a file exists **only** in local, it's loaded normally
+
+**Example**: User installs OAC globally (core standards at `~/.config/opencode/context/core/`), then runs `/add-context` in a project (creates `.opencode/context/project-intelligence/` locally). The agent loads both: core standards from global, project intelligence from local.
+
+## Path Configuration
+
+```json
+{
+  "paths": {
+    "local": ".opencode/context",
+    "global": "~/.config/opencode/context"
+  }
+}
+```
+
+Set `"global": false` to disable global context loading.
+
+## Environment Variable Override
+
+The installer supports `OPENCODE_INSTALL_DIR` to override the install location:
+
+```bash
+export OPENCODE_INSTALL_DIR=~/custom/path
+bash install.sh developer
+```
+
+OpenCode itself supports `OPENCODE_CONFIG_DIR` for a custom config directory (see [OpenCode docs](https://opencode.ai/docs/config/)). If set, context files in that directory are loaded alongside global and local configs.
+
+## Migrating Global to Local
+
+If you installed globally but want project-specific context:
+
+```bash
+/context migrate
+```
+
+This copies `project-intelligence/` from global (`~/.config/opencode/context/`) to local (`.opencode/context/`), so your project patterns are committed to git and shared with your team. See `/context migrate` for details.
+
+## Common Scenarios
+
+### Scenario 1: Everything Local (Development / Repo Maintainer)
+- OAC installed locally via `bash install.sh developer`
+- All context in `.opencode/context/`
+- Committed to git, team shares everything
+
+### Scenario 2: Global Install + Local Project Intelligence
+- OAC installed globally via `bash install.sh developer --install-dir ~/.config/opencode`
+- Core standards at `~/.config/opencode/context/core/`
+- Run `/add-context` in project → creates `.opencode/context/project-intelligence/` locally
+- Project intelligence committed to git, core standards come from global
+
+### Scenario 3: Global Personal Defaults
+- Run `/add-context --global` to save personal coding patterns
+- These apply to ALL projects as fallback
+- Any project can override with local `/add-context`

+ 40 - 0
plugins/claude-code/scripts/context/core/system/navigation.md

@@ -0,0 +1,40 @@
+<!-- Context: core/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Core System
+
+**Purpose**: System guides and paths for core operations
+
+---
+
+## Structure
+
+```
+core/system/
+├── navigation.md (this file)
+└── [system guides and paths]
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **System guides** | `./` |
+| **Core standards** | `../standards/navigation.md` |
+| **Context system** | `../context-system/navigation.md` |
+
+---
+
+## By Type
+
+**System Guides** → Operational guides for core systems  
+**Paths** → System paths and directory structures
+
+---
+
+## Related Context
+
+- **Core Navigation** → `../navigation.md`
+- **Context System** → `../context-system/navigation.md`
+- **Core Standards** → `../standards/navigation.md`

+ 129 - 0
plugins/claude-code/scripts/context/core/task-management/guides/managing-tasks.md

@@ -0,0 +1,129 @@
+<!-- Context: core/managing-tasks | Priority: high | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Guide: Managing Task Lifecycle
+
+**Purpose**: Step-by-step workflow for JSON-driven task management
+
+**Last Updated**: 2026-01-11
+
+---
+
+## Prerequisites
+
+- TaskManager agent available
+- Feature folder created in `.tmp/tasks/` (at project root)
+
+---
+
+## Workflow Overview
+
+```
+1. Initiation    → TaskManager creates task.json + subtasks
+2. Selection     → Find eligible tasks (deps satisfied)
+3. Execution     → Working agent implements task
+4. Verification  → TaskManager validates completion
+5. Archiving     → Move to completed/ when done
+```
+
+---
+
+## 1. Initiation (TaskManager)
+
+Create feature folder and files:
+```
+.tmp/tasks/{feature-slug}/
+├── task.json
+├── subtask_01.json
+├── subtask_02.json
+└── subtask_03.json
+```
+
+Validate with: `task-cli.ts validate {feature}`
+
+---
+
+## 2. Task Selection
+
+Find eligible tasks using CLI:
+```bash
+task-cli.ts next {feature}      # All ready tasks
+task-cli.ts parallel {feature}  # Parallelizable only
+```
+
+Selection criteria:
+- `status == "pending"`
+- All `depends_on` tasks have `status == "completed"`
+
+---
+
+## 3. Execution (Working Agent)
+
+When picking up task:
+
+1. Read subtask JSON
+2. Update status:
+   ```json
+   {
+     "status": "in_progress",
+     "agent_id": "coder-agent",
+     "started_at": "2026-01-11T14:30:00Z"
+   }
+   ```
+3. Load `context_files` (lazy)
+4. Implement `deliverables`
+5. Add `completion_summary` (max 200 chars)
+
+---
+
+## 4. Verification (TaskManager)
+
+After agent signals completion:
+
+1. Check each `acceptance_criteria`
+2. If all pass → Mark completed:
+   ```bash
+   task-cli.ts complete {feature} {seq} "summary"
+   ```
+3. If fail → Keep in_progress, report failures
+
+---
+
+## 5. Archiving
+
+When `completed_count == subtask_count`:
+
+1. Update task.json: `status: "completed"`
+2. Move folder: `.tmp/tasks/{slug}/` → `.tmp/tasks/completed/{slug}/`
+
+---
+
+## Status Ownership
+
+| Status | Who Sets | When |
+|--------|----------|------|
+| pending | TaskManager | Initial creation |
+| in_progress | Working agent | Picks up task |
+| completed | TaskManager | After verification |
+| blocked | Either | Dependency/issue found |
+
+---
+
+## CLI Commands Summary
+
+| Command | Use Case |
+|---------|----------|
+| `status` | Quick overview |
+| `next` | What to work on |
+| `parallel` | Batch parallel work |
+| `deps` | Understand blockers |
+| `blocked` | Identify issues |
+| `complete` | Mark task done |
+| `validate` | Health check |
+
+---
+
+## Related
+
+- `../standards/task-schema.md` - JSON field reference
+- `splitting-tasks.md` - How to create subtasks
+- `../lookup/task-commands.md` - Full CLI reference

+ 42 - 0
plugins/claude-code/scripts/context/core/task-management/guides/navigation.md

@@ -0,0 +1,42 @@
+<!-- Context: core/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Task Management Guides
+
+**Purpose**: Step-by-step guides for task management workflows
+
+---
+
+## Structure
+
+```
+guides/
+├── navigation.md (this file)
+├── managing-tasks.md
+└── splitting-tasks.md
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **Split features into tasks** | `splitting-tasks.md` |
+| **Manage task lifecycle** | `managing-tasks.md` |
+| **Task schema** | `../standards/task-schema.md` |
+| **CLI commands** | `../lookup/task-commands.md` |
+
+---
+
+## By Type
+
+**Decomposition** → How to split features into subtasks  
+**Workflow** → How to manage task lifecycle
+
+---
+
+## Related Context
+
+- **Task Management** → `../navigation.md`
+- **Standards** → `../standards/navigation.md`
+- **Lookup** → `../lookup/navigation.md`

+ 115 - 0
plugins/claude-code/scripts/context/core/task-management/guides/splitting-tasks.md

@@ -0,0 +1,115 @@
+<!-- Context: core/splitting-tasks | Priority: high | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Guide: Splitting Features into Tasks
+
+**Purpose**: How to decompose features into atomic subtasks
+
+**Last Updated**: 2026-01-11
+
+---
+
+## Prerequisites
+
+- Feature request understood
+- Context bundle loaded (project standards, patterns)
+
+---
+
+## Steps
+
+### 1. Identify Atomic Boundaries
+
+Break feature into tasks that are:
+- Completable in 1-2 hours
+- Have single, clear outcome
+- Testable independently
+- Don't overlap with other tasks
+
+**Bad**: "Implement authentication" (too big)
+**Good**: "Create password hashing utility" (atomic)
+
+---
+
+### 2. Map Dependencies
+
+For each task, ask:
+- What must exist before this can start?
+- What files/APIs does this need?
+
+```
+01 → no deps (can start immediately)
+02 → depends_on: ["01"]
+03 → depends_on: ["01", "02"]
+```
+
+---
+
+### 3. Identify Parallel Tasks
+
+Mark `parallel: true` when:
+- Task doesn't modify shared files
+- Task doesn't depend on runtime state from other tasks
+- Multiple agents could work simultaneously
+
+Example parallel tasks:
+- Writing independent unit tests
+- Creating isolated utility functions
+- Documentation for separate features
+
+---
+
+### 4. Define Acceptance Criteria
+
+Binary pass/fail conditions only:
+- "JWT tokens signed with RS256" ✓
+- "Tests pass" ✓
+- "Code is clean" ✗ (subjective)
+
+---
+
+### 5. Specify Deliverables
+
+Concrete files/endpoints:
+- `src/auth/hash.ts`
+- `POST /api/login`
+- `tests/auth.test.ts`
+
+---
+
+### 6. Reference Context Files
+
+Don't embed descriptions. Reference paths:
+```json
+"context_files": [
+  "(example: .opencode/context/development/backend/auth/jwt-patterns.md)"
+]
+```
+
+---
+
+## Verification Checklist
+
+- [ ] Each task completable in 1-2 hours?
+- [ ] Dependencies create valid execution order?
+- [ ] Parallel tasks correctly identified?
+- [ ] Acceptance criteria are binary?
+- [ ] Deliverables are concrete files/endpoints?
+
+---
+
+## Common Mistakes
+
+| Mistake | Fix |
+|---------|-----|
+| Task too big | Split into 2-3 smaller tasks |
+| Circular deps | Re-order or merge tasks |
+| Missing deps | Run `task-cli.ts validate` |
+| Vague criteria | Make binary pass/fail |
+
+---
+
+## Related
+
+- `../standards/task-schema.md` - JSON field reference
+- `managing-tasks.md` - Lifecycle workflow
+- `../lookup/task-commands.md` - CLI reference

+ 39 - 0
plugins/claude-code/scripts/context/core/task-management/lookup/navigation.md

@@ -0,0 +1,39 @@
+<!-- Context: core/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Task Management Lookup
+
+**Purpose**: Quick reference for task management commands and patterns
+
+---
+
+## Structure
+
+```
+lookup/
+├── navigation.md (this file)
+└── task-commands.md
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **CLI commands** | `task-commands.md` |
+| **Task schema** | `../standards/task-schema.md` |
+| **Splitting guide** | `../guides/splitting-tasks.md` |
+
+---
+
+## By Type
+
+**Commands** → CLI command reference
+
+---
+
+## Related Context
+
+- **Task Management** → `../navigation.md`
+- **Guides** → `../guides/navigation.md`
+- **Standards** → `../standards/navigation.md`

+ 204 - 0
plugins/claude-code/scripts/context/core/task-management/lookup/task-commands.md

@@ -0,0 +1,204 @@
+<!-- Context: core/task-commands | Priority: high | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Lookup: Task CLI Commands
+
+**Purpose**: Quick reference for task-cli.ts commands
+
+**Last Updated**: 2026-02-14
+
+---
+
+## Usage
+
+```bash
+npx ts-node .opencode/context/tasks/scripts/task-cli.ts <command> [args]
+```
+
+Task files are stored in `.tmp/tasks/` at the project root.
+
+---
+
+## Commands
+
+### status [feature]
+
+Show task status summary for all features or specific feature.
+
+```bash
+task-cli.ts status
+task-cli.ts status my-feature
+```
+
+**Output**:
+```
+[my-feature] My Feature Name
+  Status: active | Progress: 40% (2/5)
+  Pending: 2 | In Progress: 1 | Completed: 2 | Blocked: 0
+```
+
+---
+
+### next [feature]
+
+Show tasks ready to work on (deps satisfied).
+
+```bash
+task-cli.ts next
+task-cli.ts next my-feature
+```
+
+**Output**:
+```
+=== Ready Tasks (deps satisfied) ===
+
+[my-feature]
+  02 - Create JWT service  [sequential]
+  03 - Write unit tests    [parallel]
+```
+
+---
+
+### parallel [feature]
+
+Show only parallelizable tasks ready now.
+
+```bash
+task-cli.ts parallel
+task-cli.ts parallel my-feature
+```
+
+**Use**: Batch multiple isolated tasks for parallel execution.
+
+---
+
+### deps \<feature\> \<seq\>
+
+Show dependency tree for a specific task.
+
+```bash
+task-cli.ts deps my-feature 04
+```
+
+**Output**:
+```
+=== Dependency Tree: my-feature/04 ===
+
+04 - Integration tests [pending]
+  ├── ✓ 01 - Setup database [completed]
+  └── ○ 02 - Create API [pending]
+      └── ✓ 01 - Setup database [completed]
+```
+
+---
+
+### blocked [feature]
+
+Show blocked tasks and reasons.
+
+```bash
+task-cli.ts blocked
+task-cli.ts blocked my-feature
+```
+
+**Output**:
+```
+=== Blocked Tasks ===
+
+[my-feature]
+  04 - Integration tests (waiting: 02, 03)
+  05 - Deploy (explicitly blocked)
+```
+
+---
+
+### complete \<feature\> \<seq\> "summary"
+
+Mark task as completed with summary (max 200 chars).
+
+```bash
+task-cli.ts complete my-feature 02 "Created JWT service with RS256 signing"
+```
+
+**Effect**:
+- Sets `status: "completed"`
+- Sets `completed_at` timestamp
+- Sets `completion_summary`
+- Updates `task.json` counts
+
+---
+
+### validate [feature]
+
+Check JSON validity, dependencies, circular refs.
+
+```bash
+task-cli.ts validate
+task-cli.ts validate my-feature
+```
+
+**Checks**:
+- task.json exists
+- ID format correct
+- Dependencies exist
+- No circular dependencies
+- Counts match
+
+**Output**:
+```
+[my-feature]
+  ✓ All checks passed
+
+[broken-feature]
+  ✗ ERROR: 03: depends on non-existent task 99
+  ⚠ WARNING: 02: No acceptance criteria defined
+```
+
+---
+
+## Exit Codes
+
+| Code | Meaning |
+|------|---------|
+| 0 | Success |
+| 1 | Error (validate found issues, missing args) |
+
+---
+
+## Enhanced Schema Support
+
+The CLI fully supports the enhanced task schema (v2.0) with:
+- **Line-number precision** - Context files with specific line ranges
+- **Domain modeling** - bounded_context, module, vertical_slice fields
+- **Contract tracking** - API/interface dependencies
+- **Design artifacts** - Figma, wireframes, mockups
+- **ADR references** - Architecture decision records
+- **Prioritization** - RICE/WSJF scores
+
+All enhanced fields are optional and backward compatible. See `../standards/enhanced-task-schema.md` for details.
+
+---
+
+## Planning Workflow Integration
+
+For multi-stage orchestration workflows, use these planning agents before task creation:
+
+| Agent | Purpose | Output |
+|-------|---------|--------|
+| **ArchitectureAnalyzer** | DDD bounded context identification | `.tmp/architecture/contexts.json` |
+| **StoryMapper** | User journey and story mapping | `.tmp/story-maps/map.json` |
+| **PrioritizationEngine** | RICE/WSJF scoring | `.tmp/backlog/prioritized.json` |
+| **ContractManager** | API contract definition | `.tmp/contracts/{service}.json` |
+| **ADRManager** | Architecture decision records | `docs/adr/` |
+
+These agents populate enhanced schema fields (bounded_context, contracts, related_adrs, rice_score, etc.) automatically.
+
+See `.opencode/context/core/workflows/multi-stage-orchestration.md` for the complete workflow.
+
+---
+
+## Related
+
+- `../standards/task-schema.md` - Base JSON schema reference
+- `../standards/enhanced-task-schema.md` - Extended schema with advanced features
+- `../guides/managing-tasks.md` - Workflow guide
+- `../workflows/multi-stage-orchestration.md` - Planning workflow

+ 66 - 0
plugins/claude-code/scripts/context/core/task-management/navigation.md

@@ -0,0 +1,66 @@
+<!-- Context: core/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Task Management Navigation
+
+**Purpose**: JSON-driven task breakdown and tracking system
+
+**Last Updated**: 2026-02-14
+
+---
+
+## Structure
+
+```
+core/task-management/
+├── navigation.md
+├── standards/
+│   ├── task-schema.md           # Base JSON schema (v1.0)
+│   └── enhanced-task-schema.md  # Extended schema (v2.0) - line precision, domain modeling, contracts
+├── guides/
+│   ├── splitting-tasks.md       # Task decomposition
+│   └── managing-tasks.md        # Workflow guide
+└── lookup/
+    └── task-commands.md         # CLI script reference
+```
+
+---
+
+## Quick Routes
+
+| Task | Path | Priority |
+|------|------|----------|
+| **Understand base schema** | `standards/task-schema.md` | ⭐⭐⭐⭐⭐ |
+| **Use enhanced features** | `standards/enhanced-task-schema.md` | ⭐⭐⭐⭐ |
+| **Split a feature** | `guides/splitting-tasks.md` | ⭐⭐⭐⭐⭐ |
+| **Manage task lifecycle** | `guides/managing-tasks.md` | ⭐⭐⭐⭐ |
+| **Use CLI commands** | `lookup/task-commands.md` | ⭐⭐⭐⭐ |
+
+---
+
+## Loading Strategy
+
+### For Creating Basic Tasks:
+1. Load `standards/task-schema.md` (understand base structure)
+2. Load `guides/splitting-tasks.md` (decomposition approach)
+3. Reference `lookup/task-commands.md` (validate after creation)
+
+### For Multi-Stage Orchestration:
+1. Load `standards/enhanced-task-schema.md` (advanced features)
+2. Load `standards/task-schema.md` (base structure reference)
+3. Load `guides/splitting-tasks.md` (decomposition approach)
+4. Reference planning agents: ArchitectureAnalyzer, StoryMapper, PrioritizationEngine, ContractManager, ADRManager
+
+### For Managing Tasks:
+1. Load `guides/managing-tasks.md` (workflow)
+2. Reference `lookup/task-commands.md` (CLI usage)
+
+---
+
+## Related
+
+- **Active tasks** → `.tmp/tasks/{feature}/` (at project root)
+- **Completed tasks** → `.tmp/tasks/completed/{feature}/`
+- **TaskManager agent** → `.opencode/agent/subagents/core/task-manager.md`
+- **Planning agents** → `.opencode/agent/subagents/planning/` (ArchitectureAnalyzer, StoryMapper, PrioritizationEngine, ContractManager, ADRManager)
+- **Multi-stage workflow** → `../workflows/multi-stage-orchestration.md`
+- **Core navigation** → `../navigation.md`

+ 781 - 0
plugins/claude-code/scripts/context/core/task-management/standards/enhanced-task-schema.md

@@ -0,0 +1,781 @@
+<!-- Context: core/enhanced-task-schema | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Enhanced Task JSON Schema
+
+**Purpose**: Extended JSON schema for multi-stage orchestration with line-number precision, domain modeling, and prioritization
+
+**Version**: 2.0
+
+**Last Updated**: 2026-02-14
+
+**Backward Compatible**: Yes (all new fields are optional)
+
+---
+
+## Overview
+
+This schema extends the base task.json and subtask_NN.json schemas with:
+- **Line-number precision** for context and reference files
+- **Domain modeling** fields (bounded_context, module, vertical_slice)
+- **Contract tracking** for API/interface dependencies
+- **Design artifacts** linking
+- **ADR references** for architectural decisions
+- **Prioritization scores** (RICE, WSJF)
+- **Release planning** (release_slice)
+
+All enhancements are **optional** and backward compatible with existing task files.
+
+---
+
+## Enhanced task.json Schema
+
+### New Fields
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| `bounded_context` | string | No | DDD bounded context (e.g., "authentication", "billing") |
+| `module` | string | No | Module/package name (e.g., "@app/auth", "payment-service") |
+| `vertical_slice` | string | No | Feature slice identifier (e.g., "user-registration", "checkout-flow") |
+| `contracts` | array | No | API/interface contracts this feature depends on or provides |
+| `design_components` | array | No | Design artifacts (Figma URLs, wireframes, mockups) |
+| `related_adrs` | array | No | Architecture Decision Records (ADR file paths or IDs) |
+| `rice_score` | object | No | RICE prioritization (Reach, Impact, Confidence, Effort) |
+| `wsjf_score` | object | No | WSJF prioritization (Business Value, Time Criticality, Risk Reduction, Job Size) |
+| `release_slice` | string | No | Release identifier (e.g., "v1.2.0", "Q1-2026", "MVP") |
+
+### Enhanced context_files and reference_files Format
+
+**Old format** (still supported):
+```json
+"context_files": [
+  ".opencode/context/core/standards/code-quality.md"
+]
+```
+
+**New format** (line-number precision):
+```json
+"context_files": [
+  {
+    "path": ".opencode/context/core/standards/code-quality.md",
+    "lines": "1-50",
+    "reason": "Pure function patterns for service layer"
+  },
+  {
+    "path": ".opencode/context/core/standards/security-patterns.md",
+    "lines": "120-145",
+    "reason": "JWT token validation rules"
+  }
+]
+```
+
+**Backward Compatibility**: Both formats are valid. Agents should handle both:
+- String format → read entire file
+- Object format → read specified lines only
+
+---
+
+## Enhanced subtask_NN.json Schema
+
+### New Fields
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| `bounded_context` | string | No | Inherited from task.json or subtask-specific override |
+| `module` | string | No | Module this subtask modifies |
+| `vertical_slice` | string | No | Feature slice this subtask belongs to |
+| `contracts` | array | No | Contracts this subtask implements or depends on |
+| `design_components` | array | No | Design artifacts relevant to this subtask |
+| `related_adrs` | array | No | ADRs relevant to this subtask |
+
+---
+
+## TypeScript Interfaces
+
+```typescript
+// Line-number precision for context files
+interface ContextFileReference {
+  path: string;           // File path (absolute or relative to project root)
+  lines?: string;         // Line range: "10-50", "1-20,45-60", or omit for entire file
+  reason?: string;        // Why this file/section is relevant (max 200 chars)
+}
+
+// Contract definition
+interface Contract {
+  type: 'api' | 'interface' | 'event' | 'schema';
+  name: string;           // Contract identifier (e.g., "UserAPI", "AuthEvent")
+  path?: string;          // File path where contract is defined
+  status: 'draft' | 'defined' | 'implemented' | 'verified';
+  description?: string;   // Brief description (max 200 chars)
+}
+
+// Design component reference
+interface DesignComponent {
+  type: 'figma' | 'wireframe' | 'mockup' | 'prototype' | 'sketch';
+  url?: string;           // External URL (Figma, etc.)
+  path?: string;          // Local file path
+  description?: string;   // What this design covers (max 200 chars)
+}
+
+// ADR reference
+interface ADRReference {
+  id: string;             // ADR identifier (e.g., "ADR-001", "auth-strategy")
+  path?: string;          // File path to ADR document
+  title?: string;         // ADR title
+  decision?: string;      // Brief summary of decision (max 200 chars)
+}
+
+// RICE prioritization
+interface RICEScore {
+  reach: number;          // How many users affected (per time period)
+  impact: number;         // Impact score (0.25 = minimal, 0.5 = low, 1 = medium, 2 = high, 3 = massive)
+  confidence: number;     // Confidence % (0-100)
+  effort: number;         // Person-months of work
+  score?: number;         // Calculated: (reach * impact * confidence) / effort
+}
+
+// WSJF prioritization
+interface WSJFScore {
+  business_value: number;     // 1-10 scale
+  time_criticality: number;   // 1-10 scale
+  risk_reduction: number;     // 1-10 scale
+  job_size: number;           // 1-10 scale (effort estimate)
+  score?: number;             // Calculated: (business_value + time_criticality + risk_reduction) / job_size
+}
+
+// Enhanced task.json
+interface EnhancedTask {
+  // Base fields (from task-schema.md)
+  id: string;
+  name: string;
+  status: 'active' | 'completed' | 'blocked' | 'archived';
+  objective: string;
+  context_files?: (string | ContextFileReference)[];
+  reference_files?: (string | ContextFileReference)[];
+  exit_criteria?: string[];
+  subtask_count?: number;
+  completed_count?: number;
+  created_at: string;
+  completed_at?: string;
+
+  // Enhanced fields
+  bounded_context?: string;
+  module?: string;
+  vertical_slice?: string;
+  contracts?: Contract[];
+  design_components?: DesignComponent[];
+  related_adrs?: ADRReference[];
+  rice_score?: RICEScore;
+  wsjf_score?: WSJFScore;
+  release_slice?: string;
+}
+
+// Enhanced subtask_NN.json
+interface EnhancedSubtask {
+  // Base fields (from task-schema.md)
+  id: string;
+  seq: string;
+  title: string;
+  status: 'pending' | 'in_progress' | 'completed' | 'blocked';
+  depends_on?: string[];
+  parallel?: boolean;
+  context_files?: (string | ContextFileReference)[];
+  reference_files?: (string | ContextFileReference)[];
+  suggested_agent?: string;
+  acceptance_criteria?: string[];
+  deliverables?: string[];
+  agent_id?: string;
+  started_at?: string;
+  completed_at?: string;
+  completion_summary?: string;
+
+  // Enhanced fields
+  bounded_context?: string;
+  module?: string;
+  vertical_slice?: string;
+  contracts?: Contract[];
+  design_components?: DesignComponent[];
+  related_adrs?: ADRReference[];
+}
+```
+
+---
+
+## Field Examples
+
+### bounded_context
+
+**Purpose**: DDD bounded context for domain modeling
+
+```json
+{
+  "bounded_context": "authentication"
+}
+```
+
+Common values:
+- `"authentication"` - User identity and access
+- `"billing"` - Payment and invoicing
+- `"inventory"` - Product and stock management
+- `"notification"` - Messaging and alerts
+- `"analytics"` - Reporting and insights
+
+---
+
+### module
+
+**Purpose**: Module or package name for code organization
+
+```json
+{
+  "module": "@app/auth"
+}
+```
+
+Examples:
+- `"@app/auth"` - Authentication module
+- `"payment-service"` - Payment microservice
+- `"ui-components"` - Shared UI library
+- `"core/utils"` - Core utilities
+
+---
+
+### vertical_slice
+
+**Purpose**: Feature slice identifier for vertical slice architecture
+
+```json
+{
+  "vertical_slice": "user-registration"
+}
+```
+
+Examples:
+- `"user-registration"` - Complete user signup flow
+- `"checkout-flow"` - End-to-end checkout
+- `"dashboard-overview"` - Dashboard feature
+- `"report-generation"` - Report creation flow
+
+---
+
+### contracts
+
+**Purpose**: Track API/interface dependencies and implementations
+
+```json
+{
+  "contracts": [
+    {
+      "type": "api",
+      "name": "UserAPI",
+      "path": "src/api/user.contract.ts",
+      "status": "defined",
+      "description": "REST API for user CRUD operations"
+    },
+    {
+      "type": "event",
+      "name": "UserCreatedEvent",
+      "status": "draft",
+      "description": "Event emitted when new user is created"
+    }
+  ]
+}
+```
+
+Contract types:
+- `"api"` - REST/GraphQL API endpoints
+- `"interface"` - TypeScript/language interfaces
+- `"event"` - Event bus messages
+- `"schema"` - Database schemas, validation schemas
+
+Contract statuses:
+- `"draft"` - Being designed
+- `"defined"` - Specification complete
+- `"implemented"` - Code written
+- `"verified"` - Tests passing
+
+---
+
+### design_components
+
+**Purpose**: Link design artifacts to implementation tasks
+
+```json
+{
+  "design_components": [
+    {
+      "type": "figma",
+      "url": "https://figma.com/file/abc123/Login-Flow",
+      "description": "Login page mockups with responsive breakpoints"
+    },
+    {
+      "type": "wireframe",
+      "path": "docs/design/checkout-wireframe.png",
+      "description": "Checkout flow wireframe"
+    }
+  ]
+}
+```
+
+Component types:
+- `"figma"` - Figma designs
+- `"wireframe"` - Low-fidelity wireframes
+- `"mockup"` - High-fidelity mockups
+- `"prototype"` - Interactive prototypes
+- `"sketch"` - Sketch files
+
+---
+
+### related_adrs
+
+**Purpose**: Reference architectural decisions that govern implementation
+
+```json
+{
+  "related_adrs": [
+    {
+      "id": "ADR-003",
+      "path": "docs/adr/003-jwt-authentication.md",
+      "title": "Use JWT for stateless authentication",
+      "decision": "Implement JWT with RS256 signing and 15-minute expiry"
+    },
+    {
+      "id": "ADR-007",
+      "path": "docs/adr/007-database-choice.md",
+      "title": "PostgreSQL for primary database"
+    }
+  ]
+}
+```
+
+---
+
+### rice_score
+
+**Purpose**: RICE prioritization framework (Reach × Impact × Confidence / Effort)
+
+```json
+{
+  "rice_score": {
+    "reach": 5000,
+    "impact": 2,
+    "confidence": 80,
+    "effort": 3,
+    "score": 2666.67
+  }
+}
+```
+
+**Calculation**: `(5000 × 2 × 0.80) / 3 = 2666.67`
+
+Field definitions:
+- `reach`: Number of users/customers affected per time period (e.g., per quarter)
+- `impact`: 0.25 (minimal), 0.5 (low), 1 (medium), 2 (high), 3 (massive)
+- `confidence`: Percentage (0-100) - how confident are you in reach/impact estimates?
+- `effort`: Person-months of work
+- `score`: Auto-calculated or manually entered
+
+---
+
+### wsjf_score
+
+**Purpose**: WSJF prioritization (Weighted Shortest Job First) for SAFe/Agile
+
+```json
+{
+  "wsjf_score": {
+    "business_value": 8,
+    "time_criticality": 6,
+    "risk_reduction": 5,
+    "job_size": 3,
+    "score": 6.33
+  }
+}
+```
+
+**Calculation**: `(8 + 6 + 5) / 3 = 6.33`
+
+Field definitions (all on 1-10 scale):
+- `business_value`: Direct business impact
+- `time_criticality`: How time-sensitive is this?
+- `risk_reduction`: Does this reduce risk/enable other work?
+- `job_size`: Effort estimate (1 = tiny, 10 = huge)
+- `score`: Auto-calculated or manually entered
+
+---
+
+### release_slice
+
+**Purpose**: Group tasks into releases for planning
+
+```json
+{
+  "release_slice": "v1.2.0"
+}
+```
+
+Examples:
+- `"v1.2.0"` - Semantic version
+- `"Q1-2026"` - Quarterly release
+- `"MVP"` - Minimum viable product
+- `"Phase-2"` - Project phase
+- `"Sprint-15"` - Sprint identifier
+
+---
+
+## Line-Number Precision Format
+
+### Purpose
+
+Reduce cognitive load by pointing agents to **exact sections** of large files instead of forcing them to read entire documents.
+
+### Format
+
+```json
+{
+  "path": "path/to/file.md",
+  "lines": "10-50",
+  "reason": "Why these lines matter"
+}
+```
+
+### Line Range Syntax
+
+- `"10-50"` - Lines 10 through 50 (inclusive)
+- `"1-20,45-60"` - Lines 1-20 AND 45-60 (multiple ranges)
+- Omit `lines` field to read entire file
+
+### Examples
+
+**Single range**:
+```json
+{
+  "path": ".opencode/context/core/standards/code-quality.md",
+  "lines": "53-95",
+  "reason": "Pure function and immutability patterns"
+}
+```
+
+**Multiple ranges**:
+```json
+{
+  "path": ".opencode/context/core/standards/security-patterns.md",
+  "lines": "1-25,120-145,200-220",
+  "reason": "JWT validation rules and token refresh patterns"
+}
+```
+
+**Entire file** (backward compatible):
+```json
+{
+  "path": ".opencode/context/core/standards/code-quality.md",
+  "reason": "All coding standards"
+}
+```
+
+**Legacy string format** (still supported):
+```json
+".opencode/context/core/standards/code-quality.md"
+```
+
+---
+
+## Backward Compatibility Rules
+
+### Rule 1: All new fields are optional
+
+Existing task.json and subtask_NN.json files remain valid without any changes.
+
+### Rule 2: Mixed formats allowed
+
+You can mix old and new formats in the same file:
+
+```json
+{
+  "context_files": [
+    ".opencode/context/core/standards/code-quality.md",
+    {
+      "path": ".opencode/context/core/standards/security-patterns.md",
+      "lines": "120-145",
+      "reason": "JWT validation"
+    }
+  ]
+}
+```
+
+### Rule 3: Agent handling
+
+Agents MUST support both formats:
+
+```typescript
+function loadContextFile(ref: string | ContextFileReference): string {
+  if (typeof ref === 'string') {
+    // Legacy format: read entire file
+    return readFile(ref);
+  } else {
+    // New format: read specified lines
+    const content = readFile(ref.path);
+    if (ref.lines) {
+      return extractLines(content, ref.lines);
+    }
+    return content;
+  }
+}
+```
+
+### Rule 4: Gradual migration
+
+Projects can adopt enhanced fields incrementally:
+1. Start with line-number precision for large files
+2. Add domain modeling fields (bounded_context, module) when needed
+3. Add prioritization scores when planning releases
+4. Add contracts/ADRs when formalizing architecture
+
+---
+
+## Complete Example
+
+### Enhanced task.json
+
+```json
+{
+  "id": "user-authentication",
+  "name": "User Authentication System",
+  "status": "active",
+  "objective": "Implement JWT-based authentication with refresh tokens and role-based access control",
+  "context_files": [
+    {
+      "path": ".opencode/context/core/standards/code-quality.md",
+      "lines": "53-95",
+      "reason": "Pure function patterns for auth service"
+    },
+    {
+      "path": ".opencode/context/core/standards/security-patterns.md",
+      "lines": "120-145,200-220",
+      "reason": "JWT validation and token refresh patterns"
+    }
+  ],
+  "reference_files": [
+    {
+      "path": "src/middleware/auth.middleware.ts",
+      "lines": "1-50",
+      "reason": "Existing auth middleware to extend"
+    },
+    "package.json"
+  ],
+  "exit_criteria": [
+    "All tests passing with >90% coverage",
+    "JWT tokens signed with RS256",
+    "Refresh token rotation implemented",
+    "Role-based access control working"
+  ],
+  "subtask_count": 5,
+  "completed_count": 0,
+  "created_at": "2026-02-14T10:00:00Z",
+  "bounded_context": "authentication",
+  "module": "@app/auth",
+  "vertical_slice": "user-login",
+  "contracts": [
+    {
+      "type": "api",
+      "name": "AuthAPI",
+      "path": "src/api/auth.contract.ts",
+      "status": "defined",
+      "description": "REST endpoints for login, logout, refresh, verify"
+    },
+    {
+      "type": "event",
+      "name": "UserAuthenticatedEvent",
+      "status": "draft",
+      "description": "Event emitted on successful authentication"
+    }
+  ],
+  "design_components": [
+    {
+      "type": "figma",
+      "url": "https://figma.com/file/xyz789/Auth-Flows",
+      "description": "Login and registration UI mockups"
+    }
+  ],
+  "related_adrs": [
+    {
+      "id": "ADR-003",
+      "path": "docs/adr/003-jwt-authentication.md",
+      "title": "Use JWT for stateless authentication",
+      "decision": "JWT with RS256, 15-min access tokens, 7-day refresh tokens"
+    }
+  ],
+  "rice_score": {
+    "reach": 10000,
+    "impact": 3,
+    "confidence": 90,
+    "effort": 4,
+    "score": 6750
+  },
+  "wsjf_score": {
+    "business_value": 9,
+    "time_criticality": 8,
+    "risk_reduction": 7,
+    "job_size": 4,
+    "score": 6
+  },
+  "release_slice": "v1.0.0"
+}
+```
+
+### Enhanced subtask_NN.json
+
+```json
+{
+  "id": "user-authentication-02",
+  "seq": "02",
+  "title": "Implement JWT service with token generation and validation",
+  "status": "pending",
+  "depends_on": ["01"],
+  "parallel": false,
+  "context_files": [
+    {
+      "path": ".opencode/context/core/standards/code-quality.md",
+      "lines": "53-72",
+      "reason": "Pure function patterns"
+    },
+    {
+      "path": ".opencode/context/core/standards/security-patterns.md",
+      "lines": "120-145",
+      "reason": "JWT signing and validation rules"
+    }
+  ],
+  "reference_files": [
+    {
+      "path": "src/config/jwt.config.ts",
+      "reason": "JWT configuration constants"
+    }
+  ],
+  "suggested_agent": "CoderAgent",
+  "acceptance_criteria": [
+    "JWT tokens signed with RS256 algorithm",
+    "Access tokens expire in 15 minutes",
+    "Refresh tokens expire in 7 days",
+    "Token validation includes signature and expiry checks",
+    "Unit tests cover all token operations",
+    "No secrets hardcoded in code"
+  ],
+  "deliverables": [
+    "src/auth/jwt.service.ts",
+    "src/auth/jwt.service.test.ts"
+  ],
+  "bounded_context": "authentication",
+  "module": "@app/auth",
+  "contracts": [
+    {
+      "type": "interface",
+      "name": "JWTService",
+      "path": "src/auth/jwt.service.ts",
+      "status": "implemented",
+      "description": "Interface for JWT operations (sign, verify, refresh)"
+    }
+  ],
+  "related_adrs": [
+    {
+      "id": "ADR-003",
+      "path": "docs/adr/003-jwt-authentication.md"
+    }
+  ]
+}
+```
+
+---
+
+## Migration Guide
+
+### For TaskManager Agents
+
+When creating new tasks:
+
+1. **Use line-number precision for large files** (>100 lines):
+   ```json
+   {
+     "path": ".opencode/context/core/standards/code-quality.md",
+     "lines": "53-95",
+     "reason": "Pure function patterns"
+   }
+   ```
+
+2. **Add domain modeling fields** when known:
+   ```json
+   {
+     "bounded_context": "authentication",
+     "module": "@app/auth",
+     "vertical_slice": "user-login"
+   }
+   ```
+
+3. **Link design artifacts** for UI tasks:
+   ```json
+   {
+     "design_components": [
+       {
+         "type": "figma",
+         "url": "https://figma.com/...",
+         "description": "Login page mockups"
+       }
+     ]
+   }
+   ```
+
+4. **Reference ADRs** for architectural decisions:
+   ```json
+   {
+     "related_adrs": [
+       {
+         "id": "ADR-003",
+         "path": "docs/adr/003-jwt-authentication.md"
+       }
+     ]
+   }
+   ```
+
+### For Working Agents (CoderAgent, etc.)
+
+When reading tasks:
+
+1. **Handle both context file formats**:
+   ```typescript
+   const contextFiles = task.context_files || [];
+   for (const ref of contextFiles) {
+     if (typeof ref === 'string') {
+       // Read entire file
+       const content = await readFile(ref);
+     } else {
+       // Read specified lines
+       const content = await readFileLines(ref.path, ref.lines);
+       console.log(`Reading ${ref.path} (${ref.lines}): ${ref.reason}`);
+     }
+   }
+   ```
+
+2. **Use contract information** to understand dependencies:
+   ```typescript
+   const contracts = task.contracts || [];
+   const apiContracts = contracts.filter(c => c.type === 'api');
+   // Load API contract definitions before implementing
+   ```
+
+3. **Check ADRs** before making architectural decisions:
+   ```typescript
+   const adrs = task.related_adrs || [];
+   for (const adr of adrs) {
+     if (adr.path) {
+       const decision = await readFile(adr.path);
+       // Apply architectural constraints from ADR
+     }
+   }
+   ```
+
+---
+
+## Related
+
+- `task-schema.md` - Base schema (backward compatible foundation)
+- `../guides/splitting-tasks.md` - How to decompose features
+- `../guides/managing-tasks.md` - Lifecycle workflow
+- `../lookup/task-commands.md` - CLI reference

+ 42 - 0
plugins/claude-code/scripts/context/core/task-management/standards/navigation.md

@@ -0,0 +1,42 @@
+<!-- Context: core/navigation | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Task Management Standards
+
+**Purpose**: JSON schemas and standards for task definitions
+
+---
+
+## Structure
+
+```
+standards/
+├── navigation.md (this file)
+├── task-schema.md
+└── enhanced-task-schema.md
+```
+
+---
+
+## Quick Routes
+
+| Task | Path |
+|------|------|
+| **Base schema (v1.0)** | `task-schema.md` |
+| **Enhanced schema (v2.0)** | `enhanced-task-schema.md` |
+| **Splitting guide** | `../guides/splitting-tasks.md` |
+| **CLI commands** | `../lookup/task-commands.md` |
+
+---
+
+## By Type
+
+**Base Schema** → Core task structure (v1.0)  
+**Enhanced Schema** → Advanced features (v2.0) - line precision, domain modeling, contracts
+
+---
+
+## Related Context
+
+- **Task Management** → `../navigation.md`
+- **Guides** → `../guides/navigation.md`
+- **Lookup** → `../lookup/navigation.md`

+ 201 - 0
plugins/claude-code/scripts/context/core/task-management/standards/task-schema.md

@@ -0,0 +1,201 @@
+<!-- Context: core/task-schema | Priority: critical | Version: 1.0 | Updated: 2026-02-15 -->
+
+# Standard: Task JSON Schema
+
+**Purpose**: JSON schema reference for task management files
+
+**Last Updated**: 2026-02-14
+
+---
+
+## Core Concepts
+
+Task management uses two JSON file types:
+- `task.json` - Feature-level metadata and tracking
+- `subtask_NN.json` - Individual atomic tasks with dependencies
+
+Location: `.tmp/tasks/{feature-slug}/` (at project root)
+
+---
+
+## Schema Versions
+
+This document describes the **base schema** (v1.0) that all task files must follow.
+
+For **enhanced features** (line-number precision, domain modeling, contracts, ADRs, prioritization):
+- See `enhanced-task-schema.md` for extended fields and capabilities
+- All enhanced fields are **optional** and backward compatible
+- Use enhanced schema for multi-stage orchestration workflows
+
+---
+
+## task.json Schema
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| `id` | string | Yes | kebab-case identifier |
+| `name` | string | Yes | Human-readable name (max 100) |
+| `status` | enum | Yes | active / completed / blocked / archived |
+| `objective` | string | Yes | One-line objective (max 200) |
+| `context_files` | array | No | **Standards paths only** — coding conventions, patterns, security rules to follow |
+| `reference_files` | array | No | **Source material only** — project files to look at (existing code, config, schemas) |
+| `exit_criteria` | array | No | Completion conditions |
+| `subtask_count` | int | No | Total subtasks |
+| `completed_count` | int | No | Done subtasks |
+| `created_at` | datetime | Yes | ISO 8601 |
+| `completed_at` | datetime | No | ISO 8601 |
+
+---
+
+## subtask_NN.json Schema
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| `id` | string | Yes | {feature}-{seq} |
+| `seq` | string | Yes | 2-digit (01, 02) |
+| `title` | string | Yes | Task title (max 100) |
+| `status` | enum | Yes | pending / in_progress / completed / blocked |
+| `depends_on` | array | No | Sequence numbers of dependencies |
+| `parallel` | bool | No | True if can run alongside others |
+| `context_files` | array | No | **Standards paths only** — conventions and patterns to follow |
+| `reference_files` | array | No | **Source material only** — existing files to reference |
+| `suggested_agent` | string | No | Recommended agent for this task (e.g., OpenFrontendSpecialist) |
+| `acceptance_criteria` | array | No | Binary pass/fail conditions |
+| `deliverables` | array | No | Files to create/modify |
+| `agent_id` | string | No | Set when in_progress |
+| `started_at` | datetime | No | ISO 8601 |
+| `completed_at` | datetime | No | ISO 8601 |
+| `completion_summary` | string | No | What was done (max 200) |
+
+---
+
+## Status Transitions
+
+```
+pending → in_progress   (by working agent, when deps satisfied)
+in_progress → completed (by TaskManager, after verification)
+* → blocked             (by either, when issue found)
+blocked → pending       (when unblocked)
+```
+
+---
+
+## Parallel Flag
+
+- `parallel: true` = Isolated task, can run alongside others
+- `parallel: false` = May affect shared state, run sequentially
+
+Use `task-cli.ts parallel` to find all parallelizable tasks ready to run.
+
+---
+
+## context_files vs reference_files — The Rule
+
+These two fields serve fundamentally different purposes. **Never mix them.**
+
+| Field | Answers | Contains | Agent behavior |
+|-------|---------|----------|----------------|
+| `context_files` | "What rules do I follow?" | Standards, conventions, patterns from `.opencode/context/` | Load and apply as coding guidelines |
+| `reference_files` | "What existing code do I look at?" | Project source files, configs, schemas | Read to understand existing patterns |
+
+**Wrong** ❌ — mixing standards and source files:
+```json
+"context_files": [
+  ".opencode/context/core/standards/code-quality.md",
+  "package.json",
+  "src/existing-auth.ts"
+]
+```
+
+**Right** ✅ — clean separation:
+```json
+"context_files": [
+  ".opencode/context/core/standards/code-quality.md",
+  ".opencode/context/core/standards/security-patterns.md"
+],
+"reference_files": [
+  "package.json",
+  "src/existing-auth.ts"
+]
+```
+
+---
+
+## Example
+
+```json
+{
+  "id": "auth-system-02",
+  "seq": "02",
+  "title": "Create JWT service",
+  "status": "pending",
+  "depends_on": ["01"],
+  "parallel": false,
+  "context_files": [
+    ".opencode/context/core/standards/code-quality.md",
+    ".opencode/context/core/standards/security-patterns.md"
+  ],
+  "reference_files": [
+    "src/auth/token-utils.ts"
+  ],
+  "acceptance_criteria": ["JWT tokens signed with RS256", "Tests pass"],
+  "deliverables": ["src/auth/jwt.service.ts"]
+}
+```
+
+---
+
+## Migration to Enhanced Schema
+
+The enhanced schema adds powerful features while maintaining full backward compatibility:
+
+### When to Use Enhanced Schema
+
+Use `enhanced-task-schema.md` when you need:
+- **Line-number precision** - Point to specific sections of large files (reduces cognitive load)
+- **Domain modeling** - Track bounded contexts, modules, vertical slices
+- **Contract tracking** - Manage API/interface dependencies
+- **Design artifacts** - Link Figma, wireframes, mockups
+- **ADR references** - Connect architectural decisions to tasks
+- **Prioritization** - RICE/WSJF scoring for release planning
+
+### Migration Path
+
+1. **No changes required** - Existing task files work as-is
+2. **Gradual adoption** - Add enhanced fields incrementally:
+   - Start with line-number precision for large context files
+   - Add domain fields (bounded_context, module) when modeling architecture
+   - Add contracts when defining APIs
+   - Add prioritization scores when planning releases
+3. **Mixed formats** - You can mix old and new formats in the same file
+
+### Example: Adding Line-Number Precision
+
+**Old format** (still valid):
+```json
+"context_files": [
+  ".opencode/context/core/standards/code-quality.md"
+]
+```
+
+**New format** (enhanced):
+```json
+"context_files": [
+  {
+    "path": ".opencode/context/core/standards/code-quality.md",
+    "lines": "53-95",
+    "reason": "Pure function patterns for service layer"
+  }
+]
+```
+
+Both formats work. Agents handle both automatically.
+
+---
+
+## Related
+
+- `enhanced-task-schema.md` - Extended schema with advanced features
+- `../guides/splitting-tasks.md` - How to decompose features
+- `../guides/managing-tasks.md` - Lifecycle workflow
+- `../lookup/task-commands.md` - CLI reference

+ 478 - 0
plugins/claude-code/scripts/context/core/visual-development.md

@@ -0,0 +1,478 @@
+<!-- Context: visual-development | Priority: high | Version: 1.0 | Updated: 2025-01-27 -->
+# Visual Development Context
+
+**Purpose**: Visual content creation, UI design, image generation, and diagram creation
+
+---
+
+## Quick Routes
+
+| Task Type | Context File | Subagent | Tools |
+|-----------|-------------|----------|-------|
+| **Generate image/diagram** | This file | Image Specialist | tool:gemini |
+| **Edit existing image** | This file | Image Specialist | tool:gemini |
+| **UI mockup (static)** | This file | Image Specialist | tool:gemini |
+| **Interactive UI design** | `workflows/design-iteration-overview.md` | - | - |
+| **Design system** | `ui/web/design-systems.md` | - | - |
+| **UI standards** | `ui/web/ui-styling-standards.md` | - | - |
+| **Animation patterns** | `ui/web/animation-patterns.md` | - | - |
+
+---
+
+## Image Specialist Capabilities
+
+### What It Does
+
+The **Image Specialist** subagent uses Gemini Nano Banana AI to:
+
+- ✅ **Generate images from text descriptions** - Create original images, illustrations, graphics
+- ✅ **Edit existing images** - Modify, enhance, or transform images
+- ✅ **Analyze images** - Describe image content, extract information
+- ✅ **Create diagrams** - Architecture diagrams, flowcharts, system visualizations
+- ✅ **Design mockups** - UI mockups, wireframes, design concepts
+- ✅ **Generate graphics** - Social media graphics, promotional images, icons
+
+### When to Delegate
+
+Delegate to Image Specialist when users request:
+
+**Keywords to Watch For**:
+- "create image", "generate image", "make image"
+- "diagram", "flowchart", "visualization"
+- "mockup", "wireframe", "design concept"
+- "graphic", "illustration", "icon"
+- "edit image", "modify image", "enhance image"
+- "screenshot", "visual", "picture"
+
+**Common Use Cases**:
+1. **Architecture Diagrams** - Microservices, system design, infrastructure
+2. **UI Mockups** - Dashboard designs, app interfaces, web layouts
+3. **Social Media Graphics** - Announcements, promotions, branded content
+4. **Documentation Images** - Tutorial screenshots, feature highlights, guides
+5. **Presentations** - Slide graphics, charts, visual aids
+6. **Marketing Assets** - Product images, hero graphics, banners
+
+### How to Invoke
+
+```javascript
+task(
+  subagent_type="Image Specialist",
+  description="[Brief 3-5 word description]",
+  prompt="Context to load:
+          - .opencode/context/core/visual-development.md
+          
+          Task: [Detailed visual requirement]
+          
+          Requirements:
+          - Style: [Visual aesthetic - modern, minimalist, professional, etc.]
+          - Dimensions: [Width x Height or aspect ratio]
+          - Key Elements: [What must be included]
+          - Colors: [Color scheme, brand colors, palette]
+          - Format: [PNG, JPG, SVG preference]
+          
+          Output: [Expected deliverable and location]"
+)
+```
+
+---
+
+## Use Case Examples
+
+### 1. Architecture Diagram
+
+**User Request**: "Create a diagram showing our microservices architecture"
+
+**Invocation**:
+```javascript
+task(
+  subagent_type="Image Specialist",
+  description="Generate microservices architecture diagram",
+  prompt="Create a technical architecture diagram showing:
+          
+          **Services**:
+          - API Gateway (entry point)
+          - Auth Service (authentication)
+          - User Service (user management)
+          - Order Service (order processing)
+          - Payment Service (payment processing)
+          - Notification Service (emails/SMS)
+          
+          **Infrastructure**:
+          - PostgreSQL databases (one per service)
+          - Redis cache (shared)
+          - RabbitMQ message queue
+          - AWS S3 (file storage)
+          
+          **External Services**:
+          - Stripe (payments)
+          - SendGrid (emails)
+          - Twilio (SMS)
+          
+          **Style**: Clean, professional, modern tech diagram
+          **Colors**: Blue for services, green for databases, orange for external
+          **Format**: PNG, 1920x1080
+          **Layout**: Left-to-right flow, clear connections
+          
+          Output: Save to docs/architecture-diagram.png"
+)
+```
+
+---
+
+### 2. UI Mockup
+
+**User Request**: "Show me what the dashboard could look like"
+
+**Invocation**:
+```javascript
+task(
+  subagent_type="Image Specialist",
+  description="Generate analytics dashboard mockup",
+  prompt="Create a UI mockup for an analytics dashboard:
+          
+          **Layout**:
+          - Top: Header with logo, navigation, user menu
+          - Below header: 4 metric cards in a row
+            * Total Users (with trend arrow)
+            * Revenue (with percentage change)
+            * Conversion Rate (with sparkline)
+            * Active Sessions (with live indicator)
+          - Middle: Large line chart showing 30-day trends
+          - Bottom: Data table with recent transactions
+          
+          **Style**: Modern, professional SaaS aesthetic
+          **Theme**: Dark mode with subtle gradients
+          **Colors**: 
+            - Background: Dark gray (#1e293b)
+            - Cards: Slightly lighter (#334155)
+            - Accent: Blue (#3b82f6)
+            - Text: White/gray
+          **Typography**: Clean sans-serif (Inter-style)
+          **Format**: PNG, 1440x900
+          
+          Output: Save to design_iterations/dashboard_mockup.png"
+)
+```
+
+---
+
+### 3. Social Media Graphic
+
+**User Request**: "Create a graphic announcing our new feature"
+
+**Invocation**:
+```javascript
+task(
+  subagent_type="Image Specialist",
+  description="Generate feature announcement graphic",
+  prompt="Create a social media graphic for feature launch:
+          
+          **Content**:
+          - Main headline: 'Introducing Real-Time Collaboration'
+          - Subheadline: 'Work together, ship faster'
+          - Small text: 'Available now for all teams'
+          
+          **Visual Elements**:
+          - Abstract illustration of people collaborating
+          - Subtle geometric shapes in background
+          - Modern, energetic feel
+          
+          **Brand Colors**:
+          - Primary: #6366f1 (indigo)
+          - Secondary: #8b5cf6 (purple)
+          - Background: White with gradient
+          - Text: Dark gray (#1e293b)
+          
+          **Format**: PNG, 1200x630 (optimized for Twitter/LinkedIn)
+          **Style**: Modern, professional, eye-catching
+          
+          Output: Save to marketing/feature-launch-social.png"
+)
+```
+
+---
+
+### 4. Flowchart/Process Diagram
+
+**User Request**: "Diagram the user onboarding flow"
+
+**Invocation**:
+```javascript
+task(
+  subagent_type="Image Specialist",
+  description="Generate user onboarding flowchart",
+  prompt="Create a flowchart showing user onboarding process:
+          
+          **Steps**:
+          1. User signs up (email/password)
+          2. Email verification sent
+          3. User clicks verification link
+          4. Profile setup (name, company, role)
+          5. Choose plan (Free/Pro/Enterprise)
+          6. Payment (if Pro/Enterprise)
+          7. Onboarding tutorial (5 steps)
+          8. Dashboard access
+          
+          **Decision Points**:
+          - Email verified? (Yes → Continue, No → Resend)
+          - Plan selected? (Free → Skip payment, Paid → Payment)
+          - Payment successful? (Yes → Continue, No → Retry)
+          
+          **Style**: Clean flowchart with standard symbols
+          **Colors**: 
+            - Start/End: Green
+            - Process: Blue
+            - Decision: Yellow
+            - Error: Red
+          **Format**: PNG, 1600x1200
+          **Layout**: Top-to-bottom flow
+          
+          Output: Save to docs/onboarding-flow.png"
+)
+```
+
+---
+
+### 5. Icon/Illustration
+
+**User Request**: "Create an icon for our file upload feature"
+
+**Invocation**:
+```javascript
+task(
+  subagent_type="Image Specialist",
+  description="Generate file upload icon",
+  prompt="Create a modern icon for file upload feature:
+          
+          **Concept**: Cloud with upward arrow
+          **Style**: 
+            - Minimalist, clean lines
+            - Rounded corners
+            - Flat design (no gradients)
+          **Colors**: 
+            - Primary: #3b82f6 (blue)
+            - Accent: #60a5fa (lighter blue)
+          **Size**: 512x512px (will be scaled down)
+          **Format**: PNG with transparent background
+          **Usage**: App UI, documentation, marketing
+          
+          Output: Save to assets/icons/upload-icon.png"
+)
+```
+
+---
+
+### 6. Image Editing
+
+**User Request**: "Make this screenshot look more professional"
+
+**Invocation**:
+```javascript
+task(
+  subagent_type="Image Specialist",
+  description="Enhance screenshot for documentation",
+  prompt="Edit the existing screenshot at docs/raw-screenshot.png:
+          
+          **Enhancements Needed**:
+          - Add subtle drop shadow for depth
+          - Round the corners (8px radius)
+          - Add a thin border (#e5e7eb)
+          - Increase contrast slightly
+          - Ensure text is crisp and readable
+          
+          **Optional**:
+          - Add subtle gradient background
+          - Highlight key UI elements with arrows/boxes
+          
+          **Output Format**: PNG, maintain original dimensions
+          **Quality**: High (for documentation)
+          
+          Output: Save to docs/enhanced-screenshot.png"
+)
+```
+
+---
+
+## Decision Tree: Image Specialist vs Design Iteration
+
+Use this decision tree to choose the right approach:
+
+```
+User needs visual content
+    ↓
+Is it interactive/responsive HTML/CSS?
+    ↓
+  YES → Use design-iteration-overview.md workflow
+    |    - Create HTML files
+    |    - Iterate on designs
+    |    - Production-ready code
+    ↓
+  NO → Is it a static visual asset?
+    ↓
+  YES → Use Image Specialist
+    |    - Diagrams
+    |    - Mockups (non-interactive)
+    |    - Graphics
+    |    - Illustrations
+    ↓
+  NO → Clarify requirements with user
+```
+
+### Quick Reference
+
+| Need | Use |
+|------|-----|
+| **Interactive dashboard** | design-iteration-overview.md |
+| **Dashboard mockup (static image)** | Image Specialist |
+| **Responsive landing page** | design-iteration-overview.md |
+| **Landing page hero graphic** | Image Specialist |
+| **Working HTML prototype** | design-iteration-overview.md |
+| **Architecture diagram** | Image Specialist |
+| **UI component library** | design-iteration-overview.md |
+| **Social media graphic** | Image Specialist |
+
+---
+
+## Tools & Dependencies
+
+### Required Tool
+
+**tool:gemini** - Gemini Nano Banana AI
+- Automatically included in Developer profile
+- Requires GEMINI_API_KEY environment variable
+- Get API key: https://makersuite.google.com/app/apikey
+
+### Configuration
+
+Add to `.env` file:
+```bash
+GEMINI_API_KEY=your_api_key_here
+```
+
+### Capabilities
+
+- **Text-to-Image**: Generate images from descriptions
+- **Image-to-Image**: Edit and transform existing images
+- **Image Analysis**: Describe and analyze image content
+- **Multiple Formats**: PNG, JPG, WebP support
+- **High Resolution**: Up to 2048x2048 pixels
+
+---
+
+## Best Practices
+
+### Writing Effective Prompts
+
+✅ **Do**:
+- Be specific about dimensions and format
+- Describe visual style clearly (modern, minimalist, professional)
+- Specify colors using hex codes or names
+- Include key elements that must appear
+- Mention the intended use case
+- Provide context about brand/aesthetic
+
+❌ **Don't**:
+- Use vague descriptions ("make it nice")
+- Forget to specify dimensions
+- Assume default style preferences
+- Skip color specifications
+- Omit output location
+
+### Example: Good vs Bad Prompts
+
+**❌ Bad Prompt**:
+```
+"Create a diagram of our system"
+```
+
+**✅ Good Prompt**:
+```
+"Create a technical architecture diagram showing:
+- 3 microservices (API, Auth, Database)
+- AWS infrastructure (EC2, RDS, S3)
+- External APIs (Stripe, SendGrid)
+
+Style: Clean, professional, modern
+Colors: Blue for services, green for databases
+Format: PNG, 1920x1080
+Layout: Left-to-right flow with clear connections
+
+Output: docs/system-architecture.png"
+```
+
+---
+
+## Quality Checklist
+
+Before delegating to Image Specialist:
+
+- [ ] User request clearly indicates need for visual content
+- [ ] Determined static image is appropriate (not interactive HTML)
+- [ ] Gathered requirements: style, dimensions, colors, elements
+- [ ] Specified output format and location
+- [ ] Confirmed tool:gemini is available in profile
+- [ ] Prepared detailed prompt with all specifications
+
+After receiving output:
+
+- [ ] Image meets specified requirements
+- [ ] Dimensions and format are correct
+- [ ] Visual style matches request
+- [ ] All key elements are included
+- [ ] Image is saved to specified location
+- [ ] User is satisfied with result
+
+---
+
+## Troubleshooting
+
+### Common Issues
+
+**Issue**: Generated image doesn't match expectations
+**Solution**: Refine prompt with more specific details, provide reference examples
+
+**Issue**: Image quality is low
+**Solution**: Request higher resolution, specify quality requirements in prompt
+
+**Issue**: Colors don't match brand
+**Solution**: Provide exact hex codes, reference brand guidelines
+
+**Issue**: Layout is cluttered
+**Solution**: Simplify requirements, specify clear hierarchy and spacing
+
+**Issue**: Text in image is unreadable
+**Solution**: Request larger text, higher contrast, clearer typography
+
+---
+
+## Related Context
+
+- **UI Design Workflow**: `.opencode/context/core/workflows/design-iteration-overview.md`
+- **Design Systems**: `.opencode/context/ui/web/design-systems.md`
+- **UI Styling Standards**: `.opencode/context/ui/web/ui-styling-standards.md`
+- **Animation Patterns**: `.opencode/context/ui/web/animation-basics.md`, `.opencode/context/ui/web/animation-advanced.md`
+- **Subagent Invocation Guide**: `.opencode/context/openagents-repo/guides/subagent-invocation.md`
+- **Agent Capabilities**: `.opencode/context/openagents-repo/core-concepts/agents.md`
+
+---
+
+## Keywords for Discovery
+
+**ContextScout should find this file when users mention**:
+
+- image, images, picture, photo, graphic
+- diagram, flowchart, visualization, chart
+- mockup, wireframe, design, concept
+- illustration, icon, asset, visual
+- generate, create, make, design
+- screenshot, capture, render
+- architecture, system, flow, process
+- social media, marketing, promotional
+- edit, modify, enhance, transform
+- UI, interface, dashboard, layout
+
+---
+
+## Version History
+
+- **v1.0** (2025-01-27): Initial creation with comprehensive use cases and examples

+ 136 - 0
plugins/claude-code/scripts/context/core/workflows/code-review.md

@@ -0,0 +1,136 @@
+<!-- Context: workflows/review | Priority: high | Version: 2.0 | Updated: 2025-01-21 -->
+
+# Code Review Guidelines
+
+## Quick Reference
+
+**Golden Rule**: Review code as you'd want yours reviewed - thoroughly but kindly
+
+**Checklist**: Functionality, Code Quality, Security, Testing, Performance, Maintainability
+
+**Report Format**: Summary, Assessment, Issues (🔴🟡🔵), Positive Observations, Recommendations
+
+**Principles**: Constructive, Thorough, Timely
+
+---
+
+## Principles
+
+**Constructive**: Focus on code not person, explain WHY, suggest improvements, acknowledge good practices
+**Thorough**: Check functionality not just style, consider edge cases, think maintainability, look for security
+**Timely**: Review promptly, don't block unnecessarily, prioritize critical issues
+
+## Review Checklist
+
+### Functionality
+- [ ] Does what it's supposed to do
+- [ ] Edge cases handled
+- [ ] Error cases handled
+- [ ] No obvious bugs
+
+### Code Quality
+- [ ] Clear, descriptive naming
+- [ ] Functions small and focused
+- [ ] No unnecessary complexity
+- [ ] Follows coding standards
+- [ ] DRY - no duplication
+
+### Security
+- [ ] Input validation present
+- [ ] No SQL injection vulnerabilities
+- [ ] No XSS vulnerabilities
+- [ ] No hardcoded secrets
+- [ ] Sensitive data handled properly
+- [ ] Auth/authorization appropriate
+
+### Testing
+- [ ] Tests present
+- [ ] Happy path covered
+- [ ] Edge cases covered
+- [ ] Error cases covered
+- [ ] All tests pass
+
+### Performance
+- [ ] No obvious performance issues
+- [ ] Efficient algorithms
+- [ ] No unnecessary operations
+- [ ] Resources properly managed
+
+### Maintainability
+- [ ] Easy to understand
+- [ ] Complex logic documented
+- [ ] Follows project conventions
+- [ ] Easy to modify/extend
+
+## Review Report Format
+
+```markdown
+## Code Review: {Feature/PR Name}
+
+**Summary:** {Brief overview}
+**Assessment:** Approve / Needs Work / Requires Changes
+
+---
+
+### Issues Found
+
+#### 🔴 Critical (Must Fix)
+- **File:** `src/auth.js:42`
+  **Issue:** Password stored in plain text
+  **Fix:** Hash password before storing
+
+#### 🟡 Warnings (Should Fix)
+- **File:** `src/user.js:15`
+  **Issue:** No input validation
+  **Fix:** Validate email format
+
+#### 🔵 Suggestions (Nice to Have)
+- **File:** `src/utils.js:28`
+  **Issue:** Could be more concise
+  **Fix:** Use array methods instead of loop
+
+---
+
+### Positive Observations
+- ✅ Good test coverage (95%)
+- ✅ Clear function names
+- ✅ Proper error handling
+
+---
+
+### Recommendations
+{Next steps, improvements, follow-up items}
+```
+
+## Common Issues
+
+### Security
+🔴 Hardcoded credentials
+🔴 SQL injection vulnerabilities
+🔴 Missing input validation
+🔴 Exposed sensitive data
+
+### Code Quality
+🟡 Large functions (>50 lines)
+🟡 Deep nesting (>3 levels)
+🟡 Code duplication
+🟡 Unclear naming
+
+### Testing
+🟡 Missing tests
+🟡 Low coverage (<80%)
+🟡 Flaky tests
+🟡 Tests testing implementation
+
+## Best Practices
+
+✅ Review within 24 hours
+✅ Provide specific, actionable feedback
+✅ Explain WHY, not just WHAT
+✅ Suggest alternatives
+✅ Acknowledge good work
+✅ Use severity levels (Critical/Warning/Suggestion)
+✅ Test the code if possible
+✅ Check for security issues first
+
+**Golden Rule**: Review code as you'd want yours reviewed - thoroughly but kindly.

+ 96 - 0
plugins/claude-code/scripts/context/core/workflows/component-planning.md

@@ -0,0 +1,96 @@
+<!-- Context: workflows/component-planning | Priority: high | Version: 1.0 -->
+
+# Component-Based Planning Workflow
+
+## Overview
+This workflow replaces "Monolithic Planning" (planning everything at once) with "Iterative Component Planning". It is designed for complex features that require breaking down into functional units.
+
+## Core Philosophy
+**"Plan the System, Build the Component."**
+Don't try to write a detailed plan for the entire system upfront. Create a high-level roadmap, then zoom in to plan one component in detail before executing it.
+
+## The Two-Level Plan Structure
+
+### Level 1: The Master Plan (Roadmap)
+**File:** `.tmp/sessions/{id}/master-plan.md`
+**Purpose:** High-level architecture and dependency graph.
+**Content:**
+- System Architecture Diagram (ASCII)
+- List of Components (e.g., Auth, Database, API, UI)
+- Dependency Order (What must be built first?)
+- Global Standards/Decisions
+
+### Level 2: The Component Plan (Active Spec)
+**File:** `.tmp/sessions/{id}/component-{name}.md`
+**Purpose:** Detailed execution steps for the *current* focus.
+**Content:**
+- **Interface Definition**: Types, function signatures, API contracts.
+- **Test Strategy**: What specific cases will be tested?
+- **Task List**: Atomic steps (Create file, Write test, Implement logic).
+- **Verification**: How do we know this component is done?
+
+---
+
+## Workflow Steps
+
+### Phase 1: System Design (The Master Plan)
+1.  **Analyze**: Understand the full feature request.
+2.  **Decompose**: Break the system into functional Components (e.g., "User Service", "Email Worker", "Frontend Form").
+3.  **Draft Master Plan**: Create `master-plan.md`.
+4.  **Approve**: Get user buy-in on the architecture and order.
+
+### Phase 2: Component Execution Loop
+*Repeat this for each component in the Master Plan:*
+
+1.  **Select Component**: Pick the next unblocked component.
+2.  **Draft Component Plan**: Create `component-{name}.md`.
+    *   Define the *exact* interface/types first.
+    *   List the atomic implementation steps.
+3.  **Approve**: Show the detailed component plan to the user.
+4.  **Execute**:
+    *   Load `component-{name}.md` into `TodoWrite`.
+    *   Implement -> Validate -> Check off.
+5.  **Integrate**: Update `master-plan.md` to mark component as complete.
+
+---
+
+## When to Use This
+- **Complex Features**: >3 files, multiple layers (DB + API + UI).
+- **Unknowns**: When later parts of the system depend on earlier decisions.
+- **Large Scope**: Anything taking >2 hours.
+
+## Example Master Plan (`master-plan.md`)
+
+```markdown
+# Master Plan: E-Commerce Checkout
+
+## Architecture
+[Cart] -> [Order Service] -> [Payment Gateway]
+                       -> [Inventory Service]
+
+## Component Order
+1. [ ] **Inventory Service** (Check stock)
+2. [ ] **Order Service** (Create order record)
+3. [ ] **Payment Integration** (Stripe)
+4. [ ] **Checkout UI** (React components)
+```
+
+## Example Component Plan (`component-inventory.md`)
+
+```markdown
+# Component: Inventory Service
+
+## Interface
+```typescript
+interface InventoryManager {
+  checkStock(sku: string): Promise<boolean>;
+  reserve(sku: string, quantity: number): Promise<void>;
+}
+```
+
+## Tasks
+- [ ] Define `InventoryManager` interface in `src/types.ts`
+- [ ] Create mock implementation for tests
+- [ ] Implement `checkStock` logic with DB query
+- [ ] Add unit tests for race conditions
+```

+ 20 - 0
plugins/claude-code/scripts/context/core/workflows/delegation.md

@@ -0,0 +1,20 @@
+<!-- Context: workflows/delegation | Priority: high | Version: 2.0 | Updated: 2025-01-21 -->
+# Delegation Context Template
+
+> **Note**: This is a reference file. Start with [`task-delegation-basics.md`](./task-delegation-basics.md).
+
+## Quick Reference
+
+**Process**: Create context → Populate → Delegate → Cleanup
+
+**Location**: `.tmp/sessions/{timestamp}-{task-slug}/context.md`
+
+**Template Sections**: Request, Requirements, Decisions, Files, Static Context, Constraints, Progress, Instructions
+
+---
+
+For the full delegation workflow, use:
+
+- [task-delegation-basics.md](./task-delegation-basics.md)
+- [task-delegation-specialists.md](./task-delegation-specialists.md)
+- [task-delegation-caching.md](./task-delegation-caching.md)

+ 179 - 0
plugins/claude-code/scripts/context/core/workflows/design-iteration-best-practices.md

@@ -0,0 +1,179 @@
+<!-- Context: workflows/design-iteration-best-practices | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
+# Design Iteration Best Practices
+
+## Iteration Process
+
+### When to Create Iterations
+
+**Create new iteration** (`{name}_1_1.html`) when:
+- User requests changes to existing design
+- Refining based on feedback
+- A/B testing variations
+- Progressive enhancement
+
+**Create new design** (`{name}_2.html`) when:
+- Complete redesign requested
+- Different approach/style
+- Alternative layout structure
+
+### Iteration Workflow
+
+```
+User: "Can you make the buttons larger and change the color?"
+
+1. Read current file: dashboard_1.html
+2. Make requested changes
+3. Save as: dashboard_1_1.html
+4. Present changes to user
+
+User: "Perfect! Now can we add a sidebar?"
+
+1. Read current file: dashboard_1_1.html
+2. Add sidebar component
+3. Save as: dashboard_1_2.html
+4. Present changes to user
+```
+
+---
+
+## File Management
+
+### Folder Structure
+
+```
+design_iterations/
+├── theme_1.css
+├── theme_2.css
+├── landing_1.html
+├── landing_1_1.html
+├── landing_1_2.html
+├── dashboard_1.html
+├── dashboard_1_1.html
+└── README.md (optional: design notes)
+```
+
+### Version Control
+
+**Track iterations**:
+- Initial: `design_1.html`
+- Iteration 1: `design_1_1.html`
+- Iteration 2: `design_1_2.html`
+- Iteration 3: `design_1_3.html`
+
+**New major version**:
+- Complete redesign: `design_2.html`
+- Then iterate: `design_2_1.html`, `design_2_2.html`
+
+---
+
+## Communication Patterns
+
+### Stage Transitions
+
+**After Layout**:
+```
+"Here's the proposed layout structure. The design uses a [description].
+Would you like to proceed with this layout, or should we make adjustments?"
+```
+
+**After Theme**:
+```
+"I've created a [style] theme with [key features]. The theme file is saved as theme_N.css.
+Does this match your vision, or would you like to adjust colors/typography?"
+```
+
+**After Animation**:
+```
+"Here's the animation plan using [timing/style]. All animations are optimized for performance.
+Are these animations appropriate, or should we adjust the timing/effects?"
+```
+
+**After Implementation**:
+```
+"I've created the complete design as {filename}.html. The design includes [key features].
+Please review and let me know if you'd like any changes or iterations."
+```
+
+### Iteration Requests
+
+**User requests change**:
+```
+"I'll update the design with [changes] and save it as {filename}_N.html.
+This preserves the previous version for reference."
+```
+
+---
+
+## Quality Checklist
+
+Before presenting each stage:
+
+**Layout Stage**:
+- [ ] ASCII wireframe is clear and detailed
+- [ ] Components are well-organized
+- [ ] Responsive behavior is planned
+- [ ] User approval requested
+
+**Theme Stage**:
+- [ ] Theme file created and saved
+- [ ] Colors use OKLCH format
+- [ ] Fonts loaded from Google Fonts
+- [ ] Contrast ratios meet WCAG AA
+- [ ] User approval requested
+
+**Animation Stage**:
+- [ ] Animations documented in micro-syntax
+- [ ] Timing is appropriate (< 400ms)
+- [ ] Performance optimized (transform/opacity)
+- [ ] Accessibility considered
+- [ ] User approval requested
+
+**Implementation Stage**:
+- [ ] Single HTML file created
+- [ ] Theme CSS referenced
+- [ ] Tailwind loaded via script tag
+- [ ] Icons initialized
+- [ ] Responsive design tested
+- [ ] Accessibility attributes added
+- [ ] Images use valid placeholder URLs
+- [ ] Semantic HTML used
+- [ ] User review requested
+
+---
+
+## Troubleshooting
+
+### Common Issues
+
+**Issue**: User wants to skip stages
+**Solution**: Explain benefits of structured approach, but accommodate if insisted
+
+**Issue**: Theme doesn't match user vision
+**Solution**: Iterate on theme file, create theme_2.css with adjustments
+
+**Issue**: Animations feel too slow/fast
+**Solution**: Adjust timing in micro-syntax, regenerate with new values
+
+**Issue**: Design doesn't work on mobile
+**Solution**: Review responsive breakpoints, add mobile-specific styles
+
+**Issue**: Colors have poor contrast
+**Solution**: Use WCAG contrast checker, adjust OKLCH lightness values
+
+---
+
+## References
+
+- [Design Systems Context](../../ui/web/design-systems.md)
+- [UI Styling Standards](../../ui/web/ui-styling-standards.md)
+- [Animation Basics](../../ui/web/animation-basics.md)
+- [ASCII Art Generator](https://www.asciiart.eu/)
+- [WCAG Contrast Checker](https://webaim.org/resources/contrastchecker/)
+
+---
+
+## Related Files
+
+- [Overview](./design-iteration-overview.md)
+- [Stage 4: Implementation](./design-iteration-stage-implementation.md)
+- [Plan Iterations](./design-iteration-plan-iterations.md)

+ 91 - 0
plugins/claude-code/scripts/context/core/workflows/design-iteration-overview.md

@@ -0,0 +1,91 @@
+<!-- Context: workflows/design-iteration-overview | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
+# Design Iteration Workflow - Overview
+
+## Overview
+
+A structured 4-stage workflow for creating and iterating on UI designs. This process ensures thoughtful design decisions with user approval at each stage.
+
+## Quick Reference
+
+**Stages**: Layout → Theme → Animation → Implementation
+**Approval**: Required between each stage
+**Output**: Single HTML file per design iteration
+**Location**: `design_iterations/` folder
+
+---
+
+## When to Use This Workflow
+
+### Delegate to OpenFrontendSpecialist When:
+
+**✅ STRONGLY RECOMMENDED** to delegate for:
+- **New UI/UX design work** - Landing pages, dashboards, app interfaces
+- **Design system creation** - Component libraries, theme systems, style guides
+- **Complex layouts** - Multi-column grids, responsive designs, intricate structures
+- **Visual polish** - Animations, transitions, micro-interactions
+- **Brand-focused work** - Marketing pages, product showcases, hero sections
+- **Accessibility-critical UI** - Forms, navigation, interactive components
+
+**Why delegate?**
+- OpenFrontendSpecialist follows the 4-stage design workflow (Layout → Theme → Animation → Implementation)
+- Ensures thoughtful design decisions with approval gates
+- Produces polished, accessible, production-ready UI
+- Handles responsive design, OKLCH colors, semantic HTML
+- Creates single-file HTML prototypes for quick iteration
+
+### Execute Directly When:
+
+**⚠️ Simple cases only**:
+- Minor text/content updates to existing UI
+- Small CSS tweaks (colors, spacing, fonts)
+- Adding simple utility classes
+- Updating existing component props
+- Bug fixes in existing UI code
+
+### Delegation Pattern
+
+```javascript
+// For UI design work
+task(
+  subagent_type="OpenFrontendSpecialist",
+  description="Design {feature} UI",
+  prompt="Design a {feature} following the 4-stage workflow:
+  
+  Requirements:
+  - {requirement 1}
+  - {requirement 2}
+  
+  Context: {what this UI is for}
+  
+  Follow the design iteration workflow:
+  1. Layout (ASCII wireframe)
+  2. Theme (design system, colors)
+  3. Animation (micro-interactions)
+  4. Implementation (single HTML file)
+  
+  Request approval between each stage."
+)
+```
+
+### Example Scenarios
+
+| Scenario | Action | Why |
+|----------|--------|-----|
+| "Create a landing page for our SaaS product" | ✅ Delegate to OpenFrontendSpecialist | Complex UI design, needs 4-stage workflow |
+| "Design a user dashboard with charts" | ✅ Delegate to OpenFrontendSpecialist | Complex layout, visual design, interactions |
+| "Build a component library with our brand" | ✅ Delegate to OpenFrontendSpecialist | Design system work, requires theme expertise |
+| "Fix button color from blue to green" | ⚠️ Execute directly | Simple CSS change |
+| "Update hero text content" | ⚠️ Execute directly | Content update only |
+
+---
+
+## Related Files
+
+- [Design Plan File](./design-iteration-plan-file.md) - MANDATORY plan file template
+- [Stage 1: Layout](./design-iteration-stage-layout.md)
+- [Stage 2: Theme](./design-iteration-stage-theme.md)
+- [Stage 3: Animation](./design-iteration-stage-animation.md)
+- [Stage 4: Implementation](./design-iteration-stage-implementation.md)
+- [Visual Content Generation](./design-iteration-visual-content.md)
+- [Best Practices](./design-iteration-best-practices.md)
+- [Plan Iterations](./design-iteration-plan-iterations.md)

+ 182 - 0
plugins/claude-code/scripts/context/core/workflows/design-iteration-plan-file.md

@@ -0,0 +1,182 @@
+<!-- Context: workflows/design-iteration-plan-file | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
+# Design Plan File (MANDATORY)
+
+**CRITICAL**: Before starting any design work, create a persistent design plan file.
+
+**Location**: `.tmp/design-plans/{project-name}-{feature-name}.md`
+
+**Purpose**: 
+- Preserve design decisions across stages
+- Allow user to review and edit the plan
+- Maintain context for subagent calls
+- Track design evolution and iterations
+
+**When to Create**: 
+- BEFORE Stage 1 (Layout Design)
+- After understanding user requirements
+- Before any design work begins
+
+## Template
+
+```markdown
+---
+project: {project-name}
+feature: {feature-name}
+created: {ISO timestamp}
+updated: {ISO timestamp}
+status: in_progress
+current_stage: layout
+---
+
+# Design Plan: {Feature Name}
+
+## User Requirements
+{What the user asked for - verbatim or close paraphrase}
+
+## Design Goals
+- {goal 1}
+- {goal 2}
+- {goal 3}
+
+## Target Audience
+{Who will use this UI}
+
+## Technical Constraints
+- Framework: {Next.js, React, etc.}
+- Responsive: {Yes/No}
+- Accessibility: {WCAG level}
+- Browser support: {Modern, IE11+, etc.}
+
+---
+
+## Stage 1: Layout Design
+
+### Status
+- [ ] Layout planned
+- [ ] ASCII wireframe created
+- [ ] User approved
+
+### Layout Structure
+{ASCII wireframe will be added here}
+
+### Component Breakdown
+{Component list will be added here}
+
+### User Feedback
+{User comments and requested changes}
+
+---
+
+## Stage 2: Theme Design
+
+### Status
+- [ ] Design system selected
+- [ ] Color palette chosen
+- [ ] Typography defined
+- [ ] User approved
+
+### Theme Details
+{Theme specifications will be added here}
+
+### User Feedback
+{User comments and requested changes}
+
+---
+
+## Stage 3: Animation Design
+
+### Status
+- [ ] Micro-interactions defined
+- [ ] Animation timing set
+- [ ] User approved
+
+### Animation Details
+{Animation specifications will be added here}
+
+### User Feedback
+{User comments and requested changes}
+
+---
+
+## Stage 4: Implementation
+
+### Status
+- [ ] HTML structure complete
+- [ ] CSS applied
+- [ ] Animations implemented
+- [ ] User approved
+
+### Output Files
+- HTML: {file path}
+- CSS: {file path}
+- Assets: {file paths}
+
+### User Feedback
+{Final comments and requested changes}
+
+---
+
+## Design Evolution
+
+### Iteration 1
+- Date: {timestamp}
+- Changes: {what changed}
+- Reason: {why it changed}
+
+### Iteration 2
+- Date: {timestamp}
+- Changes: {what changed}
+- Reason: {why it changed}
+```
+
+## Workflow Integration
+
+1. **Create plan file** → Write to `.tmp/design-plans/{name}.md`
+2. **Each stage** → Update plan file with decisions and user feedback
+3. **User approval** → Edit plan file with approved decisions
+4. **User requests changes** → Edit plan file with feedback, iterate
+5. **Subagent calls** → Pass plan file path for context preservation
+6. **Completion** → Plan file contains full design history
+
+## Benefits
+
+- ✅ Context preserved across subagent calls
+- ✅ User can review and edit plan directly
+- ✅ Design decisions documented
+- ✅ Easy to iterate and refine
+- ✅ Full design history tracked
+
+---
+
+## Stage 0: Create Design Plan (MANDATORY FIRST STEP)
+
+**Purpose**: Create persistent plan file before any design work
+
+**Process**:
+1. Understand user requirements
+2. Identify design goals and constraints
+3. Create plan file at `.tmp/design-plans/{project-name}-{feature-name}.md`
+4. Populate with user requirements and goals
+5. Present plan file location to user
+6. Proceed to Stage 1
+
+**Deliverable**: Design plan file created and initialized
+
+**Example**:
+```
+✅ Design plan created: .tmp/design-plans/saas-landing-page.md
+
+You can review and edit this file at any time. All design decisions will be tracked here.
+
+Ready to proceed to Stage 1 (Layout Design)?
+```
+
+**Approval Gate**: "Plan file created. Ready to start layout design?"
+
+---
+
+## Related Files
+
+- [Overview](./design-iteration-overview.md)
+- [Stage 1: Layout](./design-iteration-stage-layout.md)
+- [Plan Iterations](./design-iteration-plan-iterations.md)

+ 153 - 0
plugins/claude-code/scripts/context/core/workflows/design-iteration-plan-iterations.md

@@ -0,0 +1,153 @@
+<!-- Context: workflows/design-iteration-plan-iterations | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
+# Handling Plan File Edits and Iterations
+
+## User Edits Plan File Directly
+
+**Scenario**: User opens `.tmp/design-plans/{name}.md` and makes changes
+
+**Process**:
+1. User edits plan file (changes requirements, adds constraints, modifies goals)
+2. User notifies agent: "I've updated the plan file"
+3. Agent reads updated plan file
+4. Agent identifies what changed
+5. Agent proposes how to incorporate changes
+6. Agent updates affected stages
+
+**Example**:
+```
+User: "I've updated the plan file - changed the color scheme to dark mode"
+
+Agent: 
+✅ Read updated plan: .tmp/design-plans/saas-landing-page.md
+
+Changes detected:
+- Color scheme: Light → Dark mode
+- Primary color: Blue → Purple
+
+This affects:
+- Stage 2 (Theme) - needs regeneration
+- Stage 4 (Implementation) - needs CSS update
+
+Would you like me to:
+1. Regenerate theme with dark mode
+2. Update implementation with new theme
+```
+
+---
+
+## Iteration Within a Stage
+
+**Scenario**: User requests changes during a stage
+
+**Process**:
+1. Agent presents stage output (e.g., layout wireframe)
+2. User requests changes: "Make the hero section taller"
+3. Agent updates plan file with feedback
+4. Agent makes changes
+5. Agent updates plan file with new iteration
+6. Agent presents updated output
+
+**Example**:
+```
+Stage 1 - Layout Design
+
+Agent: [presents wireframe]
+
+User: "Make the hero section taller and move CTA above the fold"
+
+Agent:
+✅ Updated plan file with feedback
+✅ Revised layout wireframe
+✅ Updated plan file with Iteration 2
+
+[presents updated wireframe]
+```
+
+---
+
+## Tracking Iterations in Plan File
+
+**Format**:
+```markdown
+## Design Evolution
+
+### Iteration 1 - Initial Layout
+- Date: 2026-01-30T10:00:00Z
+- Stage: Layout
+- Changes: Initial wireframe created
+- User feedback: "Hero section too short, CTA below fold"
+
+### Iteration 2 - Revised Layout
+- Date: 2026-01-30T10:15:00Z
+- Stage: Layout
+- Changes: Increased hero height from 400px to 600px, moved CTA above fold
+- User feedback: "Perfect! Approved."
+- Status: ✅ Approved
+
+### Iteration 3 - Theme Adjustment
+- Date: 2026-01-30T10:30:00Z
+- Stage: Theme
+- Changes: Changed from light to dark mode, primary color blue → purple
+- User feedback: "Love the dark mode!"
+- Status: ✅ Approved
+```
+
+---
+
+## Subagent Context Preservation
+
+**Problem**: Subagents lose context between calls
+
+**Solution**: Always pass plan file path
+
+**Pattern**:
+```javascript
+// When delegating to subagent
+task(
+  subagent_type="OpenFrontendSpecialist",
+  description="Implement Stage 4",
+  prompt="Load design plan from .tmp/design-plans/saas-landing-page.md
+  
+  Read the plan file for:
+  - All approved decisions from Stages 1-3
+  - User requirements and constraints
+  - Design evolution and iterations
+  
+  Implement Stage 4 (Implementation) following all approved decisions.
+  
+  Update the plan file with:
+  - Output file paths
+  - Implementation status
+  - Any issues encountered"
+)
+```
+
+---
+
+## Plan File as Single Source of Truth
+
+### Benefits
+
+- ✅ All design decisions in one place
+- ✅ User can review and edit anytime
+- ✅ Subagents have full context
+- ✅ Design history preserved
+- ✅ Easy to iterate and refine
+- ✅ No context loss between stages
+
+### Best Practices
+
+- Always read plan file at start of each stage
+- Update plan file after every user interaction
+- Track all iterations with timestamps
+- Document user feedback verbatim
+- Mark approved decisions clearly
+- Pass plan file path to all subagents
+
+---
+
+## Related Files
+
+- [Overview](./design-iteration-overview.md)
+- [Design Plan File](./design-iteration-plan-file.md)
+- [Best Practices](./design-iteration-best-practices.md)

+ 80 - 0
plugins/claude-code/scripts/context/core/workflows/design-iteration-stage-animation.md

@@ -0,0 +1,80 @@
+<!-- Context: workflows/design-iteration-stage-animation | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
+# Stage 3: Animation Design
+
+**Purpose**: Define micro-interactions and transitions
+
+## Process
+
+1. Read design plan file from `.tmp/design-plans/{name}.md`
+2. Review approved theme from Stage 2
+3. Identify key interactions (hover, click, scroll)
+4. Define animation timing and easing
+5. Plan loading states and transitions
+6. Document animations using micro-syntax
+7. **Update plan file** with animation specifications
+8. Present animation plan to user for approval
+9. **Update plan file** with user feedback and approval status
+
+## Deliverable
+
+- Animation specification in micro-syntax format
+- Updated plan file with Stage 3 complete
+
+## Example Output
+
+```
+## Animation Design: Smooth & Professional
+
+### Button Interactions
+hover: 200ms ease-out [Y0→-2, shadow↗]
+press: 100ms ease-in [S1→0.95]
+ripple: 400ms ease-out [S0→2, α1→0]
+
+### Card Interactions
+cardHover: 300ms ease-out [Y0→-4, shadow↗]
+cardClick: 200ms ease-out [S1→1.02]
+
+### Page Transitions
+pageEnter: 300ms ease-out [α0→1, Y+20→0]
+pageExit: 200ms ease-in [α1→0]
+
+### Loading States
+spinner: 1000ms ∞ linear [R360°]
+skeleton: 2000ms ∞ [bg: muted↔accent]
+
+### Micro-Interactions
+inputFocus: 200ms ease-out [S1→1.01, ring]
+linkHover: 250ms ease-out [underline 0→100%]
+
+**Philosophy**: Subtle, purposeful animations that enhance UX without distraction
+**Performance**: All animations use transform/opacity for 60fps
+**Accessibility**: Respects prefers-reduced-motion
+```
+
+## Best Practices
+
+✅ **Do**:
+- Use micro-syntax for documentation
+- Keep animations under 400ms
+- Use transform/opacity for performance
+- Respect prefers-reduced-motion
+- Make animations purposeful
+
+❌ **Don't**:
+- Animate width/height (use scale)
+- Create distracting animations
+- Ignore performance implications
+- Skip accessibility considerations
+
+## Approval Gate
+
+"Are these animations appropriate for your design, or should we adjust?"
+
+---
+
+## Related Files
+
+- [Overview](./design-iteration-overview.md)
+- [Stage 2: Theme](./design-iteration-stage-theme.md)
+- [Stage 4: Implementation](./design-iteration-stage-implementation.md)
+- [Animation Basics](../../ui/web/animation-basics.md)

+ 157 - 0
plugins/claude-code/scripts/context/core/workflows/design-iteration-stage-implementation.md

@@ -0,0 +1,157 @@
+<!-- Context: workflows/design-iteration-stage-implementation | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
+# Stage 4: Implementation
+
+**Purpose**: Generate complete HTML file with all components
+
+## Process
+
+1. Read design plan file from `.tmp/design-plans/{name}.md`
+2. Review all approved decisions from Stages 1-3
+3. Build individual UI components
+4. Integrate theme CSS
+5. Add animations and interactions
+6. Combine into single HTML file
+7. Test responsive behavior
+8. Save to design_iterations folder
+9. **Update plan file** with output file paths
+10. Present to user for review
+11. **Update plan file** with user feedback and final approval status
+
+## Deliverable
+
+- Complete HTML file with embedded or linked CSS
+- Updated plan file with Stage 4 complete and all output files documented
+
+## File Organization
+
+```
+design_iterations/
+├── theme_1.css              # Theme file from Stage 2
+├── dashboard_1.html         # Initial design
+├── dashboard_1_1.html       # First iteration
+├── dashboard_1_2.html       # Second iteration
+├── chat_ui_1.html           # Different design
+└── chat_ui_1_1.html         # Iteration of chat UI
+```
+
+## Naming Conventions
+
+| Type | Format | Example |
+|------|--------|---------|
+| Initial design | `{name}_1.html` | `table_1.html` |
+| First iteration | `{name}_1_1.html` | `table_1_1.html` |
+| Second iteration | `{name}_1_2.html` | `table_1_2.html` |
+| New design | `{name}_2.html` | `table_2.html` |
+
+## Implementation Checklist
+
+```html
+<!DOCTYPE html>
+<html lang="en">
+<head>
+  <meta charset="UTF-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1.0">
+  <title>Design Name</title>
+  
+  <!-- ✅ Preconnect to external resources -->
+  <link rel="preconnect" href="https://fonts.googleapis.com">
+  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+  
+  <!-- ✅ Load fonts -->
+  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
+  
+  <!-- ✅ Load Tailwind (script tag, not stylesheet) -->
+  <script src="https://cdn.tailwindcss.com"></script>
+  
+  <!-- ✅ Load Flowbite if needed -->
+  <link href="https://cdn.jsdelivr.net/npm/flowbite@2.0.0/dist/flowbite.min.css" rel="stylesheet">
+  
+  <!-- ✅ Load icons -->
+  <script src="https://unpkg.com/lucide@latest/dist/umd/lucide.min.js"></script>
+  
+  <!-- ✅ Link theme CSS -->
+  <link rel="stylesheet" href="theme_1.css">
+  
+  <!-- ✅ Custom styles with !important for overrides -->
+  <style>
+    body {
+      font-family: 'Inter', sans-serif !important;
+      color: var(--foreground) !important;
+    }
+    
+    h1, h2, h3, h4, h5, h6 {
+      font-weight: 600 !important;
+    }
+    
+    /* Custom animations */
+    @keyframes fadeIn {
+      from { opacity: 0; transform: translateY(20px); }
+      to { opacity: 1; transform: translateY(0); }
+    }
+    
+    .animate-fade-in {
+      animation: fadeIn 300ms ease-out;
+    }
+  </style>
+</head>
+<body>
+  <!-- ✅ Semantic HTML structure -->
+  <header>
+    <!-- Header content -->
+  </header>
+  
+  <main>
+    <!-- Main content -->
+  </main>
+  
+  <footer>
+    <!-- Footer content -->
+  </footer>
+  
+  <!-- ✅ Load Flowbite JS if needed -->
+  <script src="https://cdn.jsdelivr.net/npm/flowbite@2.0.0/dist/flowbite.min.js"></script>
+  
+  <!-- ✅ Initialize icons -->
+  <script>
+    lucide.createIcons();
+  </script>
+  
+  <!-- ✅ Custom JavaScript -->
+  <script>
+    // Interactive functionality
+  </script>
+</body>
+</html>
+```
+
+## Best Practices
+
+✅ **Do**:
+- Use single HTML file per design
+- Load Tailwind via script tag
+- Reference theme CSS file
+- Use !important for framework overrides
+- Test responsive behavior
+- Provide alt text for images
+- Use semantic HTML
+
+❌ **Don't**:
+- Split into multiple files
+- Load Tailwind as stylesheet
+- Inline all styles
+- Skip accessibility attributes
+- Use made-up image URLs
+- Use div soup (non-semantic HTML)
+
+## Approval Gate
+
+"Please review the design. Would you like any changes or iterations?"
+
+---
+
+## Related Files
+
+- [Overview](./design-iteration-overview.md)
+- [Stage 3: Animation](./design-iteration-stage-animation.md)
+- [Best Practices](./design-iteration-best-practices.md)
+- [Iteration Process](./design-iteration-plan-iterations.md)

+ 115 - 0
plugins/claude-code/scripts/context/core/workflows/design-iteration-stage-layout.md

@@ -0,0 +1,115 @@
+<!-- Context: workflows/design-iteration-stage-layout | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
+# Stage 1: Layout Design
+
+**Purpose**: Define the structure and component hierarchy before visual design
+
+## Process
+
+1. Read design plan file from `.tmp/design-plans/{name}.md`
+2. Analyze user requirements from plan
+3. Identify core UI components
+4. Plan layout structure and responsive behavior
+5. Create ASCII wireframe
+6. **Update plan file** with layout structure and component breakdown
+7. Present to user for approval
+8. **Update plan file** with user feedback and approval status
+
+## Deliverable
+
+- ASCII wireframe with component breakdown
+- Updated plan file with Stage 1 complete
+
+## Example Output
+
+```
+## Core UI Components
+
+**Header Area**
+- Logo/brand (Top left)
+- Navigation menu (Top center)
+- User actions (Top right)
+
+**Main Content Area**
+- Hero section (Full width)
+- Feature cards (3-column grid on desktop, stack on mobile)
+- Call-to-action (Centered)
+
+**Footer**
+- Links (4-column grid)
+- Social icons (Centered)
+- Copyright (Bottom)
+
+## Layout Structure
+
+Desktop (1024px+):
+┌─────────────────────────────────────────────────┐
+│ [Logo]        Navigation        [User Menu]     │
+├─────────────────────────────────────────────────┤
+│                                                 │
+│              HERO SECTION                       │
+│         (Full width, centered text)             │
+│                                                 │
+├─────────────────────────────────────────────────┤
+│  ┌─────────┐  ┌─────────┐  ┌─────────┐         │
+│  │ Card 1  │  │ Card 2  │  │ Card 3  │         │
+│  │         │  │         │  │         │         │
+│  └─────────┘  └─────────┘  └─────────┘         │
+├─────────────────────────────────────────────────┤
+│              [Call to Action]                   │
+├─────────────────────────────────────────────────┤
+│  Links    Links    Links    Social              │
+│                    Copyright                    │
+└─────────────────────────────────────────────────┘
+
+Mobile (< 768px):
+┌─────────────────┐
+│ ☰  Logo   [👤]  │
+├─────────────────┤
+│                 │
+│  HERO SECTION   │
+│                 │
+├─────────────────┤
+│  ┌───────────┐  │
+│  │  Card 1   │  │
+│  └───────────┘  │
+│  ┌───────────┐  │
+│  │  Card 2   │  │
+│  └───────────┘  │
+│  ┌───────────┐  │
+│  │  Card 3   │  │
+│  └───────────┘  │
+├─────────────────┤
+│      [CTA]      │
+├─────────────────┤
+│     Links       │
+│     Social      │
+│   Copyright     │
+└─────────────────┘
+```
+
+## Best Practices
+
+✅ **Do**:
+- Use ASCII wireframes for clarity
+- Break down into component hierarchy
+- Plan responsive behavior upfront
+- Consider mobile-first approach
+- Get approval before proceeding
+
+❌ **Don't**:
+- Skip wireframing and jump to code
+- Ignore responsive considerations
+- Proceed without user approval
+- Over-complicate initial layout
+
+## Approval Gate
+
+"Would you like to proceed with this layout or need modifications?"
+
+---
+
+## Related Files
+
+- [Overview](./design-iteration-overview.md)
+- [Design Plan File](./design-iteration-plan-file.md)
+- [Stage 2: Theme](./design-iteration-stage-theme.md)

+ 84 - 0
plugins/claude-code/scripts/context/core/workflows/design-iteration-stage-theme.md

@@ -0,0 +1,84 @@
+<!-- Context: workflows/design-iteration-stage-theme | Priority: high | Version: 1.0 | Updated: 2025-12-09 -->
+# Stage 2: Theme Design
+
+**Purpose**: Define colors, typography, spacing, and visual style
+
+## Process
+
+1. Read design plan file from `.tmp/design-plans/{name}.md`
+2. Review approved layout from Stage 1
+3. Choose design system (neo-brutalism, modern dark, custom)
+4. Select color palette (avoid Bootstrap blue unless requested)
+5. Choose typography (Google Fonts)
+6. Define spacing and shadows
+7. Generate theme CSS file
+8. **Update plan file** with theme specifications
+9. Present theme to user for approval
+10. **Update plan file** with user feedback and approval status
+
+## Deliverable
+
+- CSS theme file saved to `design_iterations/theme_N.css`
+- Updated plan file with Stage 2 complete
+
+## Theme Selection Criteria
+
+| Style | Use When | Avoid When |
+|-------|----------|------------|
+| Neo-Brutalism | Creative/artistic projects, retro aesthetic | Enterprise apps, accessibility-critical |
+| Modern Dark | SaaS, developer tools, professional dashboards | Playful consumer apps |
+| Custom | Specific brand requirements | Time-constrained projects |
+
+## Example Output
+
+```
+## Theme Design: Modern Professional
+
+**Style Reference**: Vercel/Linear aesthetic
+**Color Palette**: Monochromatic with accent
+**Typography**: Inter (UI) + JetBrains Mono (code)
+**Spacing**: 4px base unit
+**Shadows**: Subtle, soft elevation
+
+**Theme File**: design_iterations/theme_1.css
+
+Key Design Decisions:
+- Primary: Neutral gray for professional feel
+- Accent: Subtle blue for interactive elements
+- Radius: 0.625rem for modern, friendly feel
+- Shadows: Soft, minimal elevation
+- Fonts: System-like for familiarity
+```
+
+## File Naming
+
+`theme_1.css`, `theme_2.css`, etc.
+
+## Best Practices
+
+✅ **Do**:
+- Reference design system context files
+- Use CSS custom properties
+- Save theme to separate file
+- Consider accessibility (contrast ratios)
+- Avoid Bootstrap blue unless requested
+
+❌ **Don't**:
+- Hardcode colors in HTML
+- Use generic/overused color schemes
+- Skip contrast testing
+- Mix color formats (stick to OKLCH)
+
+## Approval Gate
+
+"Does this theme match your vision, or would you like adjustments?"
+
+---
+
+## Related Files
+
+- [Overview](./design-iteration-overview.md)
+- [Stage 1: Layout](./design-iteration-stage-layout.md)
+- [Stage 3: Animation](./design-iteration-stage-animation.md)
+- [Design Systems Context](../../ui/web/design-systems.md)
+- [UI Styling Standards](../../ui/web/ui-styling-standards.md)

+ 110 - 0
plugins/claude-code/scripts/context/core/workflows/design-iteration-visual-content.md

@@ -0,0 +1,110 @@
+<!-- Context: workflows/design-iteration-visual-content | Priority: medium | Version: 1.0 | Updated: 2025-12-09 -->
+# Visual Content Generation
+
+## When to Use Image Specialist
+
+Delegate to **Image Specialist** subagent when users request:
+
+- **Diagrams & Visualizations**: Architecture diagrams, flowcharts, system visualizations
+- **UI Mockups & Wireframes**: Visual mockups, design concepts, interface previews
+- **Graphics & Assets**: Social media graphics, promotional images, icons, illustrations
+- **Image Editing**: Photo enhancement, image modifications, visual adjustments
+
+## Invocation Pattern
+
+```javascript
+task(
+  subagent_type="Image Specialist",
+  description="Generate/edit visual content",
+  prompt="Context to load:
+          - .opencode/context/core/visual-development.md
+          
+          Task: [Specific visual requirement]
+          
+          Requirements:
+          - [Visual style/aesthetic]
+          - [Dimensions/format]
+          - [Key elements to include]
+          - [Color scheme/branding]
+          
+          Output: [Expected deliverable]"
+)
+```
+
+## Example Use Cases
+
+### Architecture Diagram
+
+```javascript
+task(
+  subagent_type="Image Specialist",
+  description="Generate microservices architecture diagram",
+  prompt="Create a diagram showing:
+          - 5 microservices (API Gateway, Auth, Orders, Payments, Notifications)
+          - Database connections
+          - Message queue (RabbitMQ)
+          - External services (Stripe, SendGrid)
+          
+          Style: Clean, professional, modern
+          Format: PNG, 1920x1080"
+)
+```
+
+### UI Mockup
+
+```javascript
+task(
+  subagent_type="Image Specialist",
+  description="Generate dashboard mockup",
+  prompt="Create a mockup for an analytics dashboard:
+          - Header with navigation
+          - 4 metric cards (Users, Revenue, Conversion, Retention)
+          - Line chart showing trends
+          - Data table below
+          
+          Style: Modern, dark theme, professional
+          Format: PNG, 1440x900"
+)
+```
+
+### Social Media Graphic
+
+```javascript
+task(
+  subagent_type="Image Specialist",
+  description="Generate product launch graphic",
+  prompt="Create a social media graphic announcing new feature:
+          - Bold headline: 'Introducing Real-Time Collaboration'
+          - Subtext: 'Work together, ship faster'
+          - Brand colors: #6366f1 (primary), #1e293b (dark)
+          - Include abstract collaboration visual
+          
+          Format: PNG, 1200x630 (Twitter/LinkedIn)"
+)
+```
+
+## Tools Required
+
+- **tool:gemini** - Gemini Nano Banana AI for image generation/editing
+- Automatically available in Developer profile
+
+## When NOT to Delegate
+
+**Use design-iteration workflow instead** when:
+- Creating interactive HTML/CSS designs
+- Building complete UI implementations
+- Iterating on existing HTML files
+- Need responsive, production-ready code
+
+**Use image-specialist** when:
+- Need static visual assets
+- Creating diagrams or illustrations
+- Generating mockups for presentation
+- Quick visual concepts without code
+
+---
+
+## Related Files
+
+- [Overview](./design-iteration-overview.md)
+- [Visual Development](../visual-development.md)

+ 461 - 0
plugins/claude-code/scripts/context/core/workflows/external-context-integration.md

@@ -0,0 +1,461 @@
+<!-- Context: workflows/external-context-integration | Priority: high | Version: 1.0 | Updated: 2026-01-28 -->
+# External Context Integration Guide
+
+## Overview
+
+This guide explains how to integrate external context (fetched via ExternalScout) into the main agent workflow so that subagents can access it without re-fetching.
+
+**Key Principle**: Main agents fetch external docs once → persist to disk → reference in session → subagents read (no re-fetching)
+
+---
+
+## When to Use External Context
+
+Use ExternalScout to fetch external context when:
+
+1. **User asks about external libraries** (Drizzle, Better Auth, Next.js, etc.)
+2. **Task involves integration** between multiple external libraries
+3. **Setup or configuration** of external tools is needed
+4. **API patterns or best practices** from external libraries are relevant
+
+**Don't use** when:
+- Question is about internal project code
+- Answer is in `.opencode/context/` (use ContextScout instead)
+- User is asking for general programming concepts
+
+---
+
+## Integration Workflow
+
+### Stage 1: Analyze & Discover (Before Approval)
+
+```
+Main Agent (OpenAgent, etc.)
+  ↓
+  1. Analyze user request
+  ↓
+  2. Identify external libraries mentioned
+  ↓
+  3. Call ContextScout for internal context
+  ↓
+  4. Call ExternalScout for external docs
+     - ExternalScout fetches from Context7 API
+     - ExternalScout persists to .tmp/external-context/
+     - ExternalScout returns file paths
+  ↓
+  5. Capture returned file paths
+  ↓
+  6. Do NOT write anything to disk yet
+```
+
+### Stage 2: Propose Plan (Before Approval)
+
+```
+Main Agent
+  ↓
+  1. Show user lightweight summary:
+     - What will be done
+     - Which external libraries involved
+     - Which context files will be used
+  ↓
+  2. Include discovered external context files in proposal
+  ↓
+  3. Wait for user approval
+```
+
+### Stage 3: Approve (User Gate)
+
+```
+User
+  ↓
+  Approves plan (or redirects)
+```
+
+### Stage 4: Init Session (After Approval)
+
+```
+Main Agent
+  ↓
+  1. Create .tmp/sessions/{session-id}/context.md
+  ↓
+  2. Populate sections:
+     - ## Context Files (from ContextScout)
+     - ## Reference Files (project files)
+     - ## External Context Fetched (from ExternalScout)
+     - ## Components
+     - ## Constraints
+     - ## Exit Criteria
+  ↓
+  3. CRITICAL: Add "## External Context Fetched" section with:
+     - File paths returned by ExternalScout
+     - Brief description of each file
+     - Note that files are read-only
+```
+
+### Stage 5: Delegate with Context Path
+
+```
+Main Agent
+  ↓
+  1. Call TaskManager (or other subagent)
+  ↓
+  2. Pass session path in prompt:
+     "Load context from .tmp/sessions/{session-id}/context.md"
+  ↓
+  3. TaskManager reads session context
+  ↓
+  4. TaskManager extracts external context files
+  ↓
+  5. TaskManager includes in subtask JSONs
+```
+
+### Stage 6: Subagents Read External Context
+
+```
+TaskManager / CoderAgent / TestEngineer
+  ↓
+  1. Read session context file
+  ↓
+  2. Extract "## External Context Fetched" section
+  ↓
+  3. Read referenced files from .tmp/external-context/
+  ↓
+  4. Use external docs to inform implementation
+  ↓
+  5. NO RE-FETCHING ✅
+```
+
+---
+
+## Implementation Details
+
+### Step 1: Call ExternalScout
+
+In your main agent (before approval):
+
+```javascript
+// Detect external libraries from user request
+const externalLibraries = ["drizzle-orm", "better-auth", "next.js"];
+
+// Call ExternalScout
+task(
+  subagent_type="ExternalScout",
+  description="Fetch external documentation",
+  prompt="Fetch documentation for these libraries:
+          - Drizzle ORM: modular schema organization
+          - Better Auth: Next.js integration
+          - Next.js: App Router setup
+          
+          Persist fetched docs to .tmp/external-context/
+          Return file paths for each fetched document"
+)
+
+// Capture returned file paths
+// Example return:
+// - .tmp/external-context/drizzle-orm/modular-schemas.md
+// - .tmp/external-context/better-auth/nextjs-integration.md
+// - .tmp/external-context/next.js/app-router-setup.md
+```
+
+### Step 2: Propose Plan with External Context
+
+```markdown
+## Implementation Plan
+
+**Task**: Set up Drizzle + Better Auth in Next.js
+
+**External Libraries Involved**:
+- Drizzle ORM (database)
+- Better Auth (authentication)
+- Next.js (framework)
+
+**External Context Discovered**:
+- `.tmp/external-context/drizzle-orm/modular-schemas.md`
+- `.tmp/external-context/better-auth/nextjs-integration.md`
+- `.tmp/external-context/next.js/app-router-setup.md`
+
+**Approach**:
+1. Set up Drizzle schema with modular organization
+2. Configure Better Auth with Drizzle adapter
+3. Integrate with Next.js App Router
+
+**Approval needed before proceeding.**
+```
+
+### Step 3: Create Session with External Context
+
+After approval, create `.tmp/sessions/{session-id}/context.md`:
+
+```markdown
+# Task Context: Drizzle + Better Auth Integration
+
+Session ID: 2026-01-28-drizzle-auth
+Created: 2026-01-28T14:30:22Z
+Status: in_progress
+
+## Current Request
+Set up Drizzle ORM with Better Auth in a Next.js application
+
+## Context Files (Standards to Follow)
+- .opencode/context/core/standards/code-quality.md
+- .opencode/context/core/standards/test-coverage.md
+
+## Reference Files (Source Material)
+- package.json
+- src/db/schema.ts (existing)
+- src/auth/config.ts (existing)
+
+## External Context Fetched
+These are live documentation files fetched from external libraries. Subagents should reference these instead of re-fetching.
+
+### Drizzle ORM
+- `.tmp/external-context/drizzle-orm/modular-schemas.md` — Schema organization patterns for modular architecture
+- `.tmp/external-context/drizzle-orm/postgresql-setup.md` — PostgreSQL configuration and setup
+
+### Better Auth
+- `.tmp/external-context/better-auth/nextjs-integration.md` — Integration guide for Next.js App Router
+- `.tmp/external-context/better-auth/drizzle-adapter.md` — Drizzle adapter setup and configuration
+
+### Next.js
+- `.tmp/external-context/next.js/app-router-setup.md` — App Router basics and configuration
+- `.tmp/external-context/next.js/server-actions.md` — Server Actions patterns for mutations
+
+**Important**: These files are read-only and cached for reference. Do not modify them.
+
+## Components
+- Drizzle schema setup with modular organization
+- Better Auth configuration with Drizzle adapter
+- Next.js App Router integration
+
+## Constraints
+- TypeScript strict mode
+- Must support PostgreSQL
+- Backward compatible with existing auth system
+
+## Exit Criteria
+- [ ] Drizzle schema set up with modular organization
+- [ ] Better Auth configured with Drizzle adapter
+- [ ] Next.js App Router integration complete
+- [ ] All tests passing
+- [ ] Documentation updated
+
+## Progress
+- [ ] Session initialized
+- [ ] Tasks created
+- [ ] Implementation complete
+- [ ] Tests passing
+- [ ] Handoff complete
+```
+
+### Step 4: Delegate to TaskManager
+
+```javascript
+task(
+  subagent_type="TaskManager",
+  description="Break down Drizzle + Better Auth integration",
+  prompt="Load context from .tmp/sessions/2026-01-28-drizzle-auth/context.md
+
+          Read the context file for full requirements, standards, and external documentation.
+          
+          Break down this feature into atomic subtasks:
+          1. Drizzle schema setup with modular organization
+          2. Better Auth configuration with Drizzle adapter
+          3. Next.js App Router integration
+          4. Test suite
+          
+          For each subtask, include:
+          - context_files: Standards from context.md
+          - reference_files: Project files to understand
+          - external_context: External docs to reference
+          
+          Create subtask files in tasks/subtasks/drizzle-auth-integration/"
+)
+```
+
+### Step 5: TaskManager Creates Subtasks with External Context
+
+TaskManager creates subtask JSONs like:
+
+```json
+{
+  "id": "01-drizzle-schema-setup",
+  "title": "Set up Drizzle schema with modular organization",
+  "description": "Create modular Drizzle schema following best practices",
+  "context_files": [
+    ".opencode/context/core/standards/code-quality.md",
+    ".opencode/context/core/standards/test-coverage.md"
+  ],
+  "reference_files": [
+    "package.json",
+    "src/db/schema.ts"
+  ],
+  "external_context": [
+    ".tmp/external-context/drizzle-orm/modular-schemas.md",
+    ".tmp/external-context/drizzle-orm/postgresql-setup.md"
+  ],
+  "instructions": "Set up Drizzle schema following modular patterns from external context. Reference .tmp/external-context/drizzle-orm/modular-schemas.md for best practices.",
+  "acceptance_criteria": [
+    "Schema organized into separate files by domain",
+    "PostgreSQL configuration matches external docs",
+    "TypeScript types properly exported",
+    "Tests cover schema setup"
+  ]
+}
+```
+
+### Step 6: CoderAgent Implements Using External Context
+
+CoderAgent reads subtask JSON and:
+
+1. Loads context_files (standards)
+2. Reads reference_files (existing code)
+3. **Reads external_context files** (external docs)
+4. Implements following all standards and external docs
+5. Returns completed subtask
+
+---
+
+## Best Practices
+
+### For Main Agents
+
+✅ **DO**:
+- Call ExternalScout early in planning phase
+- Capture returned file paths
+- Add to session context under "## External Context Fetched"
+- Pass session path to subagents
+- Include external context in proposal to user
+
+❌ **DON'T**:
+- Forget to call ExternalScout when external libraries involved
+- Skip adding external context to session
+- Re-fetch external docs (trust ExternalScout persistence)
+- Modify external context files
+
+### For ExternalScout
+
+✅ **DO**:
+- Always persist fetched docs to `.tmp/external-context/`
+- Update `.manifest.json` after each fetch
+- Include metadata header in every file
+- Filter aggressively to relevant sections
+- Cite sources and include official docs links
+
+❌ **DON'T**:
+- Forget to persist files
+- Skip manifest updates
+- Return entire documentation
+- Fabricate documentation content
+- Write outside `.tmp/external-context/`
+
+### For TaskManager
+
+✅ **DO**:
+- Extract external_context from session context
+- Include in subtask JSONs
+- Pass to downstream agents
+- Document which external docs informed decisions
+
+❌ **DON'T**:
+- Forget to include external_context in subtasks
+- Mix external_context with context_files
+- Assume subagents will re-fetch
+
+### For Subagents (CoderAgent, TestEngineer, etc.)
+
+✅ **DO**:
+- Read external_context files from subtask JSON
+- Use external docs to inform implementation
+- Reference external docs in comments
+- Follow patterns from external docs
+
+❌ **DON'T**:
+- Re-fetch external documentation
+- Ignore external context files
+- Modify external context files
+- Assume external docs are optional
+
+---
+
+## Example: Complete Flow
+
+### User Request
+```
+"Set up Drizzle ORM with Better Auth in Next.js, using modular schema organization"
+```
+
+### Main Agent Flow
+
+1. **Analyze**: Detect Drizzle, Better Auth, Next.js
+2. **Discover**: Call ContextScout + ExternalScout
+3. **Propose**: Show plan with external context files
+4. **Approve**: User approves
+5. **Init Session**: Create context.md with external context section
+6. **Delegate**: Call TaskManager with session path
+7. **Validate**: Check tests pass
+8. **Complete**: Update docs, cleanup
+
+### ExternalScout Flow
+
+1. **Detect**: Drizzle, Better Auth, Next.js
+2. **Fetch**: Get docs from Context7 API
+3. **Filter**: Extract relevant sections
+4. **Persist**: Write to `.tmp/external-context/{package}/{topic}.md`
+5. **Update**: Add to `.manifest.json`
+6. **Return**: File paths to main agent
+
+### TaskManager Flow
+
+1. **Read**: Session context.md
+2. **Extract**: External context files
+3. **Create**: Subtasks with external_context field
+4. **Delegate**: Pass to CoderAgent
+
+### CoderAgent Flow
+
+1. **Read**: Subtask JSON
+2. **Load**: context_files (standards)
+3. **Reference**: reference_files (existing code)
+4. **Read**: external_context files (external docs)
+5. **Implement**: Following all standards and external docs
+6. **Complete**: Return implemented subtask
+
+---
+
+## Troubleshooting
+
+### External Context Files Not Found
+
+**Problem**: Subagent can't find `.tmp/external-context/{package}/{topic}.md`
+
+**Solution**:
+1. Check ExternalScout ran successfully
+2. Verify file path in session context matches actual location
+3. Check `.manifest.json` to see what's cached
+4. If missing, re-run ExternalScout
+
+### Stale External Context
+
+**Problem**: External docs are outdated
+
+**Solution**:
+1. Delete stale files: `scripts/external-context/manage-external-context.sh delete-package {package}`
+2. Re-run ExternalScout to fetch fresh docs
+3. Update session context with new file paths
+
+### Manifest Out of Sync
+
+**Problem**: `.manifest.json` doesn't match actual files
+
+**Solution**:
+1. Regenerate manifest: `scripts/external-context/manage-external-context.sh regenerate-manifest`
+2. Verify all files have metadata headers
+
+---
+
+## References
+
+- **ExternalScout**: `.opencode/agent/subagents/core/externalscout.md`
+- **External Context Management**: `.opencode/context/core/workflows/external-context-management.md`
+- **Task Delegation**: `.opencode/context/core/workflows/task-delegation-basics.md`
+- **Management Script**: `scripts/external-context/manage-external-context.sh`

+ 406 - 0
plugins/claude-code/scripts/context/core/workflows/external-context-management.md

@@ -0,0 +1,406 @@
+<!-- Context: workflows/external-context | Priority: high | Version: 1.0 | Updated: 2026-01-28 -->
+# External Context Management
+
+## Overview
+
+External context is live documentation fetched from external libraries and frameworks (via Context7 API or official docs). Instead of re-fetching on every task, we **persist external context** to `.tmp/external-context/` so main agents can pass it to subagents.
+
+**Key Principle**: ExternalScout fetches once → persists to disk → main agents reference → subagents read (no re-fetching)
+
+---
+
+## Directory Structure
+
+```
+.tmp/external-context/
+├── .manifest.json                    # Metadata about all cached external docs
+├── drizzle-orm/
+│   ├── modular-schemas.md           # Fetched: "How to organize schemas modularly"
+│   ├── postgresql-setup.md          # Fetched: "PostgreSQL setup with Drizzle"
+│   └── typescript-config.md         # Fetched: "TypeScript configuration"
+├── better-auth/
+│   ├── nextjs-integration.md        # Fetched: "Better Auth + Next.js setup"
+│   ├── drizzle-adapter.md           # Fetched: "Drizzle adapter for Better Auth"
+│   └── session-management.md        # Fetched: "Session handling"
+├── next.js/
+│   ├── app-router-setup.md          # Fetched: "App Router basics"
+│   ├── server-actions.md            # Fetched: "Server Actions patterns"
+│   └── middleware.md                # Fetched: "Middleware configuration"
+└── tanstack-query/
+    ├── server-components.md         # Fetched: "TanStack Query + Server Components"
+    └── prefetching.md               # Fetched: "Prefetching strategies"
+```
+
+### Naming Conventions
+
+- **Package name** (directory): Exact npm package name (kebab-case)
+  - ✅ `drizzle-orm`, `better-auth`, `next.js`, `@tanstack/react-query`
+  - ❌ `drizzle`, `nextjs`, `tanstack-query`
+
+- **File name** (topic): Kebab-case description of the topic
+  - ✅ `modular-schemas.md`, `nextjs-integration.md`, `server-components.md`
+  - ❌ `modular schemas.md`, `NextJS Integration.md`, `ServerComponents.md`
+
+---
+
+## Manifest File
+
+**Location**: `.tmp/external-context/.manifest.json`
+
+**Purpose**: Track what's cached, when it was fetched, and from which source
+
+**Structure**:
+```json
+{
+  "last_updated": "2026-01-28T14:30:22Z",
+  "packages": {
+    "drizzle-orm": {
+      "files": [
+        "modular-schemas.md",
+        "postgresql-setup.md",
+        "typescript-config.md"
+      ],
+      "last_updated": "2026-01-28T14:30:22Z",
+      "source": "Context7 API",
+      "official_docs": "https://orm.drizzle.team"
+    },
+    "better-auth": {
+      "files": [
+        "nextjs-integration.md",
+        "drizzle-adapter.md",
+        "session-management.md"
+      ],
+      "last_updated": "2026-01-28T14:25:10Z",
+      "source": "Context7 API",
+      "official_docs": "https://better-auth.com"
+    },
+    "next.js": {
+      "files": [
+        "app-router-setup.md",
+        "server-actions.md",
+        "middleware.md"
+      ],
+      "last_updated": "2026-01-28T14:20:05Z",
+      "source": "Context7 API",
+      "official_docs": "https://nextjs.org"
+    }
+  }
+}
+```
+
+---
+
+## File Format
+
+Each external context file has a metadata header followed by the documentation content.
+
+**Template**:
+```markdown
+---
+source: Context7 API
+library: Drizzle ORM
+package: drizzle-orm
+topic: modular-schemas
+fetched: 2026-01-28T14:30:22Z
+official_docs: https://orm.drizzle.team/docs/goodies#multi-file-schemas
+---
+
+# Modular Schemas in Drizzle ORM
+
+[Filtered documentation content from Context7 API]
+
+## Key Concepts
+
+[Relevant sections only]
+
+## Code Examples
+
+[Practical examples from official docs]
+
+---
+
+**Source**: Context7 API (live, version-specific)
+**Official Docs**: https://orm.drizzle.team/docs/goodies#multi-file-schemas
+**Fetched**: 2026-01-28T14:30:22Z
+```
+
+---
+
+## Workflow: How External Context Flows
+
+### Stage 1: Main Agent Needs External Context
+
+```
+Main Agent (e.g., OpenAgent)
+  ↓
+  Detects: "User is asking about Drizzle + Better Auth + Next.js"
+  ↓
+  Calls: ExternalScout to fetch live docs
+```
+
+### Stage 2: ExternalScout Fetches & Persists
+
+```
+ExternalScout
+  ↓
+  1. Detects libraries: Drizzle, Better Auth, Next.js
+  ↓
+  2. Fetches from Context7 API (primary) or official docs (fallback)
+  ↓
+  3. Filters to relevant sections
+  ↓
+  4. Persists to .tmp/external-context/{package-name}/{topic}.md
+  ↓
+  5. Updates .manifest.json
+  ↓
+  Returns: File paths + formatted documentation
+```
+
+### Stage 3: Main Agent References in Session Context
+
+```
+Main Agent
+  ↓
+  Creates session: .tmp/sessions/{session-id}/context.md
+  ↓
+  Adds section: "## External Context Fetched"
+  ↓
+  Lists files:
+    - .tmp/external-context/drizzle-orm/modular-schemas.md
+    - .tmp/external-context/better-auth/nextjs-integration.md
+    - .tmp/external-context/next.js/app-router-setup.md
+  ↓
+  Delegates to TaskManager with session path
+```
+
+### Stage 4: Subagents Read External Context
+
+```
+TaskManager (or CoderAgent, TestEngineer, etc.)
+  ↓
+  Reads: .tmp/sessions/{session-id}/context.md
+  ↓
+  Extracts: "## External Context Fetched" section
+  ↓
+  Reads: .tmp/external-context/{package-name}/{topic}.md files
+  ↓
+  Uses: External docs to inform implementation
+  ↓
+  NO RE-FETCHING needed ✅
+```
+
+---
+
+## Integration with Task Delegation
+
+### In Session Context File
+
+Add this section to `.tmp/sessions/{session-id}/context.md`:
+
+```markdown
+## External Context Fetched
+
+These are live documentation files fetched from external libraries. Subagents should reference these instead of re-fetching.
+
+### Drizzle ORM
+- `.tmp/external-context/drizzle-orm/modular-schemas.md` — Schema organization patterns
+- `.tmp/external-context/drizzle-orm/postgresql-setup.md` — PostgreSQL configuration
+
+### Better Auth
+- `.tmp/external-context/better-auth/nextjs-integration.md` — Next.js integration guide
+- `.tmp/external-context/better-auth/drizzle-adapter.md` — Drizzle adapter setup
+
+### Next.js
+- `.tmp/external-context/next.js/app-router-setup.md` — App Router basics
+- `.tmp/external-context/next.js/server-actions.md` — Server Actions patterns
+
+**Important**: These files are read-only and should not be modified. They're cached for reference only.
+```
+
+### In Subtask JSONs (Created by TaskManager)
+
+When TaskManager creates subtask JSONs, it should include external context files:
+
+```json
+{
+  "id": "01-drizzle-schema-setup",
+  "title": "Set up Drizzle schema with modular organization",
+  "context_files": [
+    ".opencode/context/core/standards/code-quality.md",
+    ".opencode/context/core/standards/test-coverage.md"
+  ],
+  "reference_files": [
+    "package.json",
+    "src/db/schema.ts"
+  ],
+  "external_context": [
+    ".tmp/external-context/drizzle-orm/modular-schemas.md",
+    ".tmp/external-context/drizzle-orm/postgresql-setup.md"
+  ],
+  "instructions": "Set up Drizzle schema following modular patterns from external context..."
+}
+```
+
+---
+
+## Cleanup & Maintenance
+
+### When to Clean Up
+
+External context files should be cleaned up when:
+1. Task is complete and session is deleted
+2. External docs become stale (>7 days old)
+3. User explicitly requests cleanup
+4. Disk space is needed
+
+### How to Clean Up
+
+**Manual cleanup** (ask user first):
+```bash
+rm -rf .tmp/external-context/{package-name}/
+# Update .manifest.json to remove package entry
+```
+
+**Automatic cleanup** (future enhancement):
+- Add cleanup script that removes files older than 7 days
+- Run as part of session cleanup process
+- Update manifest after cleanup
+
+### Manifest Cleanup
+
+After deleting external context files, update `.manifest.json`:
+```json
+{
+  "last_updated": "2026-01-28T15:00:00Z",
+  "packages": {
+    // Remove entries for deleted packages
+  }
+}
+```
+
+---
+
+## Best Practices
+
+### For Main Agents (OpenAgent, etc.)
+
+1. **Call ExternalScout early** in the planning phase
+2. **Capture returned file paths** from ExternalScout
+3. **Add to session context** in "## External Context Fetched" section
+4. **Pass session path to subagents** so they know where to find external docs
+5. **Don't re-fetch** — trust that ExternalScout persisted correctly
+
+### For ExternalScout
+
+1. **Always persist** fetched documentation to `.tmp/external-context/`
+2. **Update manifest** after each fetch
+3. **Include metadata header** in every file (source, library, package, topic, fetched timestamp)
+4. **Filter aggressively** — only include relevant sections
+5. **Cite sources** — include official docs links
+
+### For Subagents (TaskManager, CoderAgent, etc.)
+
+1. **Read external context files** from session context
+2. **Don't re-fetch** — use persisted files
+3. **Reference in implementation** — cite which external docs informed decisions
+4. **Don't modify** external context files — they're read-only
+5. **Include in subtask JSONs** — pass external_context to downstream agents
+
+---
+
+## Examples
+
+### Example 1: Drizzle + Better Auth Integration
+
+**Main Agent Flow**:
+```
+1. User asks: "Set up Drizzle + Better Auth in Next.js"
+2. Main agent calls ExternalScout
+3. ExternalScout fetches:
+   - drizzle-orm/modular-schemas.md
+   - drizzle-orm/postgresql-setup.md
+   - better-auth/nextjs-integration.md
+   - better-auth/drizzle-adapter.md
+   - next.js/app-router-setup.md
+4. ExternalScout persists all files to .tmp/external-context/
+5. Main agent creates session with "## External Context Fetched" section
+6. Main agent delegates to TaskManager with session path
+7. TaskManager reads external context, creates subtasks
+8. CoderAgent implements using external docs (no re-fetching)
+```
+
+**Session Context File**:
+```markdown
+## External Context Fetched
+
+### Drizzle ORM
+- `.tmp/external-context/drizzle-orm/modular-schemas.md`
+- `.tmp/external-context/drizzle-orm/postgresql-setup.md`
+
+### Better Auth
+- `.tmp/external-context/better-auth/nextjs-integration.md`
+- `.tmp/external-context/better-auth/drizzle-adapter.md`
+
+### Next.js
+- `.tmp/external-context/next.js/app-router-setup.md`
+```
+
+### Example 2: TanStack Query + Server Components
+
+**Main Agent Flow**:
+```
+1. User asks: "How do I use TanStack Query with Next.js Server Components?"
+2. Main agent calls ExternalScout
+3. ExternalScout fetches:
+   - tanstack-query/server-components.md
+   - tanstack-query/prefetching.md
+   - next.js/server-components.md
+4. ExternalScout persists to .tmp/external-context/
+5. Main agent creates session with external context references
+6. Subagents read and implement using external docs
+```
+
+---
+
+## Troubleshooting
+
+### External Context Files Not Found
+
+**Problem**: Subagent can't find `.tmp/external-context/{package-name}/{topic}.md`
+
+**Solution**:
+1. Check that ExternalScout ran successfully
+2. Verify file path in session context matches actual file location
+3. Check `.manifest.json` to see what's cached
+4. If missing, re-run ExternalScout to fetch and persist
+
+### Stale External Context
+
+**Problem**: External docs are outdated (>7 days old)
+
+**Solution**:
+1. Delete stale files: `rm -rf .tmp/external-context/{package-name}/`
+2. Update `.manifest.json`
+3. Re-run ExternalScout to fetch fresh docs
+4. Update session context with new file paths
+
+### Manifest Out of Sync
+
+**Problem**: `.manifest.json` doesn't match actual files
+
+**Solution**:
+1. Regenerate manifest by listing actual files:
+   ```bash
+   find .tmp/external-context -name "*.md" | sort
+   ```
+2. Update `.manifest.json` to match
+3. Verify all files have metadata headers
+
+---
+
+## References
+
+- **ExternalScout**: `.opencode/agent/subagents/core/externalscout.md` — Fetches and persists external docs
+- **Task Delegation**: `.opencode/context/core/workflows/task-delegation-basics.md` — How to reference external context in sessions
+- **Session Management**: `.opencode/context/core/workflows/session-management.md` — Session lifecycle
+- **Library Registry**: `.opencode/skills/context7/library-registry.md` — Supported libraries and query patterns

+ 165 - 0
plugins/claude-code/scripts/context/core/workflows/external-libraries-faq.md

@@ -0,0 +1,165 @@
+<!-- Context: workflows/external-libraries-faq | Priority: medium | Version: 1.0 | Updated: 2026-02-05 -->
+# External Libraries: FAQ
+
+**Purpose**: Troubleshooting and common questions about ExternalScout
+
+---
+
+## When exactly should I use ExternalScout?
+
+**ALWAYS when working with external packages.**
+
+**Triggers:**
+- User mentions library
+- `import`/`require` statements
+- package.json deps
+- Build errors
+- First-time setup
+- Version upgrades
+
+**Rule**: If it's not in `.opencode/context/`, use ExternalScout.
+
+---
+
+## What if I already know the library?
+
+**DON'T rely on training data - it's outdated.**
+
+Example: You think "I know Next.js, I'll use pages/"  
+Reality: Next.js 15 uses app/  
+Result: Broken code ❌
+
+**Always fetch current docs, even if you "know" the library.**
+
+---
+
+## How do I know if something is external?
+
+**External:** npm/pip/gem/cargo packages | Third-party frameworks | ORMs | Auth libraries | UI libraries
+
+**NOT external:** Your project's code | Project utilities | Internal modules
+
+**Check:** Is it in `package.json` dependencies? → External → Use ExternalScout
+
+---
+
+## Can I use both ContextScout and ExternalScout?
+
+**YES! Use both for most features.**
+
+```javascript
+// 1. ContextScout: Project standards
+task(subagent_type="ContextScout", ...)
+
+// 2. ExternalScout: Library docs  
+task(subagent_type="ExternalScout", ...)
+
+// 3. Combine: Implement using both
+```
+
+---
+
+## What if ExternalScout doesn't have the library?
+
+ExternalScout has two sources:
+1. **Context7 API** (primary): 50+ popular libraries
+2. **Official docs** (fallback): Any library with public docs
+
+If library not in Context7: Auto-fallback to official docs via webfetch.
+
+---
+
+## How do I write a good ExternalScout prompt?
+
+**Template:**
+```javascript
+task(
+  subagent_type="ExternalScout",
+  description="Fetch [Library] docs for [specific topic]",
+  prompt="Fetch current documentation for [Library]: [specific question]
+  
+  Focus on:
+  - [What you need - be specific]
+  - [Related features/APIs]
+  
+  Context: [What you're building]"
+)
+```
+
+**Good:** ✅ Specific | ✅ Focused (3-5 things) | ✅ Contextual
+**Bad:** ❌ Vague | ❌ Too broad | ❌ No context
+
+---
+
+## What if I get an error after using ExternalScout?
+
+**Process:**
+1. Read error message carefully
+2. ExternalScout again with specific error:
+```javascript
+task(
+  subagent_type="ExternalScout",
+  description="Fetch docs for error resolution",
+  prompt="Fetch [Library] docs: [error message]
+  Error: [paste actual error]
+  Focus on: Common causes | Solutions"
+)
+```
+3. Check install scripts (maybe setup incomplete)
+4. Verify versions (package.json vs docs)
+
+---
+
+## Do I need approval to use ExternalScout?
+
+**NO - ExternalScout is read-only, no approval required.**
+
+**Approval required:** ❌ Write code | ❌ Run commands | ❌ Install packages
+**No approval:** ✅ ContextScout | ✅ ExternalScout | ✅ Read files
+
+---
+
+## ContextScout vs ExternalScout?
+
+| Aspect | ContextScout | ExternalScout |
+|--------|--------------|---------------|
+| **Searches** | Internal project files | External documentation |
+| **Location** | `.opencode/context/` | Internet (Context7, docs) |
+| **Returns** | Project standards | Library APIs |
+| **Use for** | "How we do things here" | "How this library works" |
+| **Speed** | Fast (local) | Slower (network) |
+
+**Use both together for best results.**
+
+---
+
+## Quick Checklist
+
+Before implementing with external libraries:
+
+- [ ] Used ContextScout for project standards?
+- [ ] Checked for install scripts first?
+- [ ] Used ExternalScout for EACH external library?
+- [ ] Asked for installation steps?
+- [ ] Asked for current API patterns?
+- [ ] Read returned docs before coding?
+
+**All checked? → You're doing it right! ✅**
+
+---
+
+## Supported Libraries
+
+**See**: `.opencode/skills/context7/library-registry.md`
+
+**Categories:** Database/ORM | Auth | Frontend | Infrastructure | UI | State | Validation | Testing
+
+Not listed? ExternalScout can still fetch from official docs.
+
+---
+
+## Related
+
+- `external-libraries-workflow.md` - Core workflow
+- `external-libraries-scenarios.md` - Common scenarios
+- `.opencode/agent/subagents/core/externalscout.md` - ExternalScout agent

+ 130 - 0
plugins/claude-code/scripts/context/core/workflows/external-libraries-scenarios.md

@@ -0,0 +1,130 @@
+<!-- Context: workflows/external-libraries-scenarios | Priority: medium | Version: 1.0 | Updated: 2026-02-05 -->
+# External Libraries: Common Scenarios
+
+**Purpose**: Real-world examples of using ExternalScout
+
+---
+
+## Scenario 1: New Build with External Packages
+
+**Example**: Next.js app with Drizzle + Better Auth
+
+**Process:**
+1. Check install scripts: `ls scripts/install/`
+2. Identify packages: Next.js, Drizzle ORM, Better Auth
+3. ExternalScout for each package
+4. Check requirements: PostgreSQL? Env vars?
+5. Verify version compatibility
+6. Implement following current docs
+7. Test integration points
+
+**ExternalScout calls:**
+```javascript
+// Drizzle ORM
+task(
+  subagent_type="ExternalScout",
+  description="Fetch Drizzle PostgreSQL setup",
+  prompt="Fetch Drizzle ORM docs: PostgreSQL setup w/ modular schemas
+  Focus on: Installation | DB connection | Schema patterns | Migrations
+  Context: Next.js commerce site w/ PostgreSQL"
+)
+
+// Next.js App Router
+task(
+  subagent_type="ExternalScout",
+  description="Fetch Next.js App Router docs",
+  prompt="Fetch Next.js docs: App Router w/ Server Actions
+  Focus on: Installation | Directory structure | Server Actions
+  Context: Commerce site w/ order processing"
+)
+```
+
+---
+
+## Scenario 2: Package Error During Build
+
+**Example**: `Error: Cannot find module 'drizzle-orm/pg-core'`
+
+**Process:**
+1. Identify package: Drizzle ORM
+2. ExternalScout: "Fetch Drizzle docs: PostgreSQL imports"
+3. Check current import patterns
+4. Verify package.json has correct deps
+5. Propose fix from current docs
+6. Request approval → Apply fix
+
+---
+
+## Scenario 3: First-Time Package Setup
+
+**Example**: Setting up TanStack Query in Next.js
+
+**Process:**
+1. Check install scripts
+2. ExternalScout: "Fetch TanStack Query docs: Next.js App Router setup"
+3. Get: Install steps | Peer deps | Config | Patterns
+4. If install script exists: Review → Run
+5. If no script: Follow docs for manual setup
+6. Implement → Test
+
+---
+
+## Scenario 4: Version Upgrade
+
+**Example**: Next.js 14 → 15
+
+**Process:**
+1. ExternalScout: "Fetch Next.js 15 docs: Breaking changes and migration"
+2. Review breaking changes
+3. Identify affected code
+4. Plan migration steps
+5. Request approval → Implement → Test
+
+---
+
+## Real-World Example: Auth Implementation
+
+**Task**: "Add authentication with Better Auth to Next.js commerce"
+
+```javascript
+// 1. ContextScout: Project standards
+task(
+  subagent_type="ContextScout",
+  description="Find auth standards",
+  prompt="Find context files: Auth patterns | Security standards"
+)
+// Returns: security-patterns.md, code-quality.md
+
+// 2. ExternalScout: Better Auth docs (MANDATORY)
+task(
+  subagent_type="ExternalScout",
+  description="Fetch Better Auth + Next.js docs",
+  prompt="Fetch Better Auth docs: Next.js App Router integration
+  Focus on: Installation | App Router setup | Drizzle adapter | Session mgmt
+  Context: Adding auth to Next.js commerce w/ Drizzle ORM"
+)
+// Returns: Installation | Integration patterns | Working examples
+
+// 3. Combine and implement
+// - Better Auth patterns (from ExternalScout)
+// - Security standards (from ContextScout)
+// = Secure, well-structured auth ✅
+```
+
+---
+
+## Error Handling Patterns
+
+| Error Type | Process |
+|------------|---------|
+| **Package Installation** | ExternalScout: installation docs → Verify package name/version → Check peer deps |
+| **Import/Module** | ExternalScout: import patterns → Check current API exports |
+| **API/Configuration** | ExternalScout: API docs → Check current signatures |
+| **Build Errors** | Identify package → ExternalScout: relevant docs → Check known issues |
+
+---
+
+## Related
+
+- `external-libraries-workflow.md` - Core workflow
+- `external-libraries-faq.md` - Troubleshooting FAQ

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor