Skill: wenkangwei/long-running-agent-harness (version 1.0.0)

--- name: agent-harness description: Long-running agent workflow automation. Initialize project scaffolding, manage feature lists, track progress across sessions, and orchestrate coding agents. version: 1.0.0 author: wwk commands: - harness-init - harness-run - harness-status - harness-feature - harness-commit --- # Agent Harness Skill Automates the long-running agent workflow from Anthropic's engineering blog. Manages feature lists, progress tracking, and session orchestration across multiple Claude Code sessions. ## Commands ### /harness-init <project-description> Initialize a new project with: - `feature_list.json` — comprehensive feature tracking - `claude-progress.txt` — cross-session progress log - `init.sh` — development server startup script - `.harness.json` — harness configuration ### /harness-run Start a coding session. Reads progress, picks the next feature, and follows the incremental development workflow. ### /harness-status Show current project progress: features completed, next features to implement, recent session history. ### /harness-feature <description> Add a new feature to the feature list. ### /harness-commit Commit current work with structured message and update progress file. ## Architecture ``` ┌─────────────┐ ┌──────────────┐ ┌──────────────┐ │ Initializer │────▶│ Coding Agent│────▶│ Next Coding│ │ Agent │ │ Session #1 │ │ Agent #2 │ └─────────────┘ └──────────────┘ └──────────────┘ │ │ │ ▼ ▼ ▼ ┌─────────────────────────────────────────────────────────┐ │ Shared State │ │ ┌───────────────┐ ┌──────────────┐ ┌────────────────┐ │ │ │feature_list │ │claude-progress│ │ Git History │ │ │ │ .json │ │ .txt │ │ (commits) │ │ │ └───────────────┘ └──────────────┘ └────────────────┘ │ └─────────────────────────────────────────────────────────┘ ``` ## Workflow 1. **Init**: `harness init "Build a chat app"` — sets up project skeleton 2. **Code**: `harness run` — each session picks ONE feature 3. **Track**: Features marked passing only after end-to-end testing 4. **Commit**: Progress documented in git + progress file 5. **Repeat**: Continue until all features pass ## Key Principles - **Incremental**: One feature per session - **Tested**: End-to-end testing before marking complete - **Clean state**: Always leave codebase merge-ready - **Persistent state**: Git + progress file bridge context windows

path: README.md
content: # Agent Harness Framework

基于 [Anthropic 工程博客 — Effective Harnesses for Long-Running Agents](https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents) 的长周期 Agent 自动化编码框架。

解决的核心问题：**AI Agent 如何在多个上下文窗口（context window）之间持续、稳定地推进复杂项目？**

---

## 原理

### 问题

让 AI Agent 构建一个完整应用时，常见的失败模式：

| 问题 | 表现 |
|------|------|
| 一次做太多 | Agent 试图一次性写完整个应用，context 耗尽后留下半成品 |
| 过早宣告完成 | 看到"差不多"就宣布完工，实际大量功能缺失 |
| 不测试就标记完成 | 代码写了就标 done，端到端根本跑不通 |
| 会话间无记忆 | 新 session 从零开始，不知道上一个 session 做了什么 |
| 环境残留 bug | 上次留下的 bug 没修，新功能叠加上去更糟 |

### 解决方案：两阶段 Agent + 共享状态

核心思想：**像交接班的工程师团队一样工作**——每个 Agent 上班先读交接日志，做完一个任务后写清楚交接再下班。

```
┌─────────────┐     ┌──────────────┐     ┌──────────────┐
│  Initializer │────▶│ Coding Agent │────▶│ Coding Agent │ ──▶ ...
│  (运行一次)   │     │  Session #1  │     │  Session #2  │
└─────────────┘     └──────────────┘     └──────────────┘
      │                    │                     │
      ▼                    ▼                     ▼
┌─────────────────────────────────────────────────────────┐
│                    共享状态 (跨会话持久化)                  │
│  feature_list.json  │  claude-progress.txt  │  Git 历史  │
└─────────────────────────────────────────────────────────┘
```

**三个关键机制：**

1. **Feature List（特性列表）** — 把项目拆成一个个可独立验证的小特性，全标为 `passes: false`，做完一个标记一个，避免"差不多就完事"
2. **Progress File（进度文件）** — 每个 session 结束时记录做了什么、什么能用、什么坏了、下一步是什么，下一个 Agent 上来先读这个
3. **Git History（提交历史）** — 每次改动都 commit，坏了可以 revert，新 Agent 通过 `git log` 快速了解历史

---

## 架构总览

```mermaid
graph TB
    subgraph SHARED["📦 共享状态 — 跨会话持久化"]
        FL["📄 feature_list.json<br/>• 特性 ID & 描述<br/>• 测试步骤<br/>• passes: true/false"]
        CP["📝 claude-progress.txt<br/>• 会话日志<br/>• 完成/故障/下一步"]
        GIT["🔀 Git 历史<br/>• 描述性提交<br/>• 可回滚"]
        INIT["⚙️ init.sh<br/>• 启动/停止开发服务器"]
    end

    USER["👤 用户"] -->|harness init| INIT_AGENT
    INIT_AGENT["🟢 初始化 Agent<br/><i>仅运行一次</i>"]
    CODER1["🟡 编码 Agent #1"]
    CODER2["🟡 编码 Agent #2"]
    CODERN["🟡 编码 Agent #N"]

    INIT_AGENT -->|创建| FL
    INIT_AGENT -->|创建| CP
    INIT_AGENT -->|创建| INIT
    INIT_AGENT -->|初始提交| GIT

    INIT_AGENT -->|交接| CODER1
    CODER1 -->|读/写| FL
    CODER1 -->|读/追加| CP
    CODER1 -->|提交| GIT
    CODER1 -->|交接| CODER2
    CODER2 -->|读/写| FL
    CODER2 -->|读/追加| CP
    CODER2 -->|提交| GIT
    CODER2 -->|... 重复| CODERN
    CODERN -->|全部通过 ✓| DONE["🎉 完成"]

    style INIT_AGENT fill:#a5d6a7
    style CODER1 fill:#fff9c4
    style CODER2 fill:#fff9c4
    style CODERN fill:#fff9c4
    style USER fill:#bbdefb
    style SHARED fill:#f5f5f5
    style DONE fill:#c8e6c9
```

---

## 会话流程

每个编码 session 的标准操作流程：

```mermaid
sequenceDiagram
    actor User
    participant Init as 🟢 初始化 Agent
    participant C1 as 🟡 编码 Agent #1
    participant C2 as 🟡 编码 Agent #2
    participant FL as 📄 feature_list
    participant CP as 📝 progress
    participant Git as 🔀 Git
    participant Srv as ⚙️ init.sh

    rect rgb(200, 230, 201)
        Note over User,Srv: 阶段 1 — 初始化（仅一次）
        User->>Init: "构建一个任务管理应用"
        Init->>FL: 创建 feature_list.json
        Init->>CP: 创建 progress.txt
        Init->>Srv: 创建 init.sh
        Init->>Git: git init + 初始提交
        Init-->>User: "就绪，N 个特性已规划"
    end

    rect rgb(255, 249, 196)
        Note over User,Srv: 阶段 2 — 编码会话（重复）
        User->>C1: harness run
        C1->>CP: 读取进度日志
        C1->>Git: 查看提交历史
        C1->>FL: 读取特性列表，选下一个
        C1->>Srv: 启动开发服务器
        C1->>C1: 冒烟测试（坏了先修）
        C1->>C1: 实现一个特性
        C1->>C1: 端到端测试
        C1->>FL: 标记 passes=true
        C1->>Git: git commit
        C1->>CP: 追加会话记录
        C1-->>User: "完成特性 F001"
    end

    rect rgb(255, 249, 196)
        Note over User,Srv: 下一个会话...
        User->>C2: harness run
        C2->>CP: 读取进度
        C2->>Git: 查看历史
        C2->>FL: 选下一个特性
        C2->>Srv: 启动服务器 + 冒烟测试
        C2->>C2: 实现 + 测试 + 提交
        C2-->>User: "完成特性 F002"
    end
```

---

## 文件关系

框架组件与目标项目之间的映射：

```mermaid
graph LR
    subgraph HARNESS["🔧 Agent Harness 框架"]
        subgraph TEMPLATES["📁 templates/"]
            t1["feature_list.json"]
            t2["claude-progress.txt"]
            t3["init.sh"]
        end
        subgraph PROMPTS["📁 prompts/"]
            p1["initializer.md"]
            p2["coder.md"]
        end
        subgraph SCRIPTS["📁 scripts/"]
            h["harness.sh<br/>init | run<br/>status | reset"]
        end
    end

    subgraph TARGET["🎯 目标项目"]
        l1["feature_list.json"]
        l2["claude-progress.txt"]
        l3["init.sh"]
        l4[".harness.json"]
        code["源代码"]
        gh["Git 历史"]
    end

    h -->|复制模板| t1
    h -->|复制模板| t2
    h -->|复制模板| t3
    t1 -->|harness init| l1
    t2 -->|harness init| l2
    t3 -->|harness init| l3
    h -->|创建| l4
    p2 -.->|指导 Agent 读写| l1
    p2 -.->|指导 Agent 追加| l2
    p2 -.->|指导 Agent 提交| gh
    p2 -.->|指导 Agent 实现| code

    style HARNESS fill:#f3e5f5
    style TARGET fill:#e8f5e9
```

---

## 项目结构

```
agent-harness/
├── README.md                          # 本文件
├── SKILL.md                           # Claude Code Skill 文档
├── skill.json                         # Skill 配置
├── templates/                         # 模板文件
│   ├── feature_list.json              #   特性跟踪模板
│   ├── claude-progress.txt            #   进度日志模板
│   └── init.sh                        #   开发服务器脚本模板
├── prompts/                           # Agent 提示词
│   ├── initializer.md                 #   初始化 Agent 提示词
│   └── coder.md                       #   编码 Agent 提示词
├── scripts/                           # 自动化脚本
│   └── harness.sh                     #   主控脚本
└── docs/                              # 文档 & 图表
    ├── architecture.md                #   架构总览图
    ├── sequence.md                    #   会话时序图
    ├── file-flow.md                   #   文件关系图
    ├── architecture.puml              #   PlantUML 源文件
    ├── sequence.puml
    └── file-flow.puml
```

---

## 快速开始

### 1. 初始化项目

```bash
# 在你的项目目录下运行
cd /path/to/your/project
/path/to/agent-harness/scripts/harness.sh init "构建一个任务管理应用，支持创建、编辑、删除任务"
```

这会在你的项目中创建：
- `feature_list.json` — 特性列表
- `claude-progress.txt` — 进度日志
- `init.sh` — 开发服务器脚本
- `.harness.json` — 框架配置

### 2. 用初始化 Agent 生成完整特性列表

将 `prompts/initializer.md` 的内容复制给 Claude，附上你的项目描述。Agent 会：
- 把项目拆解成 15-50+ 个可独立验证的特性
- 创建项目骨架和依赖
- 做第一次 git commit

### 3. 编码 Agent 增量推进

每个 session 用 `prompts/coder.md` 启动 Claude：

```bash
# 查看当前进度
./scripts/harness.sh status
```

每个 session 的标准流程：
1. 读进度文件 + git 历史
2. 选下一个未完成的特性
3. 启动开发服务器 + 冒烟测试
4. 实现一个特性 + 端到端测试
5. 提交代码 + 更新进度文件

### 4. 持续推进直到完成

重复步骤 3，直到所有特性都标记为 `passes: true`。

---

## 作为 Claude Code Skill 使用

本项目也可作为 Claude Code 的 Skill 集成，提供以下命令：

| 命令 | 说明 |
|------|------|
| `harness init <desc>` | 初始化新项目 |
| `harness run` | 开始编码会话 |
| `harness status` | 查看进度 |
| `harness feature <desc>` | 添加新特性 |
| `harness commit` | 提交并更新进度 |
| `harness reset` | 重置框架 |

---

## 核心原则

1. **增量推进** — 每次 session 只做一个特性，不贪多
2. **端到端验证** — 像人类用户一样测试，不只看单元测试
3. **干净交接** — 每次离开时代码状态等同于可合并到 main
4. **持久状态** — feature_list + progress + git 三重状态桥接上下文窗口
5. **先修后建** — 如果已有功能坏了，先修再开发新功能

---

## 参考

- [Anthropic — Effective Harnesses for Long-Running Agents](https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents)
- [Claude Agent SDK](https://github.com/anthropics/claude-agent-sdk)
- [Claude 4 Prompting Guide](https://docs.anthropic.com/en/docs/about-claude/models)


path: skill.json
content: {
  "name": "agent-harness",
  "displayName": "Agent Harness",
  "version": "1.0.0",
  "description": "Long-running agent workflow automation — feature tracking, progress management, and session orchestration across multiple Claude Code sessions",
  "author": "wwk",
  "category": "automation",
  "capabilities": [
    "project-initialization",
    "feature-tracking",
    "progress-management",
    "session-orchestration",
    "automated-testing-workflow"
  ],
  "commands": {
    "harness-init": {
      "description": "Initialize a new project with harness templates",
      "parameters": {
        "description": {
          "type": "string",
          "required": true,
          "description": "High-level project description"
        }
      }
    },
    "harness-run": {
      "description": "Start a coding session with the incremental workflow",
      "parameters": {}
    },
    "harness-status": {
      "description": "Show current project progress and next features",
      "parameters": {}
    },
    "harness-feature": {
      "description": "Add a new feature to the feature list",
      "parameters": {
        "description": {
          "type": "string",
          "required": true,
          "description": "Feature description"
        },
        "priority": {
          "type": "number",
          "required": false,
          "description": "Priority level (1-5, default 3)"
        }
      }
    },
    "harness-commit": {
      "description": "Commit current work and update progress",
      "parameters": {}
    }
  },
  "files": {
    "templates": {
      "feature_list.json": "Feature tracking template",
      "claude-progress.txt": "Progress log template",
      "init.sh": "Development server startup script template"
    },
    "prompts": {
      "initializer.md": "Initializer agent prompt",
      "coder.md": "Coding agent prompt"
    },
    "scripts": {
      "harness.sh": "Main harness orchestrator script"
    }
  },
  "dependencies": {
    "bash": ">=4.0",
    "git": ">=2.0",
    "python3": ">=3.7"
  }
}


path: templates/claude-progress.txt
content: # Agent Progress Log
# ===================
# Project: {{PROJECT_NAME}}
# Created: {{TIMESTAMP}}
#
# Format: Each agent session appends an entry below.
# Include: what you did, what works, what's broken, and what's next.
# This file is the PRIMARY communication channel between agent sessions.
# =======================================================================

## Session 1 — Initializer Agent
- **Date**: {{TIMESTAMP}}
- **Agent**: initializer
- **Status**: Project scaffolded
- **Done**:
  - Created project structure
  - Set up feature_list.json
  - Created init.sh development script
  - Initial git commit
- **Working**: Basic project skeleton
- **Broken**: Nothing yet
- **Next**: Start implementing features from feature_list.json in priority order


path: templates/feature_list.json
content: {
  "project": "{{PROJECT_NAME}}",
  "created_at": "{{TIMESTAMP}}",
  "description": "{{PROJECT_DESCRIPTION}}",
  "features": [
    {
      "id": "F001",
      "category": "setup",
      "priority": 1,
      "description": "Project skeleton is initialized and runs without errors",
      "steps": [
        "Run init.sh to start development server",
        "Verify server starts without errors",
        "Check basic health endpoint responds"
      ],
      "passes": false
    },
    {
      "id": "F002",
      "category": "functional",
      "priority": 2,
      "description": "TODO: Add your first feature here",
      "steps": [
        "TODO: Define test steps"
      ],
      "passes": false
    }
  ],
  "summary": {
    "total": 2,
    "passing": 0,
    "failing": 2
  }
}


path: templates/init.sh
content: #!/bin/bash
# ============================================================
# Development Server Init Script
# ============================================================
# This script starts the development environment.
# Customize the commands below to match your project stack.
#
# Usage:
#   chmod +x init.sh
#   ./init.sh          # Start servers
#   ./init.sh stop     # Stop servers
#   ./init.sh restart  # Restart servers
# ============================================================

set -e

PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$PROJECT_DIR"

# --- Configuration ---
# BACKEND_PORT=8000
# FRONTEND_PORT=3000
# PID_DIR="$PROJECT_DIR/.pids"

stop_servers() {
    echo "Stopping servers..."
    # kill $(cat "$PID_DIR/backend.pid" 2>/dev/null) 2>/dev/null || true
    # kill $(cat "$PID_DIR/frontend.pid" 2>/dev/null) 2>/dev/null || true
    # rm -rf "$PID_DIR"
    echo "Servers stopped."
}

start_servers() {
    echo "Starting development servers..."
    # mkdir -p "$PID_DIR"

    # --- Backend ---
    # echo "Starting backend..."
    # cd "$PROJECT_DIR/backend"
    # source venv/bin/activate
    # python -m uvicorn app.main:app --port $BACKEND_PORT &
    # echo $! > "$PID_DIR/backend.pid"

    # --- Frontend ---
    # echo "Starting frontend..."
    # cd "$PROJECT_DIR/frontend"
    # npm run dev -- --port $FRONTEND_PORT &
    # echo $! > "$PID_DIR/frontend.pid"

    # Wait for servers to be ready
    # echo "Waiting for servers to be ready..."
    # sleep 3

    echo "Development servers started."
    # echo "  Backend:  http://localhost:$BACKEND_PORT"
    # echo "  Frontend: http://localhost:$FRONTEND_PORT"
}

case "${1:-start}" in
    start)   start_servers ;;
    stop)    stop_servers ;;
    restart) stop_servers; sleep 1; start_servers ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac


path: scripts/harness.sh
content: #!/bin/bash
# ============================================================
# Agent Harness — Main Orchestrator
# ============================================================
# Automates the long-running agent workflow described in
# Anthropic's "Effective Harnesses for Long-Running Agents"
#
# Usage:
#   ./harness.sh init "Build a task management app"  # First run
#   ./harness.sh run                                  # Coding session
#   ./harness.sh status                               # Check progress
#   ./harness.sh reset                                # Reset project
# ============================================================

set -euo pipefail

HARNESS_DIR="$(cd "$(dirname "$0")/.." && pwd)"
TEMPLATES_DIR="$HARNESS_DIR/templates"
PROMPTS_DIR="$HARNESS_DIR/prompts"
WORK_DIR="${PROJECT_DIR:-$(pwd)}"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log()  { echo -e "${BLUE}[HARNESS]${NC} $*"; }
ok()   { echo -e "${GREEN}[OK]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
err()  { echo -e "${RED}[ERROR]${NC} $*" >&2; }

# ----------------------------------------------------------
# init — Initialize a new project with the harness
# ----------------------------------------------------------
cmd_init() {
    local description="${1:?Usage: harness.sh init \"<project description>\"}"

    if [[ -f "$WORK_DIR/feature_list.json" ]]; then
        err "Project already initialized. Use 'harness.sh reset' to start over."
        exit 1
    fi

    log "Initializing agent harness..."

    # Copy templates
    cp "$TEMPLATES_DIR/feature_list.json" "$WORK_DIR/feature_list.json"
    cp "$TEMPLATES_DIR/claude-progress.txt" "$WORK_DIR/claude-progress.txt"
    cp "$TEMPLATES_DIR/init.sh" "$WORK_DIR/init.sh"
    chmod +x "$WORK_DIR/init.sh"

    # Initialize git if needed
    if [[ ! -d "$WORK_DIR/.git" ]]; then
        git init "$WORK_DIR"
        log "Initialized git repository."
    fi

    # Create .harness config
    cat > "$WORK_DIR/.harness.json" <<EOF
{
  "initialized_at": "$(date -Iseconds)",
  "description": $(echo "$description" | python3 -c 'import sys,json; print(json.dumps(sys.stdin.read().strip()))'),
  "session_count": 0,
  "current_phase": "initialization"
}
EOF

    log "Project description: $description"
    log ""
    log "Templates copied to project root:"
    log "  - feature_list.json   (feature tracking)"
    log "  - claude-progress.txt (progress log)"
    log "  - init.sh             (dev server script)"
    log "  - .harness.json       (harness config)"
    log ""
    ok "Harness initialized! Now run the initializer agent prompt."
    log ""
    log "  cat $PROMPTS_DIR/initializer.md"
    log ""
    log "Then paste it to Claude with your project description."
}

# ----------------------------------------------------------
# run — Start a coding session
# ----------------------------------------------------------
cmd_run() {
    if [[ ! -f "$WORK_DIR/feature_list.json" ]]; then
        err "Project not initialized. Run 'harness.sh init \"<description>\"' first."
        exit 1
    fi

    # Increment session counter
    local sessions=$(python3 -c "
import json
with open('$WORK_DIR/.harness.json') as f:
    d = json.load(f)
d['session_count'] = d.get('session_count', 0) + 1
d['current_phase'] = 'coding'
with open('$WORK_DIR/.harness.json', 'w') as f:
    json.dump(d, f, indent=2)
print(d['session_count'])
")

    log "Starting coding session #$sessions"
    log ""
    log "Startup checklist:"
    log "  1. pwd"
    log "  2. Read claude-progress.txt"
    log "  3. Read feature_list.json"
    log "  4. git log --oneline -20"
    log "  5. Run ./init.sh"
    log "  6. Pick next feature & implement"
    log ""
    log "Coding agent prompt:"
    log ""
    cat "$PROMPTS_DIR/coder.md"
}

# ----------------------------------------------------------
# status — Show current progress
# ----------------------------------------------------------
cmd_status() {
    if [[ ! -f "$WORK_DIR/feature_list.json" ]]; then
        err "Project not initialized."
        exit 1
    fi

    log "Project Status"
    log "=============="

    # Parse feature list
    python3 -c "
import json
with open('$WORK_DIR/feature_list.json') as f:
    data = json.load(f)
features = data.get('features', [])
total = len(features)
passing = sum(1 for f in features if f.get('passes'))
failing = total - passing
pct = (passing / total * 100) if total > 0 else 0

print(f'  Project: {data.get(\"project\", \"?\")}')
print(f'  Features: {passing}/{total} passing ({pct:.1f}%)')
print()

# Progress bar
bar_len = 40
filled = int(bar_len * pct / 100)
bar = '█' * filled + '░' * (bar_len - filled)
print(f'  [{bar}] {pct:.1f}%')
print()

# Next features to work on
next_features = [f for f in features if not f.get('passes')]
next_features.sort(key=lambda x: x.get('priority', 99))
if next_features:
    print('  Next features to implement:')
    for f in next_features[:5]:
        print(f'    [{f[\"id\"]}] P{f.get(\"priority\",\"?\")} — {f[\"description\"][:60]}')
    if len(next_features) > 5:
        print(f'    ... and {len(next_features) - 5} more')
else:
    print('  ALL FEATURES COMPLETE!')
"

    # Show recent progress
    if [[ -f "$WORK_DIR/claude-progress.txt" ]]; then
        echo ""
        log "Recent progress (last 10 lines):"
        tail -10 "$WORK_DIR/claude-progress.txt" | sed 's/^/  /'
    fi

    # Session count
    if [[ -f "$WORK_DIR/.harness.json" ]]; then
        local sessions=$(python3 -c "import json; print(json.load(open('$WORK_DIR/.harness.json')).get('session_count', 0))")
        echo ""
        log "Total sessions: $sessions"
    fi
}

# ----------------------------------------------------------
# reset — Reset the harness (keeps code, resets tracking)
# ----------------------------------------------------------
cmd_reset() {
    warn "This will remove harness tracking files. Your code will be preserved."
    read -p "Continue? [y/N] " confirm
    if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
        log "Cancelled."
        exit 0
    fi

    rm -f "$WORK_DIR/feature_list.json"
    rm -f "$WORK_DIR/claude-progress.txt"
    rm -f "$WORK_DIR/.harness.json"
    rm -f "$WORK_DIR/init.sh"
    ok "Harness reset. Run 'harness.sh init' to start fresh."
}

# ----------------------------------------------------------
# generate — Generate a feature list using AI
# ----------------------------------------------------------
cmd_generate() {
    local description="${1:?Usage: harness.sh generate \"<project description>\"}"

    log "Generating feature list for: $description"
    log ""
    log "Copy the following prompt to Claude to generate your feature list:"
    log ""
    echo "---PROMPT START---"
    echo "Based on this project description, generate a comprehensive feature_list.json:"
    echo ""
    echo "\"$description\""
    echo ""
    echo "Requirements:"
    echo "1. List ALL features needed, ordered by priority"
    echo "2. Each feature must be end-to-end testable"
    echo "3. Include setup/infrastructure features first"
    echo "4. Use categories: setup, functional, ui, api, data, polish"
    echo "5. Format as valid JSON matching this schema:"
    cat "$TEMPLATES_DIR/feature_list.json"
    echo "---PROMPT END---"
}

# ----------------------------------------------------------
# Main
# ----------------------------------------------------------
case "${1:-help}" in
    init)     cmd_init "$2" ;;
    run)      cmd_run ;;
    status)   cmd_status ;;
    reset)    cmd_reset ;;
    generate) cmd_generate "$2" ;;
    help|*)
        echo "Agent Harness — Long-Running Agent Workflow"
        echo ""
        echo "Usage:"
        echo "  harness.sh init \"<description>\"   Initialize new project"
        echo "  harness.sh run                     Start coding session"
        echo "  harness.sh status                  Show progress"
        echo "  harness.sh generate \"<desc>\"       Generate feature list prompt"
        echo "  harness.sh reset                   Reset harness tracking"
        ;;
esac


path: prompts/coder.md
content: # Coding Agent Prompt

You are the **Coding Agent** in a long-running project. You make incremental progress on ONE feature per session, test it thoroughly, and leave clear state for the next agent.

## Startup Sequence (EVERY session)

Follow these steps IN ORDER at the start of every session:

### Step 1: Get Your Bearings
```
pwd                    # Know your working directory
```

### Step 2: Read Progress & History
- Read `claude-progress.txt` — understand what previous agents have done
- Run `git log --oneline -20` — see recent commits
- Understand current state before touching any code

### Step 3: Review Feature List
- Read `feature_list.json`
- Find the highest-priority feature that is NOT yet passing
- This is your target feature for this session

### Step 4: Start Development Environment
- Read `init.sh` and run it to start servers
- Run a basic smoke test to verify the app isn't broken
- If broken: FIX existing bugs BEFORE implementing new features

## Implementation Workflow

### Step 1: Implement ONE Feature
- Work on ONLY the chosen feature
- Write clean, minimal code
- Follow existing project patterns and conventions

### Step 2: Test End-to-End
- Test the feature as a HUMAN user would
- For web apps: use browser automation tools
- For APIs: use curl/httpie to hit real endpoints
- For CLIs: run the actual commands
- Do NOT rely solely on unit tests — verify end-to-end

### Step 3: Update Feature List
- ONLY change `passes: false` to `passes: true` for completed features
- NEVER remove or edit existing feature descriptions or test steps
- NEVER mark a feature as passing unless you've tested it end-to-end

### Step 4: Commit & Document
```bash
git add -A
git commit -m "feat: [feature-id] Brief description of what was done"
```

### Step 5: Update Progress File
Append to `claude-progress.txt`:
```
## Session N — Coding Agent
- **Date**: [timestamp]
- **Agent**: coder
- **Feature**: [feature-id] - [description]
- **Status**: completed | partial | blocked
- **Done**:
  - [What was implemented]
- **Working**: [What's confirmed working]
- **Broken**: [Any known issues, or "Nothing"]
- **Next**: [Suggested next feature or action]
```

## Critical Rules

1. **ONE feature per session** — don't try to do too much
2. **Clean state** — leave the codebase as if you'd merge it to main
3. **Test before declare** — never mark a feature done without testing
4. **Don't remove tests** — it's unacceptable to remove or edit test steps
5. **Git is your friend** — use `git diff`, `git log`, `git stash` to manage state
6. **If stuck, revert** — `git checkout .` and try a different approach
7. **Be specific in progress** — the next agent has NO memory of your session
8. **Fix before build** — if existing features are broken, fix them first

## When You're Done
1. Ensure all tests pass
2. Ensure dev server is still running
3. Commit with descriptive message
4. Update progress file
5. Output summary of what was accomplished


path: prompts/initializer.md
content: # Initializer Agent Prompt

You are the **Initializer Agent** for a long-running coding project. Your job is to set up the foundational environment that all future coding sessions will build upon. You only run ONCE — at the very beginning of the project.

## Your Task

Given the user's project description, you must:

### 1. Understand the Requirements
- Parse the user's high-level project description
- Break it down into concrete, testable features

### 2. Create the Feature List (`feature_list.json`)
- Generate a comprehensive JSON file listing ALL features needed
- Each feature must have:
  - `id`: Sequential identifier (F001, F002, ...)
  - `category`: functional | ui | api | data | setup
  - `priority`: 1 (highest) to 5 (lowest)
  - `description`: Clear, specific, end-to-end testable description
  - `steps`: Array of concrete verification steps
  - `passes`: false (all start as failing)
- Include at least 15-30 features for a medium project, 50+ for large projects
- Order by priority: setup → core features → polish → nice-to-have

### 3. Create the Progress File (`claude-progress.txt`)
- Initialize with project name and timestamp
- Document what you've set up
- Note what the next agent should work on first

### 4. Create `init.sh`
- Write a shell script that can start the development server(s)
- Include start/stop/restart commands
- Make it executable

### 5. Initialize Git
- Create the git repository
- Add all initial files
- Make the first commit with a descriptive message

### 6. Set Up Project Skeleton
- Create the basic project structure (directories, configs, package files)
- Install necessary dependencies
- Ensure the project can at least start without errors

## Important Rules
- Be thorough in the feature list — it's the roadmap for all future sessions
- Each feature should be small enough to complete in one session
- Features must be end-to-end testable (not just "code exists")
- Leave the environment in a CLEAN state: no bugs, no half-implemented features
- Document everything clearly in the progress file

## Output Format
After completing setup, output a summary:
1. Number of features planned
2. Project structure created
3. Dependencies installed
4. Next priority feature for the coding agent


path: docs/architecture.md
content: # Agent Harness — Architecture Overview
> Based on Anthropic's "Effective Harnesses for Long-Running Agents"

```mermaid
graph TB
    subgraph SHARED["📦 Shared State (Persists Across Sessions)"]
        FL["📄 feature_list.json<br/>• Feature ID & Description<br/>• Test Steps<br/>• passes: true/false"]
        CP["📝 claude-progress.txt<br/>• Session log<br/>• What was done / broken / next"]
        GIT["🔀 Git History<br/>• Descriptive commits<br/>• Revert capability"]
        INIT["⚙️ init.sh<br/>• Start/Stop dev server<br/>• Environment setup"]
    end

    USER["👤 User"] -->|1. harness init &lt;desc&gt;| INIT_AGENT
    INIT_AGENT["🟢 Initializer Agent<br/><i>runs once</i>"]
    CODER1["🟡 Coding Agent #1"]
    CODER2["🟡 Coding Agent #2"]
    CODERN["🟡 Coding Agent #N"]

    INIT_AGENT -->|Creates| FL
    INIT_AGENT -->|Creates| CP
    INIT_AGENT -->|Creates| INIT
    INIT_AGENT -->|Initial commit| GIT

    INIT_AGENT -->|Handoff via shared state| CODER1

    CODER1 -->|Reads & updates| FL
    CODER1 -->|Reads & appends| CP
    CODER1 -->|Commits| GIT
    CODER1 -->|Starts server| INIT

    CODER1 -->|Handoff via shared state| CODER2

    CODER2 -->|Reads & updates| FL
    CODER2 -->|Reads & appends| CP
    CODER2 -->|Commits| GIT

    CODER2 -->|... repeat until done| CODERN
    CODERN -->|All features pass ✓| DONE["🎉 Complete"]

    style INIT_AGENT fill:#a5d6a7
    style CODER1 fill:#fff9c4
    style CODER2 fill:#fff9c4
    style CODERN fill:#fff9c4
    style USER fill:#bbdefb
    style SHARED fill:#f5f5f5
    style DONE fill:#c8e6c9
```

## Failure Modes & Solutions

| Problem | Initializer Agent | Coding Agent |
|---------|------------------|--------------|
| Declares victory too early | Set up comprehensive feature_list.json | Read feature list, pick ONE feature per session |
| Leaves broken state | Create progress file + git repo | Read progress + git log, smoke test first, fix before build |
| Marks features done without testing | Define concrete test steps | Self-verify end-to-end before marking passes=true |
| Doesn't know how to run app | Write init.sh | Read init.sh at session start |


path: docs/file-flow.md
content: # Agent Harness — File & Component Relationships

```mermaid
graph LR
    subgraph HARNESS["🔧 Agent Harness Framework"]
        subgraph TEMPLATES["📁 templates/"]
            tmpl_fl["feature_list.json"]
            tmpl_cp["claude-progress.txt"]
            tmpl_init["init.sh"]
        end

        subgraph PROMPTS["📁 prompts/"]
            prompt_init["initializer.md"]
            prompt_coder["coder.md"]
        end

        subgraph SCRIPTS["📁 scripts/"]
            harness["harness.sh<br/>─────────<br/>• init &lt;desc&gt;<br/>• run<br/>• status<br/>• reset<br/>• generate"]
        end

        subgraph SKILL["📋 Skill Config"]
            skill_md["SKILL.md"]
            skill_json["skill.json"]
        end
    end

    subgraph TARGET["🎯 Target Project (user's project)"]
        live_fl["feature_list.json"]
        live_cp["claude-progress.txt"]
        live_init["init.sh"]
        live_config[".harness.json"]
        code["Source Code"]
        git_history["Git History"]
    end

    harness -->|copies templates| tmpl_fl
    harness -->|outputs prompts| prompt_init

    prompt_init -.->|instructs agent to create| tmpl_fl
    prompt_init -.->|instructs agent to create| tmpl_cp
    prompt_init -.->|instructs agent to create| tmpl_init

    prompt_coder -.->|reads & updates| live_fl
    prompt_coder -.->|reads & appends| live_cp
    prompt_coder -.->|reads log, commits| git_history
    prompt_coder -.->|starts dev server| live_init
    prompt_coder -.->|implements features| code

    tmpl_fl -->|harness init copies| live_fl
    tmpl_cp -->|harness init copies| live_cp
    tmpl_init -->|harness init copies| live_init

    harness -->|creates| live_config
    skill_md -->|documents| harness
    skill_json -->|configures| harness

    style HARNESS fill:#f3e5f5
    style TARGET fill:#e8f5e9
    style TEMPLATES fill:#e8eaf6
    style PROMPTS fill:#e3f2fd
    style SCRIPTS fill:#fff3e0
    style SKILL fill:#fce4ec
```


path: docs/sequence.md
content: # Agent Harness — Session Sequence Diagram

```mermaid
sequenceDiagram
    actor User
    participant Init as 🟢 Initializer Agent
    participant C1 as 🟡 Coding Agent #1
    participant C2 as 🟡 Coding Agent #2
    participant FL as 📄 feature_list.json
    participant CP as 📝 progress.txt
    participant Git as 🔀 Git Repo
    participant Srv as ⚙️ init.sh

    rect rgb(200, 230, 201)
        Note over User, Srv: Phase 1 — Initialization (runs once)
        User->>Init: "Build a task app"
        activate Init
        Init->>Init: Parse requirements & generate feature list
        Init->>FL: Write feature_list.json (all: passes=false)
        Init->>CP: Write progress file (initial notes)
        Init->>Srv: Write init.sh (dev server script)
        Init->>Git: git init + initial commit
        Init-->>User: "Ready. N features planned."
        deactivate Init
    end

    rect rgb(255, 249, 196)
        Note over User, Srv: Phase 2 — Coding Sessions (repeat)
        User->>C1: "harness run"
        activate C1

        Note over C1: === Startup Sequence ===
        C1->>CP: Read progress log
        C1->>Git: git log --oneline -20
        C1->>FL: Read features, pick highest-priority failing
        C1->>Srv: Run init.sh (start dev server)
        C1->>C1: Smoke test — verify app not broken

        Note over C1: If broken → FIX FIRST

        Note over C1: === Implementation ===
        C1->>C1: Implement ONE feature
        C1->>C1: End-to-end test (as human user)

        alt Feature passes
            C1->>FL: Mark passes=true
            C1->>Git: git commit -m "feat: [F00x] ..."
            C1->>CP: Append session notes
        else Feature fails / partial
            C1->>Git: git stash or revert
            C1->>CP: Append "partial/blocked" notes
        end

        C1-->>User: "Session done. F00x completed."
        deactivate C1
    end

    rect rgb(255, 249, 196)
        Note over User, Srv: Next session...
        User->>C2: "harness run"
        activate C2
        C2->>CP: Read progress log
        C2->>Git: git log --oneline -20
        C2->>FL: Pick next failing feature
        C2->>Srv: Start dev server + smoke test
        C2->>C2: Implement + end-to-end test
        C2->>FL: Mark passes=true
        C2->>Git: git commit
        C2->>CP: Append session notes
        C2-->>User: "Session done. F00y completed."
        deactivate C2
    end
```


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)