⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.
fix: Comprehensive pack completeness remediation
Daniel Miesslerc38a43cf8bec
diff --git a/PACKS.md b/PACKS.mdindex e567d0c5..3503a56a 100644--- a/PACKS.md+++ b/PACKS.md@@ -49,7 +49,37 @@ If you need to look something up, figure something out, or fill in gaps - the pa## Pack Types-### Feature Packs+PAI has two fundamentally different pack types. Understanding this distinction is critical.++### Skill Packs (🎯)++**AI-invoked capabilities** that Claude routes to via SKILL.md:++| Requirement | Description |+|-------------|-------------|+| SKILL.md | **Required** - defines triggers and routing |+| Workflows/ | Contains workflow definitions |+| Validation | All workflow refs must resolve |++Skill packs are invoked BY the AI when it detects relevant triggers.++### System Packs (⚙️)++**Human-installed infrastructure** that runs in the background:++| Requirement | Description |+|-------------|-------------|+| SKILL.md | **Not required** - these are infrastructure |+| src/ | Contains hooks, servers, configs |+| Validation | Must install and run correctly |++System packs are installed BY humans and provide infrastructure. They are NOT incomplete for lacking SKILL.md - that's by design.++**System packs:** kai-hook-system, kai-history-system, kai-voice-system, kai-observability-server++---++### Feature Packs (Legacy Term)**Architectural systems** that add infrastructure capabilities:diff --git a/Packs/kai-agents-skill/src/skills/Agents/Workflows/SpawnParallelAgents.md b/Packs/kai-agents-skill/src/skills/Agents/Workflows/SpawnParallelAgents.mdnew file mode 100644index 00000000..661d685d--- /dev/null+++ b/Packs/kai-agents-skill/src/skills/Agents/Workflows/SpawnParallelAgents.md@@ -0,0 +1,270 @@+# SpawnParallelAgents Workflow++**Launches multiple generic Intern agents for parallel grunt work (NOT custom agents).**++## When to Use++User says:+- "Launch 5 agents to research these companies"+- "Spin up agents to process this list"+- "Create agents to analyze these files" (no "custom")+- "Use interns to check these URLs"++**KEY: No "custom" keyword = generic Intern agents (same voice, fast parallel execution)**++**CRITICAL DISTINCTION:**++| User Says | subagent_type | Voice |+|-----------|---------------|-------|+| "**custom** agents" | `general-purpose` | Custom from AgentFactory |+| "agents" (no custom) | `Intern` | Same for all |++If user says "custom" → use CreateCustomAgent workflow, NOT this one!++## The Workflow++### Step 1: Identify Task List++Extract what needs to be done in parallel:+- List of companies to research+- Files to analyze+- URLs to check+- Data points to investigate++### Step 2: Create Task-Specific Prompts++**Each agent gets a DETAILED prompt with FULL CONTEXT:**++```typescript+const agent1Prompt = `+## Context+We're researching competitors in the AI security space for strategic planning.++## Current State+We have 10 companies identified. You're analyzing Company A.++## Task+1. Research Company A's recent product launches (last 6 months)+2. Identify their target market and positioning+3. Note any key partnerships or acquisitions+4. Assess their technical approach++## Success Criteria+- Specific product names and launch dates+- Clear target market definition+- List of partnerships with dates+- Technical stack/approach summary++Company A: Acme AI Security Corp+`;+```++### Step 3: Launch ALL Agents in SINGLE Message++**CRITICAL: Use ONE message with MULTIPLE Task calls for true parallel execution:**++```typescript+// Send as a SINGLE message with all Task calls:+Task({+ description: "Research Company A",+ prompt: agent1Prompt,+ subagent_type: "Intern",+ model: "haiku" // or "sonnet" depending on complexity+})+Task({+ description: "Research Company B",+ prompt: agent2Prompt,+ subagent_type: "Intern",+ model: "haiku"+})+Task({+ description: "Research Company C",+ prompt: agent3Prompt,+ subagent_type: "Intern",+ model: "haiku"+})+// ... up to N agents+```++**All agents run simultaneously and return results together.**++### Step 4: Spotcheck Results (Mandatory)++**ALWAYS launch a spotcheck agent after parallel work completes:**++```typescript+Task({+ description: "Spotcheck parallel results",+ prompt: `Review these research results for consistency and completeness:++Company A: [results]+Company B: [results]+Company C: [results]++Check for:+1. Missing information across any companies+2. Inconsistent data formats+3. Obvious gaps or errors+4. Recommendations for follow-up research++Provide a brief assessment and any issues found.`,+ subagent_type: "Intern",+ model: "haiku"+})+```++## Model Selection++**Choose based on task complexity, not number of agents:**++| Task Type | Model | Reason |+|-----------|-------|--------|+| Simple checks (URL validation, file existence, basic lookups) | `haiku` | 10-20x faster, more than sufficient |+| Standard research/analysis (company research, code review) | `sonnet` | Balanced capability and speed |+| Deep reasoning (strategic analysis, architectural decisions) | `opus` | Maximum intelligence required |++**Parallel execution especially benefits from `haiku` - spawning 10 haiku agents is both faster AND cheaper than 1 opus agent doing sequential work.**++## Example: Research 5 Companies++**User:** "Launch agents to research these 5 AI security companies"++**Execution:**+```typescript+// Single message with 5 Task calls:+Task({+ description: "Research Acme AI Security",+ prompt: "Research Acme AI Security Corp: products, market, partnerships, tech stack",+ subagent_type: "Intern",+ model: "sonnet"+})+Task({+ description: "Research Bolt Security AI",+ prompt: "Research Bolt Security AI: products, market, partnerships, tech stack",+ subagent_type: "Intern",+ model: "sonnet"+})+// ... more agents++// After results return, spotcheck:+Task({+ description: "Spotcheck company research",+ prompt: "Review these 5 company research results for consistency and gaps: [results]",+ subagent_type: "Intern",+ model: "haiku"+})+```++**Result:** 5 agents research in parallel, spotcheck validates consistency.++## Common Patterns++### Pattern 1: List Processing++**Input:** List of items (companies, files, URLs, people)+**Action:** Create one agent per item, identical task structure+**Model:** `haiku` for simple tasks, `sonnet` for analysis++### Pattern 2: Multi-File Analysis++**Input:** Multiple files to analyze+**Action:** One agent per file, same analysis criteria+**Model:** `sonnet` for code analysis, `haiku` for simple checks++### Pattern 3: Data Point Investigation++**Input:** Multiple data points/questions+**Action:** One agent per question, independent research+**Model:** `sonnet` for research, `haiku` for fact-checking++## Spotcheck Pattern (Mandatory)++**WHY:** Parallel agents may produce inconsistent formats, miss details, or have conflicting information.++**WHEN:** After EVERY parallel agent batch completes++**HOW:**+```typescript+Task({+ description: "Spotcheck results",+ prompt: `Review these parallel results:++[Agent 1 results]+[Agent 2 results]+[Agent N results]++Verify:+- Consistent formatting+- No missing information+- No obvious errors+- No conflicting data++Flag any issues for follow-up.`,+ subagent_type: "Intern",+ model: "haiku" // Fast spotcheck+})+```++## Common Mistakes to Avoid++**❌ WRONG: Sequential execution**+```typescript+await Task({ ... }); // Agent 1 (blocks)+await Task({ ... }); // Agent 2 (waits for 1)+await Task({ ... }); // Agent 3 (waits for 2)+// Takes 3x as long!+```++**✅ RIGHT: Parallel execution**+```typescript+// Send ONE message with multiple Task calls:+Task({ ... }) // Agent 1+Task({ ... }) // Agent 2+Task({ ... }) // Agent 3+// All run simultaneously+```++**❌ WRONG: Skipping spotcheck**+```typescript+// Launch agents, get results, done+// No validation = potential inconsistencies+```++**✅ RIGHT: Always spotcheck**+```typescript+// Launch agents+// Get results+// Spotcheck for consistency+// THEN report as complete+```++**❌ WRONG: Using opus for simple parallel tasks**+```typescript+// Each agent uses opus = slow + expensive+Task({ ..., model: "opus" })+```++**✅ RIGHT: Use haiku for grunt work**+```typescript+// 10-20x faster, sufficient for simple tasks+Task({ ..., model: "haiku" })+```++## When to Use Custom Agents Instead++Use **CreateCustomAgent workflow** when:+- You need distinct personalities/perspectives+- Voice diversity matters (presenting results)+- Different analytical approaches required+- Each agent brings unique expertise++Use **SpawnParallelAgents workflow** when:+- Simple parallel processing+- Same task, different inputs+- Speed matters more than personality+- Voice diversity not needed++## Related Workflows++- **CreateCustomAgent** - For agents with unique personalities/voices+- **ListTraits** - Show available traits for custom agentsdiff --git a/Packs/kai-core-install/src/skills/CreateSkill/SKILL.md b/Packs/kai-core-install/src/skills/CreateSkill/SKILL.mdindex efb1c91a..b13f728e 100644--- a/Packs/kai-core-install/src/skills/CreateSkill/SKILL.md+++ b/Packs/kai-core-install/src/skills/CreateSkill/SKILL.md@@ -11,28 +11,54 @@ MANDATORY skill creation framework for ALL skill creation requests.**Before creating ANY skill, READ:** `$PAI_DIR/skills/CORE/SkillSystem.md`-## Workflow Routing+This document contains the complete specification for:+- Skill directory structure+- SKILL.md format and required sections+- Workflow file conventions+- Naming conventions (TitleCase)+- Examples section requirements-| Workflow | Trigger | File |-|----------|---------|------|-| **CreateSkill** | "create a new skill" | `Workflows/CreateSkill.md` |-| **ValidateSkill** | "validate skill" | `Workflows/ValidateSkill.md` |-| **CanonicalizeSkill** | "canonicalize", "fix skill" | `Workflows/CanonicalizeSkill.md` |+## How to Create a Skill++1. **Read the spec:** `$PAI_DIR/skills/CORE/SkillSystem.md`+2. **Create directory:** `$PAI_DIR/skills/SkillName/`+3. **Create SKILL.md** with required frontmatter and sections+4. **Add Workflows/** directory if needed+5. **Validate** by checking all workflow references resolve++## How to Validate a Skill++Run the pack validator:+```bash+bun run $PAI_DIR/Tools/validate-pack.ts+```++Or manually check:+- SKILL.md exists with valid frontmatter+- All `Workflows/*.md` references in SKILL.md exist+- Examples section is present++## How to Canonicalize a Skill++1. Rename files/directories to TitleCase+2. Ensure SKILL.md has required sections+3. Verify workflow references resolve+4. Add Examples section if missing## Examples**Example 1: Create a new skill**```User: "Create a skill for managing my recipes"-→ Invokes CreateSkill workflow-→ Reads SkillSystem.md for structure-→ Creates skill with TitleCase naming+→ Read SkillSystem.md for structure+→ Create $PAI_DIR/skills/Recipes/SKILL.md+→ Use TitleCase naming throughout```**Example 2: Fix an existing skill**```User: "Canonicalize the daemon skill"-→ Invokes CanonicalizeSkill workflow-→ Renames files to TitleCase-→ Ensures Examples section exists+→ Rename files to TitleCase+→ Ensure Examples section exists+→ Validate workflow references```diff --git a/Packs/kai-history-system/src/stop-hook.ts b/Packs/kai-history-system/src/stop-hook.tsindex 6da3cf29..14235d6e 100644--- a/Packs/kai-history-system/src/stop-hook.ts+++ b/Packs/kai-history-system/src/stop-hook.ts@@ -2,7 +2,7 @@// $PAI_DIR/hooks/stop-hook.ts// Captures main agent work summaries and learnings-import { writeFileSync, mkdirSync, existsSync } from 'fs';+import { writeFileSync, mkdirSync, existsSync, readFileSync } from 'fs';import { join } from 'path';import { homedir } from 'os';@@ -68,27 +68,52 @@ function generateFilename(type: string, description: string): string {return `${timestamp}_${type}_${kebab}.md`;}-function extractLastResponse(transcriptPath: string): string | null {+/**+ * Extract the last assistant response from a transcript file.+ * Claude Code sends transcript_path but not response in Stop events.+ */+function extractResponseFromTranscript(transcriptPath: string): string | null {try {- if (!existsSync(transcriptPath)) return null;+ if (!existsSync(transcriptPath)) {+ return null;+ }++ const content = readFileSync(transcriptPath, 'utf-8');+ const lines = content.trim().split('\n').filter(l => l.trim());- const content = require('fs').readFileSync(transcriptPath, 'utf-8');- const lines = content.split('\n').filter((l: string) => l.trim());+ if (lines.length === 0) {+ return null;+ }- // Find last assistant message+ // Find the last assistant message by iterating backwardsfor (let i = lines.length - 1; i >= 0; i--) {try {const entry = JSON.parse(lines[i]);if (entry.type === 'assistant' && entry.message?.content) {// Extract text from content array- const textParts = entry.message.content- .filter((c: any) => c.type === 'text')- .map((c: any) => c.text)- .join('\n');- if (textParts.length > 50) return textParts;+ const contentArray = Array.isArray(entry.message.content)+ ? entry.message.content+ : [entry.message.content];++ const response = contentArray+ .map((c: any) => {+ if (typeof c === 'string') return c;+ if (c?.text) return c.text;+ if (c?.content) return String(c.content);+ return '';+ })+ .join('\n')+ .trim();++ if (response && response.length > 50) {+ return response;+ }}- } catch {}+ } catch {+ continue; // Skip malformed lines+ }}+return null;} catch {return null;@@ -104,10 +129,10 @@ async function main() {const payload: StopPayload = JSON.parse(stdinData);- // Get response from payload or extract from transcript+ // Try to get response from payload first, then from transcriptlet response = payload.response;if (!response && payload.transcript_path) {- response = extractLastResponse(payload.transcript_path) || undefined;+ response = extractResponseFromTranscript(payload.transcript_path) || undefined;}if (!response) {@@ -133,6 +158,9 @@ async function main() {const filename = generateFilename(type, summary);const filepath = join(outputDir, filename);+ // Limit response size to prevent huge files+ const truncatedResponse = response.slice(0, 5000);+const content = `---capture_type: ${type}timestamp: ${getLocalTimestamp()}@@ -142,7 +170,7 @@ executor: main# ${type}: ${summary}-${response.slice(0, 5000)}+${truncatedResponse}---diff --git a/Tools/validate-pack.ts b/Tools/validate-pack.tsnew file mode 100644index 00000000..3547605b--- /dev/null+++ b/Tools/validate-pack.ts@@ -0,0 +1,237 @@+#!/usr/bin/env bun+/**+ * PAI Pack Validator+ *+ * Validates that PAI packs meet completeness requirements:+ * - Skill packs have SKILL.md with valid workflow references+ * - All referenced workflows exist+ * - Required files (README.md, INSTALL.md, VERIFY.md) present+ *+ * Usage:+ * bun run Tools/validate-pack.ts # Validate all packs+ * bun run Tools/validate-pack.ts kai-agents-skill # Validate specific pack+ * bun run Tools/validate-pack.ts --changed-only # Validate changed packs (for CI)+ */++import { existsSync, readdirSync, readFileSync } from 'fs';+import { join, basename } from 'path';++const PACKS_DIR = join(import.meta.dir, '..', 'Packs');++// Pack type classification+const SYSTEM_PACKS = [+ 'kai-hook-system',+ 'kai-history-system',+ 'kai-voice-system',+ 'kai-observability-server',+ 'icons'+];++interface ValidationResult {+ pack: string;+ type: 'skill' | 'system';+ valid: boolean;+ errors: string[];+ warnings: string[];+}++function findSkillMd(packDir: string): string | null {+ // Check common locations for SKILL.md+ const locations = [+ join(packDir, 'SKILL.md'),+ join(packDir, 'src', 'skills'),+ ];++ // Direct SKILL.md at root+ if (existsSync(locations[0])) {+ return locations[0];+ }++ // Search in src/skills/*/SKILL.md+ const skillsDir = locations[1];+ if (existsSync(skillsDir)) {+ const skills = readdirSync(skillsDir, { withFileTypes: true })+ .filter(d => d.isDirectory())+ .map(d => join(skillsDir, d.name, 'SKILL.md'))+ .filter(p => existsSync(p));++ if (skills.length > 0) {+ return skills[0];+ }+ }++ return null;+}++function extractWorkflowRefs(skillMdContent: string): string[] {+ const refs: string[] = [];++ // Match patterns like: `Workflows/SomeName.md` or Workflows/SomeName.md+ const workflowPattern = /Workflows\/([A-Za-z0-9_-]+\.md)/g;+ let match;++ while ((match = workflowPattern.exec(skillMdContent)) !== null) {+ refs.push(match[1]);+ }++ return [...new Set(refs)]; // Deduplicate+}++function validatePack(packName: string): ValidationResult {+ const packDir = join(PACKS_DIR, packName);+ const result: ValidationResult = {+ pack: packName,+ type: SYSTEM_PACKS.includes(packName) ? 'system' : 'skill',+ valid: true,+ errors: [],+ warnings: []+ };++ // Check pack directory exists+ if (!existsSync(packDir)) {+ result.valid = false;+ result.errors.push(`Pack directory not found: ${packDir}`);+ return result;+ }++ // Check required files+ const requiredFiles = ['README.md', 'INSTALL.md', 'VERIFY.md'];+ for (const file of requiredFiles) {+ if (!existsSync(join(packDir, file))) {+ result.warnings.push(`Missing recommended file: ${file}`);+ }+ }++ // System packs don't need SKILL.md validation+ if (result.type === 'system') {+ return result;+ }++ // Skill packs: validate SKILL.md and workflow references+ const skillMdPath = findSkillMd(packDir);++ if (!skillMdPath) {+ result.valid = false;+ result.errors.push('Skill pack missing SKILL.md');+ return result;+ }++ const skillMdContent = readFileSync(skillMdPath, 'utf-8');+ const workflowRefs = extractWorkflowRefs(skillMdContent);++ if (workflowRefs.length === 0) {+ result.warnings.push('No workflow references found in SKILL.md');+ return result;+ }++ // Check each workflow reference exists+ const skillDir = join(skillMdPath, '..');+ const workflowsDir = join(skillDir, 'Workflows');++ for (const ref of workflowRefs) {+ const workflowPath = join(workflowsDir, ref);+ if (!existsSync(workflowPath)) {+ result.valid = false;+ result.errors.push(`Missing workflow: Workflows/${ref} (referenced in SKILL.md)`);+ }+ }++ return result;+}++function validateAllPacks(): ValidationResult[] {+ const results: ValidationResult[] = [];++ if (!existsSync(PACKS_DIR)) {+ console.error(`Packs directory not found: ${PACKS_DIR}`);+ process.exit(1);+ }++ const packs = readdirSync(PACKS_DIR, { withFileTypes: true })+ .filter(d => d.isDirectory())+ .map(d => d.name)+ .filter(name => !name.startsWith('.'));++ for (const pack of packs) {+ results.push(validatePack(pack));+ }++ return results;+}++function printResults(results: ValidationResult[]): boolean {+ let hasErrors = false;++ console.log('\n📦 PAI Pack Validation Results\n');+ console.log('═'.repeat(60));++ for (const result of results) {+ const icon = result.valid ? '✅' : '❌';+ const typeIcon = result.type === 'skill' ? '🎯' : '⚙️';++ console.log(`\n${icon} ${result.pack} ${typeIcon} (${result.type})`);++ if (result.errors.length > 0) {+ hasErrors = true;+ for (const error of result.errors) {+ console.log(` ❌ ${error}`);+ }+ }++ if (result.warnings.length > 0) {+ for (const warning of result.warnings) {+ console.log(` ⚠️ ${warning}`);+ }+ }++ if (result.valid && result.errors.length === 0 && result.warnings.length === 0) {+ console.log(' All checks passed');+ }+ }++ console.log('\n' + '═'.repeat(60));++ const valid = results.filter(r => r.valid).length;+ const total = results.length;+ console.log(`\n📊 Summary: ${valid}/${total} packs valid`);++ if (hasErrors) {+ console.log('\n❌ Validation FAILED - fix errors before merging\n');+ } else {+ console.log('\n✅ Validation PASSED\n');+ }++ return !hasErrors;+}++// Main+const args = process.argv.slice(2);++if (args.includes('--help') || args.includes('-h')) {+ console.log(`+PAI Pack Validator++Usage:+ bun run Tools/validate-pack.ts # Validate all packs+ bun run Tools/validate-pack.ts kai-agents-skill # Validate specific pack+ bun run Tools/validate-pack.ts --changed-only # Validate changed packs (for CI)++Pack Types:+ - Skill packs (🎯): Must have SKILL.md with valid workflow references+ - System packs (⚙️): Infrastructure packs, no SKILL.md required+`);+ process.exit(0);+}++let results: ValidationResult[];++if (args.length > 0 && !args[0].startsWith('--')) {+ // Validate specific pack+ results = [validatePack(args[0])];+} else {+ // Validate all packs+ results = validateAllPacks();+}++const success = printResults(results);+process.exit(success ? 0 : 1);