# Context Engineering System Enhancement Implementation Plan

> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.

**Goal:** Build a unified `.claude/` context engineering system with commands, agents, sync, and TodoList tracking for AI coding sessions.

**Architecture:** Agent-Dispatcher pattern with TodoList tracking, timestamp-aware sync, and RPI workflow orchestration.

**Tech Stack:** Node.js, TypeScript, SQLite, Handlebars, Commander.js, Inquirer, Vitest

---

## Executive Summary

This enhancement transforms k0ntext's **AI session interface** (`.claude/` folder) into a cohesive context engineering platform. The system will:

1. **Add `.claude/commands/`** - Slash commands for AI to invoke during coding sessions
2. **Enhance `.claude/agents/`** - New agents for cleanup, sync, optimization
3. **Synchronize context files** - claude.md ↔ ai_context.md stay in sync automatically
4. **TodoList tracking** - Session tasks survive compactions
5. **Index-aware operations** - All agents/commands aware of indexes folder
6. **Timestamp-aware cleanup** - Interactive file management with snapshots

---

## Architecture Diagram

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                    AI Coding Session Interface (.claude/)                    │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                    Commands Layer (/command-name)                 │    │
│  │  /context-opt     /context-sync     /snapshot:create               │    │
│  │  /cleanup:scan   /cleanup:interactive /todo:create               │    │
│  │  /dispatch-rpi    /context:status   /workflow:route              │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                    │                                         │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                     Agents Layer (@agent-name)                    │    │
│  │  @context-optimizer  @cleanup-agent    @sync-agent                  │    │
│  │  @todo-manager      @snapshot-manager  @workflow-router               │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                    │                                         │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                   Core Services Layer                              │    │
│  │  TodoList Manager    Timestamp Tracker    Context Generator          │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                    │                                         │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                      Data & Context Layer                         │    │
│  │  .claude/context/    .claude/indexes/    .claude/plans/            │    │
│  │  claude.md            ai_context.md       CLAUDE.md                  │    │
│  │  SQLite DB           File System         Git History                 │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘
```

---

## Phase 1: Foundation (TodoList & Timestamp Tracking)

**Objective:** Build core services that agents and commands will depend on

### New Files to Create

**1.1 `.claude/commands/todo-create.md`**
```yaml
---
name: todo-create
version: "1.0.0"
displayName: "Todo Create"
description: "Create a new todo list for current session with optional tasks"
category: "session-management"
arguments:
  - name: "tasks"
    description: "Optional comma-separated task descriptions"
    required: false
  - name: "--session <name>"
    description: "Session name for grouping"
    required: false
examples:
  - invocation: '/todo-create "Review PR #123"'
    description: "Create todo list for PR review"
  - invocation: '/todo-create "Refactor context system" --session v3.8.0'
    description: "Create named session todo list"
---
```

**1.2 `.claude/commands/todo-status.md`**
```yaml
---
name: todo-status
version: "1.0.0"
displayName: "Todo Status"
description: "Show current session todo list with task statuses"
category: "session-management"
arguments:
  - name: "--session <name>"
    description: "Show specific session todo"
    required: false
  - name: "--format <type>"
    description: "Output format (table|json|markdown)"
    required: false
examples:
  - invocation: '/todo-status'
    description: "Show current session todos"
---
```

**1.3 `.claude/agents/todo-manager.md`**
```markdown
---
name: todo-manager
version: "1.0.0"
displayName: "Todo Manager"
description: "Agent for managing session todo lists that survive compactions"
category: "session-management"
complexity: "low"
context_budget: "~5K tokens"
capabilities:
  - "todo-list-creation"
  - "task-tracking"
  - "session-persistence"
  - "compaction-survival"
workflows:
  - "session-management"
commands: ["/todo-create", "/todo-status", "/todo-update"]
examples:
  - invocation: '@todo-manager "Create todo list for implementing snapshot system"'
    description: "Generate structured todo list"
  - invocation: '@todo-manager "Update todo: mark task 3 as complete"'
    description: "Update specific task status"
---
```

**1.4 `src/agent-system/todolist-manager.ts`**
```typescript
// Backend service for todo lists
export class TodoListManager {
  private db: DatabaseClient;

  async createList(sessionId: string, tasks: Task[]): Promise<TodoList>;
  async updateTask(sessionId: string, taskId: string, status: TaskStatus): Promise<void>;
  async getList(sessionId: string): Promise<TodoList>;
  async exportMarkdown(sessionId: string): Promise<string>;
  async importFromMarkdown(content: string): Promise<TodoList>;
  async archiveSession(sessionId: string): Promise<void>;
}
```

**1.5 `src/agent-system/timestamp-tracker.ts`**
```typescript
// Track file timestamps for sync operations
export class TimestampTracker {
  async recordSnapshot(path: string): Promise<FileTimestamp>;
  async getChangedFiles(since: Date): Promise<ChangedFile[]>;
  async compareTimestamps(file1: string, file2: string): Promise<TimestampDiff>;
  async syncTimestampsFromGit(): Promise<void>;
}
```

### Files to Modify

**1.6 `src/db/schema.ts`** - Add new tables (after line 200)

```sql
-- Schema version update
SCHEMA_VERSION = '1.6.0'

-- Add to existing schema:
CREATE TABLE IF NOT EXISTS todo_sessions (
  id TEXT PRIMARY KEY,
  name TEXT NOT NULL,
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
  updated_at TEXT NOT NULL DEFAULT (datetime('now')),
  parent_session TEXT,  -- For linking related sessions
  metadata JSON
);

CREATE TABLE IF NOT EXISTS todo_tasks (
  id TEXT PRIMARY KEY,
  session_id TEXT NOT NULL,
  subject TEXT NOT NULL,
  description TEXT,
  status TEXT NOT NULL DEFAULT 'pending',
  dependencies TEXT,  -- JSON array of task IDs
  assigned_to TEXT,
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
  updated_at TEXT NOT NULL DEFAULT (datetime('now')),
  completed_at TEXT,
  FOREIGN KEY (session_id) REFERENCES todo_sessions(id) ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS file_timestamps (
  path TEXT PRIMARY KEY,
  modified_time TEXT NOT NULL,
  size INTEGER NOT NULL,
  hash TEXT NOT NULL,
  last_checked TEXT NOT NULL DEFAULT (datetime('now')),
  git_commit TEXT
);

CREATE INDEX IF NOT EXISTS idx_todo_sessions_created ON todo_sessions(created_at);
CREATE INDEX IF NOT EXISTS idx_todo_tasks_session ON todo_tasks(session_id);
CREATE INDEX IF NOT EXISTS idx_todo_tasks_status ON todo_tasks(status);
CREATE INDEX IF NOT EXISTS idx_file_timestamps_checked ON file_timestamps(last_checked);
```

**1.7 `src/db/client.ts`** - Add database methods (after line 700)

```typescript
// TodoList operations
public createTodoSession(name: string, metadata?: Record<string, unknown>): Promise<string>;
public createTodoTask(sessionId: string, task: Task): Promise<string>;
public updateTodoTask(taskId: string, updates: Partial<Task>): Promise<void>;
public getTodoSession(sessionId: string): Promise<TodoSession>;
public getCurrentTodoSession(): Promise<TodoSession | null>;
public getTodoTasks(sessionId: string): Promise<Task[]>;
public getPendingTodos(sessionId: string): Promise<Task[]>;

// Timestamp operations
public recordTimestamp(path: string): Promise<void>;
public batchRecordTimestamps(paths: string[]): Promise<void>;
public getChangedFiles(since: Date): Promise<string[]>;
public getFileTimestamp(path: string): Promise<FileTimestamp | null>;
public syncTimestampsFromGit(): Promise<void>;
```

**1.8 `tests/agent-system/todolist-manager.test.ts`** - Test file

**1.9 `tests/agent-system/timestamp-tracker.test.ts`** - Test file

---

## Phase 2: Context File Commands & Agents

**Objective:** Dedicated commands and agents for claude.md and ai_context.md with fixed structure and auto-sync

### New Files to Create

**2.1 `.claude/commands/context-opt.md`**
```yaml
---
name: context-opt
version: "1.0.0"
displayName: "Context Optimize"
description: "Analyze and optimize context files (claude.md, ai_context.md)"
category: "context-management"
arguments:
  - name: "--analyze"
    description: "Analyze current context state without changes"
    action: "store_true"
  - name: "--generate"
    description: "Regenerate context files from database"
    action: "store_true"
  - name: "--sync"
    description: "Sync claude.md and ai_context.md"
    action: "store_true"
  - name: "--workflow <name>"
    description: "Optimize for specific workflow"
    required: false
examples:
  - invocation: '/context-opt --analyze'
    description: "Check context health"
  - invocation: '/context-opt --generate --sync'
    description: "Regenerate and sync both context files"
---
```

**2.2 `.claude/commands/context-sync.md`**
```yaml
---
name: context-sync
version: "1.0.0"
displayName: "Context Sync"
description: "Bidirectional sync between claude.md and ai_context.md"
category: "context-management"
arguments:
  - name: "--to <target>"
    description: "Sync target: claude|ai|both"
    required: false
  - name: "--force"
    description: "Sync even with conflicts"
    action: "store_true"
  - name: "--resolve <strategy>"
    description: "Conflict resolution: newer|older|merge"
    required: false
examples:
  - invocation: '/context-sync --to both'
    description: "Sync both context files"
---
```

**2.3 `.claude/commands/context-status.md`**
```yaml
---
name: context-status
version: "1.0.0"
displayName: "Context Status"
description: "Check sync status between claude.md and ai_context.md"
category: "context-management"
arguments:
  - name: "--detailed"
    description: "Show detailed diff"
    action: "store_true"
  - name: "--json"
    description: "Output as JSON"
    action: "store_true"
examples:
  - invocation: '/context-status'
    description: "Check if context files are in sync"
---
```

**2.4 `.claude/commands/context-diff.md`**
```yaml
---
name: context-diff
version: "1.0.0"
displayName: "Context Diff"
description: "Show differences between context files"
category: "context-management"
arguments:
  - name: "--json"
    description: "Output as JSON"
    action: "store_true"
examples:
  - invocation: '/context-diff'
    description: "Show unified diff of context files"
---
```

**2.5 `.claude/agents/context-optimizer.md`**
```markdown
---
name: context-optimizer
version: "1.0.0"
displayName: "Context Optimizer"
description: "Agent for analyzing and optimizing context files with index-awareness"
category: "context-management"
complexity: "medium"
context_budget: "~15K tokens"
capabilities:
  - "context-analysis"
  - "redundancy-detection"
  - "index-awareness"
  - "recent-changes-detection"
  - "optimization-recommendations"
workflows:
  - "context-management"
  - "documentation-optimization"
commands: ["/context-opt", "/context-sync", "/context-status"]
examples:
  - invocation: '@context-optimizer "Analyze and optimize current context"'
    description: "Full context analysis and optimization"
  - invocation: '@context-optimizer "Sync context files and resolve conflicts"'
    description: "Bidirectional sync with conflict resolution"
---
```

**2.6 `.claude/agents/context-sync-agent.md`**
```markdown
---
name: context-sync-agent
version: "1.0.0"
displayName: "Context Sync Agent"
description: "Specialized agent for bidirectional sync between claude.md and ai_context.md"
category: "context-management"
complexity: "medium"
context_budget: "~10K tokens"
capabilities:
  - "bidirectional-sync"
  - "conflict-detection"
  - "timestamp-awareness"
  - "merge-resolution"
  - "backup-creation"
workflows:
  - "context-management"
  - "synchronization"
commands: ["/context-sync", "/context-diff", "/context-status"]
examples:
  - invocation: '@context-sync-agent "Sync all context files"'
    description: "Full bidirectional sync"
  - invocation: '@context-sync-agent "Resolve conflicts in context files"'
    description: "Detect and merge divergent changes"
---
```

**2.7 `src/context/generator.ts`**
```typescript
// Generate context files from database + indexes
export class ContextGenerator {
  constructor(private db: DatabaseClient, private projectRoot: string) {}

  async generateClaudeMD(): Promise<string>;
  async generateAIContextMD(): Promise<string>;
  async getIndexBasedContext(workflow?: string): Promise<ContextData>;
  async getRecentChanges(since?: Date): Promise<RecentChanges>;
  private generateQuickReference(data: ContextData): string;
  private generateRecentChanges(since?: Date): Promise<string>;
  private generateIndexBasedLookup(data: ContextData): Promise<string>;
}
```

**2.8 `src/context/sync-manager.ts`**
```typescript
// Bidirectional sync between claude.md and ai_context.md
export class ContextSyncManager {
  constructor(
    private db: DatabaseClient,
    private projectRoot: string,
    private timestampTracker: TimestampTracker
  ) {}

  async syncToAIContext(): Promise<SyncResult>;
  async syncToClaudeMD(): Promise<SyncResult>;
  async syncBoth(): Promise<SyncResult>;
  async detectDivergence(): Promise<DivergenceReport>;
  async resolveConflict(strategy: ConflictStrategy): Promise<void>;
  async createBackup(): Promise<string>;
}
```

**2.9 `src/context/types.ts`**
```typescript
export interface ContextData {
  project: ProjectInfo;
  techStack: TechStackInfo;
  architecture: ArchitectureInfo;
  workflows: WorkflowInfo[];
  commands: CommandInfo[];
  recentChanges: RecentChanges;
  indexes: IndexInfo;
}

export interface RecentChanges {
  commits: CommitInfo[];
  uncommitted: FileChange[];
  lastSync: Date;
}

export interface SyncResult {
  success: boolean;
  filesChanged: string[];
  conflicts: Conflict[];
  backupCreated?: string;
}
```

**2.10 `src/context/template.ts`** - Handlebars template for context files

**2.11 `tests/context/generator.test.ts`** - Test file

**2.12 `tests/context/sync-manager.test.ts`** - Test file

---

## Phase 3: Snapshots & Cleanup Commands

**Objective:** Timestamp-aware snapshot system with interactive cleanup agent

### New Files to Create

**3.1 `.claude/commands/snapshot-create.md`**
```yaml
---
name: snapshot-create
version: "1.0.0"
displayName: "Snapshot Create"
description: "Create a timestamped snapshot of context files and directories"
category: "snapshot-management"
arguments:
  - name: "<name>"
    description: "Snapshot name/description"
    required: true
  - name: "--paths <paths>"
    description: "Paths to include (comma-separated, defaults: .claude/ context/)"
    required: false
  - name: "--tag <tags>"
    description: "Tags to add (comma-separated)"
    required: false
examples:
  - invocation: '/snapshot-create "Before refactoring"'
    description: "Create snapshot before major work"
  - invocation: '/snapshot-create "Weekly backup" --tag weekly,manual'
    description: "Create tagged snapshot"
---
```

**3.2 `.claude/commands/snapshot-restore.md`**
```yaml
---
name: snapshot-restore
version: "1.0.0"
displayName: "Snapshot Restore"
description: "Restore context files and directories from a snapshot"
category: "snapshot-management"
arguments:
  - name: "<id>"
    description: "Snapshot ID, name, or partial match"
    required: true
  - name: "--dry-run"
    description: "Show what would be restored"
    action: "store_true"
  - name: "--paths <paths>"
    description: "Only restore specific paths"
    required: false
examples:
  - invocation: '/snapshot-restore "Before refactoring"'
    description: "Restore by name"
  - invocation: '/snapshot-restore snap-abc123 --dry-run'
    description: "Preview restoration"
---
```

**3.3 `.claude/commands/snapshot-list.md`**
```yaml
---
name: snapshot-list
version: "1.0.0"
displayName: "Snapshot List"
description: "List all available snapshots with filtering options"
category: "snapshot-management"
arguments:
  - name: "--tag <tag>"
    description: "Filter by tag"
    required: false
  - name: "--since <date>"
    description: "Filter snapshots created after date"
    required: false
  - name: "--limit <n>"
    description: "Limit results"
    required: false
  - name: "--json"
    description: "Output as JSON"
    action: "store_true"
examples:
  - invocation: '/snapshot-list --tag weekly --limit 5'
    description: "List recent weekly snapshots"
---
```

**3.4 `.claude/commands/snapshot-diff.md`**
```yaml
---
name: snapshot-diff
version: "1.0.0"
displayName: "Snapshot Diff"
description: "Compare two snapshots to see changes"
category: "snapshot-management"
arguments:
  - name: "<id1>"
    description: "First snapshot"
    required: true
  - name: "<id2>"
    description: "Second snapshot"
    required: true
examples:
  - invocation: '/snapshot-diff "Before" "After"'
    description: "Compare by name match"
---
```

**3.5 `.claude/commands/cleanup-scan.md`**
```yaml
---
name: cleanup-scan
version: "1.0.0"
displayName: "Cleanup Scan"
description: "Scan for files that can be cleaned up (snapshots, docs, contexts)"
category: "maintenance"
arguments:
  - name: "--area <name>"
    description: "Focus on: snapshots|docs|contexts|all"
    required: false
  - name: "--older-than <days>"
    description: "Only show items older than N days"
    required: false
  - name: "--larger-than <mb>"
    description: "Only show items larger than N MB"
    required: false
examples:
  - invocation: '/cleanup-scan --area snapshots --older-than 30'
    description: "Find old snapshots to clean"
---
```

**3.6 `.claude/commands/cleanup-interactive.md`**
```yaml
---
name: cleanup-interactive
version: "1.0.0"
displayName: "Cleanup Interactive"
description: "Interactive cleanup with prompts and snapshot backup"
category: "maintenance"
arguments:
  - name: "--snapshot-before"
    description: "Create snapshot before cleanup"
    action: "store_true"
  - name: "--yes"
    description: "Auto-confirm all prompts"
    action: "store_true"
examples:
  - invocation: '/cleanup-interactive --snapshot-before'
    description: "Interactive cleanup with backup"
---
```

**3.7 `.claude/agents/snapshot-manager.md`**
```markdown
---
name: snapshot-manager
version: "1.0.0"
displayName: "Snapshot Manager"
description: "Agent for managing context file snapshots with timestamp awareness"
category: "snapshot-management"
complexity: "medium"
context_budget: "~10K tokens"
capabilities:
  - "snapshot-creation"
  - "snapshot-restoration"
  - "snapshot-comparison"
  - "retention-policy"
  - "diff-generation"
workflows:
  - "snapshot-management"
  - "backup-restore"
commands: ["/snapshot-create", "/snapshot-restore", "/snapshot-list", "/snapshot-diff"]
examples:
  - invocation: '@snapshot-manager "Create snapshot before major refactoring"'
    description: "Snapshot current state"
  - invocation: '@snapshot-manager "Compare current state with last week"'
    description: "Diff snapshots for change analysis"
---
```

**3.8 `.claude/agents/cleanup-agent.md`**
```markdown
---
name: cleanup-agent
version: "1.0.0"
displayName: "Cleanup Agent"
description: "Interactive cleanup agent for snapshots, docs, and contexts with timestamp awareness"
category: "maintenance"
complexity: "medium"
context_budget: "~15K tokens"
capabilities:
  - "timestamp-aware-scanning"
  - "interactive-prompts"
  - "snapshot-backup"
  - "retention-policy"
  - "size-analysis"
  - "orphaned-file-detection"
workflows:
  - "maintenance"
  - "cleanup"
commands: ["/cleanup-scan", "/cleanup-interactive"]
examples:
  - invocation: '@cleanup-agent "Scan and clean old snapshots"'
    description: "Find and remove old snapshots"
  - invocation: '@cleanup-agent "Clean up orphaned docs with backup"'
    description: "Interactive docs cleanup with safety"
---
```

**3.9 `src/snapshots/manager.ts`**
```typescript
export class SnapshotManager {
  constructor(private db: DatabaseClient, private projectRoot: string) {}

  async createSnapshot(name: string, options: SnapshotOptions): Promise<Snapshot>;
  async restoreSnapshot(id: string, options: RestoreOptions): Promise<RestoreResult>;
  async listSnapshots(filter?: SnapshotFilter): Promise<Snapshot[]>;
  async diffSnapshots(id1: string, id2: string): Promise<SnapshotDiff>;
  async deleteSnapshot(id: string): Promise<void>;
  async autoCleanup(policy: RetentionPolicy): Promise<CleanupResult>;
  async getSnapshotSize(id: string): Promise<number>;
}
```

**3.10 `tests/snapshots/manager.test.ts`** - Test file

**3.11 `tests/cleanup/agent.test.ts`** - Test file

---

## Phase 4: Cross-Tool Sync Agent

**Objective:** Sync context to all AI tools with conflict resolution

### New Files to Create

**4.1 `.claude/commands/cross-tool-sync.md`**
```yaml
---
name: cross-tool-sync
version: "1.0.0"
displayName: "Cross-Tool Sync"
description: "Synchronize context changes to all AI tool configs (Copilot, Cursor, Cline, etc.)"
category: "synchronization"
arguments:
  - name: "--to <tools>"
    description: "Target tools: copilot,cursor,cline,windsurf,aider,continue,gemini"
    required: false
  - name: "--from <source>"
    description: "Source: claude|ai|both"
    required: false
  - name: "--check"
    description: "Only check for conflicts, don't sync"
    action: "store_true"
examples:
  - invocation: '/cross-tool-sync --to copilot,cursor'
    description: "Sync to specific tools"
---
```

**4.2 `.claude/agents/cross-tool-sync-agent.md`**
```markdown
---
name: cross-tool-sync-agent
version: "1.0.0"
displayName: "Cross-Tool Sync Agent"
description: "Propagate context changes to all AI tool configurations with conflict resolution"
category: "synchronization"
complexity: "high"
context_budget: "~20K tokens"
capabilities:
  - "multi-tool-sync"
  - "adapter-management"
  - "conflict-resolution"
  - "tool-config-detection"
  - "backup-creation"
workflows:
  - "synchronization"
  - "cross-tool-management"
commands: ["/cross-tool-sync"]
examples:
  - invocation: '@cross-tool-sync-agent "Sync latest context to all tools"'
    description: "Full cross-tool synchronization"
  - invocation: '@cross-tool-sync-agent "Check and resolve cross-tool conflicts"'
    description: "Conflict detection and resolution"
---
```

**4.3 `src/sync/cross-tool-engine.ts`**
```typescript
// Bidirectional sync across all AI tools
export class CrossToolSyncEngine {
  private adapters: Map<string, ContextAdapter>;

  registerAdapter(tool: string, adapter: ContextAdapter): void;
  async syncTo(targets: string[]): Promise<SyncResult[]>;
  async detectConflicts(): Promise<ConflictInfo[]>;
  async resolveConflicts(resolutions: ConflictResolution[]): Promise<void>;
}

export interface ContextAdapter {
  toolName: string;
  configPaths: string[];
  readContext(): Promise<string>;
  writeContext(content: string): Promise<void>;
  detectCustomChanges(): Promise<Change[]>;
}
```

**4.4 `src/sync/adapters/claude-code.ts`** - Claude Code adapter

**4.5 `src/sync/adapters/copilot.ts`** - GitHub Copilot adapter

**4.6 `src/sync/adapters/cursor.ts`** - Cursor adapter

**4.7 `src/sync/adapters/cline.ts`** - Cline adapter

**4.8 `src/sync/adapters/windsurf.ts`** - Windsurf adapter

**4.9 `src/sync/adapters/aider.ts`** - Aider adapter

**4.10 `src/sync/adapters/gemini.ts`** - Gemini adapter

**4.11 `src/sync/conflict-resolver.ts`**
```typescript
export class ConflictResolver {
  async resolve(conflict: ConflictInfo, strategy: ResolveStrategy): Promise<ResolvedContent>;
  async merge(contents: string[], strategies: MergeStrategy[]): Promise<string>;
}
```

**4.12 `tests/sync/cross-tool-engine.test.ts`** - Test file

---

## Phase 5: Integration & RPI Dispatch

**Objective:** Auto-invocation hooks and parallel RPI agent dispatcher

### New Files to Create

**5.1 `.claude/commands/dispatch-rpi.md`**
```yaml
---
name: dispatch-rpi
version: "1.0.0"
displayName: "Dispatch RPI"
description: "Dispatch up to 6 parallel RPI workflow agents (research/plan/implement)"
category: "agent-orchestration"
arguments:
  - name: "--workflow <name>"
    description: "RPI workflow to execute"
    required: true
  - name: "--parallel <n>"
    description: "Number of parallel agents (1-6, default: 6)"
    required: false
  - name: "--tasks <tasks>"
    description: "Comma-separated task descriptions"
    required: false
examples:
  - invocation: '/dispatch-rpi --workflow context-engineering --parallel 6'
    description: "Full parallel RPI workflow"
  - invocation: '/dispatch-rpi --workflow cleanup --parallel 3'
    description: "Focused parallel dispatch"
---
```

**5.2 `.claude/commands/workflow-route.md`**
```yaml
---
name: workflow-route
version: "1.0.0"
displayName: "Workflow Route"
description: "Route commands based on workflow context with automatic file detection"
category: "navigation"
arguments:
  - name: "<file>"
    description: "File path to detect workflow for"
    required: true
  - name: "--list"
    description: "List all workflow mappings"
    action: "store_true"
examples:
  - invocation: '/workflow-route src/db/schema.ts'
    description: "Detect workflow and show relevant commands"
  - invocation: '/workflow-route --list'
    description: "Show all workflow-to-command mappings"
---
```

**5.3 `.claude/agents/rpi-dispatcher.md`**
```markdown
---
name: rpi-dispatcher
version: "1.0.0"
displayName: "RPI Dispatcher"
description: "Dispatch up to 6 parallel RPI workflow agents with consolidated results"
category: "agent-orchestration"
complexity: "high"
context_budget: "~25K tokens"
capabilities:
  - "parallel-execution"
  - "result-consolidation"
  - "todolist-integration"
  - "workflow-routing"
  - "session-management"
workflows:
  - "rpi-workflow"
  - "parallel-execution"
commands: ["/dispatch-rpi", "/workflow-route"]
examples:
  - invocation: '@rpi-dispatcher "Research and plan context sync system"'
    description: "Parallel research and planning"
  - invocation: '@rpi-dispatcher "Full RPI cycle: research→plan→implement"'
    description: "Complete RPI workflow with 6 parallel agents"
---
```

**5.4 `.claude/agents/workflow-router.md`**
```markdown
---
name: workflow-router
version: "1.0.0"
displayName: "Workflow Router"
description: "Route commands based on workflow context and index awareness"
category: "navigation"
complexity: "medium"
context_budget: "~8K tokens"
capabilities:
  - "workflow-detection"
  - "index-awareness"
  - "command-routing"
  - "file-categorization"
workflows:
  - "navigation"
  - "context-lookup"
commands: ["/workflow-route"]
examples:
  - invocation: '@workflow-router "What workflow handles database schema?"'
    description: "Route question to correct workflow"
  - invocation: '@workflow-router "Show me all workflow commands"'
    description: "Display workflow-command mappings"
---
```

**5.5 `src/agent-system/dispatcher.ts`**
```typescript
// Parallel agent dispatcher (up to 6 concurrent)
export class AgentDispatcher {
  private maxConcurrent: number = 6;
  private activeAgents: Map<string, Agent>;

  async dispatch(agents: AgentConfig[]): Promise<AgentResult[]>;
  async dispatchRPI(workflow: string, options: RPIOptions): Promise<RPIResult>;
  private createTodoList(workflow: string, tasks: string[]): Promise<string>;
  private consolidateResults(results: AgentResult[]): Promise<ConsolidatedResult>;
}
```

**5.6 `src/integration/workflow-router.ts`**
```typescript
// Route commands based on workflow context
export class WorkflowRouter {
  async detectWorkflow(filePath: string): Promise<string>;
  async routeCommand(command: string, context: WorkflowContext): Promise<RouteResult>;
  async getWorkflowCommands(workflow: string): Promise<string[]>;
  async listAllWorkflows(): Promise<WorkflowMapping[]>;
}
```

**5.7 `tests/agent-system/dispatcher.test.ts`** - Test file

**5.8 `tests/integration/workflow-router.test.ts`** - Test file

---

## Database Migration

**File:** `src/db/migrations/0016_add_context_system_tables.sql`

```sql
-- Migration 0016: Context System and TodoList Support
-- From: 1.5.0
-- To: 1.6.0

-- Todo sessions (for tracking across compactions)
CREATE TABLE IF NOT EXISTS todo_sessions (
  id TEXT PRIMARY KEY,
  name TEXT NOT NULL,
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
  updated_at TEXT NOT NULL DEFAULT (datetime('now')),
  parent_session TEXT,
  metadata JSON
);

-- Todo tasks
CREATE TABLE IF NOT EXISTS todo_tasks (
  id TEXT PRIMARY KEY,
  session_id TEXT NOT NULL,
  subject TEXT NOT NULL,
  description TEXT,
  status TEXT NOT NULL DEFAULT 'pending',
  dependencies TEXT,
  assigned_to TEXT,
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
  updated_at TEXT NOT NULL DEFAULT (datetime('now')),
  completed_at TEXT,
  FOREIGN KEY (session_id) REFERENCES todo_sessions(id) ON DELETE CASCADE
);

-- Snapshots for context files
CREATE TABLE IF NOT EXISTS snapshots (
  id TEXT PRIMARY KEY,
  name TEXT NOT NULL,
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
  file_hashes TEXT NOT NULL,
  metadata JSON,
  tags TEXT
);

-- File timestamps for sync tracking
CREATE TABLE IF NOT EXISTS file_timestamps (
  path TEXT PRIMARY KEY,
  modified_time TEXT NOT NULL,
  size INTEGER NOT NULL,
  hash TEXT NOT NULL,
  last_checked TEXT NOT NULL DEFAULT (datetime('now')),
  git_commit TEXT
);

-- Cross-tool sync state
CREATE TABLE IF NOT EXISTS cross_tool_sync_state (
  tool TEXT PRIMARY KEY,
  context_path TEXT NOT NULL,
  last_synced TEXT,
  last_hash TEXT,
  last_sync_status TEXT,
  sync_count INTEGER DEFAULT 0,
  conflict_count INTEGER DEFAULT 0
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_snapshots_created ON snapshots(created_at);
CREATE INDEX IF NOT EXISTS idx_snapshots_tags ON snapshots(tags);
CREATE INDEX IF NOT EXISTS idx_todo_sessions_created ON todo_sessions(created_at);
CREATE INDEX IF NOT EXISTS idx_todo_tasks_session ON todo_tasks(session_id);
CREATE INDEX IF NOT EXISTS idx_todo_tasks_status ON todo_tasks(status);
CREATE INDEX IF NOT EXISTS idx_file_timestamps_checked ON file_timestamps(last_checked);
```

---

## Fixed Structure for claude.md / ai_context.md

Both files will follow this template structure:

```markdown
# {Project Name} - AI Context

> **Generated by k0ntext v{version}**
> **Last Updated:** {timestamp}
> **Sync Status:** {sync_status}

---

## Quick Reference

**Platform:** {platform_description}
**Tech Stack:** {primary_technologies}
**Repository:** {repo_url}
**Status:** {status}

---

## Essential Commands

{commands_table}

---

## Project Identity

{project_details}

---

## Recent Changes

> **Auto-generated from git commits and uncommitted changes**

### Latest Commits (Last 7)

{recent_commits}

### Uncommitted Changes

{uncommitted_changes}

---

## Architecture

{architecture_overview}

---

## Index-Based Context Lookup

### Workflows ({workflow_count})

{workflow_index}

### Code Domains ({code_domain_count})

{code_index}

### Agents ({agent_count})

{agent_index}

### Commands ({command_count})

{command_index}

---

## Key Files by Workflow

{workflow_file_mapping}

---

## Gotchas & Patterns

{gotchas}

---

## Sync Metadata

```json
{
  "generated_at": "{timestamp}",
  "k0ntext_version": "{version}",
  "claude_hash": "{hash}",
  "ai_context_hash": "{hash}",
  "last_commit": "{commit_sha}",
  "synced_tools": ["claude", "copilot", "cursor"]
}
```
```

---

## User Interaction Flows

### Flow 1: Context Optimization

```
User: /context-opt --analyze
       |
       v
[Scanning context files...]
       |
       v
[Context Analysis Report]
┌─────────────────────────────────────┐
│ Current Size: 85,234 tokens (42%)   │
│ Status: ⚠ Needs optimization        │
│                                     │
│ Issues Found:                       │
│ • Redundant sections (3)            │
│ • Outdated workflows (2)            │
│ • Missing recent changes (12)       │
└─────────────────────────────────────┘
       |
       v
? Apply optimizations? (Y/n)
       |
       +--Yes--> [Generating and syncing...]
```

### Flow 2: TodoList During Session

```
User: /todo-create "Implement snapshot system"
       |
       v
[✓ Todo session created: sess-abc123]
[ ] Research snapshot requirements
[ ] Design snapshot schema
[ ] Implement snapshot manager
[ ] Create snapshot commands
[ ] Write tests
       |
       v
[Session continues...]
[User completes tasks, compaction happens]
       |
       v
User: /todo-status
       |
       v
[Current Todo Session: sess-abc123]
[X] Research snapshot requirements ✓
[X] Design snapshot schema ✓
[ ] Implement snapshot manager
[ ] Create snapshot commands
[ ] Write tests
       |
       v
[Session continues from where it left off]
```

### Flow 3: Parallel RPI Dispatch

```
User: /dispatch-rpi --workflow context-engineering --parallel 6
       |
       v
[Initializing RPI workflow: context-engineering]
       |
       v
[Dispatching 6 parallel agents...]

Agent 1: @researcher (exploring/.claude/indexes)
Agent 2: @architect (analyzing workflows)
Agent 3: @database-ops (checking schema)
Agent 4: @integration-hub (examining MCP)
Agent 5: @context-optimizer (auditing context files)
Agent 6: @workflow-router (mapping commands)

       |
       v
[Creating TodoList for session: rpi-xyz]
┌────────────────────────────────────────────┐
│ [ ] Research current architecture          │
│ [ ] Design enhanced system                 │
│ [ ] Plan database changes                  │
│ [ ] Implement agent dispatcher             │
│ [ ] Test snapshot system                   │
│ [ ] Update context sync                   │
│ [ ] Verify cross-tool integration            │
└────────────────────────────────────────────┘
       |
       v
[All agents running in parallel...]
       |
       v
Agent 1: ✓ Found 15 workflow files
Agent 2: ✓ Identified 3 integration points
Agent 3: ✓ Schema v1.6.0 ready
Agent 4: ✓ 5 MCP tools to add
Agent 5: ✓ 2 context files diverged
Agent 6: ✓ 23 workflow-command mappings
       |
       v
[Consolidating results...]
       |
       v
[TodoList updated: 6/8 tasks completed]
```

---

## Verification Steps

### Manual Testing

1. **TodoList System:**
   ```bash
   # In AI session, invoke command
   /todo-create "Test session"

   # Check status
   /todo-status

   # Verify compaction survival
   # (Trigger compaction, then run /todo-status again)
   ```

2. **Context Files:**
   ```bash
   # In AI session
   /context-opt --analyze
   /context-sync --to both
   /context-status --detailed
   ```

3. **Snapshots:**
   ```bash
   /snapshot-create "Test snapshot"
   /snapshot-list
   /snapshot-restore <id>
   ```

4. **Cross-Tool Sync:**
   ```bash
   /cross-tool-sync --to copilot,cursor
   ```

5. **Parallel Dispatch:**
   ```bash
   /dispatch-rpi --workflow test --parallel 3
   ```

### Automated Tests

```bash
npm test                           # Run all tests
npm test -- agent-system          # Test agent system
npm test -- context               # Test context management
npm test -- snapshots             # Test snapshot system
npm test -- sync                  # Test cross-tool sync
```

---

## Rollback Plan

If issues arise:

1. **Per-phase rollback:** Git revert specific commits
2. **Database fallback:** Migration can be reversed
3. **Feature flags:** Add `K0NTEXT_EXPERIMENTAL_*` env vars

---

## Implementation Order

### Week 1: Foundation
- Day 1-2: TodoList manager, timestamp tracker
- Day 3-4: Database schema v1.6.0 and migration
- Day 5: Core service tests

### Week 2: Context System
- Day 1-2: Context generator, sync manager, types
- Day 3-4: Commands and agents (context:opt, sync, status, diff)
- Day 5: Testing and integration

### Week 3: Snapshots & Cleanup
- Day 1-2: Snapshot manager service
- Day 3-4: Commands and agents (snapshot:*, cleanup:*)
- Day 5: Testing and documentation

### Week 4: Cross-Tool Sync
- Day 1-3: Sync engine, adapters, conflict resolver
- Day 4-5: Commands, agents, and testing

### Week 5: Integration
- Day 1-2: Agent dispatcher, workflow router
- Day 3-4: Commands and agents (dispatch-rpi, workflow-route)
- Day 5: Final testing, MCP tools, documentation

---

## Estimation

- **Phase 1 (Foundation):** 4-6 hours
- **Phase 2 (Context System):** 6-8 hours
- **Phase 3 (Snapshots & Cleanup):** 5-7 hours
- **Phase 4 (Cross-Tool Sync):** 6-8 hours
- **Phase 5 (Integration):** 5-7 hours

**Total: 26-36 hours** for all five phases

---

## Files Summary by Phase

### Phase 1: Foundation
| Type | Files |
|-------|--------|
| Commands | `.claude/commands/todo-create.md`, `.claude/commands/todo-status.md` |
| Agents | `.claude/agents/todo-manager.md` |
| Services | `src/agent-system/todolist-manager.ts`, `src/agent-system/timestamp-tracker.ts` |
| Tests | `tests/agent-system/todolist-manager.test.ts`, `tests/agent-system/timestamp-tracker.test.ts` |

### Phase 2: Context System
| Type | Files |
|-------|--------|
| Commands | `.claude/commands/context-opt.md`, `.claude/commands/context-sync.md`, `.claude/commands/context-status.md`, `.claude/commands/context-diff.md` |
| Agents | `.claude/agents/context-optimizer.md`, `.claude/agents/context-sync-agent.md` |
| Services | `src/context/generator.ts`, `src/context/sync-manager.ts`, `src/context/types.ts`, `src/context/template.ts` |
| Tests | `tests/context/generator.test.ts`, `tests/context/sync-manager.test.ts` |

### Phase 3: Snapshots & Cleanup
| Type | Files |
|-------|--------|
| Commands | `.claude/commands/snapshot-create.md`, `.claude/commands/snapshot-restore.md`, `.claude/commands/snapshot-list.md`, `.claude/commands/snapshot-diff.md`, `.claude/commands/cleanup-scan.md`, `.claude/commands/cleanup-interactive.md` |
| Agents | `.claude/agents/snapshot-manager.md`, `.claude/agents/cleanup-agent.md` |
| Services | `src/snapshots/manager.ts` |
| Tests | `tests/snapshots/manager.test.ts`, `tests/cleanup/agent.test.ts` |

### Phase 4: Cross-Tool Sync
| Type | Files |
|-------|--------|
| Commands | `.claude/commands/cross-tool-sync.md` |
| Agents | `.claude/agents/cross-tool-sync-agent.md` |
| Services | `src/sync/cross-tool-engine.ts`, `src/sync/adapters/*.ts` (7 adapters), `src/sync/conflict-resolver.ts` |
| Tests | `tests/sync/cross-tool-engine.test.ts` |

### Phase 5: Integration
| Type | Files |
|-------|--------|
| Commands | `.claude/commands/dispatch-rpi.md`, `.claude/commands/workflow-route.md` |
| Agents | `.claude/agents/rpi-dispatcher.md`, `.claude/agents/workflow-router.md` |
| Services | `src/agent-system/dispatcher.ts`, `src/integration/workflow-router.ts` |
| Tests | `tests/agent-system/dispatcher.test.ts`, `tests/integration/workflow-router.test.ts` |

---

## Index & Context Folder Integration

All agents and commands will be **index-aware**, meaning they:

1. **Read from `.claude/indexes/`** to understand project structure
2. **Reference `.claude/context/`** for project context data
3. **Update indexes** when new workflows/agents/commands are added
4. **Maintain cross-references** between related files
5. **Use semantic RAG** when database is available for context lookup

---

## Sync Strategy: claude.md ↔ ai_context.md

### Bidirectional Sync Rules:

1. **Timestamp Awareness:** Track modification time and git commit for each file
2. **Conflict Detection:** Compare hashes to detect divergence
3. **Merge Strategy:** Offer options: newer, older, manual merge, both
4. **Backup Before Sync:** Always create timestamped backup before overwriting
5. **Sync Metadata:** JSON footer with sync status for verification

### Git Hook Integration:

- **pre-commit:** Check if claude.md or ai_context.md is staged → trigger sync
- **post-commit:** Record sync state in database
- **post-merge:** Run conflict resolution and auto-sync

---

**Next Steps:** User reviews plan, asks questions, requests approval → ExitPlanMode
