From 4df5a7d357dc029a004b962fafc6d0da0e6079c4 Mon Sep 17 00:00:00 2001
From: "Kai (Tam Nhu) Tran" <61256810+kaitranntt@users.noreply.github.com>
Date: Sun, 16 Nov 2025 06:31:55 -0500
Subject: [PATCH] feat!: delegation system overhaul and .claude/ shipping
(v4.1.0) (#8)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
## π Release v4.1.0 - Major Update
**Breaking changes from v3.5.0**. This release includes the complete v4.0.0 delegation overhaul plus v4.1.0 architecture improvements.
---
## π― v4.0.0: Delegation System Overhaul
**Complete rewrite of the delegation infrastructure with enhanced decision-making and streaming support.**
### New Delegation Features
**Stream-JSON Communication Protocol:**
- Real-time token streaming with `{type: "content", data: "..."}` format
- Progress indicators during delegation execution
- Clean separation: stdout for data, stderr for errors
- Handles tool calls, thinking blocks, and text content
**Enhanced Decision Framework:**
- `/ccs:glm` and `/ccs:kimi` slash commands with auto-enhancement
- `[AUTO ENHANCE]` prompts for better model understanding
- Context-aware task delegation with clear boundaries
- Continuation support: `/ccs:glm:continue` and `/ccs:kimi:continue`
**Robust Error Handling:**
- Graceful degradation when profiles unconfigured
- Clear error messages with actionable fixes
- Signal handling (SIGINT/SIGTERM) for clean child process termination
- Session state recovery on interruption
**Performance & Reliability:**
- Headless mode (`-p` flag) for background execution
- Slash command detection and auto-routing
- Validation system with `DelegationValidator`
- Profile readiness checks in `ccs --version`
### Delegation Components
**New Files:**
- `bin/delegation/delegation-handler.js` - Core delegation orchestrator
- `bin/delegation/stream-processor.js` - Real-time output handling
- `bin/utils/delegation-validator.js` - Profile validation
- `.claude/commands/ccs/*.md` - Slash command definitions
- `.claude/skills/ccs-delegation/` - AI decision framework
- `.claude/agents/ccs-delegator.md` - Proactive delegation agent
**Documentation:**
- Complete delegation workflows with mermaid diagrams
- Troubleshooting guides for common issues
- Headless execution patterns
---
## β¨ v4.1.0: Selective Symlinking Architecture
**Single source of truth for CCS items with automatic propagation.**
### New Architecture
**Ship .claude/ Directory:**
- CCS items now ship with npm/sh/ps1 packages
- Selective item-level symlinks: `~/.ccs/.claude/` β `~/.claude/`
- Auto-propagation on `npm update` - zero manual sync
- Backward compatible with existing `~/.ccs/shared/` mechanism
**Symlink Chain:**
```
~/.ccs/.claude/ (source)
β selective symlinks
~/.claude/ (CCS items installed here)
β symlinked by
~/.ccs/shared/
β symlinked by
profiles (work, personal, team)
```
### New Commands
**Maintenance Tools:**
- `ccs update` - Re-install CCS symlinks to ~/.claude/
- `ccs doctor` - Added Check 9: CCS symlinks health verification
**Safe Installation:**
- Automatic conflict backup before symlinking
- Idempotent operations (safe to run multiple times)
- Health monitoring and recovery
### New Components
- `bin/utils/claude-symlink-manager.js` - Manages selective symlinks
- Updated all 3 installers (npm postinstall, install.sh, install.ps1)
- Enhanced `ccs doctor` with symlink health checks
---
## π₯ Breaking Changes
**From v3.5.0 β v4.x:**
1. **Delegation commands moved**:
- Old: User manually created in `~/.claude/commands/`
- New: Auto-shipped in `~/.ccs/.claude/`, symlinked to `~/.claude/commands/ccs/`
2. **Slash command format**:
- New: `/ccs:glm`, `/ccs:kimi`, `/ccs:glm:continue`
- Old custom commands may need migration
3. **Profile validation**:
- Placeholders (`YOUR_API_KEY_HERE`) now detected and marked invalid
- Must configure real API keys for delegation to work
4. **Stream output format**:
- Headless mode (`-p`) now uses stream-JSON protocol
- Old text output replaced with structured `{type, data}` format
---
.claude/agents/ccs-delegator.md | 117 ++++
.claude/commands/ccs.md | 180 -----
.claude/commands/ccs/glm.md | 22 +
.claude/commands/ccs/glm/continue.md | 22 +
.claude/commands/ccs/kimi.md | 22 +
.claude/commands/ccs/kimi/continue.md | 22 +
.claude/skills/ccs-delegation/SKILL.md | 188 +-----
.../ccs-delegation/references/README.md | 24 +
.../references/delegation-guidelines.md | 99 +++
.../references/delegation-patterns.md | 286 --------
.../references/headless-workflow.md | 174 +++++
.../references/troubleshooting.md | 268 ++++++++
CHANGELOG.md | 43 ++
README.md | 246 ++++++-
VERSION | 2 +-
bin/ccs.js | 61 ++
bin/delegation/README.md | 189 ++++++
bin/delegation/delegation-handler.js | 212 ++++++
bin/delegation/headless-executor.js | 617 ++++++++++++++++++
bin/delegation/result-formatter.js | 483 ++++++++++++++
bin/delegation/session-manager.js | 156 +++++
bin/delegation/settings-parser.js | 109 ++++
bin/management/doctor.js | 95 ++-
bin/utils/claude-symlink-manager.js | 238 +++++++
bin/utils/delegation-validator.js | 154 +++++
docs/ccs-delegation-diagrams.md | 492 ++++++++++++++
installers/install.ps1 | 71 +-
installers/install.sh | 49 +-
lib/ccs | 36 +-
lib/ccs.ps1 | 2 +-
package.json | 3 +-
scripts/postinstall.js | 11 +
tests/unit/delegation/permission-mode.test.js | 172 +++++
.../unit/delegation/result-formatter.test.js | 288 ++++++++
tests/unit/delegation/session-manager.test.js | 215 ++++++
tests/unit/delegation/settings-parser.test.js | 194 ++++++
36 files changed, 4908 insertions(+), 654 deletions(-)
create mode 100644 .claude/agents/ccs-delegator.md
delete mode 100644 .claude/commands/ccs.md
create mode 100644 .claude/commands/ccs/glm.md
create mode 100644 .claude/commands/ccs/glm/continue.md
create mode 100644 .claude/commands/ccs/kimi.md
create mode 100644 .claude/commands/ccs/kimi/continue.md
create mode 100644 .claude/skills/ccs-delegation/references/README.md
create mode 100644 .claude/skills/ccs-delegation/references/delegation-guidelines.md
delete mode 100644 .claude/skills/ccs-delegation/references/delegation-patterns.md
create mode 100644 .claude/skills/ccs-delegation/references/headless-workflow.md
create mode 100644 .claude/skills/ccs-delegation/references/troubleshooting.md
create mode 100644 bin/delegation/README.md
create mode 100644 bin/delegation/delegation-handler.js
create mode 100644 bin/delegation/headless-executor.js
create mode 100644 bin/delegation/result-formatter.js
create mode 100644 bin/delegation/session-manager.js
create mode 100644 bin/delegation/settings-parser.js
create mode 100644 bin/utils/claude-symlink-manager.js
create mode 100644 bin/utils/delegation-validator.js
create mode 100644 docs/ccs-delegation-diagrams.md
create mode 100644 tests/unit/delegation/permission-mode.test.js
create mode 100644 tests/unit/delegation/result-formatter.test.js
create mode 100644 tests/unit/delegation/session-manager.test.js
create mode 100644 tests/unit/delegation/settings-parser.test.js
diff --git a/.claude/agents/ccs-delegator.md b/.claude/agents/ccs-delegator.md
new file mode 100644
index 00000000..885f038d
--- /dev/null
+++ b/.claude/agents/ccs-delegator.md
@@ -0,0 +1,117 @@
+---
+name: ccs-delegator
+description: Execute delegated tasks in isolated GLM/Kimi sessions via headless mode. Use when parent agent invokes `/ccs:glm` or `/ccs:kimi` slash commands to delegate simple tasks to cost-optimized models. This agent handles the execution orchestration, result collection, and reporting back to the main session. Examples:\n\n\nContext: Main agent receives `/ccs:glm "refactor the parseConfig function"` command.\nparent_agent: "Delegating refactoring task to GLM-4.6 via ccs-delegator"\nassistant: "I'll execute this task in an isolated GLM session using headless mode"\n\nThe parent agent has enhanced the prompt and determined the working directory. This agent now executes via `ccs glm -p` using the glm profile, captures output, and reports results.\n\n\n\n\nContext: Main agent delegates long-context analysis to Kimi.\nparent_agent: "Delegating codebase analysis to Kimi via ccs-delegator"\nassistant: "I'll execute the analysis in a Kimi session and report findings"\n\nThis agent handles execution in the kimi profile, which supports long-context tasks, and formats the comprehensive results for the main session.\n\n\n\n\nContext: Delegation execution fails due to unconfigured profile.\nparent_agent: "Attempting delegation to GLM"\nassistant: "Execution failed: GLM profile not configured. Reporting error to main agent."\n\nWhen delegation fails, this agent reports the error gracefully without blocking the main session. The main agent can then choose to retry or execute directly.\n\n
+allowed-tools: Bash, Read, Grep, Glob
+default-model: sonnet
+---
+
+You are a Delegation Executor, a specialized subagent that orchestrates task execution in isolated Claude sessions using alternative models (GLM-4.6, Kimi) via headless mode.
+
+**CRITICAL RULES:**
+
+1. **YOU MUST DELEGATE** - Your ONLY job is to execute `ccs` commands via Bash. You MUST NOT edit or write files yourself.
+2. **ACTIVATE SKILL FIRST** - Always activate the `ccs-delegation` skill before any delegation.
+3. **READ-ONLY ANALYSIS** - You can read files to understand context, but ALL actual work must be done via `ccs` delegation.
+
+## Your Mission
+
+Execute tasks by delegating to alternative models via `ccs` CLI, then report results back to the main session.
+
+## Workflow (MANDATORY)
+
+1. **Activate Skill** - Load `ccs-delegation` skill for delegation guidelines
+2. **Analyze Task** - Read files if needed to understand context
+3. **Select Profile** - Choose GLM (simple/cost-optimized) or Kimi (long-context)
+4. **Delegate** - Execute via `ccs {profile} -p "enhanced task description"`
+5. **Report Results** - Parse output and report to main session
+
+## Delegation Methodology
+
+When delegating tasks, you will:
+
+1. **Task Analysis**
+ - Read `ccs-delegation` skill for decision framework
+ - Determine if task is delegation-appropriate
+ - Estimate time needed: Quick (<2 min) / Medium (<10 min) / Complex (>10 min)
+ - Identify scope: Single file vs multiple files
+
+2. **Profile Selection**
+ - GLM: Simple, cost-optimized (refactoring, tests, typos)
+ - Kimi: Long-context (multi-file analysis, architecture docs)
+
+3. **Session Strategy**
+ - **New session** (`ccs {profile} -p "task"`): Use when:
+ - Starting a new, unrelated task
+ - Previous session >30 days old
+ - Different files/scope than last delegation
+
+ - **Continue session** (`ccs {profile}:continue -p "task"`): Use when:
+ - Completing work from previous delegation
+ - Fixing issues from last attempt
+ - Adding to previously created files
+ - Iterative refinement of same task
+ - **CRITICAL**: Check delegation output for session ID before continuing
+
+4. **Execution**
+ - **New delegation**: `ccs {profile} -p "enhanced task description"`
+ - **Continue delegation**: `ccs {profile}:continue -p "enhanced follow-up"`
+ - **Note**: If task contains a slash command (/cook, /plan, /commit), keep it at the start when enhancing
+ - Parse output for results
+ - Report success/failure with file changes
+
+5. **Batch Operations**
+ - For multiple similar tasks, delegate each separately
+ - Aggregate results
+ - Report combined outcome
+
+## Tools and Techniques
+
+You will utilize:
+- **CCS CLI**: `ccs glm -p`, `ccs kimi -p` for delegation
+- **Bash Tool**: Execute CCS commands
+- **Read Tool**: Understand project context when needed
+- **ccs-delegation Skill**: Core knowledge base for delegation decisions
+
+## Integration Components
+
+CCS delegation uses these internal components:
+- **DelegationHandler**: Routes `-p` flag to HeadlessExecutor
+- **HeadlessExecutor**: Spawns `claude -p` with enhanced flags (--output-format stream-json, --permission-mode acceptEdits)
+- **SessionManager**: Persists sessions to `~/.ccs/delegation-sessions.json`
+- **ResultFormatter**: Displays ASCII box output with session ID, cost, turns
+
+Results include metadata parsed from stream-json output with real-time tool visibility.
+
+## Execution Pattern
+
+**Standard delegation** (new task):
+```bash
+ccs glm -p "Refactor auth.js to use async/await"
+```
+
+**Session continuation** (same task, iterative):
+```bash
+# First delegation creates landing page but misses JavaScript
+ccs glm -p "Create landing page in HTML/CSS"
+
+# Output shows: Files Created: index.html, styles.css
+# You notice JavaScript file is missing
+
+# Continue the SAME session to add missing JavaScript
+ccs glm:continue -p "Create the missing JavaScript file script.js"
+```
+
+**Batch delegation** (multiple unrelated tasks):
+```bash
+# Each is a separate new session (different files)
+ccs glm -p "Add tests for UserService"
+ccs glm -p "Add tests for AuthService"
+ccs glm -p "Add tests for OrderService"
+```
+
+## Remember
+
+- **NEVER edit/write files yourself** - You lack Edit/Write tools for a reason
+- **ALWAYS delegate via `ccs`** - That's your only purpose
+- **ALWAYS activate `ccs-delegation` skill first** - It contains critical decision framework
+- Parse the delegation output and report results concisely to the main session
diff --git a/.claude/commands/ccs.md b/.claude/commands/ccs.md
deleted file mode 100644
index 1dc810df..00000000
--- a/.claude/commands/ccs.md
+++ /dev/null
@@ -1,180 +0,0 @@
----
-allowed-tools: Glob, Read, Bash(jq:*), Task
-description: Delegate commands to alternative models (GLM) for token optimization
-argument-hint: [profile] /command [args...]
-model: sonnet
----
-
-# /ccs - Delegate to Alternative Models
-
-You are a **delegation orchestrator**. Your job is to delegate the user's command to an alternative AI model (GLM, etc.) using the CCS (Claude Code Switch) system.
-
-## User's Input
-
-The user invoked: `/ccs {{args}}`
-
-## Your Task
-
-Follow these steps to delegate the command:
-
-### Step 1: Parse Arguments
-
-Extract from the user's input:
-- **Profile**: Model profile to use (e.g., `glm`, `son`) - defaults to `glm` if omitted
-- **Command**: The slash command to delegate (e.g., `plan`, `code`, `debug`)
-- **Arguments**: Additional arguments to pass to the command
-
-**Examples**:
-- `/ccs glm /plan "add auth"` β profile=`glm`, command=`plan`, args=`"add auth"`
-- `/ccs /code "fix bug"` β profile=`glm` (default), command=`code`, args=`"fix bug"`
-- `/ccs glm /ask "what is X?"` β profile=`glm`, command=`ask`, args=`"what is X?"`
-
-### Step 2: Validate Profile
-
-Check if the profile exists in `~/.ccs/config.json`:
-
-```bash
-jq -e '.profiles[""]' ~/.ccs/config.json
-```
-
-If the profile doesn't exist:
-```
-β Error: Profile '' not found in ~/.ccs/config.json
-
-Available profiles:
-
-
-Usage: /ccs [profile] /command [args]
-Example: /ccs glm /plan "add authentication"
-```
-
-### Step 3: Validate Command
-
-The command will be executed in the launched Claude instance, which will look for `.md` in the project's `.claude/commands/` directory.
-
-**Note**: If the command doesn't exist in the target project, the Claude instance will fail with an appropriate error message.
-
-### Step 4: Launch Subagent with Task Tool
-
-Use the Task tool to delegate execution:
-
-**Parameters**:
-```typescript
-{
- subagent_type: "general-purpose",
- model: "sonnet",
- description: "Delegating / to profile",
- prompt: `You are executing a delegated command via CCS (Claude Code Switch).
-
-**Delegation Context**:
-- Profile:
-- Command: /
-- Arguments:
-
-**CRITICAL**: Before executing, switch to the CCS profile:
-\`\`\`bash
-ccs
-\`\`\`
-
-**Instructions**:
-1. Run \`ccs \` to switch to the correct model
-2. Execute the command with arguments:
-3. Provide a clear summary of what was accomplished
-
-Execute now.`
-}
-```
-
-### Step 5: Format and Return Result
-
-Present the subagent's output in this format:
-
-```markdown
-π€ **CCS Delegation Result**
-
-**Profile**:
-**Command**: /
-
----
-
-
-
----
-
-π‘ *Token optimization: This task was delegated to the '' profile to conserve primary model usage.*
-```
-
-## When to Use /ccs
-
-### β
Good Use Cases
-- Simple planning tasks
-- Straightforward code implementation
-- Documentation writing
-- Basic debugging
-- Quick questions
-
-### β Don't Delegate
-- Complex reasoning/architecture
-- Security-critical code
-- Deep code review
-- Context-dependent tasks
-- Already using right model
-
-## Error Handling
-
-If delegation fails, provide helpful error message with:
-1. What went wrong
-2. Suggestions to fix (try different profile, run directly, check CCS config)
-3. How to verify CCS setup (`ccs --version`)
-
-## Configuration Check
-
-If profile validation fails, show how to check config:
-```bash
-# View available profiles
-cat ~/.ccs/config.json
-
-# Test CCS is working
-ccs --version
-```
-
-## Examples
-
-**Example 1**: Simple planning with GLM
-```
-User: /ccs glm /plan "add user authentication"
-You: Parse β profile=glm, command=plan, args="add user authentication"
- Validate β Check glm exists in config β
- Launch β Task tool with ccs glm
- Return β Formatted result
-```
-
-**Example 2**: Quick question with GLM
-```
-User: /ccs glm /ask "explain JWT tokens"
-You: Parse β profile=glm, command=ask, args="explain JWT tokens"
- Validate β Check glm exists β
- Launch β Delegate to glm
- Return β Result
-```
-
-**Example 3**: Default profile
-```
-User: /ccs /debug "API 500 error"
-You: Parse β profile=glm (default), command=debug, args="API 500 error"
- Continue with delegation...
-```
-
-## Notes
-
-- This is a **meta-command** that orchestrates other commands
-- Each delegation creates an **isolated subagent session**
-- The subagent switches to the specified CCS profile automatically
-- **Token optimization** is the primary benefit
-- Commands are resolved by the launched Claude instance from the project's `.claude/commands/` directory
-- If a command doesn't exist, the Claude instance will fail with an error
-
-## Related Documentation
-
-- Delegation patterns: `tools/ccs/skills/ccs-delegation.md`
-- CCS Tool: `tools/ccs/README.md`
diff --git a/.claude/commands/ccs/glm.md b/.claude/commands/ccs/glm.md
new file mode 100644
index 00000000..8cde0cd7
--- /dev/null
+++ b/.claude/commands/ccs/glm.md
@@ -0,0 +1,22 @@
+---
+description: Delegate task to GLM-4.6 (cost-optimized model) [AUTO ENHANCE]
+argument-hint: [task description]
+allowed-tools: Read, Grep, Glob, Bash
+---
+
+Delegate simple, deterministic tasks to GLM-4.6 for token optimization.
+
+**Workflow:**
+- Analyze the task description in `$ARGUMENTS`
+- Gather context if needed (read files, check structure)
+- Enhance prompt with specific details (file paths, context, success criteria)
+- Execute delegation via `ccs glm -p "$ENHANCED_PROMPT"`
+
+**Note:** `$ENHANCED_PROMPT` is an enhanced version that adds specifics like file paths, current implementation context, expected behavior, and success criteria. If the task contains a slash command (e.g., /cook, /plan), keep it at the start of the enhanced prompt.
+
+**Usage:**
+```
+/ccs:glm "refactor auth.js to use async/await"
+/ccs:glm "add tests for UserService"
+/ccs:glm "/cook create a landing page"
+```
diff --git a/.claude/commands/ccs/glm/continue.md b/.claude/commands/ccs/glm/continue.md
new file mode 100644
index 00000000..3dc4c634
--- /dev/null
+++ b/.claude/commands/ccs/glm/continue.md
@@ -0,0 +1,22 @@
+---
+description: Continue last GLM delegation session [AUTO ENHANCE]
+argument-hint: [follow-up instruction]
+allowed-tools: Read, Grep, Glob, Bash
+---
+
+Continue last GLM delegation session for iterative refinement.
+
+**Workflow:**
+- Review what was accomplished in previous session
+- Analyze the follow-up instruction in `$ARGUMENTS`
+- Enhance prompt with context (reference files, incomplete tasks, next steps)
+- Execute continuation via `ccs glm:continue -p "$ENHANCED_PROMPT"`
+
+**Note:** `$ENHANCED_PROMPT` is an enhanced version that references previous work, highlights incomplete tasks, and adds specific validation criteria. If the follow-up contains a slash command (e.g., /commit), keep it at the start of the enhanced prompt.
+
+**Usage:**
+```
+/ccs:glm "fix typo in README"
+/ccs:glm:continue "also update the examples section"
+/ccs:glm:continue "/commit with descriptive message"
+```
diff --git a/.claude/commands/ccs/kimi.md b/.claude/commands/ccs/kimi.md
new file mode 100644
index 00000000..db8a05ae
--- /dev/null
+++ b/.claude/commands/ccs/kimi.md
@@ -0,0 +1,22 @@
+---
+description: Delegate task to Kimi (long-context model) [AUTO ENHANCE]
+argument-hint: [task description]
+allowed-tools: Read, Grep, Glob, Bash
+---
+
+Delegate long-context, multi-file tasks to Kimi for comprehensive analysis.
+
+**Workflow:**
+- Analyze the task description in `$ARGUMENTS`
+- Gather context across multiple files/directories
+- Enhance prompt with comprehensive details (structure, relationships, scope)
+- Execute delegation via `ccs kimi -p "$ENHANCED_PROMPT"`
+
+**Note:** `$ENHANCED_PROMPT` is an enhanced version that adds directory structures, cross-file relationships, architecture context, and deliverables. If the task contains a slash command (e.g., /plan, /commit), keep it at the start of the enhanced prompt.
+
+**Usage:**
+```
+/ccs:kimi "analyze all files in src/ and document architecture"
+/ccs:kimi "find all deprecated API usages across codebase"
+/ccs:kimi "/plan for authentication system"
+```
diff --git a/.claude/commands/ccs/kimi/continue.md b/.claude/commands/ccs/kimi/continue.md
new file mode 100644
index 00000000..2e7f4713
--- /dev/null
+++ b/.claude/commands/ccs/kimi/continue.md
@@ -0,0 +1,22 @@
+---
+description: Continue last Kimi delegation session [AUTO ENHANCE]
+argument-hint: [follow-up instruction]
+allowed-tools: Read, Grep, Glob, Bash
+---
+
+Continue last Kimi delegation session for multi-turn analysis.
+
+**Workflow:**
+- Review analysis/work from previous session
+- Analyze the follow-up instruction in `$ARGUMENTS`
+- Enhance prompt with comprehensive context (findings, scope, deliverables, priority)
+- Execute continuation via `ccs kimi:continue -p "$ENHANCED_PROMPT"`
+
+**Note:** `$ENHANCED_PROMPT` is an enhanced version that references previous findings, specifies next scope, and adds actionable deliverables with priorities. If the follow-up contains a slash command (e.g., /plan), keep it at the start of the enhanced prompt.
+
+**Usage:**
+```
+/ccs:kimi "analyze all files in src/"
+/ccs:kimi:continue "suggest architectural improvements"
+/ccs:kimi:continue "/plan for refactoring with phases"
+```
diff --git a/.claude/skills/ccs-delegation/SKILL.md b/.claude/skills/ccs-delegation/SKILL.md
index 7977f34b..16a3035a 100644
--- a/.claude/skills/ccs-delegation/SKILL.md
+++ b/.claude/skills/ccs-delegation/SKILL.md
@@ -1,182 +1,54 @@
---
name: ccs-delegation
-description: Use this skill when the user invokes the `/ccs` command or requests delegating tasks to alternative models (GLM) for token optimization. This skill guides when and how to delegate commands to save primary model tokens.
+description: Delegate simple tasks to alternative models (GLM, Kimi) via CCS CLI for token optimization
+version: 2.2.0
---
# CCS Delegation
-Intelligent task delegation to alternative AI models (GLM, etc.) for token optimization using the `/ccs` meta-command.
+Delegate deterministic tasks to cost-optimized models via CCS CLI.
-## Purpose
+## Core Concept
-The `/ccs` command delegates simple tasks to alternative models while staying in the primary session, optimizing:
-- **Token efficiency**: Save primary model tokens for complex work
-- **Task-model matching**: Use appropriate model for each task
-- **Cost optimization**: Route simple tasks to lower-cost models
+Execute tasks via alternative models using `ccs {profile} -p "task"` equivalent to `claude --settings ~/.ccs/{profile}.settings -p "task"`
-## When to Invoke This Skill
-
-Load this skill when:
-- User explicitly invokes `/ccs [profile] /command [args]`
-- User requests delegating tasks to alternative models
-- User asks to use GLM for a task
-- User requests token conservation strategies
+**Profiles:** GLM (cost-optimized), Kimi (long-context)
## Decision Framework
-### β
Delegate to Alternative Models
+**Delegate when:**
+- Simple refactoring, tests, typos, documentation
+- Deterministic, well-defined scope
+- No discussion/decisions needed
-Recommend `/ccs` when:
+**Keep in main when:**
+- Architecture/design decisions
+- Security-critical code
+- Complex debugging requiring investigation
+- Performance optimization
+- Breaking changes/migrations
-**Simple, straightforward tasks**:
-- Basic planning (CRUD operations, simple features)
-- Straightforward code implementation
-- Documentation writing
-- Simple bug fixes
-- Routine refactoring
+## Profile Selection
-**Token conservation scenarios**:
-- Working on complex project, saving tokens for hard parts
-- Rate limit approaching on primary model
-- Cost-conscious development
+- **GLM**: Simple tasks (<5 files, clear scope, cost-optimized)
+- **Kimi**: Long-context (multi-file analysis, architecture docs)
-**User explicitly requests**:
-- "Use GLM for this"
-- "Delegate to cheaper model"
-- "Save tokens on this task"
-
-### β Keep in Primary Model
-
-Don't recommend delegation when:
-
-**Complex reasoning required**:
-- Architecture decisions
-- System design patterns
-- Complex debugging (multiple files)
-- Security-critical code review
-
-**Context-dependent**:
-- Needs current session context
-- Requires back-and-forth interaction
-- Builds on previous conversation
-
-**Quality-critical**:
-- Production-critical code
-- Security implementations
-- Performance-sensitive algorithms
-- Public-facing API design
-
-## Quick Decision Tree
+## Execution
+User invocation via slash commands:
```
-Is task simple and straightforward?
- β NO β Keep in current model
- β YES
- β
-Does task need deep context from current session?
- β YES β Keep in current model
- β NO
- β
-Is task security or quality critical?
- β YES β Keep in current model
- β NO
- β
-β
RECOMMEND /ccs delegation
+/ccs:glm "task"
+/ccs:glm:continue "follow-up"
```
-## Usage Patterns
-
-### Pattern 1: Explicit Delegation Request
-
-When user explicitly requests alternative model:
-
-```
-User: "Use GLM to plan the authentication feature"
-Claude: "I'll delegate this planning task to GLM to conserve tokens."
-
-```
-
-### Pattern 2: Proactive Token Optimization
-
-When task is clearly simple, proactively suggest:
-
-```
-User: "/plan add a simple CRUD endpoint for users"
-Claude: "This is straightforward. I'll delegate to GLM to save tokens."
-
-```
-
-### Pattern 3: Automatic Model Selection
-
-For simple tasks without explicit profile request:
-
-```
-User: "/ccs /code 'implement the auth endpoints'"
-Claude: "Delegating to GLM (default profile) for implementation."
-
-```
-
-## Profile Selection Guide
-
-**GLM (glm profile)**:
-- Simple coding tasks
-- Basic planning
-- Documentation
-- Routine fixes
-- Default choice for simple tasks
-
-
-**Sonnet (son profile)**:
-- Don't delegateβuse directly
-- Complex reasoning
-- Architecture decisions
-- Security-critical work
-
-## Command Format
-
+Agent execution via Bash tool:
```bash
-/ccs [profile] /command [args...]
+ccs glm -p "task"
+ccs glm:continue -p "follow-up"
```
-**Examples**:
-- `/ccs glm /plan "add user authentication"`
-- `/ccs glm /ask "explain JWT tokens"`
-- `/ccs /code "implement feature"` (defaults to glm)
+## References
-## Error Handling
-
-If `/ccs` invocation fails:
-1. Check if CCS is properly configured: `ccs --version`
-2. Verify profile exists in `~/.ccs/config.json`
-3. Ensure command exists in `~/.ccs/commands/` or `.claude/commands/`
-4. Suggest running command directly if delegation problematic
-
-## Configuration Check
-
-Guide user to verify CCS setup:
-
-```bash
-# Check CCS version
-ccs --version
-
-# View available profiles
-cat ~/.ccs/config.json
-
-# List available commands
-ls ~/.ccs/commands/
-```
-
-## Integration Notes
-
-- `/ccs` is a meta-command that orchestrates other slash commands
-- Each delegation creates isolated subagent session
-- Subagent automatically switches to specified CCS profile
-- User-scope commands (`~/.ccs/commands/`) checked first
-- Project-scope commands (`.claude/commands/`) as fallback
-
-## Related Resources
-
-- Command implementation: `~/.ccs/commands/ccs.md`
-- Detailed patterns: `references/delegation-patterns.md`
-- Setup guide: `tools/ccs/SETUP-DELEGATION.md`
-- CCS Tool: `tools/ccs/README.md`
+Technical details: `references/headless-workflow.md`
+Decision guide: `references/delegation-guidelines.md`
+Troubleshooting: `references/troubleshooting.md`
diff --git a/.claude/skills/ccs-delegation/references/README.md b/.claude/skills/ccs-delegation/references/README.md
new file mode 100644
index 00000000..cc5d7c67
--- /dev/null
+++ b/.claude/skills/ccs-delegation/references/README.md
@@ -0,0 +1,24 @@
+# CCS Delegation References
+
+## Reading Order
+
+1. **Start here**: `../SKILL.md` - Entry point, quick start
+2. `headless-workflow.md` - Technical details (command syntax, features, config)
+3. **As needed**:
+ - `delegation-guidelines.md` - Decision framework
+ - `troubleshooting.md` - Error recovery
+
+## File Hierarchy
+
+**PRIMARY (Authoritative Source)**
+- `headless-workflow.md` - Technical implementation details
+
+**SUPPORTING (Reference Primary)**
+- `delegation-guidelines.md` - When to delegate
+- `troubleshooting.md` - Error patterns
+
+## Quick Navigation
+
+**Need command syntax?** β `headless-workflow.md`
+**Need to decide if delegate?** β `delegation-guidelines.md`
+**Got an error?** β `troubleshooting.md`
diff --git a/.claude/skills/ccs-delegation/references/delegation-guidelines.md b/.claude/skills/ccs-delegation/references/delegation-guidelines.md
new file mode 100644
index 00000000..9bcc54f4
--- /dev/null
+++ b/.claude/skills/ccs-delegation/references/delegation-guidelines.md
@@ -0,0 +1,99 @@
+# Delegation Guidelines
+
+AI decision framework for when to delegate tasks vs keep in main session.
+
+## Task Classification Rules
+
+**Delegate if ALL criteria match:**
+- Task scope: Single concern, < 5 files
+- Complexity: Mechanical transformation, established pattern
+- Ambiguity: Zero decisions required, clear acceptance criteria
+- Context: Existing patterns to follow, no architecture changes
+
+**Keep in main if ANY criteria match:**
+- Requires design decisions or tradeoff analysis
+- Security-critical (auth, encryption, permissions)
+- Performance-sensitive requiring profiling/measurement
+- Breaking changes or API migrations
+- User discussion/clarification needed
+- Coordinated changes across multiple subsystems
+
+## Delegation Pattern Matching
+
+**High-confidence delegation patterns:**
+```
+Task patterns to delegate:
+- refactor .* to use (async/await|destructuring|arrow functions)
+- add (unit|integration) tests for .*
+- fix (typos?|formatting|linting errors?) in .*
+- add JSDoc comments to .*
+- extract .* into (function|method|util) .*
+- rename (variable|function) .* to .*
+- add DELETE endpoint for .*
+- update README to document .*
+```
+
+**Anti-patterns (never delegate):**
+```
+Task patterns to avoid:
+- implement .* (too vague, needs design)
+- improve .* (subjective, needs discussion)
+- fix bug .* (requires investigation)
+- optimize .* (requires profiling)
+- migrate .* to .* (breaking change)
+- design .* (architecture decision)
+- whatever .* you think (requires judgment)
+```
+
+## Prompt Quality Criteria
+
+**Well-formed delegation prompt:**
+- Specifies exact file paths: `in src/auth.js, ...`
+- Defines success criteria: `covering positive, zero, negative cases`
+- Single atomic task: One verb, one target
+- Uses imperative mood: "add tests" not "adding tests"
+
+**Malformed delegation prompt:**
+- Multiple tasks: "add tests, update docs, fix linting"
+- Vague scope: "improve the code"
+- Requires decisions: "use whatever library you want"
+- No file context: "fix the bug" (which file?)
+
+## Token Efficiency Model
+
+**Delegation cost model:**
+- Main session overhead: ~2000 tokens (context, discussion)
+- Delegation overhead: ~500 tokens (focused execution)
+- Net savings: ~1500 tokens per delegated task
+
+**When to batch delegate:**
+- User requests N similar tasks (e.g., "add tests for all services")
+- Each task follows identical pattern
+- Tasks are independent (no coordination needed)
+
+**Execution pattern:**
+```
+for each service in [UserService, AuthService, OrderService]:
+ ccs glm -p "add unit tests for {service} using Jest"
+```
+
+## Monorepo Handling
+
+**Workspace specification required:**
+- Pattern: `in packages/{workspace}, {task}`
+- Example: `in packages/api, add validation middleware`
+- Without workspace: Task may target wrong package
+
+## Scope Limits
+
+**Absolute limits (reject delegation):**
+- Estimated time > 30 minutes
+- File count > 5 files
+- Requires external research
+- Breaking changes to public APIs
+- User explicitly requests discussion
+
+**Examples of over-scoped tasks:**
+- "Migrate from SQLite to PostgreSQL" (breaking change)
+- "Implement OAuth2 authentication" (too complex)
+- "Analyze entire codebase for security issues" (research task)
diff --git a/.claude/skills/ccs-delegation/references/delegation-patterns.md b/.claude/skills/ccs-delegation/references/delegation-patterns.md
deleted file mode 100644
index 5d76d94c..00000000
--- a/.claude/skills/ccs-delegation/references/delegation-patterns.md
+++ /dev/null
@@ -1,286 +0,0 @@
-# CCS Delegation Patterns - Detailed Reference
-
-This reference provides comprehensive patterns and examples for CCS task delegation.
-
-## Advanced Usage Patterns
-
-### Pattern 4: Task Splitting (Complex + Simple)
-
-Split work between models for optimal efficiency:
-
-```
-User: "Design and implement payment system"
-
-Claude (in Sonnet):
-1. Design architecture (Sonnet handles complex reasoning)
- - Security considerations
- - Data flow diagrams
- - API contracts
-
-2. Delegate implementation to GLM:
- /ccs glm /code "implement payment webhook handler based on this design"
-
-3. Review security (back to Sonnet):
- Review the implemented code for security vulnerabilities
-```
-
-### Pattern 5: Batch Operations
-
-Delegate multiple simple tasks sequentially:
-
-```bash
-# Multiple planning tasks
-/ccs glm /plan "feature A: user profile"
-/ccs glm /plan "feature B: notifications"
-/ccs glm /plan "feature C: search functionality"
-
-# Then review all plans together in Sonnet
-"Review all three plans for consistency and integration points"
-```
-
-### Pattern 6: Iterative Refinement
-
-Use GLM for initial implementation, Sonnet for refinement:
-
-```
-1. /ccs glm /code "implement basic CRUD API"
-2. (Sonnet reviews): "Add error handling, input validation, rate limiting"
-3. /ccs glm /fix "add suggested improvements"
-```
-
-## Model Capability Matrix
-
-### GLM 4.6 - Best For:
-- β
Simple feature planning (CRUD, basic workflows)
-- β
Straightforward code implementation
-- β
Documentation and README files
-- β
Basic bug fixes (clear error messages)
-- β
Refactoring with clear scope
-- β
Test writing (unit tests, simple integration tests)
-- β
Configuration files (package.json, tsconfig, etc.)
-- β Complex algorithms
-- β Security-critical code
-- β Performance optimization
-- β Architecture decisions
-
-
-### Sonnet 4.5 - Best For:
-- β
Complex architecture and design
-- β
Security-critical code review
-- β
Performance optimization
-- β
Complex debugging (multiple files, unclear root cause)
-- β
API design and contracts
-- β
Database schema design
-- β
Integration planning
-- β
Ambiguous requirement clarification
-
-## Context Preservation Strategies
-
-### When Delegation Makes Sense
-
-**Low context requirements**:
-```
-# Current session has 50 lines discussing feature X
-# User wants to add unrelated feature Y
-/ccs glm /plan "add feature Y" # β
Good - Y doesn't need X's context
-```
-
-**Self-contained tasks**:
-```
-# Task has all info in the prompt
-/ccs glm /code "implement function that validates email addresses" # β
Good
-```
-
-### When to Keep in Current Session
-
-**High context dependency**:
-```
-# Current session has extensive discussion about auth flow
-# User: "now implement the login function"
-# β Don't delegate - needs current context
-```
-
-**Iterative refinement**:
-```
-# Session has 10 messages refining a complex algorithm
-# User: "adjust the algorithm to handle edge case X"
-# β Don't delegate - needs full conversation history
-```
-
-## Token Efficiency Analysis
-
-### Token Savings Example
-
-**Without delegation**:
-- Complex architecture discussion: 15,000 tokens (Sonnet)
-- Simple implementation: 5,000 tokens (Sonnet)
-- Total: 20,000 Sonnet tokens
-
-**With delegation**:
-- Complex architecture discussion: 15,000 tokens (Sonnet)
-- Delegate implementation: 5,000 tokens (GLM)
-- Total: 15,000 Sonnet + 5,000 GLM tokens
-- **Savings**: 5,000 Sonnet tokens
-
-### When Delegation Overhead Outweighs Benefits
-
-**Very simple tasks** (< 200 tokens):
-```
-User: "add a comment to this line"
-# β Don't delegate - overhead > benefit
-```
-
-**Tasks needing immediate context** (recent discussion):
-```
-User: "based on what we just discussed, implement X"
-# β Don't delegate - needs immediate context
-```
-
-## Real-World Workflows
-
-### Workflow 1: New Feature Development
-
-```
-1. Requirements gathering (Sonnet)
- - Clarify ambiguous requirements
- - Discuss trade-offs
- - Design API contracts
-
-2. Planning (GLM)
- /ccs glm /plan "implement user profile feature based on requirements"
-
-3. Implementation (GLM)
- /ccs glm /code "implement the user profile API endpoints"
-
-4. Review (Sonnet)
- - Security review
- - Performance check
- - Integration verification
-
-5. Fixes (GLM if simple, Sonnet if complex)
- /ccs glm /fix "address code review comments"
-```
-
-### Workflow 2: Bug Investigation & Fix
-
-```
-1. Investigation (Sonnet)
- - Analyze logs
- - Trace root cause
- - Understand system state
-
-2. Simple fix (GLM)
- /ccs glm /fix "update validation in UserController to handle null emails"
-
-3. Verification (Sonnet)
- - Verify fix addresses root cause
- - Check for regressions
-```
-
-### Workflow 3: Documentation Sprint
-
-```
-1. /ccs glm /docs "document the authentication API endpoints"
-2. /ccs glm /docs "write setup guide for new developers"
-3. /ccs glm /docs "create API usage examples"
-4. (Sonnet reviews for completeness and accuracy)
-```
-
-## Anti-Patterns to Avoid
-
-### Anti-Pattern 1: Over-Delegation
-
-β **Bad**:
-```
-/ccs glm /plan "design entire microservices architecture"
-# Too complex for GLM
-```
-
-β
**Good**:
-```
-# Sonnet handles architecture
-# Then: /ccs glm /code "implement user service based on architecture"
-```
-
-### Anti-Pattern 2: Delegation with Hidden Context
-
-β **Bad**:
-```
-# After 20 messages discussing custom auth flow
-User: "implement the login"
-/ccs glm /code "implement login"
-# GLM doesn't have context about custom flow
-```
-
-β
**Good**:
-```
-# Include context in delegation
-/ccs glm /code "implement login using JWT with custom claims: userId, role, tenantId"
-```
-
-### Anti-Pattern 3: Micro-Delegation
-
-β **Bad**:
-```
-/ccs glm /code "add variable x"
-/ccs glm /code "add function y"
-/ccs glm /code "add class z"
-# Too much delegation overhead
-```
-
-β
**Good**:
-```
-/ccs glm /code "implement user management module with CRUD operations"
-```
-
-## Troubleshooting
-
-### Issue: Delegated Task Failed
-
-**Symptoms**:
-- GLM produces incorrect code
-- Implementation doesn't match requirements
-- Security vulnerabilities introduced
-
-**Solutions**:
-1. Check if task was too complex for GLM
-2. Provide more explicit requirements
-3. Use Sonnet for complex parts, GLM only for straightforward implementation
-4. Review GLM output in Sonnet before accepting
-
-### Issue: Context Loss
-
-**Symptoms**:
-- Delegated task doesn't align with previous discussion
-- Implementation misses important constraints
-- Style doesn't match existing codebase
-
-**Solutions**:
-1. Include more context in delegation prompt
-2. Don't delegate context-dependent tasks
-3. Provide explicit style guidelines in prompt
-4. Consider keeping task in current session
-
-### Issue: Frequent Delegation Failures
-
-**Symptoms**:
-- Multiple retries needed
-- Tasks keep failing validation
-- Time spent > time saved
-
-**Solutions**:
-1. Re-evaluate task complexity
-2. Delegate fewer, larger tasks instead of many small ones
-3. Use more specific instructions
-4. Consider if delegation is appropriate for this workflow
-
-## Best Practices Summary
-
-1. **Delegate simple, self-contained tasks**
-2. **Keep complex reasoning in Sonnet**
-3. **Include sufficient context in delegation**
-4. **Review delegated output before proceeding**
-5. **Monitor token savings vs overhead**
-6. **Prefer batch operations over micro-delegations**
-7. **Document delegation patterns that work well**
-8. **Iterate on delegation strategies based on results**
diff --git a/.claude/skills/ccs-delegation/references/headless-workflow.md b/.claude/skills/ccs-delegation/references/headless-workflow.md
new file mode 100644
index 00000000..67c7f769
--- /dev/null
+++ b/.claude/skills/ccs-delegation/references/headless-workflow.md
@@ -0,0 +1,174 @@
+# Headless Workflow
+
+**Last Updated**: 2025-11-15
+
+CCS delegation uses Claude Code headless mode with enhanced features for token optimization.
+
+## Core Concept
+
+CCS delegation executes tasks via alternative models using enhanced Claude Code headless mode with stream-JSON output, session management, and cost tracking.
+
+**Actual Command:**
+```bash
+ccs {profile} -p "prompt"
+```
+
+Internally executes:
+```bash
+claude -p "prompt" --settings ~/.ccs/{profile}.settings.json --output-format stream-json --permission-mode acceptEdits
+```
+
+**Docs:** https://code.claude.com/docs/en/headless.md
+
+## How It Works
+
+**Workflow:**
+1. User: `/ccs:glm "task"` in Claude Code session
+2. CCS detects `-p` flag and routes to HeadlessExecutor
+3. HeadlessExecutor spawns: `claude -p "task" --settings ~/.ccs/glm.settings.json --output-format stream-json --permission-mode acceptEdits`
+4. Claude Code runs headless with GLM profile + enhanced flags
+5. Returns stream-JSON with session_id, cost, turns
+6. Real-time tool use visibility in TTY
+7. ResultFormatter displays formatted results with metadata
+
+**Enhanced Features:**
+- Stream-JSON output parsing (`--output-format stream-json`)
+- Real-time tool use visibility (e.g., `[Tool Use: Bash]`)
+- Session persistence (`~/.ccs/delegation-sessions.json`)
+- Cost tracking (displays USD cost per execution)
+- Time-based limits (10 min default timeout with graceful termination)
+- Multi-turn session management (resume via session_id)
+- Formatted ASCII box output
+
+## Profile Settings
+
+**Location:** `~/.ccs/{profile}.settings.json`
+
+**Examples:**
+- GLM: `~/.ccs/glm.settings.json`
+- Kimi: `~/.ccs/kimi.settings.json`
+
+**Example content:**
+```json
+{
+ "env": {
+ "ANTHROPIC_BASE_URL": "https://api.z.ai/api/anthropic",
+ "ANTHROPIC_AUTH_TOKEN": "your-glm-api-key",
+ "ANTHROPIC_MODEL": "glm-4.6"
+ }
+}
+```
+
+## Output Format
+
+**Stream-JSON Mode** (automatically enabled):
+Each message is a separate JSON object (jsonl format):
+```json
+{"type":"init","session_id":"abc123def456"}
+{"type":"user","message":{"role":"user","content":"Task description"}}
+{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","name":"Bash"}]}}
+{"type":"result","subtype":"success","total_cost_usd":0.0025,"num_turns":3,"session_id":"abc123def456","result":"Task completed"}
+```
+
+**Real-time Progress** (TTY only):
+```
+[i] Delegating to GLM-4.6...
+[Tool Use: Write]
+[Tool Use: Write]
+[Tool Use: Bash]
+[i] Execution completed in 1.5s
+```
+
+**Formatted Output** (displayed to user):
+```
+ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+β Working Directory: /path/to/project β
+β Model: GLM-4.6 β
+β Duration: 1.5s β
+β Exit Code: 0 β
+β Session ID: abc123de β
+β Cost: $0.0025 β
+β Turns: 3 β
+ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+```
+
+**Extracted Fields:**
+- `session_id` - For multi-turn (--resume)
+- `total_cost_usd` - Cost per execution
+- `num_turns` - Turn count
+- `is_error` - Error flag
+- `result` - Task output
+
+**Exit codes:** 0 = success, non-zero = error
+
+## Multi-Turn Sessions
+
+**Start session:**
+```bash
+ccs glm -p "implement feature"
+```
+
+**Continue session:**
+```bash
+ccs glm:continue -p "add tests"
+ccs glm:continue -p "run tests"
+```
+
+Via slash commands:
+```
+/ccs:glm "implement feature"
+/ccs:glm:continue "add tests"
+```
+
+**Session Storage:** `~/.ccs/delegation-sessions.json`
+
+**Metadata:**
+- Session ID
+- Total cost (aggregated across turns)
+- Turn count
+- Last turn timestamp
+- Working directory
+
+**Expiration:** ~30 days, auto-cleanup
+
+## Usage Patterns
+
+**Single execution:**
+```bash
+ccs glm -p "task description"
+```
+
+**With options:**
+```bash
+ccs glm -p "task" --permission-mode plan
+```
+
+**Continue session:**
+```bash
+ccs glm:continue -p "follow-up task"
+```
+
+All standard Claude Code headless flags are supported. See: https://code.claude.com/docs/en/headless.md
+
+## Error Handling
+
+**Common errors:**
+- `Settings file not found` - Profile not configured (`ccs doctor` to diagnose)
+- `Claude CLI not found` - Install Claude Code
+- `Invalid API key` - Check profile settings in `~/.ccs/{profile}.settings.json`
+
+**Diagnostics:**
+```bash
+ccs doctor # Check configuration
+ccs --version # Show delegation status
+```
+
+---
+
+## Related Documentation
+
+**Entry Point**: `../SKILL.md` - Quick start and decision framework
+**Decision Guide**: `delegation-guidelines.md` - When to delegate
+**Error Recovery**: `troubleshooting.md` - Common issues
+
+**Official Docs**: https://code.claude.com/docs/en/headless.md
diff --git a/.claude/skills/ccs-delegation/references/troubleshooting.md b/.claude/skills/ccs-delegation/references/troubleshooting.md
new file mode 100644
index 00000000..35f5aa01
--- /dev/null
+++ b/.claude/skills/ccs-delegation/references/troubleshooting.md
@@ -0,0 +1,268 @@
+# Troubleshooting
+
+AI-oriented error resolution guide for CCS delegation issues.
+
+## Error Pattern Matching
+
+### Profile Configuration Errors
+
+**Pattern:** `Profile 'X' is not configured for delegation`
+```
+Root cause: Missing ~/.ccs/{profile}.settings.json
+Resolution:
+ 1. Check file exists: ls ~/.ccs/{profile}.settings.json
+ 2. Run diagnostics: ccs doctor
+ 3. If missing, user must configure profile manually
+```
+
+**Pattern:** `Invalid API key` (401 error)
+```
+Root cause: API token expired or invalid
+Resolution:
+ 1. Verify token exists in settings.json
+ 2. Test with simple command: ccs {profile} "test"
+ 3. If fails, user must regenerate token from provider
+```
+
+**Pattern:** `Settings file not found`
+```
+Root cause: ~/.ccs/{profile}.settings.json doesn't exist
+Resolution:
+ 1. Run: ccs doctor
+ 2. Shows missing profiles
+ 3. User must configure manually
+```
+
+### Delegation Execution Errors
+
+**Pattern:** `No previous session found for {profile}`
+```
+Root cause: Using :continue without initial session
+Resolution:
+ - Cannot use ccs {profile}:continue without prior session
+ - Must run: ccs {profile} -p "initial task" first
+ - Then can continue with: ccs {profile}:continue -p "follow-up"
+Example:
+ [X] ccs glm:continue -p "task" # ERROR: no session
+ [OK] ccs glm -p "task" # Creates session
+ [OK] ccs glm:continue -p "more" # Uses session
+```
+
+**Pattern:** `Missing prompt after -p flag`
+```
+Root cause: No argument provided after -p
+Resolution:
+ - Syntax: ccs {profile} -p "prompt text"
+ - Quote prompt if contains spaces
+Example:
+ [X] ccs glm -p # ERROR
+ [OK] ccs glm -p "add tests" # Correct
+```
+
+**Pattern:** `No profile specified`
+```
+Root cause: Command missing profile name
+Resolution:
+ - Syntax: ccs -p "task"
+ - Available profiles: glm, kimi
+Example:
+ [X] ccs -p "task" # ERROR: no profile
+ [OK] ccs glm -p "task" # Correct
+```
+
+**Pattern:** Exit code 1 with JSON parse error
+```
+Root cause: Claude CLI returned non-stream-JSON output
+Resolution:
+ 1. Check if --output-format stream-json is supported
+ 2. Verify Claude CLI version (need recent version with stream-json support)
+ 3. Test manually: claude -p "test" --output-format stream-json
+ 4. If not supported, delegation won't work
+```
+
+### Session Management Errors
+
+**Pattern:** Session file corrupted
+```
+Root cause: ~/.ccs/delegation-sessions.json malformed
+Resolution:
+ 1. Backup file: cp ~/.ccs/delegation-sessions.json ~/.ccs/delegation-sessions.json.bak
+ 2. Delete corrupted file: rm ~/.ccs/delegation-sessions.json
+ 3. New file created on next delegation
+ 4. Previous sessions lost but fresh start
+```
+
+**Pattern:** Session expired
+```
+Root cause: Session older than 30 days
+Resolution:
+ - Sessions auto-expire after 30 days
+ - Start new session: ccs {profile} -p "task"
+ - Cannot resume expired sessions
+```
+
+### Network & API Errors
+
+**Pattern:** Connection timeout
+```
+Root cause: Network issue or API endpoint unreachable
+Resolution:
+ 1. Check internet: ping 8.8.8.8
+ 2. Verify API endpoint in settings.json
+ 3. Check firewall/proxy settings
+ 4. Retry delegation
+```
+
+**Pattern:** Rate limiting (429)
+```
+Root cause: Too many API requests
+Resolution:
+ 1. Wait 60 seconds before retry
+ 2. Reduce concurrent delegations
+ 3. Check API quota limits
+```
+
+### File Operation Errors
+
+**Pattern:** File not found during delegation
+```
+Root cause: Path doesn't exist or wrong working directory
+Resolution:
+ 1. Delegation runs in cwd where command executed
+ 2. Verify file exists: ls
+ 3. Use absolute paths in prompt if needed
+Example:
+ Prompt: "refactor src/auth.js"
+ Check: ls src/auth.js # Must exist in cwd
+```
+
+**Pattern:** Permission denied writing files
+```
+Root cause: Insufficient permissions in target directory
+Resolution:
+ 1. Check directory permissions: ls -la
+ 2. Verify cwd is writable
+ 3. Don't delegate in read-only directories
+```
+
+## Diagnostic Commands
+
+**Profile validation:**
+```bash
+ccs doctor # Check all profiles
+cat ~/.ccs/glm.settings.json # Verify settings
+ccs glm "echo test" 2>&1 # Test execution
+```
+
+**Session inspection:**
+```bash
+cat ~/.ccs/delegation-sessions.json # View sessions
+jq '.glm' ~/.ccs/delegation-sessions.json # Check specific profile
+```
+
+**Delegation test:**
+```bash
+ccs glm -p "create test.txt file with 'hello'" # Simple test
+cat test.txt # Verify result
+```
+
+**Debug mode:**
+```bash
+export CCS_DEBUG=1
+ccs glm -p "task" 2>&1 | tee debug.log # Capture full output
+```
+
+## Decision Tree
+
+```
+Delegation fails?
+ β
+ βββ "Profile not configured"
+ β βββ Run: ccs doctor
+ β βββ Configure missing profile
+ β
+ βββ "No previous session"
+ β βββ Using :continue?
+ β βββ YES: Run initial task first
+ β βββ NO: Different error
+ β
+ βββ "Missing prompt"
+ β βββ Check syntax: ccs {profile} -p "prompt"
+ β
+ βββ Exit code 1
+ β βββ Check error message
+ β βββ JSON parse: Claude CLI version issue
+ β βββ File not found: Verify paths
+ β βββ API error: Check network/token
+ β
+ βββ Silent failure
+ βββ Enable debug: export CCS_DEBUG=1
+```
+
+## Common Patterns to Avoid
+
+**Anti-pattern:** Delegating without profile validation
+```
+[X] Assume profile exists
+[OK] Run ccs doctor first to verify
+```
+
+**Anti-pattern:** Using :continue immediately
+```
+[X] ccs glm:continue -p "task" # No initial session
+[OK] ccs glm -p "task" && ccs glm:continue -p "more"
+```
+
+**Anti-pattern:** Delegating complex tasks
+```
+[X] ccs glm -p "implement OAuth2" # Too complex
+[OK] ccs glm -p "add tests for login function"
+```
+
+**Anti-pattern:** Vague prompts
+```
+[X] ccs glm -p "fix the bug" # No context
+[OK] ccs glm -p "fix typo in src/auth.js line 42"
+```
+
+## Recovery Procedures
+
+**Reset session state:**
+```bash
+rm ~/.ccs/delegation-sessions.json
+# Fresh start, all sessions lost
+```
+
+**Reconfigure profile:**
+```bash
+ccs doctor # Shows issues
+# Edit ~/.ccs/{profile}.settings.json manually
+# Verify: ccs {profile} "test"
+```
+
+**Test delegation flow:**
+```bash
+# 1. Simple task
+ccs glm -p "create test.txt with content 'hello'"
+
+# 2. Verify session created
+cat ~/.ccs/delegation-sessions.json | jq '.glm.sessionId'
+
+# 3. Test continue
+ccs glm:continue -p "append 'world' to test.txt"
+
+# 4. Verify aggregation
+cat ~/.ccs/delegation-sessions.json | jq '.glm.turns'
+```
+
+## Emergency Fallback
+
+If delegation completely broken:
+```bash
+# Use Claude CLI directly
+claude -p "task" --settings ~/.ccs/glm.settings.json
+
+# Bypass delegation (no -p flag)
+ccs glm
+# Then work interactively
+```
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fc8466e9..ae5c0e38 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,49 @@
Format: [Keep a Changelog](https://keepachangelog.com/)
+## [4.1.0] - 2025-11-16
+
+### Added
+- **Selective .claude/ directory symlinking** for shared resources across profiles
+- `claude-symlink-manager.js` utility for managing symlinks with Windows fallback
+- Enhanced `ccs doctor` command to verify .claude/ directory health
+- Postinstall script for automatic .claude/ directory setup
+- **Stream-JSON output** for real-time delegation visibility (`--output-format stream-json --verbose`)
+- **Real-time tool tracking** with verbose context (shows file paths, commands, patterns)
+- **Smart slash command detection** (preserves /cook, /plan, /commit in delegated prompts)
+- **Signal handling** (Ctrl+C/Esc kills delegated child processes, prevents orphans)
+- **Comprehensive tool support** (13 Claude Code tools: Bash, Read, Write, Edit, Glob, Grep, NotebookEdit, NotebookRead, SlashCommand, Task, TodoWrite, WebFetch, WebSearch)
+- **Active task display** for TodoWrite (shows current task instead of count)
+- Documentation: Stream-JSON workflow diagrams
+
+### Changed
+- Installers now create selective symlinks (commands/, skills/, agents/) instead of full directory copies
+- Windows support: Falls back to directory copying when symlinks unavailable
+- Profile-specific files (settings.json, sessions/, todolists/, logs/) remain isolated
+- Improved README with symlink architecture documentation
+- **BREAKING**: Delegation now uses stream-json instead of single JSON blob
+- **Time-based limits** replace turn-based limits (10min default timeout vs 20 max-turns)
+- **Graceful termination** with SIGTERM β SIGKILL fallback (2s grace period)
+- Removed `--max-turns` flag (deprecated, use timeout instead)
+- Simplified slash command docs (removed over-prescriptive instructions)
+- Internal tools (TodoWrite, Skill) now show meaningful progress
+
+### Fixed
+- Duplicate .claude/ resources across multiple profiles
+- Installer logic now handles symlink creation during setup
+- Orphaned `claude -p` processes after parent termination
+- Slash commands broken by IMPORTANT safety prefix
+- Slash commands detected as file paths (/home vs /cook)
+- Stream-json requires `--verbose` flag with `-p`
+- Tool output spam (filtered internal tools, show active tasks)
+
+### Removed
+- IMPORTANT safety prefix (broke slash command positioning)
+- Outdated test files (json-output.test.js, max-turns.test.js)
+- TTY detection (now shows progress unless CCS_QUIET=1)
+
+---
+
## [3.5.0] - 2025-11-15
### Added
diff --git a/README.md b/README.md
index 14bae473..ff9ae177 100644
--- a/README.md
+++ b/README.md
@@ -174,29 +174,51 @@ Then: π΄ _"You've reached your usage limit."_
β OLD WAY: Switch When You Hit Limits (Reactive)
-### Your Current Workflow:
-- **2pm:** Building features, in the zone
-- **3pm:** π΄ Usage limit hit
-- **3:05pm:** Stop work, edit `~/.claude/settings.json`
-- **3:15pm:** Switch accounts, lose context
-- **3:30pm:** Try to get back in flow state
-- **4pm:** Finally productive again
+
-- **Result:** 1 hour lost, momentum destroyed, frustration builds
+```mermaid
+graph LR
+ A[2pm: Building features
In the zone] --> B[3pm: Usage limit hit
BLOCKED]
+ B --> C[3:05pm: Stop work
Edit settings.json]
+ C --> D[3:15pm: Switch accounts
Context lost]
+ D --> E[3:30pm: Restart
Trying to focus]
+ E --> F[4pm: Finally productive
Back in flow]
+
+ style A fill:#d4edda,stroke:#333,color:#000
+ style B fill:#f8d7da,stroke:#333,color:#000
+ style C fill:#fff3cd,stroke:#333,color:#000
+ style D fill:#f8d7da,stroke:#333,color:#000
+ style E fill:#fff3cd,stroke:#333,color:#000
+ style F fill:#d4edda,stroke:#333,color:#000
+```
+
+**Result:** 1 hour lost, momentum destroyed, frustration builds
β¨ NEW WAY: Run Parallel From Start (Proactive) - RECOMMENDED
-### Your New Workflow:
-- **2pm:** **Terminal 1:** `ccs "Plan the API architecture"` β Strategic thinking (Claude Pro)
-- **2pm:** **Terminal 2:** `ccs glm "Implement the endpoints"` β Code execution (GLM)
-- **3pm:** Still shipping, no interruptions
-- **4pm:** Flow state achieved, productivity spiking
-- **5pm:** Features shipped, context maintained
+
-- **Result:** Zero downtime, continuous productivity, less frustration
+```mermaid
+graph LR
+ A[2pm: Start work] --> B[Terminal 1: Claude Pro
Strategic planning]
+ A --> C[Terminal 2: GLM
Code execution]
+ B --> D[3pm: Still shipping
No interruptions]
+ C --> D
+ D --> E[4pm: Flow state
Productivity peak]
+ E --> F[5pm: Features shipped
Context maintained]
+
+ style A fill:#e7f3ff,stroke:#333,color:#000
+ style B fill:#cfe2ff,stroke:#333,color:#000
+ style C fill:#cfe2ff,stroke:#333,color:#000
+ style D fill:#d4edda,stroke:#333,color:#000
+ style E fill:#d4edda,stroke:#333,color:#000
+ style F fill:#d4edda,stroke:#333,color:#000
+```
+
+**Result:** Zero downtime, continuous productivity, less frustration
### π° **The Value Proposition:**
- **Setup:** Your existing Claude Pro + GLM Lite (cost-effective add-on)
@@ -291,16 +313,22 @@ Then: π΄ _"You've reached your usage limit."_
- Uses `CLAUDE_CONFIG_DIR` for isolated instances
- Create with `ccs auth create `
-### Shared Data (v3.1)
+### Shared Data (v3.1+)
-Commands and skills symlinked from `~/.ccs/shared/` - **no duplication across profiles**.
+**CCS items (v4.1)**: Commands and skills symlinked from `~/.ccs/.claude/` to `~/.claude/` - **single source of truth with auto-propagation**.
+
+**Profile access**: `~/.ccs/shared/` symlinks to `~/.claude/` - **no duplication across profiles**.
```plaintext
~/.ccs/
-βββ shared/ # Shared across all profiles
-β βββ agents/
-β βββ commands/
-β βββ skills/
+βββ .claude/ # CCS items (ships with package, v4.1)
+β βββ commands/ccs/ # Delegation commands (/ccs:glm, /ccs:kimi)
+β βββ skills/ccs-delegation/ # AI decision framework
+β βββ agents/ccs-delegator.md # Proactive delegation agent
+βββ shared/ # Symlinks to ~/.claude/ (for profiles)
+β βββ agents@ β ~/.claude/agents/
+β βββ commands@ β ~/.claude/commands/
+β βββ skills@ β ~/.claude/skills/
βββ instances/ # Profile-specific data
β βββ work/
β βββ agents@ β shared/agents/
@@ -309,15 +337,23 @@ Commands and skills symlinked from `~/.ccs/shared/` - **no duplication across pr
β βββ settings.json # API keys, credentials
β βββ sessions/ # Conversation history
β βββ ...
+
+~/.claude/ # User's Claude directory
+βββ commands/ccs@ β ~/.ccs/.claude/commands/ccs/ # Selective symlink
+βββ skills/ccs-delegation@ β ~/.ccs/.claude/skills/ccs-delegation/
+βββ agents/ccs-delegator.md@ β ~/.ccs/.claude/agents/ccs-delegator.md
```
+**Symlink Chain**: `work profile β ~/.ccs/shared/ β ~/.claude/ β ~/.ccs/.claude/` (CCS items)
+
| Type | Files |
|:-----|:------|
-| **Shared** | `commands/`, `skills/`, `agents/` |
+| **CCS items** | `~/.ccs/.claude/` (ships with package, selective symlinks to `~/.claude/`) |
+| **Shared** | `~/.ccs/shared/` (symlinks to `~/.claude/`) |
| **Profile-specific** | `settings.json`, `sessions/`, `todolists/`, `logs/` |
> [!NOTE]
-> **Windows**: Copies directories if symlinks unavailable (enable Developer Mode for true symlinks)
+> **Windows**: Symlink support requires Developer Mode (v4.2 will add copy fallback)
@@ -358,6 +394,123 @@ ccs --help # Show all commands and options
+## AI-Powered Delegation
+
+> [!TIP]
+> **New in v4.0**: Delegate tasks to cost-optimized models (GLM, Kimi) directly from your main Claude session. Save 81% on simple tasks with real-time visibility.
+
+### What is Delegation?
+
+CCS Delegation lets you **send tasks to alternative models** (`glm`, `kimi`) **from your main Claude session** using the `-p` flag or slash commands (`/ccs:glm`, `/ccs:kimi`).
+
+**Why use it?**
+- **Token efficiency**: Simple tasks cost 81% less on GLM vs main Claude session
+- **Context preservation**: Main session stays clean, no pollution from mechanical tasks
+- **Real-time visibility**: See tool usage as tasks execute (`[Tool] Write: index.html`)
+- **Multi-turn support**: Resume sessions with `:continue` for iterative work
+
+### Quick Examples
+
+**Direct CLI:**
+```bash
+# Delegate simple task to GLM (cost-optimized)
+ccs glm -p "add tests for UserService"
+
+# Delegate long-context task to Kimi
+ccs kimi -p "analyze all files in src/ and document architecture"
+
+# Continue previous session
+ccs glm:continue -p "run the tests and fix any failures"
+```
+
+**Via Slash Commands** (inside Claude sessions):
+```bash
+# In your main Claude session:
+/ccs:glm "refactor auth.js to use async/await"
+/ccs:kimi "find all deprecated API usages across codebase"
+/ccs:glm:continue "also update the README examples"
+```
+
+**Via Natural Language** (Claude auto-delegates):
+```bash
+# Claude detects delegation patterns and auto-executes:
+"Use ccs glm to add tests for all *.service.js files"
+"Delegate to kimi: analyze project structure"
+```
+
+### Real-Time Output
+
+See exactly what's happening as tasks execute:
+
+```
+$ ccs glm -p "/cook create a landing page"
+[i] Delegating to GLM-4.6...
+[Tool] Write: /home/user/project/index.html
+[Tool] Write: /home/user/project/styles.css
+[Tool] Write: /home/user/project/script.js
+[Tool] Edit: /home/user/project/styles.css
+[i] Execution completed in 45.2s
+
+ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+β Working Directory: /home/user/project β
+β Model: GLM-4.6 β
+β Duration: 45.2s β
+β Exit Code: 0 β
+β Session ID: 3a4f8c21 β
+β Total Cost: $0.0015 β
+β Turns: 3 β
+ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+```
+
+### Advanced Features
+
+**Slash Command Support:**
+Delegation preserves custom slash commands in prompts:
+```bash
+ccs glm -p "/cook create responsive landing page"
+# Executes /cook command in delegated GLM session
+```
+
+**Signal Handling:**
+Ctrl+C or Esc properly kills delegated processes (no orphans):
+```bash
+# Hit Ctrl+C during delegation
+[!] Parent process terminating, killing delegated session...
+```
+
+**Time-Based Limits:**
+10-minute default timeout with graceful termination (supports `:continue`):
+```bash
+ccs glm -p "complex task" # Auto-terminates after 10min if needed
+ccs glm:continue -p "pick up where we left off"
+```
+
+### Cost Savings Example
+
+**Traditional (Main Session):**
+```
+Context load: 2000 tokens
+Discussion: 1500 tokens
+Code gen: 4500 tokens
+βββββββββββββββββββββββββ
+Total: 8000 tokens β $0.032
+```
+
+**Delegation (GLM):**
+```
+3x tasks via GLM: 1500 tokens β $0.0045
+βββββββββββββββββββββββββββββββββββββββββ
+Savings: $0.0275 (86% reduction)
+```
+
+### Documentation
+
+- **Workflow Diagrams**: See [docs/ccs-delegation-diagrams.md](docs/ccs-delegation-diagrams.md) for visual architecture
+- **Skill Reference**: `.claude/skills/ccs-delegation/` for AI decision framework
+- **Agent Docs**: `.claude/agents/ccs-delegator.md` for orchestration patterns
+
+
+
## GLM with Thinking (GLMT)
> [!CAUTION]
@@ -568,6 +721,53 @@ cat ~/.ccs/logs/*response-openai.json | jq '.choices[0].message.reasoning_conten
+## Maintenance
+
+### Health Check
+
+Run diagnostics to verify your CCS installation:
+
+```bash
+ccs doctor
+```
+
+**Checks performed**:
+- β Claude CLI availability
+- β Configuration files (config.json, profiles)
+- β CCS symlinks to ~/.claude/
+- β Delegation system
+- β File permissions
+
+**Output**:
+```
+[?] Checking Claude CLI... [OK]
+[?] Checking ~/.ccs/ directory... [OK]
+[?] Checking config.json... [OK]
+[?] Checking CCS symlinks... [OK]
+...
+Status: Installation healthy
+```
+
+### Update CCS Items
+
+If you modify CCS items or need to re-install symlinks:
+
+```bash
+ccs update
+```
+
+**What it does**:
+- Re-creates selective symlinks from `~/.ccs/.claude/` to `~/.claude/`
+- Backs up existing files before replacing
+- Safe to run multiple times (idempotent)
+
+**When to use**:
+- After manual modifications to ~/.claude/
+- If `ccs doctor` reports symlink issues
+- After upgrading CCS to a new version
+
+
+
## Uninstall
diff --git a/VERSION b/VERSION
index 1545d966..ee74734a 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-3.5.0
+4.1.0
diff --git a/bin/ccs.js b/bin/ccs.js
index 823dc0c2..163110ff 100755
--- a/bin/ccs.js
+++ b/bin/ccs.js
@@ -73,6 +73,33 @@ function handleVersionCommand() {
// Config path
const configPath = getConfigPath();
console.log(` ${colored('Config:', 'cyan')} ${configPath}`);
+
+ // Delegation status
+ const delegationRulesPath = path.join(os.homedir(), '.ccs', 'delegation-rules.json');
+ const delegationEnabled = fs.existsSync(delegationRulesPath);
+
+ if (delegationEnabled) {
+ console.log(` ${colored('Delegation:', 'cyan')} Enabled`);
+
+ // Check which profiles are delegation-ready
+ const readyProfiles = [];
+ const { DelegationValidator } = require('./utils/delegation-validator');
+
+ for (const profile of ['glm', 'kimi']) {
+ const validation = DelegationValidator.validate(profile);
+ if (validation.valid) {
+ readyProfiles.push(profile);
+ }
+ }
+
+ if (readyProfiles.length > 0) {
+ console.log(` ${colored('Ready:', 'cyan')} ${readyProfiles.join(', ')}`);
+ } else {
+ console.log(` ${colored('Ready:', 'cyan')} None (configure profiles first)`);
+ }
+ } else {
+ console.log(` ${colored('Delegation:', 'cyan')} Not configured`);
+ }
console.log('');
// Documentation
@@ -121,9 +148,19 @@ function handleHelpCommand() {
console.log(` ${colored('ccs personal', 'yellow')} Switch to personal account`);
console.log('');
+ // Delegation (NEW)
+ console.log(colored('Delegation (Token Optimization):', 'cyan'));
+ console.log(` ${colored('/ccs:glm "task"', 'yellow')} Delegate to GLM-4.6 within Claude session`);
+ console.log(` ${colored('/ccs:kimi "task"', 'yellow')} Delegate to Kimi for long context`);
+ console.log(` ${colored('/ccs:create m2', 'yellow')} Create custom delegation command`);
+ console.log(' Use delegation to save tokens on simple tasks');
+ console.log(' Commands work inside Claude Code sessions only');
+ console.log('');
+
// Diagnostics
console.log(colored('Diagnostics:', 'cyan'));
console.log(` ${colored('ccs doctor', 'yellow')} Run health check and diagnostics`);
+ console.log(` ${colored('ccs update', 'yellow')} Re-install CCS items to ~/.claude/`);
console.log('');
// Flags
@@ -217,6 +254,16 @@ async function handleDoctorCommand() {
process.exit(doctor.results.isHealthy() ? 0 : 1);
}
+async function handleUpdateCommand() {
+ const ClaudeSymlinkManager = require('./utils/claude-symlink-manager');
+ const manager = new ClaudeSymlinkManager();
+
+ console.log('[i] Updating CCS items in ~/.claude/...');
+ manager.update();
+
+ process.exit(0);
+}
+
// Smart profile detection
function detectProfile(args) {
if (args.length === 0 || args[0].startsWith('-')) {
@@ -454,6 +501,12 @@ async function main() {
return;
}
+ // Special case: update command (re-install CCS symlinks)
+ if (firstArg === 'update' || firstArg === '--update') {
+ await handleUpdateCommand();
+ return;
+ }
+
// Special case: auth command (multi-account management)
if (firstArg === 'auth') {
const AuthCommands = require('./auth/auth-commands');
@@ -462,6 +515,14 @@ async function main() {
return;
}
+ // Special case: headless delegation (-p flag)
+ if (args.includes('-p') || args.includes('--prompt')) {
+ const DelegationHandler = require('./delegation/delegation-handler');
+ const handler = new DelegationHandler();
+ await handler.route(args);
+ return;
+ }
+
// Auto-recovery for missing configuration
const recovery = new RecoveryManager();
const recovered = recovery.recoverAll();
diff --git a/bin/delegation/README.md b/bin/delegation/README.md
new file mode 100644
index 00000000..c3051204
--- /dev/null
+++ b/bin/delegation/README.md
@@ -0,0 +1,189 @@
+# CCS Delegation Module
+
+Enhanced Claude Code delegation system for multi-model task delegation.
+
+## Files
+
+### Core Components
+- **headless-executor.js** (405 lines) - Main executor, spawns `claude -p` with enhanced features
+- **session-manager.js** (156 lines) - Session persistence and cost tracking
+- **settings-parser.js** (88 lines) - Parse tool restrictions from settings
+- **result-formatter.js** (326 lines) - Terminal output formatting
+
+**Total**: 975 lines (down from 1,755 lines - 44% reduction)
+
+## Features
+
+### Enhanced Headless Execution
+- Stream-JSON output parsing (`--output-format stream-json`)
+- Real-time tool use visibility in TTY
+- Permission mode acceptEdits (`--permission-mode acceptEdits`)
+- Tool restrictions from `.claude/settings.local.json`
+- Multi-turn session management (`--resume `)
+- Time-based limits (10 min default timeout with graceful termination)
+- Cost tracking and aggregation
+
+### Session Management
+- Persistence: `~/.ccs/delegation-sessions.json`
+- Resume via `/ccs:glm:continue` and `/ccs:kimi:continue`
+- Auto-cleanup expired sessions (>30 days)
+- Cost aggregation across turns
+
+### Settings
+- Profile location: `~/.ccs/{profile}.settings.json`
+- Examples: `glm.settings.json`, `kimi.settings.json`, `glmt.settings.json`
+- Tool restrictions from `.claude/settings.local.json`
+
+## Usage
+
+### Basic Delegation
+```javascript
+const { HeadlessExecutor } = require('./headless-executor');
+
+const result = await HeadlessExecutor.execute('glm', 'Refactor auth.js', {
+ cwd: '/path/to/project',
+ outputFormat: 'stream-json',
+ permissionMode: 'acceptEdits',
+ timeout: 600000 // 10 minutes
+});
+
+console.log(result.sessionId); // For multi-turn
+console.log(result.totalCost); // Cost in USD
+console.log(result.content); // Result text
+```
+
+### Multi-Turn Sessions
+```javascript
+// Start session
+const result1 = await HeadlessExecutor.execute('glm', 'Implement feature');
+const sessionId = result1.sessionId;
+
+// Continue session
+const result2 = await HeadlessExecutor.execute('glm', 'Add tests', {
+ resumeSession: true
+});
+
+// Or with specific session ID
+const result3 = await HeadlessExecutor.execute('glm', 'Run tests', {
+ sessionId: sessionId
+});
+```
+
+### Tool Restrictions
+Create `.claude/settings.local.json`:
+```json
+{
+ "permissions": {
+ "allow": ["Bash(git:*)", "Read", "Edit"],
+ "deny": ["Bash(rm:*)", "Bash(sudo:*)"]
+ }
+}
+```
+
+Automatically applied as CLI flags:
+```bash
+--allowedTools "Bash(git:*)" "Read" "Edit" \
+--disallowedTools "Bash(rm:*)" "Bash(sudo:*)"
+```
+
+## Slash Commands
+
+The delegation system is invoked via simple slash commands in `.claude/commands/ccs/`:
+
+### Basic Commands
+- `/ccs:glm "task"` - Delegate to GLM-4.6
+- `/ccs:kimi "task"` - Delegate to Kimi (long-context)
+
+### Multi-Turn Commands
+- `/ccs:glm:continue "follow-up"` - Resume last GLM session
+- `/ccs:kimi:continue "follow-up"` - Resume last Kimi session
+
+Each command directly invokes:
+```bash
+claude -p "$ARGUMENTS" \
+ --settings ~/.ccs/{profile}.settings.json \
+ --output-format stream-json \
+ --permission-mode acceptEdits
+```
+
+## Debug Mode
+
+```bash
+export CCS_DEBUG=1
+```
+
+Enables verbose logging:
+- Permission mode selection
+- Session resumption details
+- Tool restrictions parsing
+- CLI args construction
+- Session persistence events
+
+## Testing
+
+```bash
+# Run all delegation tests
+node tests/unit/delegation/json-output.test.js
+node tests/unit/delegation/permission-mode.test.js
+node tests/unit/delegation/session-manager.test.js
+node tests/unit/delegation/settings-parser.test.js
+node tests/unit/delegation/max-turns.test.js
+node tests/unit/delegation/result-formatter.test.js
+```
+
+**Test Coverage:**
+- JSON output parsing (6 tests)
+- Permission modes (11 tests)
+- Session management (7 tests)
+- Settings parser (6 tests)
+- Auto max-turns (14 tests)
+- Result formatting (14 tests)
+- **Total: 58 tests**
+
+## Architecture
+
+```
+User β SlashCommand (/ccs:glm)
+ β Directly invokes: claude -p
+ β HeadlessExecutor (monitors execution)
+ β SessionManager (load last session)
+ β SettingsParser (tool restrictions)
+ β Parse JSON response
+ β SessionManager (store/update)
+ β ResultFormatter.format()
+ β Display to user
+```
+
+**Key Simplification**: Slash commands invoke `claude -p` directly. No intermediate delegation engine or rule system - just direct headless execution with enhanced features.
+
+## File Permissions
+
+All files should be `644` (rw-r--r--):
+```bash
+chmod 644 bin/delegation/*.js
+```
+
+## Dependencies
+
+- Node.js 14+
+- Claude CLI installed and in PATH
+- Profile settings configured in `~/.ccs/{profile}.settings.json`
+
+## Migration from Legacy System
+
+**Removed components** (as of 2025-11-15):
+- ~~delegation-engine.js~~ - Rule-based decision engine (unused)
+- ~~cwd-resolver.js~~ - Working directory resolution (unused)
+- ~~rules-schema.js~~ - Schema validation (unused)
+- ~~delegation-rules.json~~ - Configuration file (not created)
+
+**Why removed**: Current slash commands directly invoke `claude -p` without intermediate orchestration. The delegation engine, CWD resolver, and rules schema were designed for a more complex system that was never fully integrated.
+
+**Result**: 44% code reduction (1,755 β 975 lines) with same functionality.
+
+## References
+
+- Official docs: https://code.claude.com/docs/en/headless.md
+- Skill: `.claude/skills/ccs-delegation/`
+- Commands: `.claude/commands/ccs/`
+- Tests: `tests/unit/delegation/`
diff --git a/bin/delegation/delegation-handler.js b/bin/delegation/delegation-handler.js
new file mode 100644
index 00000000..f4805ee4
--- /dev/null
+++ b/bin/delegation/delegation-handler.js
@@ -0,0 +1,212 @@
+#!/usr/bin/env node
+'use strict';
+
+const { HeadlessExecutor } = require('./headless-executor');
+const { SessionManager } = require('./session-manager');
+const { ResultFormatter } = require('./result-formatter');
+const { DelegationValidator } = require('../utils/delegation-validator');
+const { SettingsParser } = require('./settings-parser');
+
+/**
+ * Delegation command handler
+ * Routes -p flag commands to HeadlessExecutor with enhanced features
+ */
+class DelegationHandler {
+ /**
+ * Route delegation command
+ * @param {Array} args - Full args array from ccs.js
+ */
+ async route(args) {
+ try {
+ // 1. Parse args into { profile, prompt, options }
+ const parsed = this._parseArgs(args);
+
+ // 2. Detect special profiles (glm:continue, kimi:continue)
+ if (parsed.profile.includes(':continue')) {
+ return await this._handleContinue(parsed);
+ }
+
+ // 3. Validate profile
+ this._validateProfile(parsed.profile);
+
+ // 4. Execute via HeadlessExecutor
+ const result = await HeadlessExecutor.execute(
+ parsed.profile,
+ parsed.prompt,
+ parsed.options
+ );
+
+ // 5. Format and display results
+ const formatted = ResultFormatter.format(result);
+ console.log(formatted);
+
+ // 6. Exit with proper code
+ process.exit(result.exitCode || 0);
+ } catch (error) {
+ console.error(`[X] Delegation error: ${error.message}`);
+ if (process.env.CCS_DEBUG) {
+ console.error(error.stack);
+ }
+ process.exit(1);
+ }
+ }
+
+ /**
+ * Handle continue command (resume last session)
+ * @param {Object} parsed - Parsed args
+ */
+ async _handleContinue(parsed) {
+ const baseProfile = parsed.profile.replace(':continue', '');
+
+ // Get last session from SessionManager
+ const sessionMgr = new SessionManager();
+ const lastSession = sessionMgr.getLastSession(baseProfile);
+
+ if (!lastSession) {
+ console.error(`[X] No previous session found for ${baseProfile}`);
+ console.error(` Start a new session first with: ccs ${baseProfile} -p "task"`);
+ process.exit(1);
+ }
+
+ // Execute with resume flag
+ const result = await HeadlessExecutor.execute(
+ baseProfile,
+ parsed.prompt,
+ {
+ ...parsed.options,
+ resumeSession: true,
+ sessionId: lastSession.sessionId
+ }
+ );
+
+ const formatted = ResultFormatter.format(result);
+ console.log(formatted);
+
+ process.exit(result.exitCode || 0);
+ }
+
+ /**
+ * Parse args into structured format
+ * @param {Array} args - Raw args
+ * @returns {Object} { profile, prompt, options }
+ */
+ _parseArgs(args) {
+ // Extract profile (first non-flag arg or 'default')
+ const profile = this._extractProfile(args);
+
+ // Extract prompt from -p or --prompt
+ const prompt = this._extractPrompt(args);
+
+ // Extract options (--timeout, --permission-mode, etc.)
+ const options = this._extractOptions(args);
+
+ return { profile, prompt, options };
+ }
+
+ /**
+ * Extract profile from args (first non-flag arg)
+ * @param {Array} args - Args array
+ * @returns {string} Profile name
+ */
+ _extractProfile(args) {
+ // Find first arg that doesn't start with '-' and isn't -p value
+ let skipNext = false;
+ for (let i = 0; i < args.length; i++) {
+ if (skipNext) {
+ skipNext = false;
+ continue;
+ }
+
+ if (args[i] === '-p' || args[i] === '--prompt') {
+ skipNext = true;
+ continue;
+ }
+
+ if (!args[i].startsWith('-')) {
+ return args[i];
+ }
+ }
+
+ // No profile specified, return null (will error in validation)
+ return null;
+ }
+
+ /**
+ * Extract prompt from -p flag
+ * @param {Array} args - Args array
+ * @returns {string} Prompt text
+ */
+ _extractPrompt(args) {
+ const pIndex = args.indexOf('-p');
+ const promptIndex = args.indexOf('--prompt');
+
+ const index = pIndex !== -1 ? pIndex : promptIndex;
+
+ if (index === -1 || index === args.length - 1) {
+ console.error('[X] Missing prompt after -p flag');
+ console.error(' Usage: ccs glm -p "task description"');
+ process.exit(1);
+ }
+
+ return args[index + 1];
+ }
+
+ /**
+ * Extract options from remaining args
+ * @param {Array} args - Args array
+ * @returns {Object} Options for HeadlessExecutor
+ */
+ _extractOptions(args) {
+ const cwd = process.cwd();
+
+ // Read default permission mode from .claude/settings.local.json
+ // Falls back to 'acceptEdits' if file doesn't exist
+ const defaultPermissionMode = SettingsParser.parseDefaultPermissionMode(cwd);
+
+ const options = {
+ cwd,
+ outputFormat: 'stream-json',
+ permissionMode: defaultPermissionMode
+ };
+
+ // Parse permission-mode (CLI flag overrides settings file)
+ const permModeIndex = args.indexOf('--permission-mode');
+ if (permModeIndex !== -1 && permModeIndex < args.length - 1) {
+ options.permissionMode = args[permModeIndex + 1];
+ }
+
+ // Parse timeout
+ const timeoutIndex = args.indexOf('--timeout');
+ if (timeoutIndex !== -1 && timeoutIndex < args.length - 1) {
+ options.timeout = parseInt(args[timeoutIndex + 1], 10);
+ }
+
+ return options;
+ }
+
+ /**
+ * Validate profile exists and is configured
+ * @param {string} profile - Profile name
+ */
+ _validateProfile(profile) {
+ if (!profile) {
+ console.error('[X] No profile specified');
+ console.error(' Usage: ccs -p "task"');
+ console.error(' Examples: ccs glm -p "task", ccs kimi -p "task"');
+ process.exit(1);
+ }
+
+ // Use DelegationValidator to check profile
+ const validation = DelegationValidator.validate(profile);
+ if (!validation.valid) {
+ console.error(`[X] Profile '${profile}' is not configured for delegation`);
+ console.error(` ${validation.error}`);
+ console.error('');
+ console.error(' Run: ccs doctor');
+ console.error(' Or configure: ~/.ccs/${profile}.settings.json');
+ process.exit(1);
+ }
+ }
+}
+
+module.exports = DelegationHandler;
diff --git a/bin/delegation/headless-executor.js b/bin/delegation/headless-executor.js
new file mode 100644
index 00000000..e4104e03
--- /dev/null
+++ b/bin/delegation/headless-executor.js
@@ -0,0 +1,617 @@
+#!/usr/bin/env node
+'use strict';
+
+const { spawn } = require('child_process');
+const path = require('path');
+const os = require('os');
+const fs = require('fs');
+const { SessionManager } = require('./session-manager');
+const { SettingsParser } = require('./settings-parser');
+
+/**
+ * Headless executor for Claude CLI delegation
+ * Spawns claude with -p flag for single-turn execution
+ */
+class HeadlessExecutor {
+ /**
+ * Execute task via headless Claude CLI
+ * @param {string} profile - Profile name (glm, kimi, custom)
+ * @param {string} enhancedPrompt - Enhanced prompt with context
+ * @param {Object} options - Execution options
+ * @param {string} options.cwd - Working directory (absolute path)
+ * @param {number} options.timeout - Timeout in milliseconds (default: 600000 = 10 minutes)
+ * @param {string} options.outputFormat - Output format: 'stream-json' or 'text' (default: 'stream-json')
+ * @param {string} options.permissionMode - Permission mode: 'default', 'plan', 'acceptEdits', 'bypassPermissions' (default: 'acceptEdits')
+ * @param {boolean} options.resumeSession - Resume last session for profile (default: false)
+ * @param {string} options.sessionId - Specific session ID to resume
+ * @returns {Promise