Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,17 @@
logs/
tmp/
temp/
.artifacts.json
.artifacts.json.lock
.quality_gate_*.json
.team_registry.json
.checkpoints/
handoff_*.md
findings_*.md.lock
review_*.md.lock
code_*.md.lock
debug_*.md.lock
completion_summary_*.md.lock

# Session and state files
SESSION-STATE.md
Expand Down
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ This section describes what actually works **today** via the scripts layer.
| EXPLORING | ✅ | — | Socratic deep exploration |
| RESEARCH | ✅ | findings_{session}.md | Web search → findings report (falls back to keyword-based if search unavailable) |
| THINKING | ✅ | — | Expert reasoning |
| PLANNING | ✅ | .specs/<feat>/spec+plan+tasks.md | Task breakdown with spec-kit chain (.specs/*/spec.md → plan.md → tasks.md) |
| PLANNING | ✅ | .specs/<feat>/spec.md → plan.md → tasks.md → .contract.json | Task breakdown with spec-kit chain |
| EXECUTING | ✅ | — | TDD-driven implementation |
| REVIEWING | ✅ | review_{session}.md | Real code analysis when files present (falls back to template-based risk assessment) |
| REVIEWING | ✅ | review_{session}.md | Real code analysis when files present (falls back to contract-scoped fallback) |
| DEBUGGING | ✅ | — | 5-step systematic debugging |
| REFINING | ✅ | — | Feedback loop iteration |
| COMPLETE | ✅ | completion_summary_{session}.md | Finalization with aggregated summary |
Expand Down Expand Up @@ -62,7 +62,7 @@ The actual executable surface:
| `.artifacts.json` | ✅ Active | Artifact registry (progress, plan, session, tracker) |
| `SESSION-STATE.md` | ✅ Active | Session state (markdown) |
| `progress.md` | ✅ Active | Phase progress (markdown) |
| `task_plan.md` | ✅ Active | Task breakdown (markdown) |
| `task_plan.md` | 🔄 Legacy | Compatibility projection for old runtime/frontier |

## Quickstart

Expand Down Expand Up @@ -111,9 +111,9 @@ python3 scripts/unified_state.py --op=list-trajectories --workdir .
python3 scripts/task_decomposer.py --prompt "实现用户认证模块:注册、登录、登出"
```

### Plan-Driven Execution (NEW)
### Plan-Driven Execution (spec-kit chain)

任务计划现在支持可执行格式:
规划现在以 spec/plan/tasks/contract 为主:

```bash
# 验证任务计划(检查循环依赖等)
Expand Down Expand Up @@ -219,7 +219,7 @@ new_state = migrate_state(old_state)

**已注册工件类型**:
- `progress.md` -> type: progress
- `task_plan.md` -> type: plan
- `task_plan.md` -> type: plan (legacy)
- `SESSION-STATE.md` -> type: session
- `.task_tracker.json` -> type: tracker

Expand Down
27 changes: 26 additions & 1 deletion SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ description: |
统一智能体工作流 - 单入口设计,所有任务从 router 开始
TRIGGER when: 开发、修复、规划、分析、审查、调研、实施
DO NOT TRIGGER when: 简单闲聊
version: 6.0.0
version: 6.1.0
tags: [core, workflow]
requires:
tools: [Read, Write, Bash, Grep, Glob]
Expand Down Expand Up @@ -78,3 +78,28 @@ RESEARCH 阶段搜索工具优先级(按可用性自动降级):
1. **WebSearch** — Claude Code 原生,最优先
2. **WebFetch** — 当已知具体 URL 时
3. **AI 知识库** — 如果所有搜索工具都不可用,**必须明确告知用户**,不要静默用自身知识回答

## Forbidden Responses(禁止输出的内容)

以下响应是明确禁止的,遇到时必须停止并重新分析:

| 禁止语句 | 原因 | 正确做法 |
|---------|------|---------|
| "这个问题无法解决" | 违反铁律一(穷尽一切) | 列出3个方案再判断 |
| "我认为完成了" | 无证据声明 | 运行测试/diff,给出证据 |
| "代码看起来不错" | REVIEWING 无实质内容 | 给出 file:line 具体意见 |
| "根据我的知识..." (RESEARCH中) | 跳过真实搜索 | 先执行 WebSearch,工具不可用时明确告知 |
| "直接跳到实现吧" | 跳过 THINKING/PLANNING | 遵循强制阶段序列 |
| "先做个小版本,后面再改" | 无计划执行 | 先 PLANNING,再 EXECUTING |

## 复杂度路由

任务自动评估复杂度,路由到对应必经阶段序列:

| 复杂度 | 示例 | 必经阶段 |
|--------|------|---------|
| **XS** | 改 typo、加 import | EXECUTING → COMPLETE |
| **S** | 修已知 bug | DEBUGGING → EXECUTING → COMPLETE |
| **M** | 新增 API endpoint | PLANNING → EXECUTING → REVIEWING → COMPLETE |
| **L** | 重构模块 | RESEARCH → THINKING → PLANNING → EXECUTING → REVIEWING → COMPLETE |
| **XL** | 设计新系统 | RESEARCH → THINKING → PLANNING → EXECUTING → REVIEWING → REFINING → COMPLETE |
8 changes: 4 additions & 4 deletions scripts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
- `task_tracker.py`: 任务状态追踪
- `team_agent.py`: 小团队多Agent编排 (lead + typed workers)

这组脚本加上 `.workflow_state.json`、`SESSION-STATE.md`、`progress.md`、`task_plan.md` 这些状态文件,就是当前的 workflow runtime layer。
这组脚本加上 `.workflow_state.json`、`SESSION-STATE.md`、`progress.md`、`.specs/`、`.contract.json` 这些状态/规划文件,就是当前的 workflow runtime layer。`task_plan.md` 仅作为 legacy 兼容投影保留。

### 🔬 实验版 (未纳入主线)

Expand Down Expand Up @@ -61,7 +61,7 @@
| `quick_tdd.sh` | 快速 TDD | 执行 TDD 循环 (红-绿-重构) |
| `check_env.sh` | 环境检查 | 检查必需工具和环境变量 |
| `auto_commit.sh` | 自动提交 | 快捷 git 提交 |
| `create_plan.sh` | 创建计划 | 生成项目内 `task_plan.md` |
| `create_plan.sh` | 创建计划 | 生成项目内 `task_plan.md` (legacy) |
| `quick_review.sh` | 快速审查 | 代码审查 (TODO/密码/空文件) |
| `watch_progress.sh` | 监控进度 | 监控 progress.md 变化 |

Expand All @@ -74,7 +74,7 @@
| `init_session.bat` | 初始化会话 | 创建 SESSION-STATE.md |
| `check_template.bat` | 检查模板 | 验证 `references\templates\` 下模板是否存在 |
| `check_env.bat` | 环境检查 | 检查必需工具和环境变量 |
| `create_plan.bat` | 创建计划 | 生成项目内 `task_plan.md` |
| `create_plan.bat` | 创建计划 | 生成项目内 `task_plan.md` (legacy) |
| `quick_review.bat` | 快速审查 | 代码审查 (TODO/密码/空文件) |

### 跨平台脚本调用
Expand Down Expand Up @@ -151,7 +151,7 @@ bash scripts/init_session.sh # 初始化会话
bash scripts/check_template.sh # 检查模板
bash scripts/check_env.sh # 检查环境
bash scripts/quick_tdd.sh "npm test" "npm run build" # TDD循环
bash scripts/create_plan.sh "新功能开发" # 创建 task_plan.md
bash scripts/create_plan.sh "新功能开发" # 创建 task_plan.md (legacy)
bash scripts/quick_review.sh src/ # 快速审查
bash scripts/auto_commit.sh . "完成功能X" # 提交代码
bash scripts/watch_progress.sh progress.md 5 # 监控进度
Expand Down
10 changes: 10 additions & 0 deletions scripts/contract_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,16 @@ def validate_contract_gate(workdir: str, state: Any) -> tuple[bool, str]:
if trigger_type in ("RESULT_ONLY", "DIRECT_ANSWER"):
return True, "" # Lenient: Q&A tasks don't need formal contracts

# Gate is skipped for STAGE trigger (simple tasks)
if trigger_type == "STAGE":
return True, "" # Simple stage-triggered tasks don't need contracts

# Gate is relaxed for low-complexity tasks (XS/S)
metadata = getattr(state, 'metadata', None) or {}
complexity = metadata.get("complexity", "")
if complexity in ("XS", "S"):
return True, "" # Simple tasks skip formal contract gate

if not json_contract_path.exists():
return True, "" # No contract = no gate

Expand Down
4 changes: 1 addition & 3 deletions scripts/reflexion.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,10 @@
from __future__ import annotations

import re
from dataclasses import dataclass, field
from dataclasses import dataclass
from datetime import datetime
from typing import Any


# Error pattern extractors - map regex patterns to hint generators
ERROR_PATTERNS: list[tuple[re.Pattern, str]] = [
# Test failures - specific assertions
Expand Down Expand Up @@ -97,7 +96,6 @@ def reflect(
ReflexionResult with hint, pattern, reflection, and is_repeated
"""
context = context or {}
error_lower = error.lower()
retry_count = context.get("retry_count", 0)

# Check for repeated errors
Expand Down
3 changes: 2 additions & 1 deletion scripts/team_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -729,7 +729,8 @@ def main():
else:
# 团队模式
team = TeamAgent(args.workdir, task=args.task)
team.add_task(args.task, WorkerType.CODER)
if not team.contract.get("goals") and not team.frontier.get("executable_frontier") and not team.frontier.get("parallel_candidates") and not team.frontier.get("conflict_groups"):
team.add_task(args.task, WorkerType.CODER)
result = team.run()
print(f"Team Session: {result['session_id']}")
print(f"Tasks: {result['tasks_completed']} completed, {result['tasks_failed']} failed")
Expand Down
9 changes: 5 additions & 4 deletions scripts/utils/lru_cache.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
from __future__ import annotations
"""
LRU Cache 实现 - 基于 OrderedDict 的 O(1) 实现

Expand All @@ -9,8 +8,10 @@
- 容量超限时自动淘汰最久未使用的条目
"""

from __future__ import annotations

from collections import OrderedDict
from typing import Any, Optional, cast
from typing import Any, cast


class LRUCache:
Expand Down Expand Up @@ -135,8 +136,8 @@ class _Node:
def __init__(self, key: int = 0, value: Any = None) -> None:
self.key = key
self.value = value
self.prev: Optional[_Node] = None
self.next: Optional[_Node] = None
self.prev: _Node | None = None
self.next: _Node | None = None


class LRUCacheManual:
Expand Down
25 changes: 12 additions & 13 deletions scripts/workflow_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def _run_quality_gate_if_applicable(workdir: str, task_id: str, tracker_path: st
gate_result_path = Path(workdir) / f".quality_gate_{task_id}.json"
safe_write_json(gate_result_path, report.to_dict())

return report.all_passed
return bool(report.all_passed)
except Exception:
# If quality gate fails for any reason, block completion for code tasks
# This is fail-closed: code tasks must pass quality gate to complete
Expand Down Expand Up @@ -804,7 +804,8 @@ def should_checkpoint(
"""
# Delegate to checkpoint_manager (imported lazily to avoid circular dependency)
from checkpoint_manager import should_checkpoint as _impl
return _impl(workdir, config)
result: tuple[bool, str] = _impl(workdir, config)
return bool(result[0]), str(result[1])


def conditional_checkpoint(
Expand Down Expand Up @@ -834,7 +835,8 @@ def conditional_checkpoint(
"""
# Delegate to checkpoint_manager (imported lazily to avoid circular dependency)
from checkpoint_manager import conditional_checkpoint as _impl
return _impl(workdir, config)
result: dict[str, Any] = _impl(workdir, config)
return result


def validate_task_plan(workdir: str = ".") -> tuple[bool, list[str]]:
Expand Down Expand Up @@ -1483,9 +1485,9 @@ def advance_workflow(
plan_content = plan_path.read_text(encoding="utf-8", errors="ignore")
owned_pattern = re.compile(r'owned_files:\s*(.+)', re.IGNORECASE)
for line in plan_content.split('\n'):
match = owned_pattern.search(line)
if match:
files_str = match.group(1).strip()
owned_match: re.Match[str] | None = owned_pattern.search(line)
if owned_match:
files_str = owned_match.group(1).strip()
for f in files_str.split(','):
f = f.strip()
if f:
Expand Down Expand Up @@ -1860,6 +1862,10 @@ def complete_workflow(

current_phase = state.phase.get("current", "IDLE")
session_id = state.session_id or "unknown"
if final_state == "completed":
contract_valid, contract_error = validate_contract_gate(workdir, state)
if not contract_valid:
raise ValueError(f"Cannot complete workflow: {contract_error}")

# Gate blocking for code tasks - same logic as advance_workflow COMPLETE
phase_history = state.phase.get("history", [])
Expand Down Expand Up @@ -1905,13 +1911,6 @@ def complete_workflow(
f"Allowed transitions: stay in {current_phase}, go to DEBUGGING, or abort."
)

# Contract fulfillment gate: validate contract is properly fulfilled
contract_valid, contract_error = validate_contract_gate(workdir, state)
if not contract_valid:
raise ValueError(
f"Cannot complete workflow: {contract_error}"
)

# Complete trajectory logging
if state.session_id in _active_loggers:
logger = _active_loggers[state.session_id]
Expand Down
41 changes: 29 additions & 12 deletions skills/_shared/preamble.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,42 @@ name: preamble
version: 3.0.0
description: |
标准化 Preamble - 每个 skill 启动时的最小共享约定
当前版本只引用真实存在的文件,不引用历史设计
---

## Preamble

### 状态文件

- `.workflow_state.json` — 唯一真实状态源(session_id, task, phase, trigger_type)
唯一可信的状态文件是 `.workflow_state.json`(位于项目根目录)。

### 阶段执行流程
```bash
# 读取当前状态
python3 scripts/workflow_engine.py --op status --workdir .

1. 读取 `.workflow_state.json` 确认当前 phase 和 session
2. 执行当前阶段的 Core Process
3. 完成后推进:`python3 scripts/workflow_engine.py --op advance --phase NEXT --workdir .`
# 恢复上一次会话
python3 scripts/workflow_engine.py --op resume --workdir .
```

### 产出文件约定
### 规划产出

| 阶段 | 产出文件 |
|------|---------|
| RESEARCH | `findings.md` |
| PLANNING | `task_plan.md` |
| EXECUTING | 实际代码变更 |
| REVIEWING | review 意见(含 file:line 定位) |
| 文件 | 说明 |
|------|------|
| `.specs/<feature>/spec.md` | 用户故事 + 验收标准 |
| `.specs/<feature>/plan.md` | 技术方案 + 约束 |
| `.specs/<feature>/tasks.md` | 可执行任务清单 |
| `task_plan.md` | legacy,兼容旧 runtime |

### 研究产出

`findings_{session}.md` — RESEARCH 阶段输出,THINKING 阶段必须读取。

### 进度格式

每进入新阶段时输出:`[N/M PHASE] 一句话描述当前要做什么`

### 注意

- 不要引用 `SESSION-STATE.md`(已移除)
- 不要引用 `~/.gstack`(历史设计)
- 不要假定 telemetry daemon、preload 或 session 守护进程存在
24 changes: 22 additions & 2 deletions skills/complete/skill.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,33 @@ COMPLETE 阶段负责收尾、同步状态、记录经验,并给出清晰的

## Exit Criteria

退出 COMPLETE 的条件:
<HARD-GATE name="complete-exit-gate">
声称任务完成之前,必须:
1. 运行测试并看到通过结果(不得仅凭"我认为通过了")
2. 更新 `.workflow_state.json`(phase = COMPLETE)
3. 输出明确的完成状态(DONE / DONE_WITH_CONCERNS / BLOCKED)

无验证证据 = 未完成。
</HARD-GATE>

**Iron Law**: `NO DONE WITHOUT EVIDENCE FIRST`

退出 COMPLETE 的条件(全部满足):

- `.workflow_state.json` 已更新(phase 设为 COMPLETE)
- 验证状态已说明
- 验证状态已说明(有命令输出为证)
- 自反思或经验记录已补充
- 已明确输出 `DONE / DONE_WITH_CONCERNS / BLOCKED / NEEDS_CONTEXT`

### 可选: 触发 LEARN

对于 M+ 复杂度的任务,COMPLETE 后建议触发 learn 技能提炼经验:

```bash
# 提炼本次会话模式
python3 scripts/memory_longterm.py --op refine --days 1
```

## Core Process

### 1. Run Final Verification Checklist
Expand Down
17 changes: 13 additions & 4 deletions skills/debugging/skill.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,23 @@ DEBUGGING 阶段是 agentic-workflow 的系统化调试阶段,采用5步调试
- 遇到执行失败、错误异常或不符合预期的情况
- 从其他阶段转来的需要调试的问题

**禁止**:在未充分分析前直接修改代码
<HARD-GATE name="no-fix-before-root-cause">
禁止在未完成 Phase 1(根因调查)前提出任何修复方案。
"我觉得可能是..." 不是根因。"代码第 42 行的条件判断在 X 场景下失效" 才是根因。
</HARD-GATE>

**Iron Law**: `NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST`

## Exit Criteria

退出 DEBUGGING 阶段的条件:
- 问题已定位且修复完成
- 所有相关测试通过
- 复盘总结已记录

<HARD-GATE name="debug-exit-gate">
以下三项必须全部满足,缺一不可:
1. 根本原因已用具体 file:line 证据确认(不是猜测)
2. 修复后相关测试全部通过(必须运行并看到输出)
3. 复盘总结已记录(至少包含:根因 + 修复方案 + 预防措施)
</HARD-GATE>

## Core Process

Expand Down
Loading
Loading