Skip to content

⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.

feat: Add icon references to all pack READMEs + pai-algorithm-skill pack

Daniel Miessler120cc8fa5888
diff --git a/Packs/icons/pai-algorithm-skill.png b/Packs/icons/pai-algorithm-skill.png
new file mode 100644
index 00000000..547e8bd1
Binary files /dev/null and b/Packs/icons/pai-algorithm-skill.png differ
diff --git a/Packs/pai-agents-skill/README.md b/Packs/pai-agents-skill/README.md
index 3b7e9e26..64b833a8 100644
--- a/Packs/pai-agents-skill/README.md
+++ b/Packs/pai-agents-skill/README.md
@@ -11,7 +11,11 @@ dependencies: [danielmiessler-core-install-core-v1.0.0]
keywords: [agents, delegation, parallel, traits, personalities, voice, composition, dynamic, factory, custom, orchestration, subagents]
---
-# Kai Agents Skill
+<p align="center">
+ <img src="../icons/agents-skill.png" alt="PAI Agents Skill" width="256">
+</p>
+
+# PAI Agents Skill
> Dynamic agent composition system - create specialized agents with unique personalities and voices, composed from traits on-the-fly
diff --git a/Packs/pai-algorithm-skill/INSTALL.md b/Packs/pai-algorithm-skill/INSTALL.md
new file mode 100644
index 00000000..e65b84bc
--- /dev/null
+++ b/Packs/pai-algorithm-skill/INSTALL.md
@@ -0,0 +1,175 @@
+# Installation Guide - THE ALGORITHM Skill
+
+## Prerequisites
+
+- **Bun runtime**: `curl -fsSL https://bun.sh/install | bash`
+- **Claude Code** (or compatible agent system)
+- **pai-core-install** pack installed (provides skill routing and CORE context)
+- **pai-agents-skill** pack installed (provides AgentFactory for custom agents)
+- **Optional**: pai-voice-system pack for voice notifications during phase transitions
+
+## Pre-Installation: System Analysis
+
+```bash
+# 1. Check PAI_DIR
+echo "PAI_DIR: ${PAI_DIR:-'NOT SET - will use ~/.config/pai'}"
+
+# 2. Check for existing THEALGORITHM skill
+PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"
+if [ -d "$PAI_CHECK/skills/THEALGORITHM" ]; then
+ echo "Warning: THEALGORITHM skill already exists"
+ ls -la "$PAI_CHECK/skills/THEALGORITHM"
+else
+ echo "Clean install - no existing THEALGORITHM skill"
+fi
+
+# 3. Check dependencies
+if [ -f "$PAI_CHECK/skills/CORE/SKILL.md" ]; then
+ echo "pai-core-install: INSTALLED"
+else
+ echo "Warning: pai-core-install not found (required)"
+fi
+
+if [ -f "$PAI_CHECK/skills/Agents/SKILL.md" ]; then
+ echo "pai-agents-skill: INSTALLED"
+else
+ echo "Warning: pai-agents-skill not found (required for custom agents)"
+fi
+```
+
+---
+
+## Installation Steps
+
+### Step 1: Create Directory Structure
+
+```bash
+PAI_DIR="${PAI_DIR:-$HOME/.config/pai}"
+
+mkdir -p "$PAI_DIR/skills/THEALGORITHM/Tools"
+mkdir -p "$PAI_DIR/skills/THEALGORITHM/Data"
+mkdir -p "$PAI_DIR/skills/THEALGORITHM/Phases"
+mkdir -p "$PAI_DIR/skills/THEALGORITHM/Reference"
+mkdir -p "$PAI_DIR/MEMORY/Work"
+mkdir -p "$PAI_DIR/MEMORY/State"
+
+ls -la "$PAI_DIR/skills/THEALGORITHM/"
+```
+
+### Step 2: Copy Skill Files
+
+Copy from this pack's `src/` directory to your PAI installation:
+
+| Source | Destination |
+|--------|-------------|
+| `src/skills/THEALGORITHM/SKILL.md` | `$PAI_DIR/skills/THEALGORITHM/SKILL.md` |
+| `src/skills/THEALGORITHM/Data/Capabilities.yaml` | `$PAI_DIR/skills/THEALGORITHM/Data/Capabilities.yaml` |
+| `src/skills/THEALGORITHM/Tools/*.ts` | `$PAI_DIR/skills/THEALGORITHM/Tools/` |
+| `src/skills/THEALGORITHM/Phases/*.md` | `$PAI_DIR/skills/THEALGORITHM/Phases/` |
+| `src/skills/THEALGORITHM/Reference/*.md` | `$PAI_DIR/skills/THEALGORITHM/Reference/` |
+
+```bash
+PAI_DIR="${PAI_DIR:-$HOME/.config/pai}"
+PACK_DIR="[PATH_TO_THIS_PACK]"
+
+# Copy main skill file
+cp "$PACK_DIR/src/skills/THEALGORITHM/SKILL.md" "$PAI_DIR/skills/THEALGORITHM/"
+
+# Copy data files
+cp "$PACK_DIR/src/skills/THEALGORITHM/Data/Capabilities.yaml" "$PAI_DIR/skills/THEALGORITHM/Data/"
+
+# Copy tools
+cp "$PACK_DIR/src/skills/THEALGORITHM/Tools/"*.ts "$PAI_DIR/skills/THEALGORITHM/Tools/"
+
+# Copy phase documentation
+cp "$PACK_DIR/src/skills/THEALGORITHM/Phases/"*.md "$PAI_DIR/skills/THEALGORITHM/Phases/"
+
+# Copy reference documentation
+cp "$PACK_DIR/src/skills/THEALGORITHM/Reference/"*.md "$PAI_DIR/skills/THEALGORITHM/Reference/"
+```
+
+### Step 3: Install Dependencies
+
+```bash
+cd "$PAI_DIR/skills/THEALGORITHM/Tools"
+bun add yaml
+```
+
+### Step 4: Update Path References
+
+The tools use `$PAI_DIR` environment variable or default to `~/.config/pai`. If your PAI installation is elsewhere, set the environment variable:
+
+```bash
+# Add to your shell profile (.zshrc, .bashrc, etc.)
+export PAI_DIR="$HOME/.config/pai"
+```
+
+### Step 5: Register Skill (Optional)
+
+If using the skill index system, regenerate the skill index:
+
+```bash
+bun run "$PAI_DIR/Tools/GenerateSkillIndex.ts"
+```
+
+---
+
+## Verification
+
+```bash
+PAI_DIR="${PAI_DIR:-$HOME/.config/pai}"
+
+echo "Checking installation..."
+
+[ -f "$PAI_DIR/skills/THEALGORITHM/SKILL.md" ] && echo "[OK] SKILL.md" || echo "[MISSING] SKILL.md"
+[ -f "$PAI_DIR/skills/THEALGORITHM/Data/Capabilities.yaml" ] && echo "[OK] Capabilities.yaml" || echo "[MISSING] Capabilities.yaml"
+[ -f "$PAI_DIR/skills/THEALGORITHM/Tools/EffortClassifier.ts" ] && echo "[OK] EffortClassifier.ts" || echo "[MISSING] EffortClassifier.ts"
+[ -f "$PAI_DIR/skills/THEALGORITHM/Tools/ISCManager.ts" ] && echo "[OK] ISCManager.ts" || echo "[MISSING] ISCManager.ts"
+[ -f "$PAI_DIR/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts" ] && echo "[OK] AlgorithmDisplay.ts" || echo "[MISSING] AlgorithmDisplay.ts"
+
+echo ""
+echo "Testing EffortClassifier..."
+bun run "$PAI_DIR/skills/THEALGORITHM/Tools/EffortClassifier.ts" --request "Add a new feature" --output json | head -10
+
+echo ""
+echo "Testing ISCManager..."
+bun run "$PAI_DIR/skills/THEALGORITHM/Tools/ISCManager.ts" --help | head -5
+```
+
+---
+
+## Environment Variables
+
+| Variable | Required | Description |
+|----------|----------|-------------|
+| `PAI_DIR` | No | Custom PAI directory (default: `~/.config/pai`) |
+
+## Post-Installation
+
+### Voice Support (Optional)
+
+If you have the pai-voice-system pack installed, the AlgorithmDisplay tool will automatically send voice notifications during phase transitions. No additional configuration needed.
+
+### Integration with Other Skills
+
+THE ALGORITHM integrates with:
+- **Agents skill** - For custom agent composition via AgentFactory
+- **BeCreative skill** - For UltraThink thinking mode
+- **Council skill** - For multi-perspective debate (THOROUGH+)
+- **RedTeam skill** - For adversarial analysis (DETERMINED)
+- **FirstPrinciples skill** - For assumption challenging
+- **Browser skill** - For web verification
+
+These integrations work automatically if the skills are installed.
+
+---
+
+## Troubleshooting
+
+| Issue | Solution |
+|-------|----------|
+| EffortClassifier not found | Check `$PAI_DIR` is set correctly |
+| Missing dependencies | Run `bun add yaml` in Tools directory |
+| Voice not working | Ensure pai-voice-system is installed and running |
+| ISC not saving | Check `$PAI_DIR/MEMORY/Work/` directory exists |
+| Capability loading fails | Verify Capabilities.yaml syntax is valid |
diff --git a/Packs/pai-algorithm-skill/README.md b/Packs/pai-algorithm-skill/README.md
new file mode 100644
index 00000000..fd58b579
--- /dev/null
+++ b/Packs/pai-algorithm-skill/README.md
@@ -0,0 +1,200 @@
+---
+name: THE ALGORITHM Skill
+pack-id: danielmiessler-algorithm-skill-core-v0.5.0
+version: 0.5.0
+author: danielmiessler
+description: Universal execution engine using the scientific method to achieve ideal state. ISC (Ideal State Criteria) tracking, effort-based capability selection, and the Ralph Loop for persistent iteration.
+type: skill
+purpose-type: [productivity, automation, development, workflow]
+platform: claude-code
+dependencies: [danielmiessler-core-install-core-v1.0.0, danielmiessler-agents-skill-core-v1.0.0]
+keywords: [algorithm, execution, isc, ideal-state, effort, scientific-method, phases, ralph-loop, iteration, capability, orchestration]
+---
+
+<p align="center">
+ <img src="../icons/pai-algorithm-skill.png" alt="THE ALGORITHM Skill" width="256">
+</p>
+
+# THE ALGORITHM Skill
+
+> Universal execution engine using the scientific method to achieve ideal state - from current state to ideal state through structured phases and capability-driven execution.
+
+> **Version 0.5.0** - Early release. Core concepts are solid, but expect refinements as the system evolves.
+
+> **Installation:** This pack is designed for AI-assisted installation. Give this directory to your AI and ask it to install using the wizard in `INSTALL.md`. The installation dynamically adapts to your system state. See [AI-First Installation Philosophy](../../README.md#ai-first-installation-philosophy) for details.
+
+---
+
+## What's Included
+
+| Component | File | Purpose |
+|-----------|------|---------|
+| Skill definition | `src/skills/THEALGORITHM/SKILL.md` | Main skill file with routing and quick reference |
+| Capabilities registry | `src/skills/THEALGORITHM/Data/Capabilities.yaml` | Source of truth for all orchestratable capabilities |
+| Algorithm display | `src/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts` | LCARS-style visual display with voice support |
+| Effort classifier | `src/skills/THEALGORITHM/Tools/EffortClassifier.ts` | Classify requests by effort level |
+| Capability loader | `src/skills/THEALGORITHM/Tools/CapabilityLoader.ts` | Load capabilities by effort level |
+| Capability selector | `src/skills/THEALGORITHM/Tools/CapabilitySelector.ts` | Select capabilities for ISC rows |
+| ISC manager | `src/skills/THEALGORITHM/Tools/ISCManager.ts` | Create, update, query ISC tables |
+| Trait modifiers | `src/skills/THEALGORITHM/Tools/TraitModifiers.ts` | Effort-to-trait mappings |
+| Ralph loop executor | `src/skills/THEALGORITHM/Tools/RalphLoopExecutor.ts` | Persistent iteration until success |
+| Phase docs | `src/skills/THEALGORITHM/Phases/*.md` | Detailed documentation for each phase |
+| Reference docs | `src/skills/THEALGORITHM/Reference/*.md` | Capability and effort matrices |
+
+## The Problem
+
+AI assistants often approach tasks with a one-size-fits-all mentality:
+
+**Inconsistent Effort:**
+- Simple tasks get over-engineered
+- Complex tasks get under-analyzed
+- No clear framework for matching effort to task complexity
+
+**Missing Structure:**
+- No systematic way to track progress toward ideal state
+- Unclear success criteria
+- Verification is an afterthought
+
+**Limited Iteration:**
+- Tasks are "done" after first attempt
+- No persistent iteration until truly complete
+- No feedback loop for continuous improvement
+
+## The Solution
+
+### Effort-Based Capability Selection
+
+Match computational resources to task complexity:
+
+| Effort | When | Capabilities |
+|--------|------|--------------|
+| **TRIVIAL** | Greetings, acknowledgments | Skip algorithm entirely |
+| **QUICK** | Simple fixes, lookups | haiku, Intern agents |
+| **STANDARD** | Most development work | sonnet, research, Engineer, verification |
+| **THOROUGH** | Complex architectural work | Council debate, Architect, parallel research |
+| **DETERMINED** | Mission-critical, unlimited | opus, RedTeam, unlimited iteration |
+
+### The 7 Phases
+
+Execute in order, each phase mutates the ISC:
+
+```
+OBSERVE → THINK → PLAN → BUILD → EXECUTE → VERIFY → LEARN
+```
+
+1. **OBSERVE** - CREATE ISC rows from request + context
+2. **THINK** - COMPLETE rows, ensure nothing missing
+3. **PLAN** - ORDER rows, identify dependencies and parallelization
+4. **BUILD** - REFINE rows to be testable
+5. **EXECUTE** - DO the work, spawn agents by capability
+6. **VERIFY** - TEST each row against success criteria
+7. **LEARN** - OUTPUT results for user evaluation
+
+### ISC (Ideal State Criteria)
+
+The ISC is the central artifact - a living document tracking the gap between current and ideal state:
+
+```markdown
+## ISC: Add dark mode
+
+**Effort:** STANDARD | **Phase:** EXECUTE | **Iteration:** 1
+
+| # | What Ideal Looks Like | Source | Capability | Status |
+|---|----------------------|--------|------------|--------|
+| 1 | Research good patterns | INFERRED | research.perplexity | DONE |
+| 2 | Toggle component works | EXPLICIT | execution.engineer | ACTIVE |
+| 3 | Theme state persists | EXPLICIT | execution.engineer | PENDING |
+| 4 | Uses TypeScript | INFERRED | - | DONE |
+| 5 | Tests pass | IMPLICIT | verification.qa | PENDING |
+```
+
+### The Ralph Loop
+
+Persistent iteration until success criteria are met:
+
+```bash
+# Start a Ralph loop
+bun run RalphLoopExecutor.ts \
+ --prompt "Fix the auth bug" \
+ --completion-promise "All tests pass" \
+ --max-iterations 15
+```
+
+The Ralph Loop continues iterating until:
+- Completion promise is detected in output
+- Max iterations reached
+
+Named after the persistent, never-give-up spirit of iteration.
+
+## Example Usage
+
+```bash
+# 1. START with visual display
+bun run AlgorithmDisplay.ts start STANDARD -r "Add dark mode toggle"
+
+# 2. CLASSIFY effort (or use display start)
+bun run EffortClassifier.ts --request "Add dark mode toggle"
+
+# 3. CREATE ISC
+bun run ISCManager.ts create --request "Add dark mode toggle"
+
+# 4. TRANSITION phases with voice
+bun run AlgorithmDisplay.ts phase THINK
+bun run AlgorithmDisplay.ts phase EXECUTE
+
+# 5. MANAGE ISC during execution
+bun run ISCManager.ts update --row 1 --status DONE
+bun run ISCManager.ts show
+```
+
+## Core Concepts
+
+### Capability Categories
+
+- **Models:** haiku, sonnet, opus - compute resources
+- **Thinking:** UltraThink, TreeOfThought - enhanced reasoning
+- **Debate:** Council (4 agents), RedTeam (32 agents)
+- **Analysis:** FirstPrinciples, Science - structured analysis
+- **Research:** Perplexity, Gemini, Grok, Claude, Codex
+- **Execution:** Intern, Engineer, Designer, Architect, Pentester
+- **Verification:** Browser, Skeptical Verifier
+
+### Source Types
+
+- **EXPLICIT** - User literally said this
+- **INFERRED** - Derived from user context/preferences
+- **IMPLICIT** - Universal standards (security, quality)
+
+### Status Progression
+
+```
+PENDING → ACTIVE → DONE
+ → ADJUSTED (acceptable deviation)
+ → BLOCKED (cannot proceed)
+```
+
+## Philosophy
+
+**PURPOSE:** Produce euphoric, highly surprising, exceptional results that solve the problem better than expected.
+
+**METHOD:** Scientific method applied to execution:
+1. Observe the problem
+2. Form hypothesis (ISC rows)
+3. Plan experiments (capability selection)
+4. Execute and measure
+5. Verify results
+6. Learn and iterate
+
+**PRINCIPLE:** The ISC captures what "ideal" looks like. Execute against it. Verify against it. Iterate until achieved.
+
+## Changelog
+
+### 0.5.0 - 2026-01-08
+- Initial public release
+- Core 7-phase execution engine
+- ISC (Ideal State Criteria) tracking
+- Effort-based capability selection (TRIVIAL → DETERMINED)
+- Ralph Loop for persistent iteration
+- LCARS-style visual display with voice support
+- Capability registry with 30+ orchestratable capabilities
+- Integration with Agents skill for dynamic agent composition
diff --git a/Packs/pai-algorithm-skill/VERIFY.md b/Packs/pai-algorithm-skill/VERIFY.md
new file mode 100644
index 00000000..ba005276
--- /dev/null
+++ b/Packs/pai-algorithm-skill/VERIFY.md
@@ -0,0 +1,210 @@
+# Verification Checklist - THE ALGORITHM Skill
+
+## Mandatory Completion Checklist
+
+**IMPORTANT**: This checklist MUST be completed before marking installation as done.
+
+### File Structure Verification
+
+- [ ] `$PAI_DIR/skills/THEALGORITHM/SKILL.md` exists
+- [ ] `$PAI_DIR/skills/THEALGORITHM/Data/Capabilities.yaml` exists
+- [ ] `$PAI_DIR/skills/THEALGORITHM/Tools/EffortClassifier.ts` exists
+- [ ] `$PAI_DIR/skills/THEALGORITHM/Tools/CapabilityLoader.ts` exists
+- [ ] `$PAI_DIR/skills/THEALGORITHM/Tools/CapabilitySelector.ts` exists
+- [ ] `$PAI_DIR/skills/THEALGORITHM/Tools/ISCManager.ts` exists
+- [ ] `$PAI_DIR/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts` exists
+- [ ] `$PAI_DIR/skills/THEALGORITHM/Tools/TraitModifiers.ts` exists
+- [ ] `$PAI_DIR/skills/THEALGORITHM/Tools/RalphLoopExecutor.ts` exists
+- [ ] `$PAI_DIR/skills/THEALGORITHM/Phases/Observe.md` exists
+- [ ] `$PAI_DIR/skills/THEALGORITHM/Phases/Think.md` exists
+- [ ] `$PAI_DIR/skills/THEALGORITHM/Phases/Plan.md` exists
+- [ ] `$PAI_DIR/skills/THEALGORITHM/Phases/Build.md` exists
+- [ ] `$PAI_DIR/skills/THEALGORITHM/Phases/Execute.md` exists
+- [ ] `$PAI_DIR/skills/THEALGORITHM/Phases/Verify.md` exists
+- [ ] `$PAI_DIR/skills/THEALGORITHM/Phases/Learn.md` exists
+- [ ] `$PAI_DIR/MEMORY/Work/` directory exists
+
+### CLI Tool Verification
+
+- [ ] `bun run EffortClassifier.ts --help` shows usage information
+- [ ] `bun run CapabilityLoader.ts --list-all` displays all capabilities
+- [ ] `bun run ISCManager.ts --help` shows usage information
+- [ ] `bun run AlgorithmDisplay.ts --help` shows usage information
+- [ ] `bun run TraitModifiers.ts --list` shows effort configurations
+- [ ] `bun run RalphLoopExecutor.ts --help` shows usage information
+
+### Functional Tests
+
+#### Test 1: Effort Classification
+```bash
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/EffortClassifier.ts \
+ --request "Add a new authentication system" \
+ --output json
+```
+**Expected**: Returns JSON with effort level (likely THOROUGH), confidence score, and reasoning
+
+#### Test 2: Capability Loading
+```bash
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/CapabilityLoader.ts \
+ --effort STANDARD \
+ --output markdown
+```
+**Expected**: Shows available capabilities for STANDARD effort level
+
+#### Test 3: ISC Creation
+```bash
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/ISCManager.ts create \
+ --request "Test feature" \
+ --effort STANDARD
+```
+**Expected**: Creates new ISC, outputs confirmation message
+
+#### Test 4: ISC Row Addition
+```bash
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/ISCManager.ts add \
+ -d "Feature works correctly" \
+ -s EXPLICIT
+```
+**Expected**: Adds row to ISC, shows row ID
+
+#### Test 5: ISC Display
+```bash
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/ISCManager.ts show -o markdown
+```
+**Expected**: Displays formatted ISC table
+
+#### Test 6: Capability Selection
+```bash
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/CapabilitySelector.ts \
+ --row "Research best practices for API design" \
+ --effort STANDARD
+```
+**Expected**: Suggests research capability (likely perplexity)
+
+#### Test 7: Algorithm Display
+```bash
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts show
+```
+**Expected**: Shows LCARS-style display with phase progression
+
+#### Test 8: Trait Modifiers
+```bash
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/TraitModifiers.ts \
+ --effort THOROUGH \
+ --phase verify
+```
+**Expected**: Returns verification traits (skeptical, meticulous, adversarial)
+
+#### Test 9: Ralph Loop Status
+```bash
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/RalphLoopExecutor.ts --status
+```
+**Expected**: Shows "No active Ralph loop" or current loop status
+
+#### Test 10: Clean ISC
+```bash
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/ISCManager.ts clear
+```
+**Expected**: Archives and clears current ISC
+
+---
+
+## Quick Verification Script
+
+```bash
+#!/bin/bash
+PAI_DIR="${PAI_DIR:-$HOME/.config/pai}"
+
+echo "=== THE ALGORITHM Skill Verification ==="
+echo ""
+
+PASS=0
+FAIL=0
+
+check() {
+ if [ "$1" = "0" ]; then
+ echo "[PASS] $2"
+ ((PASS++))
+ else
+ echo "[FAIL] $2"
+ ((FAIL++))
+ fi
+}
+
+# File checks
+[ -f "$PAI_DIR/skills/THEALGORITHM/SKILL.md" ]
+check $? "SKILL.md exists"
+
+[ -f "$PAI_DIR/skills/THEALGORITHM/Data/Capabilities.yaml" ]
+check $? "Capabilities.yaml exists"
+
+[ -f "$PAI_DIR/skills/THEALGORITHM/Tools/EffortClassifier.ts" ]
+check $? "EffortClassifier.ts exists"
+
+[ -f "$PAI_DIR/skills/THEALGORITHM/Tools/ISCManager.ts" ]
+check $? "ISCManager.ts exists"
+
+[ -f "$PAI_DIR/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts" ]
+check $? "AlgorithmDisplay.ts exists"
+
+[ -f "$PAI_DIR/skills/THEALGORITHM/Tools/RalphLoopExecutor.ts" ]
+check $? "RalphLoopExecutor.ts exists"
+
+[ -d "$PAI_DIR/MEMORY/Work" ]
+check $? "MEMORY/Work directory exists"
+
+# CLI checks
+bun run "$PAI_DIR/skills/THEALGORITHM/Tools/EffortClassifier.ts" --help >/dev/null 2>&1
+check $? "EffortClassifier CLI runs"
+
+bun run "$PAI_DIR/skills/THEALGORITHM/Tools/ISCManager.ts" --help >/dev/null 2>&1
+check $? "ISCManager CLI runs"
+
+bun run "$PAI_DIR/skills/THEALGORITHM/Tools/CapabilityLoader.ts" --list-all >/dev/null 2>&1
+check $? "CapabilityLoader CLI runs"
+
+# Functional checks
+bun run "$PAI_DIR/skills/THEALGORITHM/Tools/EffortClassifier.ts" \
+ --request "Test request" --output json 2>/dev/null | grep -q "effort"
+check $? "Effort classification works"
+
+bun run "$PAI_DIR/skills/THEALGORITHM/Tools/TraitModifiers.ts" \
+ --effort STANDARD --output json 2>/dev/null | grep -q "traits"
+check $? "Trait modifiers work"
+
+echo ""
+echo "=== Results: $PASS passed, $FAIL failed ==="
+
+if [ $FAIL -eq 0 ]; then
+ echo "THE ALGORITHM Skill installation verified successfully!"
+ exit 0
+else
+ echo "Some checks failed. Review the output above."
+ exit 1
+fi
+```
+
+---
+
+## Troubleshooting
+
+| Issue | Solution |
+|-------|----------|
+| Tool not found | Check `$PAI_DIR` is set correctly |
+| YAML parse error | Verify Capabilities.yaml syntax |
+| ISC not saving | Ensure MEMORY/Work directory exists with write permissions |
+| Missing dependencies | Run `bun add yaml` in Tools directory |
+| Voice not working | Check pai-voice-system is running on port 8888 |
+| Display garbled | Terminal may not support ANSI colors |
+
+## Integration Verification
+
+After installation, verify integration with other skills:
+
+```bash
+# Test that Agents skill is available (for custom agent composition)
+[ -f "$PAI_DIR/skills/Agents/Tools/AgentFactory.ts" ] && echo "Agents skill: OK" || echo "Agents skill: MISSING"
+
+# Test that CORE skill is available (for user context)
+[ -f "$PAI_DIR/skills/CORE/SKILL.md" ] && echo "CORE skill: OK" || echo "CORE skill: MISSING"
+```
diff --git a/Packs/pai-algorithm-skill/package.json b/Packs/pai-algorithm-skill/package.json
new file mode 100644
index 00000000..ca8bf982
--- /dev/null
+++ b/Packs/pai-algorithm-skill/package.json
@@ -0,0 +1,54 @@
+{
+ "name": "pai-algorithm-skill",
+ "version": "0.5.0",
+ "description": "THE ALGORITHM - Universal execution engine using scientific method to achieve ideal state",
+ "type": "module",
+ "scripts": {
+ "effort": "bun run src/skills/THEALGORITHM/Tools/EffortClassifier.ts",
+ "capabilities": "bun run src/skills/THEALGORITHM/Tools/CapabilityLoader.ts",
+ "select": "bun run src/skills/THEALGORITHM/Tools/CapabilitySelector.ts",
+ "isc": "bun run src/skills/THEALGORITHM/Tools/ISCManager.ts",
+ "traits": "bun run src/skills/THEALGORITHM/Tools/TraitModifiers.ts",
+ "ralph": "bun run src/skills/THEALGORITHM/Tools/RalphLoopExecutor.ts",
+ "display": "bun run src/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts"
+ },
+ "keywords": [
+ "pai",
+ "personal-ai-infrastructure",
+ "algorithm",
+ "execution-engine",
+ "isc",
+ "ideal-state-criteria",
+ "capability-routing",
+ "effort-classification",
+ "ralph-loop"
+ ],
+ "author": "PAI Community",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "yaml": "^2.3.0"
+ },
+ "devDependencies": {
+ "bun-types": "latest",
+ "typescript": "^5.0.0"
+ },
+ "engines": {
+ "bun": ">=1.0.0"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/danielmiessler/PAI"
+ },
+ "bugs": {
+ "url": "https://github.com/danielmiessler/PAI/issues"
+ },
+ "pai": {
+ "pack_version": "1.0",
+ "skills": ["THEALGORITHM"],
+ "requires_core": true,
+ "optional_dependencies": [
+ "pai-agents-skill",
+ "pai-browser-skill"
+ ]
+ }
+}
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Data/Capabilities.yaml b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Data/Capabilities.yaml
new file mode 100644
index 00000000..1e4ec0ea
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Data/Capabilities.yaml
@@ -0,0 +1,240 @@
+# THE ALGORITHM Capabilities Registry
+# Source of truth for all orchestratable capabilities
+# Effort levels: TRIVIAL < QUICK < STANDARD < THOROUGH < DETERMINED
+
+version: "1.0"
+
+# === COMPUTE RESOURCES ===
+models:
+ haiku:
+ effort_min: QUICK
+ description: "Fast, cheap execution"
+ use_for: "Parallel grunt work, simple execution, spotchecks"
+ sonnet:
+ effort_min: STANDARD
+ description: "Balanced reasoning"
+ use_for: "Analysis, planning, research, standard work"
+ opus:
+ effort_min: DETERMINED
+ description: "Maximum intelligence"
+ use_for: "Architecture, critical decisions, complex reasoning"
+
+# === THINKING MODES ===
+thinking:
+ ultrathink:
+ skill: BeCreative
+ workflow: StandardCreativity
+ effort_min: STANDARD
+ use_when: "Need creative solutions, novel approaches, quality thinking"
+
+ tree_of_thought:
+ skill: BeCreative
+ workflow: TreeOfThoughts
+ effort_min: THOROUGH
+ use_when: "Complex multi-factor decisions, branching exploration"
+
+ plan_mode:
+ tool: EnterPlanMode
+ effort_min: THOROUGH
+ use_when: "Complex multi-step implementation needing user approval"
+
+# === DEBATE SYSTEMS ===
+debate:
+ council:
+ skill: Council
+ workflow: DEBATE
+ effort_min: THOROUGH
+ agents: 4
+ rounds: 3
+ use_when: "Need multiple perspectives, collaborative analysis, design decisions"
+
+ redteam:
+ skill: RedTeam
+ workflow: ParallelAnalysis
+ effort_min: DETERMINED
+ agents: 32
+ use_when: "Adversarial validation, stress-testing, find weaknesses"
+
+# === ANALYSIS MODES ===
+analysis:
+ first_principles:
+ skill: FirstPrinciples
+ effort_min: STANDARD
+ use_when: "Challenge assumptions, find root truths, deconstruct problems"
+
+ science:
+ skill: Science
+ effort_min: STANDARD
+ use_when: "Hypothesis-driven exploration, systematic experimentation"
+
+# === RESEARCH AGENTS ===
+research:
+ perplexity:
+ subagent_type: PerplexityResearcher
+ model: sonnet
+ effort_min: STANDARD
+ use_when: "Web research, current events, citations needed"
+
+ gemini:
+ subagent_type: GeminiResearcher
+ model: sonnet
+ effort_min: STANDARD
+ use_when: "Multi-perspective research, parallel query decomposition"
+
+ grok:
+ subagent_type: GrokResearcher
+ model: sonnet
+ effort_min: STANDARD
+ use_when: "Contrarian analysis, unbiased fact-checking"
+
+ claude:
+ subagent_type: ClaudeResearcher
+ model: sonnet
+ effort_min: STANDARD
+ use_when: "Academic research, scholarly sources"
+
+ codex:
+ subagent_type: CodexResearcher
+ model: sonnet
+ effort_min: STANDARD
+ use_when: "Technical archaeology, code pattern research"
+
+# === EXECUTION AGENTS ===
+execution:
+ intern:
+ subagent_type: Intern
+ model: haiku
+ effort_min: QUICK
+ use_when: "Parallel grunt work, simple tasks, data gathering"
+
+ architect:
+ subagent_type: Architect
+ model: opus
+ effort_min: THOROUGH
+ use_when: "System design, architectural decisions"
+
+ engineer:
+ subagent_type: Engineer
+ model: sonnet
+ effort_min: STANDARD
+ use_when: "Implementation, coding tasks"
+
+ qa_tester:
+ subagent_type: QATester
+ model: sonnet
+ effort_min: STANDARD
+ use_when: "Testing, validation, quality assurance"
+
+ designer:
+ subagent_type: Designer
+ model: sonnet
+ effort_min: STANDARD
+ use_when: "UX/UI design, user-centered solutions"
+
+ pentester:
+ subagent_type: Pentester
+ model: sonnet
+ effort_min: THOROUGH
+ use_when: "Security testing, vulnerability assessment"
+
+ ralph_loop:
+ type: iterative_loop
+ model: sonnet
+ effort_min: QUICK
+ icon: "loop"
+ keywords:
+ - "iterate until"
+ - "keep trying"
+ - "until tests pass"
+ - "until it works"
+ - "persistent"
+ - "retry until"
+ - "loop until"
+ - "ralph"
+ - "keep iterating"
+ - "don't stop until"
+ max_iterations_default: 10
+ completion_detection: promise_tags
+ plugin_source: ralph-wiggum
+ use_when: "Need persistent iteration until success criteria met - tests passing, goal achieved, or completion promise detected"
+
+# === AGENT COMPOSITION ===
+agent_composition:
+ factory:
+ tool: AgentFactory
+ location: $PAI_DIR/skills/Agents/Tools/AgentFactory.ts
+ effort_min: STANDARD
+ traits_file: $PAI_DIR/skills/Agents/Data/Traits.yaml
+ use_when: "Need custom agent with specific trait combination"
+
+# === PARALLEL EXECUTION ===
+parallel:
+ max_concurrent:
+ QUICK: 1
+ STANDARD: 3
+ THOROUGH: 5
+ DETERMINED: 10
+ background_enabled: true
+ spotcheck_required: true
+ spotcheck_model: haiku
+
+# === VERIFICATION ===
+verification:
+ browser:
+ skill: Browser
+ effort_min: STANDARD
+ use_when: "Web application validation, visual verification"
+
+ skeptical_verifier:
+ traits: [skeptical, meticulous, adversarial]
+ model: sonnet
+ rule: "Must be different agent than executor"
+ use_when: "Validate work against ISC criteria"
+
+# === EFFORT SUMMARY ===
+effort_unlocks:
+ TRIVIAL:
+ description: "Skip algorithm, direct response"
+ capabilities: []
+
+ QUICK:
+ description: "Single-step, fast execution"
+ capabilities:
+ - models.haiku
+ - execution.intern
+ - execution.ralph_loop
+
+ STANDARD:
+ description: "Multi-step bounded work"
+ capabilities:
+ - models.haiku
+ - models.sonnet
+ - thinking.ultrathink
+ - analysis.first_principles
+ - analysis.science
+ - research.* # single researcher
+ - execution.intern
+ - execution.engineer
+ - execution.qa_tester
+ - execution.designer
+ - agent_composition
+ - verification.browser
+ - verification.skeptical_verifier
+
+ THOROUGH:
+ description: "Complex, multi-file work"
+ capabilities:
+ - all_standard
+ - thinking.tree_of_thought
+ - thinking.plan_mode
+ - debate.council
+ - research.* # parallel researchers
+ - execution.architect
+ - execution.pentester
+
+ DETERMINED:
+ description: "Mission-critical, unlimited iteration"
+ capabilities:
+ - all_capabilities
+ - models.opus
+ - debate.redteam
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Build.md b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Build.md
new file mode 100644
index 00000000..0ef43d51
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Build.md
@@ -0,0 +1,76 @@
+# BUILD Phase
+
+**Purpose:** REFINE ISC rows for testability.
+
+**ISC Mutation:** REFINE rows (make each verifiable)
+
+**Gate Question:** Is each row specific enough to verify?
+
+## What Happens
+
+1. **Review each row** - Can it be tested?
+2. **Add success criteria** - How do we know it's done?
+3. **Make rows measurable** - Specific, not vague
+4. **Prepare verification plan** - How will VERIFY phase check this?
+
+## Testability Checklist
+
+For each row, ask:
+- [ ] Can I write a test for this?
+- [ ] Can I visually verify this?
+- [ ] Is there a measurable outcome?
+- [ ] Will I know when it's done?
+
+## Refinement Examples
+
+**Vague → Specific:**
+
+| Before | After |
+|--------|-------|
+| "Works well" | "Response time < 200ms" |
+| "Looks good" | "Matches design mockup, passes visual diff" |
+| "Secure" | "No XSS, SQL injection, or CSRF vulnerabilities" |
+| "Tests pass" | "All existing tests pass, 2+ new tests added" |
+| "Handles errors" | "Shows user-friendly error message on failure" |
+
+**Adding verification method:**
+
+| Row | Verification Method |
+|-----|---------------------|
+| "Button in navbar" | Browser screenshot shows button |
+| "Logout works" | Click test, verify redirect |
+| "Tests pass" | `bun test` exits 0 |
+| "TypeScript" | `tsc --noEmit` passes |
+
+## Example
+
+**Before BUILD:**
+| # | What Ideal Looks Like |
+|---|------------------------|
+| 1 | Logout button in navbar |
+| 2 | Clicking logs out and redirects |
+| 7 | Browser-verified |
+
+**After BUILD:**
+| # | What Ideal Looks Like |
+|---|------------------------|
+| 1 | Logout button visible in navbar (top-right, matches existing button style) |
+| 2 | Click logout → clears session → redirects to /login within 500ms |
+| 7 | Browser screenshot confirms button visible and functional |
+
+## Commands
+
+```bash
+# Update phase
+bun run ISCManager.ts phase -p BUILD
+
+# Rows are refined in place (update descriptions if needed)
+bun run ISCManager.ts show -o markdown
+```
+
+## Exit Criteria
+
+- Every row has clear success criteria
+- Verification method identified for each
+- No vague or unmeasurable rows
+- Ready for EXECUTE phase
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Execute.md b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Execute.md
new file mode 100644
index 00000000..10ef4635
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Execute.md
@@ -0,0 +1,263 @@
+# EXECUTE Phase
+
+**Purpose:** DO the work - spawn agents based on assigned capabilities for each ISC row.
+
+**ISC Mutation:** STATUS changes (PENDING → ACTIVE → DONE/ADJUSTED/BLOCKED)
+
+**Gate Question:** All rows addressed? Capabilities executed properly?
+
+## What Happens
+
+1. **Execute by capability phase** - Research first, then thinking, then execution
+2. **Update status in real-time** - Mark ACTIVE when starting, DONE when complete
+3. **Spawn agents based on assigned capabilities** - Use Task tool with appropriate subagent_type
+4. **Handle blockers** - Mark BLOCKED with reason if stuck
+5. **Run parallel rows simultaneously** - Rows marked × execute concurrently
+
+## Capability-Based Execution Flow
+
+Execute ISC rows in phases based on their assigned capabilities:
+
+```
+PHASE A: RESEARCH (first - parallel)
+├─ 🔬 research.perplexity → Task(subagent_type: PerplexityResearcher)
+├─ 🔬 research.gemini → Task(subagent_type: GeminiResearcher)
+├─ 🔬 research.grok → Task(subagent_type: GrokResearcher)
+├─ 🔬 research.claude → Task(subagent_type: ClaudeResearcher)
+└─ 🔬 research.codex → Task(subagent_type: CodexResearcher)
+
+PHASE B: THINKING (synthesis - sequential)
+├─ 💡 thinking.ultrathink → Skill(BeCreative)
+├─ 💡 thinking.tree_of_thought → Skill(BeCreative, workflow: TreeOfThoughts)
+├─ 🔍 analysis.first_principles → Skill(FirstPrinciples)
+├─ 🔍 analysis.science → Skill(Science)
+└─ 🗣️ debate.council → Skill(Council)
+
+PHASE C: EXECUTION (implementation - parallel where marked)
+├─ 🤖 execution.intern → Task(subagent_type: Intern, model: haiku)
+├─ 🤖 execution.engineer → Task(subagent_type: Engineer)
+├─ 🤖 execution.designer → Task(subagent_type: Designer)
+├─ 🤖 execution.architect → Task(subagent_type: Architect, model: opus)
+├─ 🤖 execution.pentester → Task(subagent_type: Pentester)
+└─ 🔄 execution.ralph_loop → RalphLoopExecutor (iterative until success)
+
+PHASE D: VERIFICATION (validation - last)
+├─ ✅ verification.browser → Skill(Browser)
+└─ ✅ verification.skeptical_verifier → Task with skeptical,meticulous,adversarial traits
+```
+
+## Spawning Agents by Capability
+
+### Research Agents
+
+```typescript
+// For rows with research.* capability
+Task({
+ description: "Research: [ISC row description]",
+ prompt: "[Row description] - find current best practices, cite sources",
+ subagent_type: "PerplexityResearcher", // or GeminiResearcher, GrokResearcher, etc.
+ model: "sonnet",
+ run_in_background: true // for parallel research
+})
+```
+
+### Execution Agents
+
+```typescript
+// For rows with execution.* capability
+Task({
+ description: "Execute: [ISC row description]",
+ prompt: "[Row description] - implement this requirement",
+ subagent_type: "Engineer", // or Architect, Designer, etc.
+ model: "sonnet" // or opus for Architect
+})
+```
+
+### Skills (Thinking/Debate/Analysis)
+
+```typescript
+// For rows with thinking.*, analysis.*, or debate.* capability
+Skill({
+ skill: "BeCreative", // or Council, FirstPrinciples, etc.
+ args: "[Row description]"
+})
+```
+
+### Ralph Loop Execution (🔄)
+
+For ISC rows assigned `execution.ralph_loop` - persistent iteration until success:
+
+```bash
+# Start a Ralph loop for an ISC row
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/RalphLoopExecutor.ts \
+ --prompt "Fix the auth bug until all tests pass" \
+ --completion-promise "All tests pass" \
+ --max-iterations 15 \
+ --isc-row 3
+```
+
+**How Ralph Loop works:**
+1. Creates state file with prompt and completion criteria
+2. Claude works on the task, tries to exit
+3. Stop hook intercepts exit and feeds SAME prompt back
+4. Claude sees previous work in files/git history
+5. Loop continues until:
+ - Completion promise detected in `<promise>PROMISE_TEXT</promise>` tags
+ - Max iterations reached
+
+**When to use Ralph Loop:**
+- Tasks requiring iteration until tests pass
+- Bug fixes that need multiple attempts
+- Refactoring that benefits from progressive improvement
+- Any task with clear, verifiable success criteria
+
+**ISC Status for Ralph rows:**
+- `⏳ PENDING` - Not started
+- `🔄 LOOPING` - Ralph loop active (custom status)
+- `✅ DONE` - Completion promise detected
+- `🚫 BLOCKED` - Max iterations exhausted without success
+
+**Monitoring Ralph loops:**
+```bash
+# Check status
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/RalphLoopExecutor.ts --status
+
+# Cancel loop
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/RalphLoopExecutor.ts --cancel
+```
+
+**Keywords that trigger Ralph Loop assignment:**
+- "iterate until", "keep trying", "until tests pass"
+- "until it works", "persistent", "retry until"
+- "loop until", "ralph", "keep iterating"
+
+## Parallel Execution
+
+Rows marked with × (parallel) can be executed simultaneously:
+
+```typescript
+// Multiple agents in single response = parallel execution
+Task({ description: "Row 1", subagent_type: "Engineer", run_in_background: true })
+Task({ description: "Row 2", subagent_type: "Engineer", run_in_background: true })
+Task({ description: "Row 3", subagent_type: "Designer", run_in_background: true })
+```
+
+**Max concurrent by effort level:**
+| Effort | Max Parallel |
+|--------|--------------|
+| QUICK | 1 |
+| STANDARD | 3 |
+| THOROUGH | 5 |
+| DETERMINED | 10 |
+
+**Parallelization rules:**
+- Research tasks = usually parallelizable
+- Independent implementation tasks = parallelizable
+- Sequential dependencies = NOT parallelizable
+- Rows with × suffix on capability = parallelizable
+
+## Status Updates
+
+```bash
+# Mark row as active (starting work)
+bun run ISCManager.ts update --row 1 --status ACTIVE
+
+# Mark row as done
+bun run ISCManager.ts update --row 1 --status DONE
+
+# Mark row as blocked
+bun run ISCManager.ts update --row 1 --status BLOCKED --reason "Missing API key"
+
+# Mark row as adjusted (scope changed)
+bun run ISCManager.ts update --row 1 --status ADJUSTED --reason "Used REST instead of GraphQL"
+```
+
+## Example Execution
+
+**ISC before EXECUTE:**
+```markdown
+| # | What Ideal Looks Like | Capability | Status |
+|---|----------------------|------------|--------|
+| 1 | Research good patterns | 🔬 perplexity× | ⏳ PENDING |
+| 2 | Research competitor impl | 🔬 gemini× | ⏳ PENDING |
+| 3 | Synthesize findings | 💡 ultrathink | ⏳ PENDING |
+| 4 | Design component | 🤖 designer | ⏳ PENDING |
+| 5 | Implement component | 🤖 engineer× | ⏳ PENDING |
+| 6 | Implement styling | 🤖 engineer× | ⏳ PENDING |
+| 7 | Browser verify | ✅ browser | ⏳ PENDING |
+```
+
+**Execution flow:**
+
+**Phase A: Research (parallel)**
+```typescript
+// Both run in background simultaneously
+Task({ description: "Research patterns", subagent_type: "PerplexityResearcher", run_in_background: true })
+Task({ description: "Research competitors", subagent_type: "GeminiResearcher", run_in_background: true })
+```
+→ Wait for both to complete → Mark rows 1, 2 DONE
+
+**Phase B: Thinking**
+```typescript
+Skill({ skill: "BeCreative", args: "Synthesize research findings into design approach" })
+```
+→ Mark row 3 DONE
+
+**Phase C: Execution (parallel where marked)**
+```typescript
+Task({ description: "Design component", subagent_type: "Designer" })
+```
+→ Mark row 4 DONE
+
+```typescript
+// Parallel implementation
+Task({ description: "Implement component", subagent_type: "Engineer", run_in_background: true })
+Task({ description: "Implement styling", subagent_type: "Engineer", run_in_background: true })
+```
+→ Wait for both → Mark rows 5, 6 DONE
+
+**Phase D: Verification**
+```typescript
+Skill({ skill: "Browser", args: "Verify component renders correctly" })
+```
+→ Mark row 7 DONE
+
+**ISC after EXECUTE:**
+```markdown
+| # | What Ideal Looks Like | Capability | Status |
+|---|----------------------|------------|--------|
+| 1 | Research good patterns | 🔬 perplexity× | ✅ DONE |
+| 2 | Research competitor impl | 🔬 gemini× | ✅ DONE |
+| 3 | Synthesize findings | 💡 ultrathink | ✅ DONE |
+| 4 | Design component | 🤖 designer | ✅ DONE |
+| 5 | Implement component | 🤖 engineer× | ✅ DONE |
+| 6 | Implement styling | 🤖 engineer× | ✅ DONE |
+| 7 | Browser verify | ✅ browser | ✅ DONE |
+```
+
+## Commands
+
+```bash
+# Update phase
+bun run ISCManager.ts phase -p EXECUTE
+
+# Start a row
+bun run ISCManager.ts update --row 1 --status ACTIVE
+
+# Complete a row
+bun run ISCManager.ts update --row 1 --status DONE
+
+# Check progress
+bun run ISCManager.ts summary
+
+# View current ISC
+bun run ISCManager.ts show
+```
+
+## Exit Criteria
+
+- All rows have been attempted
+- Capabilities executed in correct phase order
+- Each row is DONE, ADJUSTED, or BLOCKED
+- No row left in PENDING or ACTIVE state
+- Ready for VERIFY phase
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Learn.md b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Learn.md
new file mode 100644
index 00000000..04ab60a0
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Learn.md
@@ -0,0 +1,178 @@
+# LEARN Phase
+
+**Purpose:** OUTPUT results for user to evaluate. User rates outputs for the memory system.
+
+**ISC Mutation:** ARCHIVE completed ISC, output results
+
+**Gate Question:** Have I provided everything the user needs to evaluate the work?
+
+**CRITICAL:** NO SELF-RATING. The assistant does NOT rate its own work. User rates outputs for the memory system.
+
+## What Happens
+
+1. **Output final ISC** - Show completed state with all capabilities and statuses
+2. **Present deliverables** - Show what was produced
+3. **Document capability usage** - What capabilities were used and how they performed
+4. **Archive or iterate** - Complete if successful, iterate if blocked
+
+## NO Self-Rating
+
+**DO NOT:**
+- Rate your own work on a scale
+- Assign "fidelity scores"
+- Self-assess quality
+- Grade your own performance
+
+**DO:**
+- Present the work clearly
+- Show what was accomplished
+- Document what capabilities were used
+- Let user evaluate and rate for memory
+
+## Output Format
+
+Present results clearly for user to evaluate:
+
+```markdown
+## 🎯 FINAL ISC
+
+**Request:** [original request]
+**Effort:** [LEVEL] | **Iterations:** [count]
+
+| # | What Ideal Looks Like | Source | Capability | Status |
+|---|----------------------|--------|------------|--------|
+| 1 | [row 1] | EXPLICIT | 🔬 perplexity | ✅ DONE |
+| 2 | [row 2] | INFERRED | 🤖 engineer | ✅ DONE |
+...
+
+## Deliverables
+
+[Present what was created/accomplished]
+
+## Capability Performance
+
+| Capability Used | Result | Notes |
+|----------------|--------|-------|
+| research.perplexity | Success | Found key patterns |
+| execution.engineer | Success | Parallel tasks efficient |
+...
+
+## For Memory System
+
+User: Please rate this work for the memory system.
+```
+
+## Learning Categories
+
+| Category | What to Document | For |
+|----------|------------------|-----|
+| **Capability Usage** | Which capabilities were effective? | Future task planning |
+| **Process** | What phases were hard? Easy? | Algorithm improvement |
+| **Estimation** | Was effort level accurate? | Calibration |
+
+## Review the Evolution
+
+```bash
+# View the full evolution log
+bun run ISCManager.ts log
+
+# View final ISC state
+bun run ISCManager.ts show -o markdown
+
+# Get summary statistics
+bun run ISCManager.ts summary
+```
+
+## Document Capability Usage
+
+For each capability used, note:
+- **What capability:** e.g., `research.perplexity`, `execution.engineer`
+- **What it did:** Brief description of how it was used
+- **Effectiveness:** Did it work well for this task?
+
+This helps improve future capability selection.
+
+## Iteration Decision
+
+| Outcome | Action |
+|---------|--------|
+| All rows PASS/ADJUSTED | Archive ISC, output for user |
+| Some rows BLOCKED | Iterate - return to appropriate phase |
+| Scope fundamentally wrong | Iterate from OBSERVE |
+
+**Iteration flow:**
+```
+BLOCKED in verification
+ ↓
+Analyze blockers
+ ↓
+If implementation issue → Return to EXECUTE
+If plan issue → Return to PLAN
+If requirements issue → Return to THINK
+If scope issue → Return to OBSERVE
+ ↓
+Increment iteration counter
+ ↓
+Re-run from that phase
+```
+
+## Archive Completed Work
+
+```bash
+# Archive the ISC (saves to archive, clears current)
+bun run ISCManager.ts clear
+
+# This creates: $PAI_DIR/MEMORY/Work/archive-{timestamp}.json
+```
+
+## Example Output
+
+**Request:** "Add logout button to navbar"
+**Effort:** STANDARD | **Iterations:** 1
+
+**ISC Final State:**
+- 7 rows total
+- 6 PASS, 1 ADJUSTED
+- 2 parallel execution groups
+
+**Capabilities Used:**
+| Capability | Result | Notes |
+|------------|--------|-------|
+| execution.engineer×2 | Success | Parallel UI tasks |
+| execution.qa_tester | Success | Caught mobile issue |
+| verification.browser | Success | Visual verification |
+
+**Deliverables:**
+- Logout button component in `components/LogoutButton.tsx`
+- Updated navbar with logout integration
+- Tests passing, browser-verified
+
+**For Memory System:**
+User: Please rate this work for the memory system.
+
+## Commands
+
+```bash
+# Update phase
+bun run ISCManager.ts phase -p LEARN
+
+# Start new iteration (if needed)
+bun run ISCManager.ts iterate
+
+# Archive completed ISC
+bun run ISCManager.ts clear
+```
+
+## Exit Criteria
+
+**If successful:**
+- Final ISC displayed with capabilities
+- Deliverables presented
+- Capability usage documented
+- Ready for user's evaluation
+
+**If iterating:**
+- Blockers analyzed
+- Return phase identified
+- Iteration counter incremented
+- Ready to re-enter earlier phase
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Observe.md b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Observe.md
new file mode 100644
index 00000000..247b3442
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Observe.md
@@ -0,0 +1,76 @@
+# OBSERVE Phase
+
+**Purpose:** CREATE ISC rows from the request and user context.
+
+**ISC Mutation:** CREATE rows
+
+**Gate Question:** Do I have 2+ rows? Did I use user context to infer requirements?
+
+## What Happens
+
+1. **Parse the request** - Identify explicit requirements
+2. **Load user context** - Read CORE preferences, tech stack, patterns
+3. **Create EXPLICIT rows** - What user literally asked for
+4. **Create INFERRED rows** - What context implies (TypeScript from prefs, etc.)
+5. **Create IMPLICIT rows** - Universal standards (security, tests pass, quality)
+
+## Context Sources
+
+| Source | File | Infers |
+|--------|------|--------|
+| Tech Stack | TECHSTACKPREFERENCES.md | TypeScript > Python, bun, markdown |
+| Assets | ASSETMANAGEMENT.md | Deployment patterns, project structure |
+| Definitions | DEFINITIONS.md | User's canonical terms |
+| Contacts | CONTACTS.md | People references |
+
+## Row Creation Guidelines
+
+**EXPLICIT rows:**
+- Direct quotes from the request
+- Specific features mentioned
+- Clear success criteria stated
+
+**INFERRED rows:**
+- From TECHSTACKPREFERENCES: "Uses TypeScript", "Uses bun"
+- From project context: "Follows existing patterns"
+- From session history: "Consistent with previous work"
+
+**IMPLICIT rows:**
+- "No security vulnerabilities"
+- "Existing tests continue to pass"
+- "No regressions introduced"
+- "Code is readable and maintainable"
+
+## Example
+
+**Request:** "Add a logout button to the navbar"
+
+**OBSERVE creates:**
+
+| # | What Ideal Looks Like | Source |
+|---|------------------------|--------|
+| 1 | Logout button in navbar | EXPLICIT |
+| 2 | Clicking logs user out | EXPLICIT |
+| 3 | Uses TypeScript | INFERRED |
+| 4 | Follows existing component patterns | INFERRED |
+| 5 | No security issues | IMPLICIT |
+| 6 | Existing tests pass | IMPLICIT |
+
+## Commands
+
+```bash
+# Create ISC with request
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/ISCManager.ts create --request "Add logout button"
+
+# Add rows as you identify them
+bun run ISCManager.ts add -d "Logout button in navbar" -s EXPLICIT
+bun run ISCManager.ts add -d "Uses TypeScript" -s INFERRED
+bun run ISCManager.ts add -d "Tests pass" -s IMPLICIT
+```
+
+## Exit Criteria
+
+- At least 2 ISC rows created
+- User context was consulted for INFERRED rows
+- IMPLICIT standards are included
+- Ready for THINK phase
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Plan.md b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Plan.md
new file mode 100644
index 00000000..dcac7789
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Plan.md
@@ -0,0 +1,88 @@
+# PLAN Phase
+
+**Purpose:** ORDER ISC rows for execution.
+
+**ISC Mutation:** ORDER rows (sequence, mark parallel)
+
+**Gate Question:** Dependencies mapped? Know the sequence?
+
+## What Happens
+
+1. **Identify dependencies** - What must happen before what?
+2. **Mark parallel rows** - Which can run simultaneously?
+3. **Determine sequence** - Order for execution
+4. **Identify blockers** - What could block progress?
+
+## Parallelization Rules
+
+Mark rows with `[P]` if they:
+- Don't depend on other rows' output
+- Don't modify the same files
+- Can be verified independently
+
+**Example parallel groups:**
+- Research tasks (different topics)
+- Independent file changes
+- Separate test suites
+
+**Example sequential dependencies:**
+- Implementation → Tests → Deployment
+- Create file → Modify file → Verify file
+
+## Example
+
+**Before PLAN:**
+| # | What Ideal Looks Like | Source | Parallel |
+|---|------------------------|--------|----------|
+| 1 | Logout button in navbar | EXPLICIT | ? |
+| 2 | Clicking logs out and redirects | EXPLICIT | ? |
+| 3 | Uses TypeScript | INFERRED | ? |
+| 4 | Handles failure gracefully | INFERRED | ? |
+| 5 | CSRF protection | IMPLICIT | ? |
+| 6 | Tests pass | IMPLICIT | ? |
+| 7 | Browser-verified | IMPLICIT | ? |
+
+**After PLAN:**
+| # | What Ideal Looks Like | Source | Parallel | Order |
+|---|------------------------|--------|----------|-------|
+| 3 | Uses TypeScript | INFERRED | ✓ | 1 |
+| 5 | CSRF protection | IMPLICIT | ✓ | 1 |
+| 1 | Logout button in navbar | EXPLICIT | ✓ | 2 |
+| 4 | Handles failure gracefully | INFERRED | ✓ | 2 |
+| 2 | Clicking logs out and redirects | EXPLICIT | - | 3 |
+| 6 | Tests pass | IMPLICIT | - | 4 |
+| 7 | Browser-verified | IMPLICIT | - | 5 |
+
+**Execution groups:**
+1. Setup (parallel): TypeScript config, CSRF setup
+2. Implementation (parallel): Button component, error handling
+3. Integration: Wire up logout action
+4. Validation: Run tests
+5. Verification: Browser check
+
+## Commands
+
+```bash
+# Update phase
+bun run ISCManager.ts phase -p PLAN
+
+# View current ISC
+bun run ISCManager.ts show -o markdown
+```
+
+## For THOROUGH+ Effort
+
+Consider using Architect agent for complex sequencing:
+
+```bash
+bun run $PAI_DIR/skills/Agents/Tools/AgentFactory.ts \
+ --task "Plan execution order for these requirements" \
+ --traits "analytical,systematic,meticulous"
+```
+
+## Exit Criteria
+
+- All dependencies identified
+- Parallel rows marked
+- Execution sequence clear
+- Ready for BUILD phase
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Think.md b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Think.md
new file mode 100644
index 00000000..595ee166
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Think.md
@@ -0,0 +1,78 @@
+# THINK Phase
+
+**Purpose:** COMPLETE ISC rows - ensure nothing is missing.
+
+**ISC Mutation:** COMPLETE rows (add missing, refine existing)
+
+**Gate Question:** All rows clear and testable? Missing anything from user preferences?
+
+## What Happens
+
+1. **Review all rows** - Are they complete?
+2. **Check for gaps** - What's missing?
+3. **Add missing rows** - INFERRED and IMPLICIT
+4. **Refine descriptions** - Make them clearer
+5. **Consider edge cases** - What could go wrong?
+
+## For THOROUGH+ Effort
+
+Consider using additional resources:
+
+- **BeCreative skill** - UltraThink for deep analysis
+- **Council skill** - Multiple perspectives on requirements
+- **AgentFactory** - Spawn a "thinking" agent with `analytical,exploratory` traits
+
+```bash
+# Compose a thinking agent
+bun run $PAI_DIR/skills/Agents/Tools/AgentFactory.ts \
+ --task "What requirements might be missing for: [request]" \
+ --traits "analytical,exploratory,thorough"
+```
+
+## Completeness Checklist
+
+- [ ] All explicit requirements captured?
+- [ ] Tech stack preferences applied?
+- [ ] Security considerations included?
+- [ ] Error handling considered?
+- [ ] Edge cases identified?
+- [ ] Testing requirements clear?
+- [ ] Performance expectations stated?
+- [ ] Deployment/verification needs?
+
+## Example
+
+**After OBSERVE:**
+| # | What Ideal Looks Like | Source |
+|---|------------------------|--------|
+| 1 | Logout button in navbar | EXPLICIT |
+| 2 | Uses TypeScript | INFERRED |
+
+**After THINK (gaps identified):**
+| # | What Ideal Looks Like | Source |
+|---|------------------------|--------|
+| 1 | Logout button in navbar | EXPLICIT |
+| 2 | Clicking logs user out and redirects to login | EXPLICIT (refined) |
+| 3 | Uses TypeScript | INFERRED |
+| 4 | Handles logout failure gracefully | INFERRED |
+| 5 | No security issues (CSRF protection) | IMPLICIT |
+| 6 | Existing tests pass | IMPLICIT |
+| 7 | Browser-verified working | IMPLICIT |
+
+## Commands
+
+```bash
+# Update phase
+bun run ISCManager.ts phase -p THINK
+
+# Add missing rows
+bun run ISCManager.ts add -d "Handles logout failure gracefully" -s INFERRED
+bun run ISCManager.ts add -d "Browser-verified working" -s IMPLICIT
+```
+
+## Exit Criteria
+
+- All rows are clear and specific
+- No obvious gaps remain
+- Edge cases considered
+- Ready for PLAN phase
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Verify.md b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Verify.md
new file mode 100644
index 00000000..0d90e826
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Phases/Verify.md
@@ -0,0 +1,150 @@
+# VERIFY Phase
+
+**Purpose:** CHECK each ISC row against its success criteria.
+
+**ISC Mutation:** VERIFY results (PASS/ADJUSTED/BLOCKED)
+
+**Gate Question:** Does reality match ideal? What gaps remain?
+
+## What Happens
+
+1. **Verify each row** - Test against success criteria from BUILD phase
+2. **Use appropriate verification method** - Tests, visual checks, browser automation
+3. **Record results** - PASS, ADJUSTED (acceptable deviation), or BLOCKED
+4. **Identify gaps** - What didn't work as expected?
+
+## Verification Traits
+
+**CRITICAL:** Verification agents ALWAYS use skeptical traits, regardless of effort level.
+
+```bash
+# Verification always uses these traits:
+--traits "skeptical,meticulous,adversarial"
+```
+
+This ensures verification is independent and rigorous, not just confirming what we expect.
+
+## Verification Methods
+
+| Verification Type | Method | Example |
+|-------------------|--------|---------|
+| **Automated Tests** | `bun test`, `npm test` | "All tests pass" |
+| **Type Checking** | `tsc --noEmit` | "TypeScript compiles" |
+| **Visual** | Browser skill screenshot | "Button visible in navbar" |
+| **Functional** | Browser skill interaction | "Click logs out user" |
+| **Performance** | Timing measurement | "Response < 200ms" |
+| **Security** | Security scan tools | "No XSS vulnerabilities" |
+
+## Browser Verification
+
+For UI/UX verification, use the Browser skill:
+
+```bash
+# Take screenshot
+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot <url> /tmp/verify.png
+
+# Verify element exists
+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts verify <url> "button.logout"
+
+# View screenshot
+Read /tmp/verify.png
+```
+
+## Verification Results
+
+| Result | Meaning | Action |
+|--------|---------|--------|
+| **PASS** | Meets success criteria exactly | Row complete |
+| **ADJUSTED** | Acceptable deviation from ideal | Document why, row complete |
+| **BLOCKED** | Cannot verify, issue found | Escalate or iterate |
+
+## Recording Results
+
+```bash
+# Row passes verification
+bun run ISCManager.ts verify --row 1 --result PASS
+
+# Row adjusted (acceptable deviation)
+bun run ISCManager.ts verify --row 2 --result ADJUSTED --reason "250ms instead of 200ms - acceptable"
+
+# Row blocked (verification failed)
+bun run ISCManager.ts verify --row 3 --result BLOCKED --reason "Button not visible on mobile"
+```
+
+## Example Verification
+
+**ISC rows to verify:**
+| # | What Ideal Looks Like | Verification Method |
+|---|------------------------|---------------------|
+| 1 | Logout button visible (top-right) | Browser screenshot |
+| 2 | Click logout → redirect to /login | Browser interaction |
+| 3 | Tests pass | `bun test` |
+| 4 | TypeScript compiles | `tsc --noEmit` |
+
+**Verification sequence:**
+
+```bash
+# 1. Screenshot verification
+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts screenshot http://localhost:3000 /tmp/navbar.png
+# Check: Is logout button visible top-right?
+
+# 2. Functional verification
+bun run $PAI_DIR/skills/Browser/Tools/Browse.ts open http://localhost:3000
+# Click logout, verify redirect to /login
+
+# 3. Test verification
+bun test
+# Check: Exit code 0?
+
+# 4. Type verification
+tsc --noEmit
+# Check: No errors?
+```
+
+**Results:**
+```bash
+bun run ISCManager.ts verify --row 1 --result PASS
+bun run ISCManager.ts verify --row 2 --result PASS
+bun run ISCManager.ts verify --row 3 --result PASS
+bun run ISCManager.ts verify --row 4 --result ADJUSTED --reason "1 type warning, non-blocking"
+```
+
+## Parallel Verification
+
+Independent verifications can run in parallel:
+
+- Screenshot checks (different pages)
+- Independent test suites
+- Separate type checks
+
+Sequential verification needed for:
+- Tests that modify state
+- Checks that depend on prior results
+
+## Commands
+
+```bash
+# Update phase
+bun run ISCManager.ts phase -p VERIFY
+
+# Record verification result
+bun run ISCManager.ts verify --row <id> --result <PASS|ADJUSTED|BLOCKED> [--reason "..."]
+
+# View current state
+bun run ISCManager.ts show -o markdown
+```
+
+## Handling Failures
+
+If verification finds issues:
+
+1. **Minor issue** → Mark ADJUSTED with reason, continue
+2. **Significant issue** → Mark BLOCKED, return to EXECUTE
+3. **Scope change needed** → Mark BLOCKED, return to THINK/PLAN
+
+## Exit Criteria
+
+- Every row has been verified
+- Results recorded: PASS, ADJUSTED, or BLOCKED
+- BLOCKED rows have clear reasons
+- Decision made: LEARN (success) or iterate (blocked rows)
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Reference/CapabilityMatrix.md b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Reference/CapabilityMatrix.md
new file mode 100644
index 00000000..e4f8601e
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Reference/CapabilityMatrix.md
@@ -0,0 +1,197 @@
+# Capability Matrix
+
+**Source of Truth:** `Data/Capabilities.yaml`
+
+This document describes what capabilities are unlocked at each effort level. Effort classification happens FIRST and determines which tools are available.
+
+## The Matrix
+
+| Effort Level | Models | Thinking | Debate | Analysis | Research | Execution | Verification | Parallel |
+|--------------|--------|----------|--------|----------|----------|-----------|--------------|----------|
+| **TRIVIAL** | — | — | — | — | — | — | — | 0 |
+| **QUICK** | haiku | — | — | — | — | Intern | — | 1 |
+| **STANDARD** | haiku, sonnet | UltraThink | — | FirstPrinciples, Science | single | Engineer, QA, Designer | Browser, Skeptical | 1-3 |
+| **THOROUGH** | haiku, sonnet | All | Council | All | parallel | All + Architect, Pentester | All | 3-5 |
+| **DETERMINED** | all + opus | All | Council + RedTeam | All | all | unlimited | All | 10 |
+
+## Detailed Breakdown
+
+### TRIVIAL (Skip Algorithm)
+- **When:** Greetings, simple Q&A, acknowledgments
+- **Capabilities:** None - direct response, no ISC
+- **ISC Rows:** 0
+- **Example:** "Hello", "Thanks", "What's 2+2?"
+
+### QUICK
+- **When:** Single-step tasks, simple lookups, quick fixes
+- **Capabilities:**
+ - `models.haiku` - Fast, cheap execution
+ - `execution.intern` - Parallel grunt work, simple tasks
+- **ISC Rows:** Typically 1-3, but can be more if needed
+- **Traits Added:** rapid, pragmatic
+- **Max Parallel:** 1
+- **Example:** "Fix the typo in README", "What does this function do?"
+
+### STANDARD
+- **When:** Multi-step tasks, bounded scope, most development work
+- **Capabilities:**
+ - `models.haiku` - For spotchecks, parallel work
+ - `models.sonnet` - Main reasoning model
+ - `thinking.ultrathink` - BeCreative for creative solutions
+ - `analysis.first_principles` - Challenge assumptions
+ - `analysis.science` - Hypothesis-driven exploration
+ - `research.*` (single) - One research agent at a time
+ - `execution.engineer` - Implementation
+ - `execution.qa_tester` - Testing
+ - `execution.designer` - UX/UI
+ - `verification.browser` - Web validation
+ - `verification.skeptical_verifier` - Independent verification
+ - `agent_composition` - AgentFactory for custom agents
+- **ISC Rows:** As many as needed to capture ideal state
+- **Traits Added:** analytical, systematic
+- **Max Parallel:** 3
+- **Example:** "Add dark mode to settings", "Create a new API endpoint"
+
+### THOROUGH
+- **When:** Complex work, multi-file changes, architectural decisions
+- **Capabilities:**
+ - All STANDARD capabilities
+ - `thinking.tree_of_thought` - Branching exploration
+ - `thinking.plan_mode` - EnterPlanMode for approval
+ - `debate.council` - 4-agent collaborative analysis
+ - `research.*` (parallel) - Multiple research agents simultaneously
+ - `execution.architect` - System design decisions
+ - `execution.pentester` - Security testing
+- **ISC Rows:** Dozens typically, can be hundreds for complex projects
+- **Traits Added:** thorough, meticulous
+- **Max Parallel:** 5
+- **Example:** "Refactor the authentication system", "Design a new microservice"
+
+### DETERMINED
+- **When:** Mission-critical, "until done", overnight tasks, unlimited iteration
+- **Capabilities:**
+ - All capabilities unlocked
+ - `models.opus` - Maximum intelligence model
+ - `debate.redteam` - 32-agent adversarial analysis
+ - Unlimited agents
+ - Unlimited iterations
+- **ISC Rows:** Can be hundreds or thousands for major projects
+- **Traits Added:** thorough, meticulous, adversarial
+- **Max Parallel:** 10
+- **Example:** "Build the entire feature from scratch", "Security audit everything"
+
+## ISC Scale by Effort
+
+**ISC size is NOT strictly bounded by effort level.** The effort level determines QUALITY expectations and available capabilities, not a hard limit on rows.
+
+| Effort | Typical ISC Size | Quality Standard | Notes |
+|--------|------------------|------------------|-------|
+| QUICK | 1-5 rows | Good enough | Fast execution, minimal verification |
+| STANDARD | 5-20 rows | High | Thorough verification, single-pass research |
+| THOROUGH | 20-100 rows | Very high | Multiple research passes, council debate |
+| DETERMINED | 50-1000+ rows | Exceptional | Unlimited iteration until perfect |
+
+**Key insight:** A complex problem at DETERMINED effort might have hundreds of ISC rows covering:
+- Research findings (what to do)
+- Anti-patterns (what to avoid)
+- Best practices (how to do it well)
+- Edge cases (what to handle)
+- Verification criteria (how to confirm)
+- Security considerations (what to protect)
+
+## Capability Categories Explained
+
+### Models
+Compute resources for reasoning. Higher effort unlocks more powerful models.
+
+| Model | Cost | Speed | Use For |
+|-------|------|-------|---------|
+| haiku | Low | Fast | Parallel grunt work, spotchecks, simple execution |
+| sonnet | Medium | Medium | Analysis, planning, research, standard work |
+| opus | High | Slower | Architecture, critical decisions, complex reasoning |
+
+### Thinking Modes
+Enhanced reasoning approaches.
+
+| Mode | Skill | When |
+|------|-------|------|
+| ultrathink | BeCreative | Creative solutions, novel approaches |
+| tree_of_thought | BeCreative (workflow) | Complex multi-factor decisions |
+| plan_mode | EnterPlanMode tool | Multi-step implementations needing approval |
+
+### Debate Systems
+Multi-agent discussion for better decisions.
+
+| System | Agents | Mode | When |
+|--------|--------|------|------|
+| council | 4 | Collaborative | Design decisions, trade-offs, perspectives |
+| redteam | 32 | Adversarial | Stress-testing, find weaknesses, attack surface |
+
+### Analysis Modes
+Structured analytical approaches.
+
+| Mode | Skill | When |
+|------|-------|------|
+| first_principles | FirstPrinciples | Challenge assumptions, find root truths |
+| science | Science | Hypothesis-driven exploration, experiments |
+
+### Research Agents
+Multi-source information gathering.
+
+| Agent | Model | Strength |
+|-------|-------|----------|
+| perplexity | PerplexityResearcher | Web research, current events, citations |
+| gemini | GeminiResearcher | Multi-perspective, parallel decomposition |
+| grok | GrokResearcher | Contrarian analysis, fact-checking |
+| claude | ClaudeResearcher | Academic research, scholarly sources |
+| codex | CodexResearcher | Technical archaeology, code patterns |
+
+### Execution Agents
+Work performers.
+
+| Agent | Model | When |
+|-------|-------|------|
+| intern | haiku | Parallel grunt work, simple tasks |
+| engineer | sonnet | Implementation, coding |
+| qa_tester | sonnet | Testing, validation |
+| designer | sonnet | UX/UI design |
+| architect | opus | System design, architecture |
+| pentester | sonnet | Security testing |
+
+### Verification
+Validation approaches.
+
+| Method | How | When |
+|--------|-----|------|
+| browser | Browser skill | Web application validation |
+| skeptical_verifier | Custom agent | Independent verification, different from executor |
+
+## Override Methods
+
+### CLI Override
+```bash
+bun run EffortClassifier.ts --request "any request" --override DETERMINED
+```
+
+### Inline Override
+```
+algorithm effort THOROUGH: build this complex feature
+```
+
+The inline pattern is stripped from the request and effort is forced to the specified level.
+
+## Commands
+
+```bash
+# Classify effort for a request
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/EffortClassifier.ts --request "your request"
+
+# Load capabilities for an effort level
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/CapabilityLoader.ts --effort STANDARD
+
+# List all capabilities
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/CapabilityLoader.ts --list-all
+
+# Select capabilities for an ISC row
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/CapabilitySelector.ts --row "Research best practices" --effort STANDARD
+```
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Reference/EffortMatrix.md b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Reference/EffortMatrix.md
new file mode 100644
index 00000000..04f7de91
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Reference/EffortMatrix.md
@@ -0,0 +1,133 @@
+# Effort Matrix Reference
+
+Quick reference for effort level characteristics and when to use each.
+
+## Effort Levels Overview
+
+| Level | Thinking | Agents | Iteration | Model | Use When |
+|-------|----------|--------|-----------|-------|----------|
+| TRIVIAL | None | None | None | - | Skip THE ALGORITHM entirely |
+| QUICK | Minimal | haiku | 1 | haiku | Simple, fast, low-risk |
+| STANDARD | Normal | sonnet | 1-2 | sonnet | Default for most work |
+| THOROUGH | Extended | sonnet | 2-3 | sonnet | Important, complex |
+| DETERMINED | UltraThink | opus | Until done | opus | Critical, unlimited |
+
+## Detection Keywords
+
+### TRIVIAL (Skip Algorithm)
+- "quick", "just", "simple", "tiny", "minor"
+- Single-line fixes, typos, obvious changes
+- **Action:** Do immediately, no ISC needed
+
+### QUICK
+- "fast", "brief", "quickly", "don't overthink"
+- "straightforward", "obvious"
+- Simple features, quick fixes, low complexity
+
+### STANDARD (Default)
+- Most requests without explicit effort markers
+- Normal features, typical bugs, standard implementation
+- **This is the default if no signals detected**
+
+### THOROUGH
+- "thorough", "careful", "comprehensive", "detailed"
+- "important", "critical path", "production"
+- Complex features, sensitive changes, architectural work
+
+### DETERMINED
+- "until done", "don't stop", "keep going"
+- "overnight", "whatever it takes", "unlimited"
+- Mission-critical, must succeed, no time limit
+
+## Trait Modifiers by Effort
+
+```typescript
+const EFFORT_TRAITS = {
+ QUICK: {
+ traits: ["rapid", "pragmatic"],
+ model: "haiku",
+ },
+ STANDARD: {
+ traits: ["analytical", "systematic"],
+ model: "sonnet",
+ },
+ THOROUGH: {
+ traits: ["thorough", "meticulous"],
+ model: "sonnet",
+ },
+ DETERMINED: {
+ traits: ["thorough", "meticulous", "adversarial"],
+ model: "opus",
+ },
+};
+```
+
+## Phase-Specific Traits
+
+Some phases override default traits:
+
+| Phase | Override Traits | Reason |
+|-------|-----------------|--------|
+| THINK | analytical, exploratory | Need divergent thinking |
+| VERIFY | skeptical, meticulous, adversarial | Independent validation |
+| LEARN | reflective, analytical | Pattern recognition |
+
+## Model Selection
+
+| Model | Use For | Characteristics |
+|-------|---------|-----------------|
+| haiku | QUICK tasks, simple execution | Fast, cheap, good enough |
+| sonnet | STANDARD/THOROUGH tasks | Balanced, reliable |
+| opus | DETERMINED tasks, complex analysis | Deep thinking, highest quality |
+
+## Cost/Speed Tradeoffs
+
+```
+QUICK: haiku = lowest cost, fastest
+STANDARD: sonnet = balanced
+THOROUGH: sonnet = same cost, more iterations
+DETERMINED: opus = highest cost, slowest, best quality
+```
+
+## Override Examples
+
+User can override detected effort:
+
+```
+"Do this thoroughly" → THOROUGH (even if task seems simple)
+"Quick fix please" → QUICK (even if task seems complex)
+"Take your time" → THOROUGH
+"Don't overthink it" → QUICK
+```
+
+## Confidence Levels
+
+The EffortClassifier reports confidence:
+
+| Confidence | Meaning | Action |
+|------------|---------|--------|
+| HIGH | Clear signals detected | Use detected level |
+| MEDIUM | Some signals, ambiguous | Use detected, note uncertainty |
+| LOW | No clear signals | Default to STANDARD |
+
+## ISC Row Counts by Effort
+
+Typical ISC complexity:
+
+| Effort | Typical Rows | Phases Used |
+|--------|--------------|-------------|
+| TRIVIAL | 0 | None (skip algorithm) |
+| QUICK | 2-4 | Light OBSERVE → EXECUTE → VERIFY |
+| STANDARD | 5-10 | Full cycle |
+| THOROUGH | 10-20 | Full cycle with deep THINK |
+| DETERMINED | 15-50+ | Multiple iterations |
+
+## Quick Decision Guide
+
+```
+Is it a typo/one-liner? → TRIVIAL (skip)
+Is it low-risk and simple? → QUICK
+Is it normal work? → STANDARD
+Is it important or complex? → THOROUGH
+Is it mission-critical? → DETERMINED
+```
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Reference/ISCFormat.md b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Reference/ISCFormat.md
new file mode 100644
index 00000000..b9c010ff
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Reference/ISCFormat.md
@@ -0,0 +1,188 @@
+# ISC (Ideal State Criteria) Format Reference
+
+The ISC is THE ALGORITHM's central artifact - a living document that tracks the gap between current state and ideal state.
+
+## ISC Table Structure
+
+```markdown
+## ISC: [Request Summary]
+
+**Effort:** [LEVEL] | **Phase:** [PHASE] | **Iteration:** [N]
+
+| # | What Ideal Looks Like | Source | Status | [P] |
+|---|------------------------|--------|--------|-----|
+| 1 | [Criterion 1] | [SRC] | [STAT] | [✓] |
+| 2 | [Criterion 2] | [SRC] | [STAT] | [✓] |
+```
+
+## Row Fields
+
+### ID (#)
+- Sequential number
+- Assigned at creation
+- Never changes
+
+### What Ideal Looks Like
+- Description of success criterion
+- Should be specific and testable
+- Gets refined during BUILD phase
+
+**Evolution:**
+```
+OBSERVE: "Logout button"
+THINK: "Logout button in navbar"
+BUILD: "Logout button visible in navbar (top-right, matches existing style)"
+```
+
+### Source
+
+| Source | Meaning | Example |
+|--------|---------|---------|
+| **EXPLICIT** | Directly stated by user | "Add a logout button" |
+| **INFERRED** | Derived from user context | "Uses TypeScript" (from prefs) |
+| **IMPLICIT** | Universal standards | "Tests pass", "No security issues" |
+
+### Status
+
+| Status | Meaning | Set During |
+|--------|---------|------------|
+| **PENDING** | Not started | Initial state |
+| **ACTIVE** | Work in progress | EXECUTE phase |
+| **DONE** | Successfully completed | EXECUTE phase |
+| **ADJUSTED** | Completed with deviation | EXECUTE or VERIFY |
+| **BLOCKED** | Cannot proceed | EXECUTE or VERIFY |
+
+### Parallel [P]
+- ✓ = Can run in parallel with other rows
+- (empty) = Must run sequentially
+- Set during PLAN phase
+
+## JSON Storage Format
+
+ISC is stored at `$PAI_DIR/MEMORY/Work/current-isc.json`:
+
+```json
+{
+ "request": "Add logout button to navbar",
+ "effort": "STANDARD",
+ "created": "2024-01-15T10:30:00Z",
+ "lastModified": "2024-01-15T11:45:00Z",
+ "phase": "EXECUTE",
+ "iteration": 1,
+ "rows": [
+ {
+ "id": 1,
+ "description": "Logout button visible in navbar",
+ "source": "EXPLICIT",
+ "status": "DONE",
+ "parallel": true,
+ "timestamp": "2024-01-15T10:30:00Z"
+ },
+ {
+ "id": 2,
+ "description": "Click logout clears session",
+ "source": "EXPLICIT",
+ "status": "ACTIVE",
+ "parallel": false,
+ "timestamp": "2024-01-15T10:30:00Z"
+ }
+ ],
+ "log": [
+ "[2024-01-15T10:30:00Z] ISC created for: Add logout button",
+ "[2024-01-15T10:31:00Z] Added row 1: Logout button visible",
+ "[2024-01-15T11:00:00Z] Row 1: PENDING → ACTIVE",
+ "[2024-01-15T11:30:00Z] Row 1: ACTIVE → DONE"
+ ]
+}
+```
+
+## Evolution Log
+
+The log tracks all changes to the ISC:
+
+```
+[timestamp] ISC created for: [request]
+[timestamp] Added row N: [description] ([source])
+[timestamp] Row N: [old_status] → [new_status]
+[timestamp] Phase: [old_phase] → [new_phase]
+[timestamp] Verify row N: [result] ([reason])
+[timestamp] Starting iteration N
+```
+
+## ISC Lifecycle
+
+```
+CREATE (OBSERVE)
+ ↓
+COMPLETE (THINK) - add missing rows
+ ↓
+ORDER (PLAN) - set parallel, sequence
+ ↓
+REFINE (BUILD) - make testable
+ ↓
+STATUS CHANGES (EXECUTE) - PENDING → ACTIVE → DONE
+ ↓
+VERIFY RESULTS (VERIFY) - PASS/ADJUSTED/BLOCKED
+ ↓
+ARCHIVE (LEARN) - save and clear
+```
+
+## CLI Commands
+
+```bash
+# Create new ISC
+bun run ISCManager.ts create --request "Add feature X" --effort STANDARD
+
+# Add rows
+bun run ISCManager.ts add -d "Feature works" -s EXPLICIT
+bun run ISCManager.ts add -d "Uses TypeScript" -s INFERRED
+bun run ISCManager.ts add -d "Tests pass" -s IMPLICIT
+
+# Update status
+bun run ISCManager.ts update --row 1 --status ACTIVE
+bun run ISCManager.ts update --row 1 --status DONE
+bun run ISCManager.ts update --row 2 --status BLOCKED --reason "API unavailable"
+
+# Set verification result
+bun run ISCManager.ts verify --row 1 --result PASS
+bun run ISCManager.ts verify --row 2 --result ADJUSTED --reason "250ms vs 200ms"
+
+# Change phase
+bun run ISCManager.ts phase -p EXECUTE
+
+# View ISC
+bun run ISCManager.ts show # default text
+bun run ISCManager.ts show -o markdown # markdown table
+bun run ISCManager.ts show -o json # full JSON
+
+# View log
+bun run ISCManager.ts log
+
+# View summary
+bun run ISCManager.ts summary
+
+# Archive and clear
+bun run ISCManager.ts clear
+```
+
+## Best Practices
+
+### Row Descriptions
+- **Specific** over vague: "Button top-right" not "Button somewhere"
+- **Testable**: Must be verifiable somehow
+- **Outcome-focused**: "User sees X" not "Code does Y"
+
+### Source Assignment
+- When in doubt, use INFERRED
+- EXPLICIT only for direct quotes from request
+- IMPLICIT for universal quality standards
+
+### Status Management
+- Update immediately when status changes
+- Never skip ACTIVE - always mark work in progress
+- Always include reason for BLOCKED/ADJUSTED
+
+### Parallelization
+- Default to parallel unless clear dependency
+- Mark [P] only during PLAN phase
+- Don't parallelize if rows touch same files
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/SKILL.md b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/SKILL.md
new file mode 100644
index 00000000..e4165af3
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/SKILL.md
@@ -0,0 +1,347 @@
+---
+name: THEALGORITHM
+description: Universal execution engine using scientific method to achieve ideal state. USE WHEN complex tasks, multi-step work, "run the algorithm", "use the algorithm", OR any non-trivial request that benefits from structured execution with ISC (Ideal State Criteria) tracking.
+---
+
+# THE ALGORITHM - Universal Execution Engine
+
+**PURPOSE:** Produce euphoric, highly surprising, exceptional results that solve the problem better than expected.
+
+**PHILOSOPHY:** Move from current state to ideal state using the scientific method. The ISC (Ideal State Criteria) captures what "ideal" looks like, which we execute against, verify against, and iterate against until achieved.
+
+**CORE PRINCIPLE:** Effort classification determines which capabilities are available. Higher effort unlocks more powerful tools.
+
+## Visual Display & Voice Notifications
+
+**Use the LCARS-style AlgorithmDisplay for visual feedback and voice announcements:**
+
+```bash
+# Start algorithm with effort level (shows banner + announces via voice)
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts start THOROUGH -r "your request"
+
+# Transition phases (updates display + voice announcement)
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts phase THINK
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts phase EXECUTE
+
+# Show current status anytime
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts show
+
+# Show just the effort banner
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts effort DETERMINED
+```
+
+**The display shows:**
+- Current effort level (TRIVIAL to DETERMINED) with color-coded banner
+- Phase progression bar (7 phases with completion status)
+- ISC summary (rows pending/active/done)
+- Voice announcements when transitioning phases
+
+**Phase Icons:** OBSERVE -> THINK -> PLAN -> BUILD -> EXECUTE -> VERIFY -> LEARN
+
+## Quick Start
+
+```bash
+# 1. START WITH VISUAL DISPLAY (shows banner + voice announcement)
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts start STANDARD -r "your request"
+
+# 2. CLASSIFY EFFORT (if not using display start)
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/EffortClassifier.ts --request "your request"
+# Or with override: --override DETERMINED
+# Or inline: "algorithm effort THOROUGH: your request"
+
+# 3. LOAD CAPABILITIES for effort level
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/CapabilityLoader.ts --effort STANDARD
+
+# 4. CREATE ISC
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/ISCManager.ts create --request "your request"
+
+# 5. TRANSITION PHASES (voice + visual update)
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts phase THINK
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts phase PLAN
+# ... continues through EXECUTE, VERIFY, LEARN
+
+# 6. MANAGE ISC during EXECUTE
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/ISCManager.ts capability --row 1 -c research.perplexity
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/ISCManager.ts update --row 1 --status DONE
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/ISCManager.ts show
+```
+
+## Effort to Capability Matrix
+
+**Capabilities.yaml is the source of truth.** See `Data/Capabilities.yaml`.
+
+| Effort | Models | Thinking | Debate | Research | Agents | Parallel |
+|--------|--------|----------|--------|----------|--------|----------|
+| **TRIVIAL** | - | - | - | - | - | 0 |
+| **QUICK** | haiku | - | - | - | Intern | 1 |
+| **STANDARD** | haiku, sonnet | UltraThink, FirstPrinciples | - | 1 agent | Engineer, QA, Designer | 1-3 |
+| **THOROUGH** | haiku, sonnet | All | Council | parallel | All + Architect, Pentester | 3-5 |
+| **DETERMINED** | all + opus | All | Council + RedTeam | all | unlimited | 10 |
+
+## ISC Scale (CRITICAL)
+
+**The ISC is NOT limited to a small number of rows.** The ISC captures what "ideal" looks like, and for complex problems this can be massive:
+
+| Scale | When | Examples |
+|-------|------|----------|
+| **5-10 rows** | Quick fixes, simple features | "Fix typo", "Add button" |
+| **20-50 rows** | Standard development work | "Add dark mode", "Create API endpoint" |
+| **50-200 rows** | Complex features, refactors | "Redesign auth system", "Add new major feature" |
+| **200-1000+ rows** | Major projects, DETERMINED effort | "Build entire system", "Security audit" |
+
+**ISC rows come from:**
+- **EXPLICIT requirements** - What user literally asked for
+- **INFERRED requirements** - From context (tech stack preferences, past work, etc.)
+- **IMPLICIT requirements** - Security, quality, testing standards
+- **Research findings** - Best practices discovered via research agents
+- **Anti-patterns** - Things to AVOID discovered via research
+- **Edge cases** - Discovered through thinking/analysis
+- **Verification criteria** - How to confirm each requirement is met
+
+**The algorithm's capabilities EXPAND the ISC:**
+- Research agents find best practices -> add ISC rows
+- Research agents find anti-patterns -> add "avoid X" ISC rows
+- Council debate surfaces edge cases -> add ISC rows
+- FirstPrinciples analysis reveals assumptions -> add ISC rows
+- Verification requirements -> add ISC rows for each testable criterion
+
+**Higher effort = larger, higher quality ISC.** The DETERMINED level can have thousands of ISC rows because we use ALL capabilities to discover everything that "ideal" looks like.
+
+## The 7 Phases
+
+Execute IN ORDER. Each phase mutates the ISC:
+
+| Phase | Action | ISC Mutation | Gate Question |
+|-------|--------|--------------|---------------|
+| **OBSERVE** | Understand request + user context | CREATE rows | Do I have 2+ rows? Used context to infer? |
+| **THINK** | Ensure nothing missing | COMPLETE rows | All rows clear, testable? |
+| **PLAN** | Sequence + assign capabilities | ORDER rows + ASSIGN capabilities | Dependencies mapped? Capabilities assigned? |
+| **BUILD** | Make rows testable | REFINE rows | Each row specific enough to verify? |
+| **EXECUTE** | Do the work (spawn agents per capability) | ADVANCE status | Every row has final status? |
+| **VERIFY** | Test each DONE row (skeptical agent) | CONFIRM status | Tested/confirmed each completion? |
+| **LEARN** | Output for user to rate | OUTPUT results | User rates for memory system |
+
+**CRITICAL:** The LEARN phase does NOT self-rate. User rates outputs for the memory system.
+
+## The ISC Table (FRONT AND CENTER)
+
+Every non-trivial task has an ISC. **Display this prominently throughout execution:**
+
+```markdown
+## ISC: Request Summary
+
+**Request:** Add dark mode to the settings page
+**Effort:** STANDARD | **Phase:** EXECUTE | **Iteration:** 1
+
+| # | What Ideal Looks Like | Source | Capability | Status |
+|---|----------------------|--------|------------|--------|
+| 1 | Research good patterns | INFERRED | research.perplexity | PENDING |
+| 2 | Toggle component works | EXPLICIT | execution.engineer | ACTIVE |
+| 3 | Theme state persists | EXPLICIT | execution.engineer | PENDING |
+| 4 | Uses TypeScript | INFERRED | - | DONE |
+| 5 | Tests pass | IMPLICIT | verification.qa | PENDING |
+| 6 | Browser-verified | IMPLICIT | verification.browser | PENDING |
+
+**Legend:** Research | Thinking | Debate | Analysis | Execution | Verify | x Parallel
+```
+
+**Source types:**
+- `EXPLICIT` - User literally said this
+- `INFERRED` - Derived from user context (tech stack preferences, etc.)
+- `IMPLICIT` - Universal standards (security, quality)
+
+**Status progression:**
+- `PENDING` -> `ACTIVE` -> `DONE`
+- `ADJUSTED` - Modified with reason
+- `BLOCKED` - Cannot achieve, triggers loop-back
+
+## Execution Flow
+
+### Step 1: EFFORT CLASSIFICATION (REQUIRED FIRST)
+
+```bash
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/EffortClassifier.ts --request "your request"
+```
+
+**Override methods:**
+- CLI flag: `--override THOROUGH`
+- Inline pattern: `"algorithm effort DETERMINED: build this feature"`
+
+The effort level determines ALL available capabilities.
+
+### Step 2: CAPABILITY LOADING
+
+```bash
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/CapabilityLoader.ts --effort STANDARD
+```
+
+Returns available: models, thinking modes, debate systems, research agents, execution agents, verification.
+
+### Step 3: ISC CREATION + CAPABILITY ASSIGNMENT
+
+For each ISC row, select appropriate capability:
+
+```bash
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/CapabilitySelector.ts --row "Research best practices" --effort STANDARD
+# Returns: research.perplexity as primary, with icon
+
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/ISCManager.ts capability --row 1 -c research.perplexity
+```
+
+### Step 4: ORCHESTRATED EXECUTION
+
+Execute in phases based on capability assignments:
+
+```
+PHASE A: RESEARCH (parallel for independent queries)
+- Row with research.perplexity -> Spawn PerplexityResearcher
+- Row with research.gemini -> Spawn GeminiResearcher
+- Row with research.grok -> Spawn GrokResearcher
+
+PHASE B: THINKING (for creative/analysis needs)
+- Row with thinking.ultrathink -> Invoke BeCreative skill
+- Row with analysis.first_principles -> Invoke FirstPrinciples skill
+- Row with debate.council -> Invoke Council skill
+
+PHASE C: EXECUTION (parallel agents)
+- Row with execution.engineer -> Spawn Engineer agent
+- Row with execution.architect -> Spawn Architect agent (THOROUGH+)
+- Rows marked x -> Run in parallel
+
+PHASE D: VERIFICATION (skeptical, different from executor)
+- Row with verification.browser -> Browser skill validation
+- All rows -> Skeptical verifier agent (skeptical,meticulous,adversarial traits)
+```
+
+### For TRIVIAL (skip algorithm):
+Direct response, no ISC, no capability loading. Just answer.
+
+## Capability Categories
+
+### Models (compute resources)
+- `models.haiku` - Fast, cheap (QUICK+)
+- `models.sonnet` - Balanced reasoning (STANDARD+)
+- `models.opus` - Maximum intelligence (DETERMINED)
+
+### Thinking Modes
+- `thinking.ultrathink` - BeCreative skill for creative solutions (STANDARD+)
+- `thinking.tree_of_thought` - Branching exploration (THOROUGH+)
+- `thinking.plan_mode` - EnterPlanMode for complex implementations (THOROUGH+)
+
+### Debate Systems
+- `debate.council` - 4 agents, collaborative analysis (THOROUGH+)
+- `debate.redteam` - 32 agents, adversarial stress-testing (DETERMINED)
+
+### Analysis Modes
+- `analysis.first_principles` - Challenge assumptions (STANDARD+)
+- `analysis.science` - Hypothesis-driven exploration (STANDARD+)
+
+### Research Agents
+- `research.perplexity` - Web research, current events (STANDARD+)
+- `research.gemini` - Multi-perspective research (STANDARD+)
+- `research.grok` - Contrarian fact-checking (STANDARD+)
+- `research.claude` - Academic/scholarly sources (STANDARD+)
+- `research.codex` - Technical code pattern research (STANDARD+)
+
+### Execution Agents
+- `execution.intern` - Parallel grunt work (QUICK+)
+- `execution.engineer` - Implementation/coding (STANDARD+)
+- `execution.qa_tester` - Testing/validation (STANDARD+)
+- `execution.designer` - UX/UI design (STANDARD+)
+- `execution.architect` - System design (THOROUGH+)
+- `execution.pentester` - Security testing (THOROUGH+)
+- `execution.ralph_loop` - Persistent iteration until success (QUICK+)
+
+### Verification
+- `verification.browser` - Web application validation (STANDARD+)
+- `verification.skeptical_verifier` - Different agent than executor (STANDARD+)
+
+## The Ralph Loop
+
+For persistent iteration until success criteria are met:
+
+```bash
+# Start a Ralph loop
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/RalphLoopExecutor.ts \
+ --prompt "Fix the auth bug" \
+ --completion-promise "All tests pass" \
+ --max-iterations 15
+
+# Check status
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/RalphLoopExecutor.ts --status
+
+# Cancel loop
+bun run $PAI_DIR/skills/THEALGORITHM/Tools/RalphLoopExecutor.ts --cancel
+```
+
+**Keywords that trigger Ralph Loop:**
+- "iterate until", "keep trying", "until tests pass"
+- "until it works", "persistent", "retry until"
+- "loop until", "ralph", "keep iterating"
+
+## Iteration Loop
+
+When VERIFY finds issues:
+
+```
+BLOCKED row
+ |
+ +- Unclear what ideal looks like? -> Loop to THINK
+ +- Wrong approach? -> Loop to PLAN
+ +- Execution error? -> Loop to EXECUTE
+
+Iteration count bounded by effort level:
+- QUICK: 1 iteration max
+- STANDARD: 2 iterations
+- THOROUGH: 3-5 iterations
+- DETERMINED: Unlimited until success
+```
+
+## Integration
+
+### Uses
+- **Agents Skill** - AgentFactory for dynamic agent composition
+- **CORE Skill** - User context for ISC inference
+- **Browser Skill** - Web verification in VERIFY phase
+- **BeCreative Skill** - UltraThink for THINK phase
+- **Council Skill** - Multi-perspective debate (THOROUGH+)
+- **RedTeam Skill** - Adversarial analysis (DETERMINED)
+- **FirstPrinciples Skill** - Assumption challenging
+- **Research Skill** - Multi-source research agents
+
+### Memory
+- ISC artifacts: `$PAI_DIR/MEMORY/Work/{session}/ISC.md`
+- Learnings: `$PAI_DIR/MEMORY/Learning/ALGORITHM/`
+- Patterns: `$PAI_DIR/MEMORY/Signals/algorithm-patterns.jsonl`
+
+## Workflow Routing
+
+| Trigger | Action |
+|---------|--------|
+| "run the algorithm" | Full execution |
+| "use the algorithm" | Full execution |
+| "algorithm effort LEVEL" | Force effort level + full execution |
+| Complex multi-step request | Auto-invoke if appropriate |
+
+## Files
+
+| File | Purpose |
+|------|---------|
+| `Data/Capabilities.yaml` | **Source of truth** for all capabilities |
+| `Tools/AlgorithmDisplay.ts` | **LCARS visual display** + voice announcements |
+| `Tools/EffortClassifier.ts` | Classify TRIVIAL->DETERMINED |
+| `Tools/CapabilityLoader.ts` | Load + filter capabilities by effort |
+| `Tools/CapabilitySelector.ts` | Select capabilities for ISC rows |
+| `Tools/ISCManager.ts` | Create/update/query ISC with capabilities |
+| `Tools/TraitModifiers.ts` | Effort -> trait mappings |
+| `Tools/RalphLoopExecutor.ts` | Persistent iteration until success |
+| `Phases/*.md` | Detailed phase documentation |
+| `Reference/CapabilityMatrix.md` | Effort -> capability documentation |
+
+## The Purpose
+
+**Produce euphoric, highly surprising, exceptional results that solve the user's problem better than expected.**
+
+The ISC captures what "ideal" looks like. Effort determines available capabilities. Execute against it. Verify against it. Iterate until achieved.
+
+**This is not documentation. This is a command. Execute the algorithm.**
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts
new file mode 100644
index 00000000..c2f42ba1
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/AlgorithmDisplay.ts
@@ -0,0 +1,522 @@
+#!/usr/bin/env bun
+
+/**
+ * AlgorithmDisplay - LCARS-style visual display for THE ALGORITHM
+ *
+ * Shows current effort level, phase progression, and ISC status with
+ * Star Trek LCARS-inspired design. Supports voice announcements.
+ *
+ * Usage:
+ * bun run AlgorithmDisplay.ts show # Full display
+ * bun run AlgorithmDisplay.ts phase THINK # Update phase + voice
+ * bun run AlgorithmDisplay.ts effort THOROUGH # Show effort banner
+ * bun run AlgorithmDisplay.ts transition THINK PLAN # Animated transition
+ */
+
+import { parseArgs } from "util";
+import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
+import { join } from "path";
+
+const PAI_DIR = process.env.PAI_DIR || join(process.env.HOME!, ".config/pai");
+const STATE_DIR = join(PAI_DIR, "MEMORY/State");
+const ISC_PATH = join(PAI_DIR, "MEMORY/Work/current-isc.json");
+const ALGORITHM_STATE_PATH = join(STATE_DIR, "algorithm-state.json");
+
+// ANSI color codes - Tokyo Night / LCARS palette
+const RESET = "\x1b[0m";
+const BOLD = "\x1b[1m";
+const DIM = "\x1b[2m";
+
+// LCARS colors
+const LCARS = {
+ // Primary colors
+ ORANGE: "\x1b[38;2;255;153;0m",
+ GOLD: "\x1b[38;2;204;153;0m",
+ YELLOW: "\x1b[38;2;255;204;0m",
+ BLUE: "\x1b[38;2;153;204;255m",
+ PURPLE: "\x1b[38;2;204;153;255m",
+ PINK: "\x1b[38;2;255;153;204m",
+ RED: "\x1b[38;2;255;102;102m",
+ GREEN: "\x1b[38;2;153;255;153m",
+ CYAN: "\x1b[38;2;102;255;255m",
+ // Background
+ BG_ORANGE: "\x1b[48;2;255;153;0m",
+ BG_GOLD: "\x1b[48;2;204;153;0m",
+ BG_PURPLE: "\x1b[48;2;147;112;219m",
+ BG_BLUE: "\x1b[48;2;100;149;237m",
+ BG_BLACK: "\x1b[48;2;0;0;0m",
+};
+
+// Effort level colors
+const EFFORT_COLORS: Record<string, { fg: string; bg: string; emoji: string }> = {
+ TRIVIAL: { fg: LCARS.BLUE, bg: "\x1b[48;2;50;80;120m", emoji: "💭" },
+ QUICK: { fg: LCARS.GREEN, bg: "\x1b[48;2;40;100;40m", emoji: "⚡" },
+ STANDARD: { fg: LCARS.YELLOW, bg: "\x1b[48;2;120;100;20m", emoji: "📊" },
+ THOROUGH: { fg: LCARS.ORANGE, bg: "\x1b[48;2;140;80;0m", emoji: "🔬" },
+ DETERMINED: { fg: LCARS.RED, bg: "\x1b[48;2;140;40;40m", emoji: "🎯" },
+};
+
+// Phase definitions with icons and colors
+const PHASES = [
+ { name: "OBSERVE", icon: "👁️", color: LCARS.CYAN, description: "Understanding request" },
+ { name: "THINK", icon: "🧠", color: LCARS.PURPLE, description: "Analyzing requirements" },
+ { name: "PLAN", icon: "📋", color: LCARS.BLUE, description: "Sequencing steps" },
+ { name: "BUILD", icon: "🔨", color: LCARS.YELLOW, description: "Making testable" },
+ { name: "EXECUTE", icon: "⚡", color: LCARS.ORANGE, description: "Doing the work" },
+ { name: "VERIFY", icon: "✅", color: LCARS.GREEN, description: "Testing results" },
+ { name: "LEARN", icon: "📚", color: LCARS.PINK, description: "Capturing learnings" },
+] as const;
+
+type PhaseName = (typeof PHASES)[number]["name"];
+
+interface AlgorithmState {
+ currentPhase: PhaseName;
+ effortLevel: string;
+ iteration: number;
+ startTime: string;
+ lastPhaseChange: string;
+ request?: string;
+}
+
+// Voice notification
+async function announceVoice(message: string): Promise<void> {
+ try {
+ await fetch("http://localhost:8888/notify", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ message }),
+ });
+ } catch {
+ // Voice server not running - silent fail
+ }
+}
+
+function ensureStateDir(): void {
+ if (!existsSync(STATE_DIR)) {
+ mkdirSync(STATE_DIR, { recursive: true });
+ }
+}
+
+function loadState(): AlgorithmState | null {
+ try {
+ if (existsSync(ALGORITHM_STATE_PATH)) {
+ return JSON.parse(readFileSync(ALGORITHM_STATE_PATH, "utf-8"));
+ }
+ } catch {}
+ return null;
+}
+
+function saveState(state: AlgorithmState): void {
+ ensureStateDir();
+ writeFileSync(ALGORITHM_STATE_PATH, JSON.stringify(state, null, 2));
+}
+
+function loadISC(): { request: string; effort: string; phase: string; rows: any[]; iteration: number } | null {
+ try {
+ if (existsSync(ISC_PATH)) {
+ const data = readFileSync(ISC_PATH, "utf-8");
+ if (data.trim()) {
+ return JSON.parse(data);
+ }
+ }
+ } catch {}
+ return null;
+}
+
+function getPhaseIndex(phase: string): number {
+ return PHASES.findIndex((p) => p.name === phase.toUpperCase());
+}
+
+// LCARS bar component
+function lcarsBar(
+ width: number,
+ color: string,
+ bgColor: string,
+ label?: string,
+ rounded: "left" | "right" | "both" | "none" = "none"
+): string {
+ const leftCap = rounded === "left" || rounded === "both" ? "╭" : "│";
+ const rightCap = rounded === "right" || rounded === "both" ? "╮" : "│";
+ const content = label ? ` ${label} `.padEnd(width - 2) : "━".repeat(width - 2);
+ return `${color}${bgColor}${leftCap}${content}${rightCap}${RESET}`;
+}
+
+// Phase progress display
+function renderPhaseBar(currentPhase: string): string {
+ const lines: string[] = [];
+ const idx = getPhaseIndex(currentPhase);
+ const width = 70;
+
+ // Header bar
+ lines.push(`${LCARS.ORANGE}╭${"━".repeat(width - 2)}╮${RESET}`);
+ lines.push(`${LCARS.ORANGE}│${RESET} ${BOLD}${LCARS.GOLD}THE ALGORITHM${RESET} ${DIM}Phase Progression${RESET}`.padEnd(width + 20) + `${LCARS.ORANGE}│${RESET}`);
+ lines.push(`${LCARS.ORANGE}├${"━".repeat(width - 2)}┤${RESET}`);
+
+ // Phase blocks
+ let phaseLine = `${LCARS.ORANGE}│${RESET} `;
+ for (let i = 0; i < PHASES.length; i++) {
+ const phase = PHASES[i];
+ const isActive = i === idx;
+ const isComplete = i < idx;
+ const isPending = i > idx;
+
+ let blockColor = DIM;
+ let bg = "";
+ if (isActive) {
+ blockColor = BOLD + phase.color;
+ bg = "\x1b[48;2;40;40;60m";
+ } else if (isComplete) {
+ blockColor = LCARS.GREEN;
+ }
+
+ const block = `${bg}${blockColor}${phase.icon}${RESET}`;
+ phaseLine += block + " ";
+ }
+ lines.push(phaseLine.padEnd(width + 50) + `${LCARS.ORANGE}│${RESET}`);
+
+ // Current phase detail
+ if (idx >= 0) {
+ const active = PHASES[idx];
+ lines.push(`${LCARS.ORANGE}│${RESET}`);
+ lines.push(`${LCARS.ORANGE}│${RESET} ${active.color}${BOLD}▶ ${active.name}${RESET} ${DIM}- ${active.description}${RESET}`.padEnd(width + 30) + `${LCARS.ORANGE}│${RESET}`);
+ }
+
+ lines.push(`${LCARS.ORANGE}╰${"━".repeat(width - 2)}╯${RESET}`);
+
+ return lines.join("\n");
+}
+
+// Effort level display
+function renderEffortBanner(effort: string): string {
+ const config = EFFORT_COLORS[effort.toUpperCase()] || EFFORT_COLORS.STANDARD;
+ const lines: string[] = [];
+ const width = 40;
+
+ const barContent = `${config.emoji} EFFORT: ${effort.toUpperCase()} `.padEnd(width - 4);
+ lines.push(`${config.fg}${config.bg}╭${"━".repeat(width - 2)}╮${RESET}`);
+ lines.push(`${config.fg}${config.bg}│ ${BOLD}${barContent}${RESET}${config.fg}${config.bg}│${RESET}`);
+ lines.push(`${config.fg}${config.bg}╰${"━".repeat(width - 2)}╯${RESET}`);
+
+ return lines.join("\n");
+}
+
+// ISC status summary
+function renderISCSummary(isc: ReturnType<typeof loadISC>): string {
+ if (!isc || !isc.rows || isc.rows.length === 0) {
+ return `${DIM}No active ISC${RESET}`;
+ }
+
+ const pending = isc.rows.filter((r: any) => r.status === "PENDING").length;
+ const active = isc.rows.filter((r: any) => r.status === "ACTIVE").length;
+ const done = isc.rows.filter((r: any) => r.status === "DONE").length;
+ const blocked = isc.rows.filter((r: any) => r.status === "BLOCKED").length;
+
+ const lines: string[] = [];
+ lines.push(`${LCARS.BLUE}╭────────────────────────────────╮${RESET}`);
+ lines.push(`${LCARS.BLUE}│${RESET} ${BOLD}ISC STATUS${RESET} ${DIM}(${isc.rows.length} rows)${RESET}`.padEnd(45) + `${LCARS.BLUE}│${RESET}`);
+ lines.push(`${LCARS.BLUE}├────────────────────────────────┤${RESET}`);
+ lines.push(`${LCARS.BLUE}│${RESET} ⏳ Pending: ${pending} 🔄 Active: ${active}`.padEnd(40) + `${LCARS.BLUE}│${RESET}`);
+ lines.push(`${LCARS.BLUE}│${RESET} ${LCARS.GREEN}✅ Done: ${done}${RESET} ${blocked > 0 ? LCARS.RED + "🚫 Blocked: " + blocked + RESET : ""}`.padEnd(blocked > 0 ? 45 : 40) + `${LCARS.BLUE}│${RESET}`);
+ lines.push(`${LCARS.BLUE}╰────────────────────────────────╯${RESET}`);
+
+ return lines.join("\n");
+}
+
+// Full display
+function renderFullDisplay(): string {
+ const isc = loadISC();
+ const state = loadState();
+
+ const effort = isc?.effort || state?.effortLevel || "STANDARD";
+ const phase = isc?.phase || state?.currentPhase || "OBSERVE";
+ const iteration = isc?.iteration || state?.iteration || 1;
+ const request = isc?.request || state?.request || "";
+
+ const lines: string[] = [];
+
+ // Title banner
+ lines.push("");
+ lines.push(`${LCARS.ORANGE}${"\x1b[48;2;255;153;0m"} THE ${RESET}${LCARS.GOLD}${"\x1b[48;2;204;153;0m"} ALGORITHM ${RESET}${LCARS.ORANGE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╮${RESET}`);
+
+ // Request line
+ if (request) {
+ const truncatedRequest = request.length > 50 ? request.slice(0, 47) + "..." : request;
+ lines.push(`${LCARS.ORANGE}│${RESET} ${DIM}Request:${RESET} ${truncatedRequest}`);
+ }
+
+ // Effort and iteration
+ const effortConfig = EFFORT_COLORS[effort.toUpperCase()] || EFFORT_COLORS.STANDARD;
+ lines.push(`${LCARS.ORANGE}│${RESET} ${effortConfig.emoji} ${effortConfig.fg}${effort.toUpperCase()}${RESET} ${DIM}|${RESET} Iteration ${BOLD}${iteration}${RESET}`);
+ lines.push(`${LCARS.ORANGE}├━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╯${RESET}`);
+
+ // Phase progression
+ const phaseIdx = getPhaseIndex(phase);
+ lines.push(`${LCARS.ORANGE}│${RESET}`);
+
+ // Phase icons row
+ let phaseIcons = `${LCARS.ORANGE}│${RESET} `;
+ for (let i = 0; i < PHASES.length; i++) {
+ const p = PHASES[i];
+ const isActive = i === phaseIdx;
+ const isComplete = i < phaseIdx;
+
+ if (isActive) {
+ phaseIcons += `${"\x1b[48;2;60;60;80m"}${BOLD}${p.color}[${p.icon}]${RESET} `;
+ } else if (isComplete) {
+ phaseIcons += `${LCARS.GREEN}${p.icon}${RESET} `;
+ } else {
+ phaseIcons += `${DIM}${p.icon}${RESET} `;
+ }
+ }
+ lines.push(phaseIcons);
+
+ // Phase names row
+ let phaseNames = `${LCARS.ORANGE}│${RESET} `;
+ for (let i = 0; i < PHASES.length; i++) {
+ const p = PHASES[i];
+ const isActive = i === phaseIdx;
+ const isComplete = i < phaseIdx;
+
+ const shortName = p.name.slice(0, 3);
+ if (isActive) {
+ phaseNames += `${BOLD}${p.color}${shortName}${RESET} `;
+ } else if (isComplete) {
+ phaseNames += `${LCARS.GREEN}${shortName}${RESET} `;
+ } else {
+ phaseNames += `${DIM}${shortName}${RESET} `;
+ }
+ }
+ lines.push(phaseNames);
+
+ // Current phase description
+ if (phaseIdx >= 0) {
+ const active = PHASES[phaseIdx];
+ lines.push(`${LCARS.ORANGE}│${RESET}`);
+ lines.push(`${LCARS.ORANGE}│${RESET} ${BOLD}${active.color}▶ ${active.name}${RESET} ${DIM}— ${active.description}${RESET}`);
+ }
+
+ lines.push(`${LCARS.ORANGE}│${RESET}`);
+
+ // ISC summary if available
+ if (isc && isc.rows && isc.rows.length > 0) {
+ const pending = isc.rows.filter((r: any) => r.status === "PENDING").length;
+ const active = isc.rows.filter((r: any) => r.status === "ACTIVE").length;
+ const done = isc.rows.filter((r: any) => r.status === "DONE").length;
+
+ lines.push(`${LCARS.ORANGE}│${RESET} ${LCARS.BLUE}ISC:${RESET} ${isc.rows.length} rows ${DIM}|${RESET} ⏳${pending} 🔄${active} ${LCARS.GREEN}✅${done}${RESET}`);
+ }
+
+ // Footer
+ lines.push(`${LCARS.ORANGE}╰━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╯${RESET}`);
+ lines.push("");
+
+ return lines.join("\n");
+}
+
+// Phase transition with voice
+async function transitionPhase(
+ newPhase: string,
+ announce: boolean = true
+): Promise<void> {
+ const isc = loadISC();
+ const state = loadState() || {
+ currentPhase: "OBSERVE" as PhaseName,
+ effortLevel: "STANDARD",
+ iteration: 1,
+ startTime: new Date().toISOString(),
+ lastPhaseChange: new Date().toISOString(),
+ };
+
+ const oldPhase = isc?.phase || state.currentPhase;
+ const normalizedNewPhase = newPhase.toUpperCase() as PhaseName;
+
+ // Validate phase
+ const phaseInfo = PHASES.find((p) => p.name === normalizedNewPhase);
+ if (!phaseInfo) {
+ console.error(`Invalid phase: ${newPhase}`);
+ console.error(`Valid phases: ${PHASES.map((p) => p.name).join(", ")}`);
+ process.exit(1);
+ }
+
+ // Update state
+ state.currentPhase = normalizedNewPhase;
+ state.lastPhaseChange = new Date().toISOString();
+ saveState(state);
+
+ // Voice announcement
+ if (announce) {
+ const announcement = `Algorithm entering ${normalizedNewPhase} phase. ${phaseInfo.description}.`;
+ await announceVoice(announcement);
+ }
+
+ // Visual display
+ console.log("");
+ console.log(`${LCARS.ORANGE}━━━━━ PHASE TRANSITION ━━━━━${RESET}`);
+ console.log(`${DIM}${oldPhase}${RESET} ${LCARS.GOLD}→${RESET} ${BOLD}${phaseInfo.color}${normalizedNewPhase}${RESET}`);
+ console.log(`${phaseInfo.icon} ${phaseInfo.description}`);
+ console.log("");
+
+ // Show full display
+ console.log(renderFullDisplay());
+}
+
+// Start algorithm with effort level
+async function startAlgorithm(
+ effort: string,
+ request?: string,
+ announce: boolean = true
+): Promise<void> {
+ const normalizedEffort = effort.toUpperCase();
+ const config = EFFORT_COLORS[normalizedEffort];
+
+ if (!config) {
+ console.error(`Invalid effort level: ${effort}`);
+ console.error(`Valid levels: ${Object.keys(EFFORT_COLORS).join(", ")}`);
+ process.exit(1);
+ }
+
+ const state: AlgorithmState = {
+ currentPhase: "OBSERVE",
+ effortLevel: normalizedEffort,
+ iteration: 1,
+ startTime: new Date().toISOString(),
+ lastPhaseChange: new Date().toISOString(),
+ request,
+ };
+ saveState(state);
+
+ // Voice announcement
+ if (announce) {
+ const announcement = `Starting THE ALGORITHM at ${normalizedEffort} effort level.`;
+ await announceVoice(announcement);
+ }
+
+ // Display effort banner
+ console.log("");
+ console.log(renderEffortBanner(normalizedEffort));
+ console.log("");
+ console.log(renderFullDisplay());
+}
+
+async function main() {
+ const { values, positionals } = parseArgs({
+ args: Bun.argv.slice(2),
+ options: {
+ voice: { type: "boolean", short: "v", default: true },
+ request: { type: "string", short: "r" },
+ help: { type: "boolean", short: "h" },
+ },
+ allowPositionals: true,
+ });
+
+ const command = positionals[0]?.toLowerCase() || "show";
+
+ if (values.help) {
+ console.log(`
+AlgorithmDisplay - LCARS-style visual display for THE ALGORITHM
+
+USAGE:
+ bun run AlgorithmDisplay.ts [command] [args] [options]
+
+COMMANDS:
+ show Full algorithm status display (default)
+ phase <PHASE> Transition to phase with voice announcement
+ effort <LEVEL> Show effort level banner
+ start <LEVEL> [request] Start algorithm at effort level
+ banner Show just the phase progression bar
+
+OPTIONS:
+ -v, --voice Enable voice announcements (default: true)
+ --no-voice Disable voice announcements
+ -r, --request <text> Request text for context
+ -h, --help Show this help
+
+PHASES:
+ OBSERVE - Understanding the request
+ THINK - Analyzing requirements
+ PLAN - Sequencing steps
+ BUILD - Making criteria testable
+ EXECUTE - Doing the work
+ VERIFY - Testing results
+ LEARN - Capturing learnings
+
+EFFORT LEVELS:
+ TRIVIAL - Simple greetings/acknowledgments
+ QUICK - Single-step tasks
+ STANDARD - Multi-step bounded work
+ THOROUGH - Complex architectural work
+ DETERMINED - Unlimited until done
+
+EXAMPLES:
+ bun run AlgorithmDisplay.ts show
+ bun run AlgorithmDisplay.ts phase THINK
+ bun run AlgorithmDisplay.ts start THOROUGH -r "Refactor the auth system"
+ bun run AlgorithmDisplay.ts effort DETERMINED
+`);
+ return;
+ }
+
+ switch (command) {
+ case "show":
+ console.log(renderFullDisplay());
+ break;
+
+ case "phase": {
+ const phase = positionals[1];
+ if (!phase) {
+ console.error("Error: Phase name required");
+ console.error(`Valid phases: ${PHASES.map((p) => p.name).join(", ")}`);
+ process.exit(1);
+ }
+ await transitionPhase(phase, values.voice);
+ break;
+ }
+
+ case "effort": {
+ const effort = positionals[1];
+ if (!effort) {
+ console.error("Error: Effort level required");
+ console.error(`Valid levels: ${Object.keys(EFFORT_COLORS).join(", ")}`);
+ process.exit(1);
+ }
+ console.log("");
+ console.log(renderEffortBanner(effort));
+ console.log("");
+ break;
+ }
+
+ case "start": {
+ const effort = positionals[1] || "STANDARD";
+ await startAlgorithm(effort, values.request, values.voice);
+ break;
+ }
+
+ case "banner":
+ const state = loadState();
+ const isc = loadISC();
+ const phase = isc?.phase || state?.currentPhase || "OBSERVE";
+ console.log("");
+ console.log(renderPhaseBar(phase));
+ console.log("");
+ break;
+
+ case "transition": {
+ // Show animated transition between phases
+ const fromPhase = positionals[1];
+ const toPhase = positionals[2];
+ if (!fromPhase || !toPhase) {
+ console.error("Error: transition requires FROM and TO phases");
+ process.exit(1);
+ }
+ await transitionPhase(toPhase, values.voice);
+ break;
+ }
+
+ default:
+ console.error(`Unknown command: ${command}`);
+ console.error("Use --help for usage information");
+ process.exit(1);
+ }
+}
+
+main().catch(console.error);
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/CapabilityLoader.ts b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/CapabilityLoader.ts
new file mode 100644
index 00000000..992dc1a2
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/CapabilityLoader.ts
@@ -0,0 +1,414 @@
+#!/usr/bin/env bun
+
+/**
+ * CapabilityLoader - Load and filter capabilities by effort level
+ *
+ * Loads the Capabilities.yaml registry and filters available capabilities
+ * based on the current effort level.
+ *
+ * Usage:
+ * bun run CapabilityLoader.ts --effort STANDARD
+ * bun run CapabilityLoader.ts --effort THOROUGH --output json
+ * bun run CapabilityLoader.ts --list-all
+ */
+
+import { parseArgs } from "util";
+import { readFileSync, existsSync } from "fs";
+import { parse as parseYaml } from "yaml";
+import { join, dirname } from "path";
+
+type EffortLevel = "TRIVIAL" | "QUICK" | "STANDARD" | "THOROUGH" | "DETERMINED";
+
+interface Capability {
+ name: string;
+ category: string;
+ skill?: string;
+ workflow?: string;
+ tool?: string;
+ subagent_type?: string;
+ model?: string;
+ effort_min: EffortLevel;
+ use_when: string;
+ agents?: number;
+ traits?: string[];
+ icon?: string;
+ type?: string; // For special types like "iterative_loop"
+ keywords?: string[];
+ max_iterations_default?: number;
+ completion_detection?: string;
+ plugin_source?: string;
+}
+
+interface CapabilityRegistry {
+ version: string;
+ models: Record<string, any>;
+ thinking: Record<string, any>;
+ debate: Record<string, any>;
+ analysis: Record<string, any>;
+ research: Record<string, any>;
+ execution: Record<string, any>;
+ agent_composition: any;
+ parallel: any;
+ verification: any;
+ effort_unlocks: Record<string, any>;
+}
+
+interface LoadResult {
+ effort: EffortLevel;
+ available: Capability[];
+ unavailable: Capability[];
+ parallelConfig: {
+ maxConcurrent: number;
+ backgroundEnabled: boolean;
+ spotcheckRequired: boolean;
+ };
+ models: string[];
+}
+
+const EFFORT_ORDER: EffortLevel[] = [
+ "TRIVIAL",
+ "QUICK",
+ "STANDARD",
+ "THOROUGH",
+ "DETERMINED",
+];
+
+function effortMeetsMinimum(
+ current: EffortLevel,
+ minimum: EffortLevel
+): boolean {
+ return EFFORT_ORDER.indexOf(current) >= EFFORT_ORDER.indexOf(minimum);
+}
+
+function loadCapabilities(): CapabilityRegistry {
+ const scriptDir = dirname(import.meta.path);
+ const yamlPath = join(scriptDir, "..", "Data", "Capabilities.yaml");
+
+ if (!existsSync(yamlPath)) {
+ throw new Error(`Capabilities.yaml not found at ${yamlPath}`);
+ }
+
+ const content = readFileSync(yamlPath, "utf-8");
+ return parseYaml(content) as CapabilityRegistry;
+}
+
+function flattenCapabilities(registry: CapabilityRegistry): Capability[] {
+ const capabilities: Capability[] = [];
+
+ // Models
+ for (const [name, config] of Object.entries(registry.models || {})) {
+ capabilities.push({
+ name,
+ category: "models",
+ effort_min: config.effort_min,
+ use_when: config.use_for || config.description,
+ });
+ }
+
+ // Thinking modes
+ for (const [name, config] of Object.entries(registry.thinking || {})) {
+ capabilities.push({
+ name,
+ category: "thinking",
+ skill: config.skill,
+ workflow: config.workflow,
+ tool: config.tool,
+ effort_min: config.effort_min,
+ use_when: config.use_when,
+ });
+ }
+
+ // Debate systems
+ for (const [name, config] of Object.entries(registry.debate || {})) {
+ capabilities.push({
+ name,
+ category: "debate",
+ skill: config.skill,
+ workflow: config.workflow,
+ effort_min: config.effort_min,
+ use_when: config.use_when,
+ agents: config.agents,
+ });
+ }
+
+ // Analysis modes
+ for (const [name, config] of Object.entries(registry.analysis || {})) {
+ capabilities.push({
+ name,
+ category: "analysis",
+ skill: config.skill,
+ effort_min: config.effort_min,
+ use_when: config.use_when,
+ });
+ }
+
+ // Research agents
+ for (const [name, config] of Object.entries(registry.research || {})) {
+ capabilities.push({
+ name,
+ category: "research",
+ subagent_type: config.subagent_type,
+ model: config.model,
+ effort_min: config.effort_min,
+ use_when: config.use_when,
+ });
+ }
+
+ // Execution agents
+ for (const [name, config] of Object.entries(registry.execution || {})) {
+ capabilities.push({
+ name,
+ category: "execution",
+ subagent_type: config.subagent_type,
+ model: config.model,
+ effort_min: config.effort_min,
+ use_when: config.use_when,
+ // Ralph loop and other special execution types
+ icon: config.icon,
+ type: config.type,
+ keywords: config.keywords,
+ max_iterations_default: config.max_iterations_default,
+ completion_detection: config.completion_detection,
+ plugin_source: config.plugin_source,
+ });
+ }
+
+ // Agent composition
+ if (registry.agent_composition?.factory) {
+ capabilities.push({
+ name: "agent_factory",
+ category: "composition",
+ tool: "AgentFactory",
+ effort_min: registry.agent_composition.factory.effort_min || "STANDARD",
+ use_when: registry.agent_composition.use_when || "Custom agent composition",
+ });
+ }
+
+ // Verification
+ for (const [name, config] of Object.entries(registry.verification || {})) {
+ capabilities.push({
+ name,
+ category: "verification",
+ skill: config.skill,
+ traits: config.traits,
+ model: config.model,
+ effort_min: config.effort_min || "STANDARD",
+ use_when: config.use_when,
+ });
+ }
+
+ return capabilities;
+}
+
+function filterByEffort(
+ capabilities: Capability[],
+ effort: EffortLevel
+): { available: Capability[]; unavailable: Capability[] } {
+ const available: Capability[] = [];
+ const unavailable: Capability[] = [];
+
+ for (const cap of capabilities) {
+ if (effortMeetsMinimum(effort, cap.effort_min)) {
+ available.push(cap);
+ } else {
+ unavailable.push(cap);
+ }
+ }
+
+ return { available, unavailable };
+}
+
+function getParallelConfig(
+ registry: CapabilityRegistry,
+ effort: EffortLevel
+): LoadResult["parallelConfig"] {
+ const parallel = registry.parallel || {};
+ const maxConcurrent = parallel.max_concurrent?.[effort] || 1;
+
+ return {
+ maxConcurrent,
+ backgroundEnabled: parallel.background_enabled ?? true,
+ spotcheckRequired: parallel.spotcheck_required ?? true,
+ };
+}
+
+function getAvailableModels(
+ registry: CapabilityRegistry,
+ effort: EffortLevel
+): string[] {
+ const models: string[] = [];
+ for (const [name, config] of Object.entries(registry.models || {})) {
+ if (effortMeetsMinimum(effort, config.effort_min)) {
+ models.push(name);
+ }
+ }
+ return models;
+}
+
+function loadAndFilter(effort: EffortLevel): LoadResult {
+ const registry = loadCapabilities();
+ const allCapabilities = flattenCapabilities(registry);
+ const { available, unavailable } = filterByEffort(allCapabilities, effort);
+ const parallelConfig = getParallelConfig(registry, effort);
+ const models = getAvailableModels(registry, effort);
+
+ return {
+ effort,
+ available,
+ unavailable,
+ parallelConfig,
+ models,
+ };
+}
+
+async function main() {
+ const { values } = parseArgs({
+ args: Bun.argv.slice(2),
+ options: {
+ effort: { type: "string", short: "e" },
+ output: { type: "string", short: "o", default: "text" },
+ "list-all": { type: "boolean" },
+ help: { type: "boolean", short: "h" },
+ },
+ });
+
+ if (values.help) {
+ console.log(`
+CapabilityLoader - Load and filter capabilities by effort level
+
+USAGE:
+ bun run CapabilityLoader.ts --effort STANDARD
+ bun run CapabilityLoader.ts --effort THOROUGH --output json
+ bun run CapabilityLoader.ts --list-all
+
+OPTIONS:
+ -e, --effort <level> Effort level: TRIVIAL, QUICK, STANDARD, THOROUGH, DETERMINED
+ -o, --output <fmt> Output format: text (default), json, markdown
+ --list-all List all capabilities regardless of effort
+ -h, --help Show this help
+
+EXAMPLES:
+ bun run CapabilityLoader.ts -e STANDARD
+ # Shows capabilities available at STANDARD effort
+
+ bun run CapabilityLoader.ts -e THOROUGH -o json
+ # JSON output for programmatic use
+
+ bun run CapabilityLoader.ts --list-all
+ # Show all capabilities with their effort thresholds
+`);
+ return;
+ }
+
+ if (values["list-all"]) {
+ const registry = loadCapabilities();
+ const all = flattenCapabilities(registry);
+
+ if (values.output === "json") {
+ console.log(JSON.stringify(all, null, 2));
+ } else {
+ console.log("ALL CAPABILITIES:\n");
+ const byCategory = new Map<string, Capability[]>();
+ for (const cap of all) {
+ const list = byCategory.get(cap.category) || [];
+ list.push(cap);
+ byCategory.set(cap.category, list);
+ }
+
+ for (const [category, caps] of byCategory) {
+ console.log(`\n=== ${category.toUpperCase()} ===`);
+ for (const cap of caps) {
+ console.log(` ${cap.name} (${cap.effort_min})`);
+ console.log(` → ${cap.use_when}`);
+ }
+ }
+ }
+ return;
+ }
+
+ if (!values.effort) {
+ console.error("Error: --effort is required (or use --list-all)");
+ console.error("Use --help for usage information");
+ process.exit(1);
+ }
+
+ const effort = values.effort.toUpperCase() as EffortLevel;
+ if (!EFFORT_ORDER.includes(effort)) {
+ console.error(`Error: Invalid effort level: ${values.effort}`);
+ console.error(`Valid levels: ${EFFORT_ORDER.join(", ")}`);
+ process.exit(1);
+ }
+
+ const result = loadAndFilter(effort);
+
+ if (values.output === "json") {
+ console.log(JSON.stringify(result, null, 2));
+ } else if (values.output === "markdown") {
+ console.log(`## Capabilities for ${result.effort}\n`);
+ console.log(`**Models:** ${result.models.join(", ")}`);
+ console.log(`**Max Parallel:** ${result.parallelConfig.maxConcurrent}`);
+ console.log(`**Background:** ${result.parallelConfig.backgroundEnabled}`);
+ console.log(`**Spotcheck:** ${result.parallelConfig.spotcheckRequired}\n`);
+
+ console.log("### Available\n");
+ const byCategory = new Map<string, Capability[]>();
+ for (const cap of result.available) {
+ const list = byCategory.get(cap.category) || [];
+ list.push(cap);
+ byCategory.set(cap.category, list);
+ }
+ for (const [category, caps] of byCategory) {
+ console.log(`**${category}:** ${caps.map((c) => c.name).join(", ")}`);
+ }
+
+ if (result.unavailable.length > 0) {
+ console.log("\n### Unavailable (higher effort required)\n");
+ for (const cap of result.unavailable) {
+ console.log(`- ${cap.name} (requires ${cap.effort_min})`);
+ }
+ }
+ } else {
+ console.log(`EFFORT LEVEL: ${result.effort}`);
+ console.log(`AVAILABLE MODELS: ${result.models.join(", ")}`);
+ console.log(`MAX PARALLEL: ${result.parallelConfig.maxConcurrent}`);
+ console.log(`BACKGROUND ENABLED: ${result.parallelConfig.backgroundEnabled}`);
+ console.log(`SPOTCHECK REQUIRED: ${result.parallelConfig.spotcheckRequired}`);
+ console.log(`\nAVAILABLE CAPABILITIES (${result.available.length}):`);
+
+ const byCategory = new Map<string, Capability[]>();
+ for (const cap of result.available) {
+ const list = byCategory.get(cap.category) || [];
+ list.push(cap);
+ byCategory.set(cap.category, list);
+ }
+
+ for (const [category, caps] of byCategory) {
+ console.log(`\n ${category.toUpperCase()}:`);
+ for (const cap of caps) {
+ console.log(` - ${cap.name}`);
+ }
+ }
+
+ if (result.unavailable.length > 0) {
+ console.log(`\nUNAVAILABLE (${result.unavailable.length}):`);
+ for (const cap of result.unavailable) {
+ console.log(` - ${cap.name} (requires ${cap.effort_min})`);
+ }
+ }
+ }
+}
+
+main().catch(console.error);
+
+// Export for programmatic use
+export {
+ loadCapabilities,
+ flattenCapabilities,
+ filterByEffort,
+ loadAndFilter,
+ effortMeetsMinimum,
+ type Capability,
+ type CapabilityRegistry,
+ type LoadResult,
+ type EffortLevel,
+};
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/CapabilitySelector.ts b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/CapabilitySelector.ts
new file mode 100644
index 00000000..4bdeeba2
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/CapabilitySelector.ts
@@ -0,0 +1,395 @@
+#!/usr/bin/env bun
+
+/**
+ * CapabilitySelector - Select appropriate capabilities for ISC rows
+ *
+ * Analyzes ISC row descriptions and matches them to available capabilities.
+ * Used by THE ALGORITHM to determine which capabilities to invoke for each row.
+ *
+ * Usage:
+ * bun run CapabilitySelector.ts --row "Research what makes good encounters" --effort STANDARD
+ * bun run CapabilitySelector.ts --isc-file current-isc.json --effort THOROUGH
+ */
+
+import { parseArgs } from "util";
+import {
+ loadAndFilter,
+ type Capability,
+ type EffortLevel,
+} from "./CapabilityLoader";
+
+interface CapabilityMatch {
+ capability: Capability;
+ score: number;
+ reasoning: string;
+}
+
+interface SelectionResult {
+ row: string;
+ effort: EffortLevel;
+ primaryCapability: Capability | null;
+ alternativeCapabilities: Capability[];
+ icon: string;
+ reasoning: string;
+}
+
+// Keywords that suggest specific capability categories
+const CAPABILITY_INDICATORS = {
+ research: {
+ keywords: [
+ "research",
+ "find out",
+ "investigate",
+ "look up",
+ "search",
+ "discover",
+ "learn about",
+ "understand",
+ "what is",
+ "how does",
+ "current",
+ "latest",
+ "state of",
+ ],
+ category: "research",
+ icon: "🔬",
+ },
+ thinking: {
+ keywords: [
+ "creative",
+ "novel",
+ "innovative",
+ "unique",
+ "think",
+ "brainstorm",
+ "generate",
+ "ideate",
+ "come up with",
+ "design",
+ "architect",
+ ],
+ category: "thinking",
+ icon: "💡",
+ },
+ debate: {
+ keywords: [
+ "perspectives",
+ "viewpoints",
+ "debate",
+ "discuss",
+ "pros and cons",
+ "trade-offs",
+ "compare",
+ "evaluate options",
+ "council",
+ "adversarial",
+ "stress test",
+ "red team",
+ ],
+ category: "debate",
+ icon: "🗣️",
+ },
+ analysis: {
+ keywords: [
+ "first principles",
+ "fundamental",
+ "root cause",
+ "assumptions",
+ "deconstruct",
+ "break down",
+ "analyze deeply",
+ "why",
+ "underlying",
+ ],
+ category: "analysis",
+ icon: "🔍",
+ },
+ execution: {
+ keywords: [
+ "create",
+ "build",
+ "implement",
+ "write",
+ "code",
+ "develop",
+ "make",
+ "produce",
+ "generate",
+ "construct",
+ ],
+ category: "execution",
+ icon: "🤖",
+ },
+ verification: {
+ keywords: [
+ "verify",
+ "validate",
+ "test",
+ "check",
+ "confirm",
+ "ensure",
+ "quality",
+ "review",
+ "audit",
+ ],
+ category: "verification",
+ icon: "✅",
+ },
+};
+
+// Specific capability selectors
+const SPECIFIC_SELECTORS = {
+ // Research agents
+ perplexity: ["web", "current events", "citations", "sources", "articles"],
+ gemini: ["multiple perspectives", "parallel", "comprehensive research"],
+ grok: ["contrarian", "fact-check", "unbiased", "critical"],
+ claude: ["academic", "scholarly", "papers", "literature"],
+ codex: ["code", "technical", "implementation patterns", "architecture"],
+
+ // Thinking modes
+ ultrathink: ["creative", "novel", "innovative", "quality thinking"],
+ tree_of_thought: ["complex decision", "branching", "multi-factor", "paths"],
+ plan_mode: ["multi-step", "implementation", "approval needed"],
+
+ // Debate
+ council: ["perspectives", "collaborative", "design decision", "trade-offs"],
+ redteam: ["adversarial", "attack", "weaknesses", "stress test", "vulnerabilities"],
+
+ // Analysis
+ first_principles: ["assumptions", "fundamental", "root", "deconstruct"],
+ science: ["hypothesis", "experiment", "systematic", "test"],
+
+ // Execution
+ intern: ["simple", "parallel", "grunt work", "data gathering"],
+ architect: ["system design", "architecture", "high-level"],
+ engineer: ["implement", "code", "build", "develop"],
+ qa_tester: ["test", "quality", "validation"],
+ designer: ["ui", "ux", "user experience", "interface"],
+ pentester: ["security", "vulnerability", "penetration"],
+
+ // Iterative execution
+ ralph_loop: [
+ "iterate until",
+ "keep trying",
+ "until tests pass",
+ "until it works",
+ "persistent",
+ "retry until",
+ "loop until",
+ "ralph",
+ "keep iterating",
+ "don't stop until",
+ "iterate on",
+ "keep at it",
+ "until success",
+ "until done",
+ "until fixed",
+ ],
+};
+
+function scoreCapability(
+ row: string,
+ capability: Capability,
+ availableCapabilities: Capability[]
+): CapabilityMatch {
+ const rowLower = row.toLowerCase();
+ let score = 0;
+ const reasons: string[] = [];
+
+ // Check category indicators
+ for (const [indicatorName, indicator] of Object.entries(CAPABILITY_INDICATORS)) {
+ if (indicator.category === capability.category) {
+ for (const keyword of indicator.keywords) {
+ if (rowLower.includes(keyword)) {
+ score += 2;
+ reasons.push(`matches "${keyword}"`);
+ }
+ }
+ }
+ }
+
+ // Check specific selectors
+ const specificKeywords = SPECIFIC_SELECTORS[capability.name as keyof typeof SPECIFIC_SELECTORS];
+ if (specificKeywords) {
+ for (const keyword of specificKeywords) {
+ if (rowLower.includes(keyword)) {
+ score += 3;
+ reasons.push(`specific match: "${keyword}"`);
+ }
+ }
+ }
+
+ // Check use_when field
+ if (capability.use_when) {
+ const useWhenLower = capability.use_when.toLowerCase();
+ const useWhenWords = useWhenLower.split(/\s+/);
+ for (const word of useWhenWords) {
+ if (word.length > 3 && rowLower.includes(word)) {
+ score += 1;
+ reasons.push(`use_when match: "${word}"`);
+ }
+ }
+ }
+
+ return {
+ capability,
+ score,
+ reasoning: reasons.length > 0 ? reasons.join(", ") : "no specific matches",
+ };
+}
+
+function selectCapabilities(
+ row: string,
+ effort: EffortLevel
+): SelectionResult {
+ const { available } = loadAndFilter(effort);
+
+ // Score all available capabilities
+ const scores: CapabilityMatch[] = available.map((cap) =>
+ scoreCapability(row, cap, available)
+ );
+
+ // Sort by score descending
+ scores.sort((a, b) => b.score - a.score);
+
+ // Filter to meaningful matches (score > 0)
+ const meaningfulMatches = scores.filter((s) => s.score > 0);
+
+ // Determine primary capability
+ const primary = meaningfulMatches.length > 0 ? meaningfulMatches[0] : null;
+
+ // Determine icon based on:
+ // 1. Capability's own icon (if defined)
+ // 2. Category indicator icon
+ // 3. Default
+ let icon = "🤖";
+ if (primary) {
+ // Check if capability has its own icon defined
+ if (primary.capability.icon) {
+ icon = primary.capability.icon;
+ } else {
+ const indicator = Object.values(CAPABILITY_INDICATORS).find(
+ (ind) => ind.category === primary.capability.category
+ );
+ if (indicator) {
+ icon = indicator.icon;
+ }
+ }
+ }
+
+ // Check for parallel execution indicator
+ const rowLower = row.toLowerCase();
+ const parallelIndicators = ["each", "all", "multiple", "10", "5", "parallel", "batch"];
+ const isParallel = parallelIndicators.some((ind) => rowLower.includes(ind));
+ if (isParallel) {
+ icon = icon + "×";
+ }
+
+ return {
+ row,
+ effort,
+ primaryCapability: primary?.capability || null,
+ alternativeCapabilities: meaningfulMatches
+ .slice(1, 4)
+ .map((m) => m.capability),
+ icon,
+ reasoning: primary?.reasoning || "No specific capability match - default execution",
+ };
+}
+
+function selectForMultipleRows(
+ rows: string[],
+ effort: EffortLevel
+): SelectionResult[] {
+ return rows.map((row) => selectCapabilities(row, effort));
+}
+
+async function main() {
+ const { values } = parseArgs({
+ args: Bun.argv.slice(2),
+ options: {
+ row: { type: "string", short: "r" },
+ effort: { type: "string", short: "e", default: "STANDARD" },
+ output: { type: "string", short: "o", default: "text" },
+ help: { type: "boolean", short: "h" },
+ },
+ });
+
+ if (values.help) {
+ console.log(`
+CapabilitySelector - Select capabilities for ISC rows
+
+USAGE:
+ bun run CapabilitySelector.ts --row "Research what makes good encounters" --effort STANDARD
+ bun run CapabilitySelector.ts -r "Create 10 balanced encounters" -e THOROUGH
+
+OPTIONS:
+ -r, --row <text> ISC row description to analyze
+ -e, --effort <level> Effort level (default: STANDARD)
+ -o, --output <fmt> Output format: text (default), json
+ -h, --help Show this help
+
+EXAMPLES:
+ bun run CapabilitySelector.ts -r "Research best practices for API design"
+ # → Suggests research.perplexity or research.claude
+
+ bun run CapabilitySelector.ts -r "Generate novel solutions creatively" -e THOROUGH
+ # → Suggests thinking.ultrathink
+
+ bun run CapabilitySelector.ts -r "Verify implementation against requirements"
+ # → Suggests verification.skeptical_verifier
+`);
+ return;
+ }
+
+ if (!values.row) {
+ console.error("Error: --row is required");
+ console.error("Use --help for usage information");
+ process.exit(1);
+ }
+
+ const effort = values.effort?.toUpperCase() as EffortLevel;
+ const result = selectCapabilities(values.row, effort);
+
+ if (values.output === "json") {
+ console.log(JSON.stringify(result, null, 2));
+ } else {
+ console.log(`ROW: ${result.row}`);
+ console.log(`EFFORT: ${result.effort}`);
+ console.log(`ICON: ${result.icon}`);
+
+ if (result.primaryCapability) {
+ console.log(`\nPRIMARY CAPABILITY:`);
+ console.log(` Name: ${result.primaryCapability.name}`);
+ console.log(` Category: ${result.primaryCapability.category}`);
+ if (result.primaryCapability.skill) {
+ console.log(` Skill: ${result.primaryCapability.skill}`);
+ }
+ if (result.primaryCapability.subagent_type) {
+ console.log(` Subagent: ${result.primaryCapability.subagent_type}`);
+ }
+ console.log(` Reasoning: ${result.reasoning}`);
+ } else {
+ console.log(`\nNO SPECIFIC CAPABILITY MATCH`);
+ console.log(`Will use default execution agent`);
+ }
+
+ if (result.alternativeCapabilities.length > 0) {
+ console.log(`\nALTERNATIVES:`);
+ for (const alt of result.alternativeCapabilities) {
+ console.log(` - ${alt.name} (${alt.category})`);
+ }
+ }
+ }
+}
+
+main().catch(console.error);
+
+// Export for programmatic use
+export {
+ selectCapabilities,
+ selectForMultipleRows,
+ scoreCapability,
+ type SelectionResult,
+ type CapabilityMatch,
+};
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/EffortClassifier.ts b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/EffortClassifier.ts
new file mode 100644
index 00000000..614e7390
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/EffortClassifier.ts
@@ -0,0 +1,480 @@
+#!/usr/bin/env bun
+
+/**
+ * EffortClassifier - Classify request effort level for THE ALGORITHM
+ *
+ * Analyzes a request and determines the appropriate effort level:
+ * - TRIVIAL: Greetings, simple Q&A, acknowledgments
+ * - QUICK: Single-step tasks, simple lookups
+ * - STANDARD: Most work, multi-step but bounded
+ * - THOROUGH: Complex, multi-file, architectural
+ * - DETERMINED: "Until done", overnight, unlimited
+ *
+ * Supports override via --override flag or "algorithm effort LEVEL" in request.
+ *
+ * Usage:
+ * bun run EffortClassifier.ts --request "Add dark mode to settings"
+ * bun run EffortClassifier.ts --request "Fix the typo" --output json
+ * bun run EffortClassifier.ts --request "anything" --override DETERMINED
+ * bun run EffortClassifier.ts --request "algorithm effort THOROUGH: create feature"
+ */
+
+import { parseArgs } from "util";
+
+type EffortLevel = "TRIVIAL" | "QUICK" | "STANDARD" | "THOROUGH" | "DETERMINED";
+
+interface ClassificationResult {
+ effort: EffortLevel;
+ confidence: number;
+ reasoning: string;
+ minISCRows: number; // Minimum expected, NOT a limit - ISC can have dozens/hundreds/thousands
+ suggestedModel: string;
+ suggestedTraits: string[];
+ wasOverridden: boolean;
+ originalRequest?: string;
+}
+
+const EFFORT_LEVELS: EffortLevel[] = ["TRIVIAL", "QUICK", "STANDARD", "THOROUGH", "DETERMINED"];
+
+// Check for "algorithm effort LEVEL" pattern in request
+function checkInlineOverride(request: string): { override: EffortLevel | null; cleanedRequest: string } {
+ const pattern = /algorithm\s+effort\s+(TRIVIAL|QUICK|STANDARD|THOROUGH|DETERMINED)\s*:?\s*/i;
+ const match = request.match(pattern);
+
+ if (match) {
+ const level = match[1].toUpperCase() as EffortLevel;
+ const cleanedRequest = request.replace(pattern, "").trim();
+ return { override: level, cleanedRequest };
+ }
+
+ return { override: null, cleanedRequest: request };
+}
+
+// Patterns for each effort level
+const PATTERNS = {
+ TRIVIAL: {
+ keywords: [
+ "hello",
+ "hi",
+ "hey",
+ "thanks",
+ "thank you",
+ "got it",
+ "ok",
+ "okay",
+ "cool",
+ "awesome",
+ "great",
+ "nice",
+ "yes",
+ "no",
+ "sure",
+ ],
+ patterns: [
+ /^(hi|hello|hey)[\s!.,]*$/i,
+ /^thanks?[\s!.,]*$/i,
+ /^(ok|okay|got it|sure)[\s!.,]*$/i,
+ /^(yes|no|yep|nope)[\s!.,]*$/i,
+ ],
+ },
+ QUICK: {
+ keywords: [
+ "quick",
+ "simple",
+ "just",
+ "only",
+ "typo",
+ "rename",
+ "change",
+ "update",
+ ],
+ patterns: [
+ /fix (the |a )?typo/i,
+ /rename \w+ to \w+/i,
+ /^what (is|does)/i,
+ /^where (is|are)/i,
+ /^how do I/i,
+ /change .{1,30} to .{1,30}$/i,
+ ],
+ maxWords: 15,
+ },
+ THOROUGH: {
+ keywords: [
+ "thorough",
+ "comprehensive",
+ "complete",
+ "full",
+ "architecture",
+ "refactor",
+ "redesign",
+ "overhaul",
+ "system",
+ "complex",
+ ],
+ patterns: [
+ /refactor/i,
+ /redesign/i,
+ /architect/i,
+ /comprehensive/i,
+ /thorough/i,
+ /multi.?file/i,
+ /across (the |all )?codebase/i,
+ ],
+ },
+ DETERMINED: {
+ keywords: [
+ "determined",
+ "until done",
+ "don't stop",
+ "keep going",
+ "overnight",
+ "walk away",
+ "unlimited",
+ "whatever it takes",
+ ],
+ patterns: [
+ /until (it('s| is))? done/i,
+ /don'?t stop/i,
+ /keep going/i,
+ /overnight/i,
+ /walk away/i,
+ /whatever it takes/i,
+ /no matter what/i,
+ ],
+ },
+};
+
+// Complexity indicators
+const COMPLEXITY_INDICATORS = {
+ high: [
+ "authentication",
+ "authorization",
+ "security",
+ "database",
+ "migration",
+ "api",
+ "integration",
+ "deploy",
+ "infrastructure",
+ "performance",
+ "optimization",
+ "architecture",
+ "refactor",
+ "redesign",
+ ],
+ medium: [
+ "feature",
+ "component",
+ "page",
+ "form",
+ "validation",
+ "test",
+ "style",
+ "layout",
+ "responsive",
+ "modal",
+ "dialog",
+ ],
+ low: [
+ "typo",
+ "comment",
+ "rename",
+ "color",
+ "text",
+ "label",
+ "spacing",
+ "margin",
+ "padding",
+ ],
+};
+
+function getEffortConfig(effort: EffortLevel): Pick<ClassificationResult, "minISCRows" | "suggestedModel" | "suggestedTraits"> {
+ // minISCRows = minimum expected, NOT a limit. ISC can have dozens/hundreds/thousands of rows.
+ const configs: Record<EffortLevel, Pick<ClassificationResult, "minISCRows" | "suggestedModel" | "suggestedTraits">> = {
+ TRIVIAL: { minISCRows: 0, suggestedModel: "none", suggestedTraits: [] },
+ QUICK: { minISCRows: 2, suggestedModel: "haiku", suggestedTraits: ["rapid", "pragmatic"] },
+ STANDARD: { minISCRows: 5, suggestedModel: "sonnet", suggestedTraits: ["analytical", "systematic"] },
+ THOROUGH: { minISCRows: 10, suggestedModel: "sonnet", suggestedTraits: ["thorough", "meticulous"] },
+ DETERMINED: { minISCRows: 20, suggestedModel: "opus", suggestedTraits: ["thorough", "meticulous", "adversarial"] },
+ };
+ return configs[effort];
+}
+
+function classifyEffort(request: string, overrideLevel?: EffortLevel): ClassificationResult {
+ // Check for inline override first (e.g., "algorithm effort THOROUGH: do the thing")
+ const { override: inlineOverride, cleanedRequest } = checkInlineOverride(request);
+
+ // Priority: CLI override > inline override > auto-classification
+ const effectiveOverride = overrideLevel || inlineOverride;
+
+ if (effectiveOverride) {
+ const config = getEffortConfig(effectiveOverride);
+ return {
+ effort: effectiveOverride,
+ confidence: 1.0,
+ reasoning: overrideLevel
+ ? `Overridden via --override flag to ${effectiveOverride}`
+ : `Overridden via inline "algorithm effort ${effectiveOverride}" pattern`,
+ ...config,
+ wasOverridden: true,
+ originalRequest: inlineOverride ? cleanedRequest : undefined,
+ };
+ }
+
+ const requestLower = request.toLowerCase().trim();
+ const words = requestLower.split(/\s+/);
+ const wordCount = words.length;
+
+ // Check TRIVIAL patterns first
+ for (const pattern of PATTERNS.TRIVIAL.patterns) {
+ if (pattern.test(requestLower)) {
+ return {
+ effort: "TRIVIAL",
+ confidence: 0.95,
+ reasoning: "Matches trivial pattern (greeting/acknowledgment)",
+ minISCRows: 0,
+ suggestedModel: "none",
+ suggestedTraits: [],
+ wasOverridden: false,
+ };
+ }
+ }
+
+ // Check if it's just a trivial keyword
+ if (
+ wordCount <= 3 &&
+ PATTERNS.TRIVIAL.keywords.some((kw) => requestLower.includes(kw))
+ ) {
+ return {
+ effort: "TRIVIAL",
+ confidence: 0.9,
+ reasoning: "Short request with trivial keyword",
+ minISCRows: 0,
+ suggestedModel: "none",
+ suggestedTraits: [],
+ wasOverridden: false,
+ };
+ }
+
+ // Check DETERMINED patterns (explicit override)
+ for (const pattern of PATTERNS.DETERMINED.patterns) {
+ if (pattern.test(requestLower)) {
+ return {
+ effort: "DETERMINED",
+ confidence: 0.95,
+ reasoning: "Explicit determination pattern detected",
+ minISCRows: 10,
+ suggestedModel: "opus",
+ suggestedTraits: ["thorough", "meticulous", "adversarial"],
+ wasOverridden: false,
+ };
+ }
+ }
+
+ if (
+ PATTERNS.DETERMINED.keywords.some((kw) => requestLower.includes(kw))
+ ) {
+ return {
+ effort: "DETERMINED",
+ confidence: 0.9,
+ reasoning: "Determination keyword detected",
+ minISCRows: 10,
+ suggestedModel: "opus",
+ suggestedTraits: ["thorough", "meticulous", "adversarial"],
+ wasOverridden: false,
+ };
+ }
+
+ // Check THOROUGH patterns
+ for (const pattern of PATTERNS.THOROUGH.patterns) {
+ if (pattern.test(requestLower)) {
+ return {
+ effort: "THOROUGH",
+ confidence: 0.85,
+ reasoning: "Matches thorough pattern (complex work)",
+ minISCRows: 10,
+ suggestedModel: "sonnet",
+ suggestedTraits: ["thorough", "meticulous"],
+ wasOverridden: false,
+ };
+ }
+ }
+
+ // Check complexity indicators
+ const highComplexity = COMPLEXITY_INDICATORS.high.filter((ind) =>
+ requestLower.includes(ind)
+ );
+ const mediumComplexity = COMPLEXITY_INDICATORS.medium.filter((ind) =>
+ requestLower.includes(ind)
+ );
+ const lowComplexity = COMPLEXITY_INDICATORS.low.filter((ind) =>
+ requestLower.includes(ind)
+ );
+
+ // Score based on complexity
+ const complexityScore =
+ highComplexity.length * 3 +
+ mediumComplexity.length * 2 +
+ lowComplexity.length * 1;
+
+ // Check QUICK patterns
+ for (const pattern of PATTERNS.QUICK.patterns) {
+ if (pattern.test(requestLower)) {
+ // But override if complexity indicators suggest otherwise
+ if (complexityScore >= 4) {
+ return {
+ effort: "STANDARD",
+ confidence: 0.7,
+ reasoning:
+ "Quick pattern but complexity indicators suggest more depth",
+ minISCRows: 5,
+ suggestedModel: "sonnet",
+ suggestedTraits: ["analytical", "systematic"],
+ wasOverridden: false,
+ };
+ }
+ return {
+ effort: "QUICK",
+ confidence: 0.85,
+ reasoning: "Matches quick pattern",
+ minISCRows: 2,
+ suggestedModel: "haiku",
+ suggestedTraits: ["rapid", "pragmatic"],
+ wasOverridden: false,
+ };
+ }
+ }
+
+ // Very short requests are likely QUICK
+ if (wordCount <= (PATTERNS.QUICK.maxWords || 15) && complexityScore <= 2) {
+ return {
+ effort: "QUICK",
+ confidence: 0.75,
+ reasoning: "Short request with low complexity",
+ minISCRows: 2,
+ suggestedModel: "haiku",
+ suggestedTraits: ["rapid", "pragmatic"],
+ wasOverridden: false,
+ };
+ }
+
+ // High complexity score → THOROUGH
+ if (complexityScore >= 6 || highComplexity.length >= 2) {
+ return {
+ effort: "THOROUGH",
+ confidence: 0.8,
+ reasoning: `High complexity score (${complexityScore}): ${highComplexity.join(", ")}`,
+ minISCRows: 10,
+ suggestedModel: "sonnet",
+ suggestedTraits: ["thorough", "meticulous"],
+ wasOverridden: false,
+ };
+ }
+
+ // Default to STANDARD
+ return {
+ effort: "STANDARD",
+ confidence: 0.7,
+ reasoning: "Default classification for bounded multi-step work",
+ minISCRows: 5,
+ suggestedModel: "sonnet",
+ suggestedTraits: ["analytical", "systematic"],
+ wasOverridden: false,
+ };
+}
+
+async function main() {
+ const { values } = parseArgs({
+ args: Bun.argv.slice(2),
+ options: {
+ request: { type: "string", short: "r" },
+ override: { type: "string" },
+ output: { type: "string", short: "o", default: "text" },
+ help: { type: "boolean", short: "h" },
+ },
+ });
+
+ if (values.help) {
+ console.log(`
+EffortClassifier - Classify request effort level
+
+USAGE:
+ bun run EffortClassifier.ts --request "your request here"
+ bun run EffortClassifier.ts -r "your request" --output json
+ bun run EffortClassifier.ts -r "anything" --override DETERMINED
+
+OPTIONS:
+ -r, --request <text> The request to classify
+ --override <level> Force specific effort level (TRIVIAL/QUICK/STANDARD/THOROUGH/DETERMINED)
+ -o, --output <fmt> Output format: text (default), json
+ -h, --help Show this help
+
+EFFORT LEVELS:
+ TRIVIAL - Greetings, acknowledgments, simple Q&A
+ QUICK - Single-step tasks, simple changes
+ STANDARD - Multi-step work, bounded scope
+ THOROUGH - Complex, multi-file, architectural
+ DETERMINED - Unlimited iteration until done
+
+OVERRIDE METHODS:
+ 1. CLI flag: --override THOROUGH
+ 2. Inline: "algorithm effort THOROUGH: create a feature"
+
+EXAMPLES:
+ bun run EffortClassifier.ts -r "Hello"
+ # → TRIVIAL
+
+ bun run EffortClassifier.ts -r "Fix the typo in README"
+ # → QUICK
+
+ bun run EffortClassifier.ts -r "Add authentication to the API"
+ # → THOROUGH
+
+ bun run EffortClassifier.ts -r "Keep going until all tests pass"
+ # → DETERMINED
+
+ bun run EffortClassifier.ts -r "simple task" --override DETERMINED
+ # → DETERMINED (forced)
+
+ bun run EffortClassifier.ts -r "algorithm effort THOROUGH: create feature"
+ # → THOROUGH (inline override)
+`);
+ return;
+ }
+
+ if (!values.request) {
+ console.error("Error: --request is required");
+ console.error("Use --help for usage information");
+ process.exit(1);
+ }
+
+ // Validate and apply override if provided
+ let overrideLevel: EffortLevel | undefined;
+ if (values.override) {
+ const upperOverride = values.override.toUpperCase() as EffortLevel;
+ if (!EFFORT_LEVELS.includes(upperOverride)) {
+ console.error(`Error: Invalid override level: ${values.override}`);
+ console.error(`Valid levels: ${EFFORT_LEVELS.join(", ")}`);
+ process.exit(1);
+ }
+ overrideLevel = upperOverride;
+ }
+
+ const result = classifyEffort(values.request, overrideLevel);
+
+ if (values.output === "json") {
+ console.log(JSON.stringify(result, null, 2));
+ } else {
+ console.log(`EFFORT: ${result.effort}${result.wasOverridden ? " (OVERRIDDEN)" : ""}`);
+ console.log(`CONFIDENCE: ${(result.confidence * 100).toFixed(0)}%`);
+ console.log(`REASONING: ${result.reasoning}`);
+ if (result.originalRequest) {
+ console.log(`ORIGINAL REQUEST: ${result.originalRequest}`);
+ }
+ console.log(`MIN ISC ROWS: ${result.minISCRows} (can grow to dozens/hundreds/thousands)`);
+ console.log(`SUGGESTED MODEL: ${result.suggestedModel}`);
+ console.log(`SUGGESTED TRAITS: ${result.suggestedTraits.join(", ") || "none"}`);
+ }
+}
+
+main().catch(console.error);
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/ISCManager.ts b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/ISCManager.ts
new file mode 100644
index 00000000..0fe84a29
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/ISCManager.ts
@@ -0,0 +1,571 @@
+#!/usr/bin/env bun
+
+/**
+ * ISCManager - Manage Ideal State Criteria tables for THE ALGORITHM
+ *
+ * Creates, updates, and queries ISC tables that track work toward ideal state.
+ *
+ * Usage:
+ * bun run ISCManager.ts create --request "Add dark mode"
+ * bun run ISCManager.ts add --description "Tests pass" --source IMPLICIT
+ * bun run ISCManager.ts update --row 1 --status DONE
+ * bun run ISCManager.ts show
+ * bun run ISCManager.ts verify --row 1 --result PASS
+ */
+
+import { parseArgs } from "util";
+import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
+import { join } from "path";
+
+type Source = "EXPLICIT" | "INFERRED" | "IMPLICIT";
+type Status = "PENDING" | "ACTIVE" | "DONE" | "ADJUSTED" | "BLOCKED";
+type VerifyResult = "PASS" | "ADJUSTED" | "BLOCKED";
+
+interface ISCRow {
+ id: number;
+ description: string;
+ source: Source;
+ status: Status;
+ parallel: boolean; // Can run in parallel with others
+ capability?: string; // Assigned capability (e.g., "research.perplexity", "thinking.ultrathink")
+ capabilityIcon?: string; // Icon for display (e.g., "🔬", "💡", "🤖")
+ result?: string;
+ adjustedReason?: string;
+ blockedReason?: string;
+ verifyResult?: VerifyResult;
+ timestamp: string;
+}
+
+interface ISCTable {
+ request: string;
+ effort: string;
+ created: string;
+ lastModified: string;
+ phase: string;
+ iteration: number;
+ rows: ISCRow[];
+ log: string[];
+}
+
+const PAI_DIR = process.env.PAI_DIR || join(process.env.HOME || "~", ".config/pai");
+const ISC_DIR = join(PAI_DIR, "MEMORY/Work");
+const CURRENT_ISC_PATH = join(ISC_DIR, "current-isc.json");
+
+// Capability category to icon mapping
+const CAPABILITY_ICONS: Record<string, string> = {
+ research: "🔬",
+ thinking: "💡",
+ debate: "🗣️",
+ analysis: "🔍",
+ execution: "🤖",
+ verification: "✅",
+ models: "⚡",
+ composition: "🧩",
+};
+
+function ensureDir() {
+ if (!existsSync(ISC_DIR)) {
+ mkdirSync(ISC_DIR, { recursive: true });
+ }
+}
+
+function loadISC(): ISCTable | null {
+ if (!existsSync(CURRENT_ISC_PATH)) {
+ return null;
+ }
+ const content = readFileSync(CURRENT_ISC_PATH, "utf-8");
+ return JSON.parse(content) as ISCTable;
+}
+
+function saveISC(isc: ISCTable) {
+ ensureDir();
+ isc.lastModified = new Date().toISOString();
+ writeFileSync(CURRENT_ISC_PATH, JSON.stringify(isc, null, 2));
+}
+
+function createISC(request: string, effort: string): ISCTable {
+ const isc: ISCTable = {
+ request,
+ effort,
+ created: new Date().toISOString(),
+ lastModified: new Date().toISOString(),
+ phase: "OBSERVE",
+ iteration: 1,
+ rows: [],
+ log: [`[${new Date().toISOString()}] ISC created for: ${request}`],
+ };
+ saveISC(isc);
+ return isc;
+}
+
+function addRow(
+ isc: ISCTable,
+ description: string,
+ source: Source,
+ parallel: boolean = true
+): ISCRow {
+ const row: ISCRow = {
+ id: isc.rows.length + 1,
+ description,
+ source,
+ status: "PENDING",
+ parallel,
+ timestamp: new Date().toISOString(),
+ };
+ isc.rows.push(row);
+ isc.log.push(
+ `[${new Date().toISOString()}] Added row ${row.id}: ${description} (${source})`
+ );
+ saveISC(isc);
+ return row;
+}
+
+function updateRowStatus(
+ isc: ISCTable,
+ rowId: number,
+ status: Status,
+ reason?: string
+): ISCRow | null {
+ const row = isc.rows.find((r) => r.id === rowId);
+ if (!row) return null;
+
+ const oldStatus = row.status;
+ row.status = status;
+
+ if (status === "ADJUSTED" && reason) {
+ row.adjustedReason = reason;
+ }
+ if (status === "BLOCKED" && reason) {
+ row.blockedReason = reason;
+ }
+
+ isc.log.push(
+ `[${new Date().toISOString()}] Row ${rowId}: ${oldStatus} → ${status}${reason ? ` (${reason})` : ""}`
+ );
+ saveISC(isc);
+ return row;
+}
+
+function setVerifyResult(
+ isc: ISCTable,
+ rowId: number,
+ result: VerifyResult,
+ reason?: string
+): ISCRow | null {
+ const row = isc.rows.find((r) => r.id === rowId);
+ if (!row) return null;
+
+ row.verifyResult = result;
+ if (result === "ADJUSTED" && reason) {
+ row.adjustedReason = reason;
+ row.status = "ADJUSTED";
+ }
+ if (result === "BLOCKED" && reason) {
+ row.blockedReason = reason;
+ row.status = "BLOCKED";
+ }
+
+ isc.log.push(
+ `[${new Date().toISOString()}] Verify row ${rowId}: ${result}${reason ? ` (${reason})` : ""}`
+ );
+ saveISC(isc);
+ return row;
+}
+
+function setCapability(
+ isc: ISCTable,
+ rowId: number,
+ capability: string
+): ISCRow | null {
+ const row = isc.rows.find((r) => r.id === rowId);
+ if (!row) return null;
+
+ row.capability = capability;
+ // Extract category from capability name (e.g., "research.perplexity" → "research")
+ const category = capability.split(".")[0];
+ row.capabilityIcon = CAPABILITY_ICONS[category] || "🤖";
+
+ isc.log.push(
+ `[${new Date().toISOString()}] Row ${rowId}: capability → ${capability}`
+ );
+ saveISC(isc);
+ return row;
+}
+
+function setPhase(isc: ISCTable, phase: string) {
+ const oldPhase = isc.phase;
+ isc.phase = phase;
+ isc.log.push(`[${new Date().toISOString()}] Phase: ${oldPhase} → ${phase}`);
+ saveISC(isc);
+}
+
+function incrementIteration(isc: ISCTable) {
+ isc.iteration++;
+ isc.log.push(
+ `[${new Date().toISOString()}] Starting iteration ${isc.iteration}`
+ );
+ saveISC(isc);
+}
+
+function formatTable(isc: ISCTable): string {
+ let output = `## 🎯 IDEAL STATE CRITERIA\n\n`;
+ output += `**Request:** ${isc.request}\n`;
+ output += `**Effort:** ${isc.effort} | **Phase:** ${isc.phase} | **Iteration:** ${isc.iteration}\n\n`;
+ output += `| # | What Ideal Looks Like | Source | Capability | Status |\n`;
+ output += `|---|----------------------|--------|------------|--------|\n`;
+
+ for (const row of isc.rows) {
+ let desc = row.description;
+ if (row.adjustedReason) {
+ desc += ` *(adjusted: ${row.adjustedReason})*`;
+ }
+ if (row.blockedReason) {
+ desc += ` *(blocked: ${row.blockedReason})*`;
+ }
+ // Format capability with icon
+ let capDisplay = "—";
+ if (row.capability) {
+ const icon = row.capabilityIcon || "🤖";
+ const capName = row.capability.split(".").pop() || row.capability;
+ capDisplay = `${icon} ${capName}`;
+ if (row.parallel) {
+ capDisplay += "×";
+ }
+ }
+ // Status emoji
+ const statusEmoji: Record<Status, string> = {
+ PENDING: "⏳",
+ ACTIVE: "🔄",
+ DONE: "✅",
+ ADJUSTED: "🔧",
+ BLOCKED: "🚫",
+ };
+ const statusDisplay = `${statusEmoji[row.status]} ${row.status}`;
+ output += `| ${row.id} | ${desc} | ${row.source} | ${capDisplay} | ${statusDisplay} |\n`;
+ }
+
+ output += `\n**Legend:** 🔬 Research | 💡 Thinking | 🗣️ Debate | 🔍 Analysis | 🤖 Execution | ✅ Verify | × Parallel\n`;
+
+ return output;
+}
+
+function formatLog(isc: ISCTable): string {
+ let output = `## Evolution Log\n\n`;
+ for (const entry of isc.log) {
+ output += `${entry}\n`;
+ }
+ return output;
+}
+
+function getSummary(isc: ISCTable): {
+ total: number;
+ pending: number;
+ active: number;
+ done: number;
+ adjusted: number;
+ blocked: number;
+ parallelizable: number;
+} {
+ return {
+ total: isc.rows.length,
+ pending: isc.rows.filter((r) => r.status === "PENDING").length,
+ active: isc.rows.filter((r) => r.status === "ACTIVE").length,
+ done: isc.rows.filter((r) => r.status === "DONE").length,
+ adjusted: isc.rows.filter((r) => r.status === "ADJUSTED").length,
+ blocked: isc.rows.filter((r) => r.status === "BLOCKED").length,
+ parallelizable: isc.rows.filter((r) => r.parallel && r.status === "PENDING")
+ .length,
+ };
+}
+
+async function main() {
+ const { values, positionals } = parseArgs({
+ args: Bun.argv.slice(2),
+ options: {
+ request: { type: "string", short: "r" },
+ effort: { type: "string", short: "e", default: "STANDARD" },
+ description: { type: "string", short: "d" },
+ source: { type: "string", short: "s" },
+ row: { type: "string" },
+ status: { type: "string" },
+ result: { type: "string" },
+ reason: { type: "string" },
+ phase: { type: "string", short: "p" },
+ capability: { type: "string", short: "c" },
+ parallel: { type: "boolean", default: true },
+ output: { type: "string", short: "o", default: "text" },
+ help: { type: "boolean", short: "h" },
+ },
+ allowPositionals: true,
+ });
+
+ const command = positionals[0];
+
+ if (values.help || !command) {
+ console.log(`
+ISCManager - Manage Ideal State Criteria tables
+
+USAGE:
+ bun run ISCManager.ts <command> [options]
+
+COMMANDS:
+ create Create new ISC table
+ add Add a row to current ISC
+ update Update row status
+ capability Set capability for a row
+ verify Set verification result for a row
+ phase Set current phase
+ iterate Increment iteration counter
+ show Display current ISC table
+ log Show evolution log
+ summary Show status summary
+ clear Clear current ISC
+
+OPTIONS:
+ -r, --request <text> Request text (for create)
+ -e, --effort <level> Effort level (for create)
+ -d, --description <text> Row description (for add)
+ -s, --source <type> Source: EXPLICIT, INFERRED, IMPLICIT (for add)
+ --row <id> Row ID (for update/verify/capability)
+ --status <status> Status: PENDING, ACTIVE, DONE, ADJUSTED, BLOCKED
+ -c, --capability <cap> Capability: research.perplexity, thinking.ultrathink, etc.
+ --result <result> Verify result: PASS, ADJUSTED, BLOCKED
+ --reason <text> Reason for adjustment/block
+ -p, --phase <phase> Phase name (for phase command)
+ --parallel Row can run in parallel (default: true)
+ -o, --output <fmt> Output format: text, json, markdown
+ -h, --help Show this help
+
+EXAMPLES:
+ # Create new ISC
+ bun run ISCManager.ts create -r "Add dark mode to settings"
+
+ # Add rows
+ bun run ISCManager.ts add -d "Toggle component works" -s EXPLICIT
+ bun run ISCManager.ts add -d "Uses TypeScript" -s INFERRED
+ bun run ISCManager.ts add -d "Tests pass" -s IMPLICIT
+
+ # Update status
+ bun run ISCManager.ts update --row 1 --status ACTIVE
+ bun run ISCManager.ts update --row 1 --status DONE
+
+ # Set capability
+ bun run ISCManager.ts capability --row 1 -c research.perplexity
+ bun run ISCManager.ts capability --row 2 -c thinking.ultrathink
+
+ # Verify
+ bun run ISCManager.ts verify --row 1 --result PASS
+ bun run ISCManager.ts verify --row 2 --result ADJUSTED --reason "250ms instead of 200ms"
+
+ # Show table
+ bun run ISCManager.ts show
+ bun run ISCManager.ts show -o markdown
+`);
+ return;
+ }
+
+ switch (command) {
+ case "create": {
+ if (!values.request) {
+ console.error("Error: --request is required for create");
+ process.exit(1);
+ }
+ const isc = createISC(values.request, values.effort || "STANDARD");
+ console.log(`ISC created for: ${values.request}`);
+ console.log(`Effort: ${isc.effort}`);
+ console.log(`Saved to: ${CURRENT_ISC_PATH}`);
+ break;
+ }
+
+ case "add": {
+ const isc = loadISC();
+ if (!isc) {
+ console.error("Error: No current ISC. Use 'create' first.");
+ process.exit(1);
+ }
+ if (!values.description) {
+ console.error("Error: --description is required for add");
+ process.exit(1);
+ }
+ const source = (values.source?.toUpperCase() || "EXPLICIT") as Source;
+ if (!["EXPLICIT", "INFERRED", "IMPLICIT"].includes(source)) {
+ console.error("Error: --source must be EXPLICIT, INFERRED, or IMPLICIT");
+ process.exit(1);
+ }
+ const row = addRow(isc, values.description, source, values.parallel);
+ console.log(`Added row ${row.id}: ${row.description} (${row.source})`);
+ break;
+ }
+
+ case "update": {
+ const isc = loadISC();
+ if (!isc) {
+ console.error("Error: No current ISC. Use 'create' first.");
+ process.exit(1);
+ }
+ if (!values.row) {
+ console.error("Error: --row is required for update");
+ process.exit(1);
+ }
+ if (!values.status) {
+ console.error("Error: --status is required for update");
+ process.exit(1);
+ }
+ const status = values.status.toUpperCase() as Status;
+ if (!["PENDING", "ACTIVE", "DONE", "ADJUSTED", "BLOCKED"].includes(status)) {
+ console.error("Error: Invalid status");
+ process.exit(1);
+ }
+ const row = updateRowStatus(isc, parseInt(values.row), status, values.reason);
+ if (!row) {
+ console.error(`Error: Row ${values.row} not found`);
+ process.exit(1);
+ }
+ console.log(`Row ${row.id}: ${row.status}`);
+ break;
+ }
+
+ case "capability": {
+ const isc = loadISC();
+ if (!isc) {
+ console.error("Error: No current ISC. Use 'create' first.");
+ process.exit(1);
+ }
+ if (!values.row) {
+ console.error("Error: --row is required for capability");
+ process.exit(1);
+ }
+ if (!values.capability) {
+ console.error("Error: --capability is required");
+ console.error("Examples: research.perplexity, thinking.ultrathink, execution.engineer");
+ process.exit(1);
+ }
+ const row = setCapability(isc, parseInt(values.row), values.capability);
+ if (!row) {
+ console.error(`Error: Row ${values.row} not found`);
+ process.exit(1);
+ }
+ console.log(`Row ${row.id}: capability → ${row.capability} (${row.capabilityIcon})`);
+ break;
+ }
+
+ case "verify": {
+ const isc = loadISC();
+ if (!isc) {
+ console.error("Error: No current ISC.");
+ process.exit(1);
+ }
+ if (!values.row || !values.result) {
+ console.error("Error: --row and --result are required for verify");
+ process.exit(1);
+ }
+ const result = values.result.toUpperCase() as VerifyResult;
+ if (!["PASS", "ADJUSTED", "BLOCKED"].includes(result)) {
+ console.error("Error: --result must be PASS, ADJUSTED, or BLOCKED");
+ process.exit(1);
+ }
+ const row = setVerifyResult(isc, parseInt(values.row), result, values.reason);
+ if (!row) {
+ console.error(`Error: Row ${values.row} not found`);
+ process.exit(1);
+ }
+ console.log(`Row ${row.id} verified: ${result}`);
+ break;
+ }
+
+ case "phase": {
+ const isc = loadISC();
+ if (!isc) {
+ console.error("Error: No current ISC.");
+ process.exit(1);
+ }
+ if (!values.phase) {
+ console.error("Error: --phase is required");
+ process.exit(1);
+ }
+ setPhase(isc, values.phase.toUpperCase());
+ console.log(`Phase set to: ${isc.phase}`);
+ break;
+ }
+
+ case "iterate": {
+ const isc = loadISC();
+ if (!isc) {
+ console.error("Error: No current ISC.");
+ process.exit(1);
+ }
+ incrementIteration(isc);
+ console.log(`Now on iteration: ${isc.iteration}`);
+ break;
+ }
+
+ case "show": {
+ const isc = loadISC();
+ if (!isc) {
+ console.error("No current ISC.");
+ process.exit(1);
+ }
+ if (values.output === "json") {
+ console.log(JSON.stringify(isc, null, 2));
+ } else if (values.output === "markdown") {
+ console.log(formatTable(isc));
+ } else {
+ console.log(formatTable(isc));
+ }
+ break;
+ }
+
+ case "log": {
+ const isc = loadISC();
+ if (!isc) {
+ console.error("No current ISC.");
+ process.exit(1);
+ }
+ console.log(formatLog(isc));
+ break;
+ }
+
+ case "summary": {
+ const isc = loadISC();
+ if (!isc) {
+ console.error("No current ISC.");
+ process.exit(1);
+ }
+ const summary = getSummary(isc);
+ if (values.output === "json") {
+ console.log(JSON.stringify({ ...summary, phase: isc.phase, iteration: isc.iteration }, null, 2));
+ } else {
+ console.log(`ISC Summary: ${isc.request}`);
+ console.log(`Phase: ${isc.phase} | Iteration: ${isc.iteration}`);
+ console.log(`Total: ${summary.total} | Pending: ${summary.pending} | Active: ${summary.active}`);
+ console.log(`Done: ${summary.done} | Adjusted: ${summary.adjusted} | Blocked: ${summary.blocked}`);
+ console.log(`Parallelizable: ${summary.parallelizable}`);
+ }
+ break;
+ }
+
+ case "clear": {
+ if (existsSync(CURRENT_ISC_PATH)) {
+ const isc = loadISC();
+ // Archive before clearing
+ if (isc) {
+ const archivePath = join(ISC_DIR, `archive-${Date.now()}.json`);
+ writeFileSync(archivePath, JSON.stringify(isc, null, 2));
+ console.log(`Archived to: ${archivePath}`);
+ }
+ writeFileSync(CURRENT_ISC_PATH, "");
+ console.log("Current ISC cleared.");
+ } else {
+ console.log("No current ISC to clear.");
+ }
+ break;
+ }
+
+ default:
+ console.error(`Unknown command: ${command}`);
+ console.error("Use --help for usage information");
+ process.exit(1);
+ }
+}
+
+main().catch(console.error);
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/RalphLoopExecutor.ts b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/RalphLoopExecutor.ts
new file mode 100644
index 00000000..2e092528
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/RalphLoopExecutor.ts
@@ -0,0 +1,313 @@
+#!/usr/bin/env bun
+
+/**
+ * RalphLoopExecutor - Spawn Ralph Loops for ISC rows
+ *
+ * Interfaces with the Ralph Wiggum plugin to execute ISC rows that require
+ * persistent iteration until success criteria are met.
+ *
+ * Usage:
+ * bun run RalphLoopExecutor.ts --prompt "Fix the auth bug" --completion-promise "All tests pass"
+ * bun run RalphLoopExecutor.ts --isc-row 3 --max-iterations 15
+ * bun run RalphLoopExecutor.ts --status
+ * bun run RalphLoopExecutor.ts --cancel
+ */
+
+import { parseArgs } from "util";
+import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync } from "fs";
+import { join, dirname } from "path";
+
+interface RalphLoopConfig {
+ prompt: string;
+ completionPromise: string;
+ maxIterations: number;
+ iscRowId?: number;
+}
+
+interface RalphLoopState {
+ active: boolean;
+ iteration: number;
+ max_iterations: number;
+ completion_promise: string;
+ started_at: string;
+ isc_row_id?: number;
+ prompt: string;
+}
+
+// PAI_DIR configurable via environment variable
+const PAI_DIR = process.env.PAI_DIR || join(process.env.HOME || "~", ".config/pai");
+const STATE_FILE_NAME = "ralph-loop.local.md";
+
+function getStatePath(): string {
+ // First check for project-local .pai directory
+ let dir = process.cwd();
+ while (dir !== "/") {
+ if (existsSync(join(dir, ".pai"))) {
+ return join(dir, ".pai", STATE_FILE_NAME);
+ }
+ dir = dirname(dir);
+ }
+ // Default to PAI state directory
+ return join(PAI_DIR, "MEMORY/State", STATE_FILE_NAME);
+}
+
+function parseState(content: string): RalphLoopState | null {
+ const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
+ if (!frontmatterMatch) return null;
+
+ const frontmatter = frontmatterMatch[1];
+ const prompt = frontmatterMatch[2].trim();
+
+ // Parse YAML frontmatter manually (simple parsing)
+ const getValue = (key: string): string => {
+ const match = frontmatter.match(new RegExp(`^${key}:\\s*(.*)$`, "m"));
+ if (!match) return "";
+ let value = match[1].trim();
+ // Remove surrounding quotes
+ if ((value.startsWith('"') && value.endsWith('"')) ||
+ (value.startsWith("'") && value.endsWith("'"))) {
+ value = value.slice(1, -1);
+ }
+ return value;
+ };
+
+ return {
+ active: getValue("active") === "true",
+ iteration: parseInt(getValue("iteration")) || 1,
+ max_iterations: parseInt(getValue("max_iterations")) || 0,
+ completion_promise: getValue("completion_promise"),
+ started_at: getValue("started_at"),
+ isc_row_id: parseInt(getValue("isc_row_id")) || undefined,
+ prompt,
+ };
+}
+
+function createStateFile(config: RalphLoopConfig): void {
+ const statePath = getStatePath();
+ const stateDir = dirname(statePath);
+
+ // Ensure state directory exists
+ if (!existsSync(stateDir)) {
+ mkdirSync(stateDir, { recursive: true });
+ }
+
+ // Format completion promise for YAML
+ const completionPromiseYaml = config.completionPromise && config.completionPromise !== "null"
+ ? `"${config.completionPromise}"`
+ : "null";
+
+ // Build state file content
+ const content = `---
+active: true
+iteration: 1
+max_iterations: ${config.maxIterations}
+completion_promise: ${completionPromiseYaml}
+started_at: "${new Date().toISOString()}"
+${config.iscRowId !== undefined ? `isc_row_id: ${config.iscRowId}` : ""}
+---
+
+${config.prompt}
+`;
+
+ writeFileSync(statePath, content);
+}
+
+function getStatus(): RalphLoopState | null {
+ const statePath = getStatePath();
+ if (!existsSync(statePath)) {
+ return null;
+ }
+
+ const content = readFileSync(statePath, "utf-8");
+ return parseState(content);
+}
+
+function cancelLoop(): boolean {
+ const statePath = getStatePath();
+ if (!existsSync(statePath)) {
+ return false;
+ }
+
+ unlinkSync(statePath);
+ return true;
+}
+
+function formatStatus(state: RalphLoopState | null): string {
+ if (!state) {
+ return "No active Ralph loop.";
+ }
+
+ const lines = [
+ "🔄 RALPH LOOP STATUS",
+ "═══════════════════════════════════════",
+ "",
+ `Active: ${state.active}`,
+ `Iteration: ${state.iteration}`,
+ `Max iterations: ${state.max_iterations === 0 ? "unlimited" : state.max_iterations}`,
+ `Completion promise: ${state.completion_promise === "null" ? "none" : state.completion_promise}`,
+ `Started: ${state.started_at}`,
+ ];
+
+ if (state.isc_row_id !== undefined) {
+ lines.push(`ISC Row: #${state.isc_row_id}`);
+ }
+
+ lines.push("", "Prompt:", "───────────────────────────────────────", state.prompt);
+
+ return lines.join("\n");
+}
+
+async function main() {
+ const { values } = parseArgs({
+ args: Bun.argv.slice(2),
+ options: {
+ prompt: { type: "string", short: "p" },
+ "completion-promise": { type: "string", short: "c" },
+ "max-iterations": { type: "string", short: "m", default: "10" },
+ "isc-row": { type: "string", short: "r" },
+ status: { type: "boolean", short: "s" },
+ cancel: { type: "boolean" },
+ output: { type: "string", short: "o", default: "text" },
+ help: { type: "boolean", short: "h" },
+ },
+ });
+
+ if (values.help) {
+ console.log(`
+RalphLoopExecutor - Spawn Ralph Loops for ISC rows
+
+USAGE:
+ bun run RalphLoopExecutor.ts --prompt "Fix the bug" --completion-promise "All tests pass"
+ bun run RalphLoopExecutor.ts --status
+ bun run RalphLoopExecutor.ts --cancel
+
+OPTIONS:
+ -p, --prompt <text> Task prompt to iterate on
+ -c, --completion-promise <text> Success criteria (required for meaningful loops)
+ -m, --max-iterations <n> Max iterations (default: 10, 0 = unlimited)
+ -r, --isc-row <n> ISC row ID (for tracking)
+ -s, --status Show current loop status
+ --cancel Cancel active loop
+ -o, --output <fmt> Output format: text (default), json
+ -h, --help Show this help
+
+ENVIRONMENT:
+ PAI_DIR PAI installation directory (default: ~/.config/pai)
+
+INTEGRATION WITH THEALGORITHM:
+ When an ISC row is assigned execution.ralph_loop capability, this tool:
+ 1. Creates the Ralph loop state file
+ 2. The existing stop hook handles iteration
+ 3. Loop continues until completion promise detected or max iterations
+
+EXAMPLES:
+ # Start a loop for fixing tests
+ bun run RalphLoopExecutor.ts -p "Fix failing tests" -c "All tests pass" -m 15
+
+ # Start a loop for ISC row #3
+ bun run RalphLoopExecutor.ts -p "Implement auth feature" -c "Feature complete" -r 3
+
+ # Check status
+ bun run RalphLoopExecutor.ts --status
+
+ # Cancel current loop
+ bun run RalphLoopExecutor.ts --cancel
+`);
+ return;
+ }
+
+ // Status command
+ if (values.status) {
+ const state = getStatus();
+ if (values.output === "json") {
+ console.log(JSON.stringify(state, null, 2));
+ } else {
+ console.log(formatStatus(state));
+ }
+ return;
+ }
+
+ // Cancel command
+ if (values.cancel) {
+ const success = cancelLoop();
+ if (values.output === "json") {
+ console.log(JSON.stringify({ cancelled: success }));
+ } else {
+ console.log(success ? "✅ Ralph loop cancelled." : "No active Ralph loop to cancel.");
+ }
+ return;
+ }
+
+ // Start a new loop
+ if (!values.prompt) {
+ console.error("Error: --prompt is required to start a loop");
+ console.error("Use --help for usage information");
+ process.exit(1);
+ }
+
+ // Check if loop already active
+ const existingState = getStatus();
+ if (existingState?.active) {
+ console.error("⚠️ Ralph loop already active!");
+ console.error(` Iteration: ${existingState.iteration}`);
+ console.error(` Prompt: ${existingState.prompt.substring(0, 50)}...`);
+ console.error("");
+ console.error("Use --cancel to stop the current loop first, or --status to check status.");
+ process.exit(1);
+ }
+
+ const config: RalphLoopConfig = {
+ prompt: values.prompt,
+ completionPromise: values["completion-promise"] || "DONE",
+ maxIterations: parseInt(values["max-iterations"] || "10"),
+ iscRowId: values["isc-row"] ? parseInt(values["isc-row"]) : undefined,
+ };
+
+ // Create the state file
+ createStateFile(config);
+
+ const result = {
+ success: true,
+ state_file: getStatePath(),
+ config,
+ message: `Ralph loop activated. Will iterate until "${config.completionPromise}" or ${config.maxIterations} iterations.`,
+ };
+
+ if (values.output === "json") {
+ console.log(JSON.stringify(result, null, 2));
+ } else {
+ console.log(`
+🔄 Ralph Loop Activated for THEALGORITHM
+═══════════════════════════════════════════════════════════
+
+Prompt: ${config.prompt}
+Completion Promise: ${config.completionPromise}
+Max Iterations: ${config.maxIterations === 0 ? "unlimited" : config.maxIterations}
+${config.iscRowId !== undefined ? `ISC Row: #${config.iscRowId}` : ""}
+
+The stop hook is now active. When Claude tries to exit, the SAME PROMPT
+will be fed back for the next iteration until:
+ • <promise>${config.completionPromise}</promise> is output (ONLY when TRUE!)
+ • Max iterations (${config.maxIterations}) reached
+
+To monitor: bun run RalphLoopExecutor.ts --status
+To cancel: bun run RalphLoopExecutor.ts --cancel
+
+═══════════════════════════════════════════════════════════
+
+${config.prompt}
+`);
+ }
+}
+
+main().catch(console.error);
+
+// Export for programmatic use
+export {
+ createStateFile,
+ getStatus,
+ cancelLoop,
+ parseState,
+ type RalphLoopConfig,
+ type RalphLoopState,
+};
diff --git a/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/TraitModifiers.ts b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/TraitModifiers.ts
new file mode 100644
index 00000000..8daf4dba
--- /dev/null
+++ b/Packs/pai-algorithm-skill/src/skills/THEALGORITHM/Tools/TraitModifiers.ts
@@ -0,0 +1,274 @@
+#!/usr/bin/env bun
+
+/**
+ * TraitModifiers - Map effort levels to AgentFactory trait modifiers
+ *
+ * THE ALGORITHM uses AgentFactory to compose custom agents.
+ * This tool provides the trait modifiers that should be added
+ * based on effort level.
+ *
+ * Usage:
+ * bun run TraitModifiers.ts --effort STANDARD
+ * bun run TraitModifiers.ts --effort THOROUGH --phase execute
+ * bun run TraitModifiers.ts --effort STANDARD --phase verify
+ */
+
+import { parseArgs } from "util";
+
+type EffortLevel = "TRIVIAL" | "QUICK" | "STANDARD" | "THOROUGH" | "DETERMINED";
+type Phase = "execute" | "verify" | "think";
+
+interface TraitConfig {
+ traits: string[];
+ model: string;
+ maxIterations: number;
+ parallelAgents: number;
+ description: string;
+}
+
+// Effort level → base trait modifiers for EXECUTE phase
+const EFFORT_TRAITS: Record<EffortLevel, TraitConfig> = {
+ TRIVIAL: {
+ traits: [],
+ model: "none",
+ maxIterations: 0,
+ parallelAgents: 0,
+ description: "No agents - direct response",
+ },
+ QUICK: {
+ traits: ["rapid", "pragmatic"],
+ model: "haiku",
+ maxIterations: 1,
+ parallelAgents: 2,
+ description: "Fast execution, minimal depth",
+ },
+ STANDARD: {
+ traits: ["analytical", "systematic"],
+ model: "sonnet",
+ maxIterations: 2,
+ parallelAgents: 4,
+ description: "Balanced analysis and execution",
+ },
+ THOROUGH: {
+ traits: ["thorough", "meticulous"],
+ model: "sonnet",
+ maxIterations: 5,
+ parallelAgents: 6,
+ description: "Deep analysis, comprehensive coverage",
+ },
+ DETERMINED: {
+ traits: ["thorough", "meticulous", "adversarial"],
+ model: "opus",
+ maxIterations: Infinity,
+ parallelAgents: 10,
+ description: "Unlimited iteration until success",
+ },
+};
+
+// Phase-specific trait overrides
+const PHASE_TRAITS: Record<Phase, string[]> = {
+ execute: [], // Uses effort level traits
+ verify: ["skeptical", "meticulous", "adversarial"], // Always skeptical
+ think: ["analytical", "exploratory"], // Deep thinking
+};
+
+// Phase-specific model overrides
+const PHASE_MODELS: Record<Phase, Record<EffortLevel, string>> = {
+ execute: {
+ TRIVIAL: "none",
+ QUICK: "haiku",
+ STANDARD: "sonnet",
+ THOROUGH: "sonnet",
+ DETERMINED: "opus",
+ },
+ verify: {
+ TRIVIAL: "none",
+ QUICK: "haiku",
+ STANDARD: "sonnet",
+ THOROUGH: "sonnet",
+ DETERMINED: "sonnet", // Verify doesn't need opus
+ },
+ think: {
+ TRIVIAL: "none",
+ QUICK: "haiku",
+ STANDARD: "sonnet",
+ THOROUGH: "opus", // Deep thinking benefits from opus
+ DETERMINED: "opus",
+ },
+};
+
+function getTraitsForPhase(
+ effort: EffortLevel,
+ phase: Phase
+): { traits: string[]; model: string; description: string } {
+ const baseConfig = EFFORT_TRAITS[effort];
+
+ if (effort === "TRIVIAL") {
+ return {
+ traits: [],
+ model: "none",
+ description: "TRIVIAL effort - no agents used",
+ };
+ }
+
+ // Verify phase always uses skeptical traits
+ if (phase === "verify") {
+ return {
+ traits: PHASE_TRAITS.verify,
+ model: PHASE_MODELS.verify[effort],
+ description: "Verification agents - always skeptical and meticulous",
+ };
+ }
+
+ // Think phase combines effort traits with exploratory
+ if (phase === "think") {
+ const combined = [...new Set([...baseConfig.traits, ...PHASE_TRAITS.think])];
+ return {
+ traits: combined,
+ model: PHASE_MODELS.think[effort],
+ description: `Think phase - ${baseConfig.description} with exploration`,
+ };
+ }
+
+ // Execute phase uses base effort traits
+ return {
+ traits: baseConfig.traits,
+ model: PHASE_MODELS.execute[effort],
+ description: baseConfig.description,
+ };
+}
+
+function getFullConfig(effort: EffortLevel) {
+ const base = EFFORT_TRAITS[effort];
+ return {
+ effort,
+ ...base,
+ phases: {
+ execute: getTraitsForPhase(effort, "execute"),
+ verify: getTraitsForPhase(effort, "verify"),
+ think: getTraitsForPhase(effort, "think"),
+ },
+ };
+}
+
+async function main() {
+ const { values } = parseArgs({
+ args: Bun.argv.slice(2),
+ options: {
+ effort: { type: "string", short: "e" },
+ phase: { type: "string", short: "p" },
+ output: { type: "string", short: "o", default: "text" },
+ list: { type: "boolean", short: "l" },
+ help: { type: "boolean", short: "h" },
+ },
+ });
+
+ if (values.help) {
+ console.log(`
+TraitModifiers - Get trait modifiers for THE ALGORITHM
+
+USAGE:
+ bun run TraitModifiers.ts --effort STANDARD
+ bun run TraitModifiers.ts --effort THOROUGH --phase verify
+ bun run TraitModifiers.ts --list
+
+OPTIONS:
+ -e, --effort <level> Effort level: TRIVIAL, QUICK, STANDARD, THOROUGH, DETERMINED
+ -p, --phase <phase> Phase: execute (default), verify, think
+ -o, --output <fmt> Output format: text (default), json, traits-only
+ -l, --list List all effort configurations
+ -h, --help Show this help
+
+EFFORT LEVELS:
+ TRIVIAL → No traits (direct response)
+ QUICK → rapid, pragmatic (haiku)
+ STANDARD → analytical, systematic (sonnet)
+ THOROUGH → thorough, meticulous (sonnet/opus)
+ DETERMINED → thorough, meticulous, adversarial (opus)
+
+PHASES:
+ execute → Uses effort-level traits
+ verify → Always: skeptical, meticulous, adversarial
+ think → Effort traits + analytical, exploratory
+
+EXAMPLES:
+ # Get traits for STANDARD execute phase
+ bun run TraitModifiers.ts -e STANDARD
+
+ # Get verification traits
+ bun run TraitModifiers.ts -e THOROUGH -p verify
+
+ # Get just the trait string for AgentFactory
+ bun run TraitModifiers.ts -e STANDARD -o traits-only
+ # Output: analytical,systematic
+`);
+ return;
+ }
+
+ if (values.list) {
+ console.log("EFFORT LEVEL CONFIGURATIONS\n");
+ for (const effort of Object.keys(EFFORT_TRAITS) as EffortLevel[]) {
+ const config = getFullConfig(effort);
+ console.log(`${effort}:`);
+ console.log(` Model: ${config.model}`);
+ console.log(` Max Iterations: ${config.maxIterations}`);
+ console.log(` Parallel Agents: ${config.parallelAgents}`);
+ console.log(` Execute Traits: ${config.phases.execute.traits.join(", ") || "none"}`);
+ console.log(` Verify Traits: ${config.phases.verify.traits.join(", ") || "none"}`);
+ console.log(` Think Traits: ${config.phases.think.traits.join(", ") || "none"}`);
+ console.log("");
+ }
+ return;
+ }
+
+ if (!values.effort) {
+ console.error("Error: --effort is required");
+ console.error("Use --help for usage information");
+ process.exit(1);
+ }
+
+ const effort = values.effort.toUpperCase() as EffortLevel;
+ if (!EFFORT_TRAITS[effort]) {
+ console.error(`Error: Invalid effort level: ${values.effort}`);
+ console.error("Valid levels: TRIVIAL, QUICK, STANDARD, THOROUGH, DETERMINED");
+ process.exit(1);
+ }
+
+ const phase = (values.phase?.toLowerCase() || "execute") as Phase;
+ if (!["execute", "verify", "think"].includes(phase)) {
+ console.error(`Error: Invalid phase: ${values.phase}`);
+ console.error("Valid phases: execute, verify, think");
+ process.exit(1);
+ }
+
+ const result = getTraitsForPhase(effort, phase);
+ const fullConfig = EFFORT_TRAITS[effort];
+
+ if (values.output === "json") {
+ console.log(
+ JSON.stringify(
+ {
+ effort,
+ phase,
+ ...result,
+ maxIterations: fullConfig.maxIterations,
+ parallelAgents: fullConfig.parallelAgents,
+ },
+ null,
+ 2
+ )
+ );
+ } else if (values.output === "traits-only") {
+ console.log(result.traits.join(","));
+ } else {
+ console.log(`EFFORT: ${effort}`);
+ console.log(`PHASE: ${phase}`);
+ console.log(`TRAITS: ${result.traits.join(", ") || "none"}`);
+ console.log(`MODEL: ${result.model}`);
+ console.log(`DESCRIPTION: ${result.description}`);
+ console.log(`MAX ITERATIONS: ${fullConfig.maxIterations}`);
+ console.log(`PARALLEL AGENTS: ${fullConfig.parallelAgents}`);
+ }
+}
+
+main().catch(console.error);
diff --git a/Packs/pai-art-skill/README.md b/Packs/pai-art-skill/README.md
index b28a39c6..a1488a11 100644
--- a/Packs/pai-art-skill/README.md
+++ b/Packs/pai-art-skill/README.md
@@ -11,7 +11,11 @@ dependencies: []
keywords: [art, visualization, diagrams, comics, excalidraw, hand-drawn, technical-diagrams, image-generation, illustrations, dark-mode]
---
-# Kai Art Skill
+<p align="center">
+ <img src="../icons/pai-art-skill.png" alt="PAI Art Skill" width="256">
+</p>
+
+# PAI Art Skill
> Visual content generation system with Excalidraw hand-drawn aesthetic - technical diagrams, comics, and editorial illustrations with consistent dark-mode styling
diff --git a/Packs/pai-browser-skill/README.md b/Packs/pai-browser-skill/README.md
index ef2ad8e5..0982af06 100644
--- a/Packs/pai-browser-skill/README.md
+++ b/Packs/pai-browser-skill/README.md
@@ -12,7 +12,7 @@ keywords: [browser, playwright, automation, screenshot, web-testing, verificatio
---
<p align="center">
- <img src="icons/pai-browser-skill-v3.png" alt="Kai Browser Skill" width="256">
+ <img src="icons/pai-browser-skill-v3.png" alt="PAI Browser Skill" width="256">
</p>
# Browser Skill v1.2.0
diff --git a/Packs/pai-observability-server/README.md b/Packs/pai-observability-server/README.md
index aa56f8d7..4a40dd45 100644
--- a/Packs/pai-observability-server/README.md
+++ b/Packs/pai-observability-server/README.md
@@ -11,7 +11,11 @@ dependencies: [pai-hook-system]
keywords: [observability, dashboard, monitoring, agents, websocket, streaming, events, debugging, visualization, real-time]
---
-# Kai Observability Server
+<p align="center">
+ <img src="../icons/pai-observability-server-v2.png" alt="PAI Observability Server" width="256">
+</p>
+
+# PAI Observability Server
> Real-time multi-agent activity monitoring dashboard - see exactly what your AI agents are doing as they work
diff --git a/Packs/pai-prompting-skill/README.md b/Packs/pai-prompting-skill/README.md
index 273deb09..435e15c6 100644
--- a/Packs/pai-prompting-skill/README.md
+++ b/Packs/pai-prompting-skill/README.md
@@ -13,7 +13,11 @@ dependencies:
keywords: [prompting, templates, handlebars, meta-prompting, prompt-engineering, fabric, claude-4, context-engineering, templating]
---
-# Kai Prompting Skill (pai-prompting-skill)
+<p align="center">
+ <img src="../icons/pai-prompting-skill.png" alt="PAI Prompting Skill" width="256">
+</p>
+
+# PAI Prompting Skill (pai-prompting-skill)
> Prompts that write prompts. Meta-prompting enables dynamic composition where structure is fixed but content is parameterized.
diff --git a/Packs/pai-upgrades-skill/README.md b/Packs/pai-upgrades-skill/README.md
index 379aba12..ec9e6efe 100644
--- a/Packs/pai-upgrades-skill/README.md
+++ b/Packs/pai-upgrades-skill/README.md
@@ -13,6 +13,10 @@ dependencies:
keywords: [upgrades, anthropic, claude-code, monitoring, changelog, youtube, release-notes, research, automation]
---
+<p align="center">
+ <img src="../icons/pai-upgrades-skill.png" alt="PAI Upgrades Skill" width="256">
+</p>
+
# PAI Upgrades Skill (pai-upgrades-skill)
> Stay ahead of Claude Code, MCP, and Anthropic ecosystem updates. Monitor 30+ official sources and AI development YouTube channels, then get prioritized recommendations for your system.