Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(cos): add task-type skill templates for M40-P1
Adam Eivy3b4ced6a0204
diff --git a/.changelog/v0.12.x.md b/.changelog/v0.12.x.mdindex b2a7926470..4c1b10b7bc 100644--- a/.changelog/v0.12.x.md+++ b/.changelog/v0.12.x.md@@ -442,7 +442,7 @@ This release adds branch management and automated release workflow capabilities- `client/src/components/city/CityScene.jsx` — Integrated all 5 new scene layers, extended orbit range### M40: Agent Skill System — In Progress-- **Task-type-specific prompt templates**: New `data/prompts/skills/` directory with specialized agent briefings per task category (bug-fix, feature, security-audit, refactor, documentation, mobile-responsive) — each with routing descriptions, embedded examples, and task-specific guidelines to improve agent accuracy+- **Task-type-specific prompt templates** ✅: New `data/prompts/skills/` directory with 6 specialized agent briefings per task category (bug-fix, feature, security-audit, refactor, documentation, mobile-responsive) — each with routing descriptions, embedded examples, and task-specific guidelines. `buildAgentPrompt()` now detects skill type via keyword matching and injects the matched template into the agent briefing. Templates only load when matched to avoid token inflation.- **Agent context compaction** ✅: Context-limit and output-limit error patterns now include compaction metadata (output size, retry hints) that propagates through task retry metadata. When an agent retries after a context-limit failure, the briefing prompt includes a "Context Compaction Required" section with mandatory output constraints. Agent briefing template updated with task-type-specific output format constraints for documentation, refactors, security audits, and bug fixes.- **Negative example routing**: Anti-pattern recording in task learning so failed model/task-type combinations are tracked and auto-avoided, with routing accuracy surfaced in the Learning tab- **Deterministic workflow skills**: Recurring autonomous jobs (daily briefing, git maintenance, security audit, app improvement) converted from inline prompts to versioned, editable skill templates with defined steps, outputs, and success criteriadiff --git a/PLAN.md b/PLAN.mdindex 9d739756b7..637bec8d7e 100644--- a/PLAN.md+++ b/PLAN.md@@ -119,16 +119,18 @@ Based on recent work and incomplete milestones:Inspired by [OpenAI Skills & Shell Tips](https://developers.openai.com/blog/skills-shell-tips), this milestone improves CoS agent accuracy and reliability through better task routing, prompt specificity, and context management.-### P1: Task-Type-Specific Agent Prompts (Skill Templates)-Currently all agents use the same generic `cos-agent-briefing.md` prompt template regardless of task type. Create specialized prompt templates per task category that include:-- **Routing descriptions**: "Use when..." / "Don't use when..." sections that help the system match tasks to the right skill template-- **Embedded examples**: Worked examples of successful completions for that task type (bug fix, feature, security audit, etc.)-- **Task-specific guidelines**: E.g., security audit skills include OWASP checklist; feature skills include test requirements; refactor skills include before/after patterns--**Implementation**:-- Add a `data/prompts/skills/` directory with task-type templates (e.g., `bug-fix.md`, `feature.md`, `security-audit.md`, `refactor.md`, `documentation.md`, `mobile-responsive.md`)-- Update `buildAgentPrompt()` in `subAgentSpawner.js` to select the appropriate skill template based on task type/description keywords-- Each template loaded only when matched (avoids token inflation for unrelated tasks)+### P1: Task-Type-Specific Agent Prompts (Skill Templates) ✅+Created specialized prompt templates per task category with routing, examples, and guidelines:+- **Routing descriptions**: "Use when..." / "Don't use when..." sections in each skill template+- **Embedded examples**: Worked examples of successful completions for each task type+- **Task-specific guidelines**: Security audit includes OWASP checklist; feature includes validation/convention requirements; refactor emphasizes behavior preservation++**Implemented**:+- Added `data/prompts/skills/` directory with 6 task-type templates: `bug-fix.md`, `feature.md`, `security-audit.md`, `refactor.md`, `documentation.md`, `mobile-responsive.md`+- Added `detectSkillTemplate()` and `loadSkillTemplate()` in `subAgentSpawner.js` with keyword-based matching (ordered by specificity — security/mobile before generic bug-fix/feature)+- Updated `buildAgentPrompt()` to inject matched skill template into both the Mustache template system and the fallback template+- Updated `cos-agent-briefing.md` with `{{#skillSection}}` conditional block+- Templates only loaded when matched to avoid token inflation### P2: Agent Context Compaction ✅Long-running agents can hit context limits causing failures. Add proactive context management:diff --git a/data.sample/prompts/skills/bug-fix.md b/data.sample/prompts/skills/bug-fix.mdnew file mode 100644index 0000000000..056dc1edc0--- /dev/null+++ b/data.sample/prompts/skills/bug-fix.md@@ -0,0 +1,45 @@+# Bug Fix Skill Template++## Routing+**Use when**: Task description contains keywords like "fix", "bug", "broken", "error", "crash", "issue", "not working", "fails", "regression", "defect", "wrong", "incorrect"+**Don't use when**: Task is about adding new functionality, refactoring for style, or writing documentation without a specific bug to fix++## Task-Specific Guidelines++You are fixing a bug. Follow this systematic debugging approach:++### 1. Reproduce First+- Read the task description carefully to understand the expected vs actual behavior+- Identify the affected code path before making changes+- If test commands are available, run existing tests to see current failures++### 2. Root Cause Analysis+- Trace the issue from symptom to source — don't just patch the symptom+- Check git blame or recent commits if the bug is a regression+- Look for related issues in nearby code that might have the same root cause++### 3. Fix With Minimal Impact+- Make the smallest change that correctly fixes the issue+- Do NOT refactor surrounding code — fix only the bug+- Do NOT add features or "improvements" alongside the fix+- Preserve existing behavior for all non-buggy code paths++### 4. Verify the Fix+- Run tests after your change to confirm the fix+- If no tests cover this path, consider adding a focused test for the specific bug+- Check that you haven't introduced regressions in related functionality++### 5. Commit Message Format+Use prefix: `fix(scope): description`++## Example: Successful Bug Fix++**Task**: "Fix: API returns 500 when user email is null"++**What the agent did**:+1. Read the error logs and traced to `server/routes/users.js:45` where `user.email.toLowerCase()` throws on null+2. Added a null check: `const email = user.email?.toLowerCase() || ''`+3. Ran `npm test` — 14 passed, 0 failed+4. Committed: `fix(users): handle null email in user lookup`++**Why it succeeded**: Found root cause, minimal fix, verified with tests, didn't touch unrelated code.diff --git a/data.sample/prompts/skills/documentation.md b/data.sample/prompts/skills/documentation.mdnew file mode 100644index 0000000000..d000849f59--- /dev/null+++ b/data.sample/prompts/skills/documentation.md@@ -0,0 +1,50 @@+# Documentation Skill Template++## Routing+**Use when**: Task description contains keywords like "document", "documentation", "docs", "readme", "jsdoc", "comment", "explain", "describe", "api docs", "guide", "tutorial", "changelog", "wiki"+**Don't use when**: Task is primarily about code changes with documentation as a side note, or task just needs inline code comments++## Task-Specific Guidelines++You are writing or updating documentation. Focus on clarity, accuracy, and usefulness.++### 1. Understand the Audience+- Developer documentation: assume familiarity with the tech stack+- User documentation: assume no codebase knowledge+- API documentation: include request/response examples+- Architecture docs: include the "why" behind decisions++### 2. Accuracy First+- Read the actual code before documenting it — never guess at behavior+- Test any commands or code snippets you include+- Verify file paths, function signatures, and configuration options exist+- If behavior is ambiguous, check the implementation rather than assuming++### 3. Documentation Style+- Use clear, direct language — avoid jargon when simpler words work+- Include practical examples for every concept+- Structure with headers for scanability+- Keep sections focused — one topic per section+- Use code blocks with language identifiers for syntax highlighting++### 4. What NOT to Do+- Don't document obvious code (e.g., `// increment counter` above `counter++`)+- Don't create documentation files unless explicitly requested+- Don't add JSDoc to functions you didn't write or modify+- Don't duplicate information that exists elsewhere — link to it instead++### 5. Commit Message Format+Use prefix: `docs(scope): description`++## Example: Successful Documentation Task++**Task**: "Document the WebSocket events used between client and server"++**What the agent did**:+1. Read `server/services/socket.js` and `client/src/services/socket.js` to catalog all events+2. Found 12 events: 6 server→client, 4 client→server, 2 bidirectional+3. Created a table with event name, direction, payload shape, and when it fires+4. Added code examples showing how to listen/emit each event+5. Committed: `docs(websocket): document all socket events with payload shapes`++**Why it succeeded**: Derived documentation from actual code, structured for quick reference, included practical examples.diff --git a/data.sample/prompts/skills/feature.md b/data.sample/prompts/skills/feature.mdnew file mode 100644index 0000000000..0fbbeeb349--- /dev/null+++ b/data.sample/prompts/skills/feature.md@@ -0,0 +1,51 @@+# Feature Implementation Skill Template++## Routing+**Use when**: Task description contains keywords like "add", "create", "implement", "build", "new", "feature", "support", "enable", "integrate", "endpoint", "page", "component"+**Don't use when**: Task is fixing a bug, refactoring existing code, or writing documentation for existing features++## Task-Specific Guidelines++You are implementing a new feature. Follow this structured approach:++### 1. Understand the Requirements+- Parse the task description for explicit and implicit requirements+- Identify the scope boundary — what's included and what's NOT+- Check for existing patterns in the codebase that your feature should follow++### 2. Plan Before Coding+- Identify all files that need to be created or modified+- Follow existing architectural patterns (routes → services → data layer)+- Check if similar features exist and mirror their structure+- Plan the API contract (if adding endpoints) before writing implementation++### 3. Implementation Order+- Start with data layer / backend logic+- Add route/API handlers with Zod validation+- Add client-side service calls+- Add UI components last+- Follow existing code conventions exactly — match spacing, naming, patterns++### 4. Quality Checklist+- All new routes must have Zod validation+- No hardcoded localhost — use `window.location.hostname`+- Full URL route paths for any new UI views (no modals without deep links)+- No try/catch — let errors bubble to centralized middleware+- Single-line emoji-prefixed logging for server code++### 5. Commit Message Format+Use prefix: `feat(scope): description`++## Example: Successful Feature Implementation++**Task**: "Add a health check endpoint that returns system uptime and version"++**What the agent did**:+1. Read existing routes to understand patterns (`server/routes/system.js`)+2. Added `GET /api/health` route with Zod response schema+3. Created service function `getHealthStatus()` returning `{ uptime, version, timestamp }`+4. Added `console.log('🏥 Health check requested')` logging+5. Ran `npm test` — all passing+6. Committed: `feat(system): add health check endpoint with uptime and version`++**Why it succeeded**: Followed existing patterns, proper validation, no over-engineering, clean logging.diff --git a/data.sample/prompts/skills/mobile-responsive.md b/data.sample/prompts/skills/mobile-responsive.mdnew file mode 100644index 0000000000..bc123e0c0d--- /dev/null+++ b/data.sample/prompts/skills/mobile-responsive.md@@ -0,0 +1,58 @@+# Mobile Responsive Skill Template++## Routing+**Use when**: Task description contains keywords like "mobile", "responsive", "tablet", "breakpoint", "viewport", "touch", "swipe", "small screen", "media query", "mobile-friendly", "adaptive", "layout"+**Don't use when**: Task is about desktop-only features, backend changes, or general CSS styling unrelated to responsiveness++## Task-Specific Guidelines++You are making UI components responsive or fixing mobile layout issues.++### 1. Understand the Current State+- Check existing Tailwind breakpoint usage in the component and its parents+- Identify which elements need to reflow, resize, or hide on smaller screens+- Test the current layout at common breakpoints: 375px (mobile), 768px (tablet), 1024px (desktop)++### 2. Tailwind-First Approach+- Use Tailwind responsive prefixes: `sm:`, `md:`, `lg:`, `xl:`+- Mobile-first design: base styles are mobile, add complexity at larger breakpoints+- Use `flex` and `grid` for layout — avoid fixed widths+- Use `w-full`, `max-w-*`, and `min-w-0` to prevent overflow+- Use `truncate` or `line-clamp-*` for text that might overflow on mobile++### 3. Common Responsive Patterns+- **Navigation**: Collapse to hamburger menu or bottom nav on mobile+- **Tables**: Horizontal scroll wrapper (`overflow-x-auto`) or card layout on mobile+- **Side panels**: Stack vertically on mobile (`flex-col md:flex-row`)+- **Forms**: Full-width inputs on mobile, multi-column on desktop+- **Modals/Dialogs**: Full-screen on mobile, centered overlay on desktop++### 4. Touch Considerations+- Minimum touch target: 44x44px (use `min-h-[44px] min-w-[44px]`)+- Add appropriate spacing between interactive elements+- Ensure hover-only interactions have touch alternatives+- Use `touch-manipulation` for better touch responsiveness++### 5. Design Token Compliance+Use project design tokens:+- Backgrounds: `bg-port-bg`, `bg-port-card`+- Borders: `border-port-border`+- Colors: `text-port-accent`, `text-port-success`, `text-port-warning`, `text-port-error`++### 6. Commit Message Format+Use prefix: `style(scope): description` or `fix(scope): description` for layout bugs++## Example: Successful Mobile Responsive Task++**Task**: "Make the settings page responsive for mobile devices"++**What the agent did**:+1. Read `client/src/pages/Settings.jsx` — found fixed-width sidebar and content area+2. Changed layout from `flex-row` to `flex-col md:flex-row`+3. Made sidebar full-width on mobile with horizontal scroll for tabs+4. Converted settings grid from `grid-cols-3` to `grid-cols-1 md:grid-cols-2 lg:grid-cols-3`+5. Added `overflow-x-auto` to data tables+6. Ensured all touch targets met 44px minimum+7. Committed: `style(settings): make settings page responsive for mobile and tablet`++**Why it succeeded**: Mobile-first approach, used Tailwind utilities, maintained design tokens, considered touch targets.diff --git a/data.sample/prompts/skills/refactor.md b/data.sample/prompts/skills/refactor.mdnew file mode 100644index 0000000000..e34d2faa63--- /dev/null+++ b/data.sample/prompts/skills/refactor.md@@ -0,0 +1,50 @@+# Refactor Skill Template++## Routing+**Use when**: Task description contains keywords like "refactor", "reorganize", "restructure", "clean up", "simplify", "extract", "consolidate", "decouple", "modularize", "split", "merge", "rename", "move"+**Don't use when**: Task is adding new functionality, fixing a specific bug, or the "refactoring" is really a feature request in disguise++## Task-Specific Guidelines++You are refactoring existing code. The goal is to improve internal structure without changing external behavior.++### 1. Understand Before Changing+- Read ALL code you plan to refactor before making any changes+- Map out the current structure: what calls what, what depends on what+- Identify the specific structural problem the refactor addresses+- Find all callers/consumers of code you plan to move or rename++### 2. Preserve Behavior+- The #1 rule: external behavior MUST NOT change+- Run existing tests before AND after refactoring+- If tests don't exist for the code being refactored, consider adding them first+- Keep API contracts (function signatures, route paths, response shapes) identical unless the task explicitly says to change them++### 3. Refactoring Approach+- Make one type of change at a time (don't rename + restructure + optimize simultaneously)+- Update all references when renaming or moving code+- Remove dead code completely — no commented-out blocks or `_unused` prefixes+- Follow existing naming conventions in the codebase++### 4. Avoid Scope Creep+- Do NOT add features during a refactor+- Do NOT fix unrelated bugs during a refactor+- Do NOT add error handling that wasn't there before (unless it's the refactor's goal)+- Do NOT add types, comments, or documentation unless explicitly requested++### 5. Commit Message Format+Use prefix: `refactor(scope): description`++## Example: Successful Refactor++**Task**: "Refactor the provider selection logic out of subAgentSpawner.js into its own module"++**What the agent did**:+1. Read `subAgentSpawner.js` and identified the provider selection functions (3 functions, ~120 lines)+2. Created `server/services/providerSelector.js` with the extracted functions+3. Updated imports in `subAgentSpawner.js` to use the new module+4. Searched for any other files importing these functions — found 1, updated it+5. Ran `npm test` — all 47 tests passing, same as before+6. Committed: `refactor(agent): extract provider selection into dedicated module`++**Why it succeeded**: Understood the full dependency graph, moved code without changing behavior, updated all references, verified with tests.diff --git a/data.sample/prompts/skills/security-audit.md b/data.sample/prompts/skills/security-audit.mdnew file mode 100644index 0000000000..b34bff5564--- /dev/null+++ b/data.sample/prompts/skills/security-audit.md@@ -0,0 +1,59 @@+# Security Audit Skill Template++## Routing+**Use when**: Task description contains keywords like "security", "audit", "vulnerability", "xss", "injection", "owasp", "cve", "penetration", "hardening", "sanitize", "escape", "auth", "authentication", "authorization", "permissions"+**Don't use when**: Task is about general code quality, performance optimization, or adding features unrelated to security++## Task-Specific Guidelines++You are performing a security audit or fixing security issues. Follow this thorough approach:++### 1. Scope the Audit+- Identify which components are in scope (routes, services, client, dependencies)+- Focus on OWASP Top 10 categories relevant to this codebase:+ - **Injection**: SQL/NoSQL/command injection in user inputs+ - **XSS**: Unescaped user content rendered in HTML/React+ - **Broken Auth**: Missing or weak authentication/authorization checks+ - **Sensitive Data**: Secrets in code, logs, or responses+ - **Misconfiguration**: Permissive CORS, missing headers, debug endpoints+ - **Command Injection**: Shell command construction from user input++### 2. Audit Methodology+- Check all route handlers for input validation (Zod schemas)+- Verify the command allowlist in shell execution paths+- Scan for hardcoded secrets, API keys, or credentials+- Check file path handling for directory traversal+- Review CORS and security header configuration+- Examine WebSocket message handling for injection++### 3. Reporting Format+For each finding, document:+- **Severity**: CRITICAL / HIGH / MEDIUM / LOW / INFO+- **Location**: File path and line number+- **Issue**: What the vulnerability is+- **Impact**: What an attacker could do+- **Fix**: Specific remediation with code example++### 4. Fix Priority+- CRITICAL/HIGH: Fix immediately in this task+- MEDIUM: Fix if straightforward, otherwise document+- LOW/INFO: Document only, don't change code++### 5. Commit Message Format+Use prefix: `security(scope): description`++## Example: Successful Security Audit++**Task**: "Audit the API routes for injection vulnerabilities"++**What the agent did**:+1. Scanned all route files in `server/routes/` for input handling+2. Found 2 issues:+ - HIGH: `req.query.name` used directly in file path without sanitization (`server/routes/files.js:23`)+ - MEDIUM: Missing rate limiting on auth endpoint+3. Fixed the HIGH issue by adding path validation against directory traversal+4. Documented the MEDIUM issue in task notes+5. Ran tests to verify fix didn't break functionality+6. Committed: `security(routes): sanitize file path input to prevent directory traversal`++**Why it succeeded**: Systematic scan, prioritized fixes, documented what wasn't fixed, verified no regressions.diff --git a/data.sample/prompts/stages/cos-agent-briefing.md b/data.sample/prompts/stages/cos-agent-briefing.mdindex bdb4f3553c..5d56ee13f6 100644--- a/data.sample/prompts/stages/cos-agent-briefing.md+++ b/data.sample/prompts/stages/cos-agent-briefing.md@@ -24,6 +24,12 @@ Your job is to complete the assigned task independently and efficiently.{{{compactionSection}}}{{/compactionSection}}+{{#skillSection}}+## Task-Type Skill Guidelines++{{skillSection}}+{{/skillSection}}+## Instructions1. **Analyze** the task requirements carefully before making changes