
Team Tech Debt
- 44 installs
- 2.1k repo stars
- Updated June 18, 2026
- catlog22/claude-code-workflow
Support for team-tech-debt
About
Provides workflow support for team-tech-debt. Solo builders use this to streamline development.
- team-tech-debt
Team Tech Debt by the numbers
- 44 all-time installs (skills.sh)
- Ranked #1,686 of 3,282 Productivity & Planning skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/catlog22/claude-code-workflow --skill team-tech-debtAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 44 |
|---|---|
| repo stars | ★ 2.1k |
| Last updated | June 18, 2026 |
| Repository | catlog22/claude-code-workflow ↗ |
What it does
Support for team-tech-debt
Files
Team Tech Debt
Systematic tech debt governance: scan -> assess -> plan -> fix -> validate. Built on team-worker agent architecture — all worker roles share a single agent definition with role-specific Phase 2-4 loaded from roles/<role>/role.md.
Architecture
Skill(skill="team-tech-debt", args="task description")
|
SKILL.md (this file) = Router
|
+--------------+--------------+
| |
no --role flag --role <name>
| |
Coordinator Worker
roles/coordinator/role.md roles/<name>/role.md
|
+-- analyze → dispatch → spawn workers → STOP
|
+-------+-------+-------+-------+
v v v v v
[team-worker agents, each loads roles/<role>/role.md]
scanner assessor planner executor validatorRole Registry
| Role | Path | Prefix | Inner Loop |
|---|---|---|---|
| coordinator | roles/coordinator/role.md | — | — |
| scanner | roles/scanner/role.md | TDSCAN-* | false |
| assessor | roles/assessor/role.md | TDEVAL-* | false |
| planner | roles/planner/role.md | TDPLAN-* | false |
| executor | roles/executor/role.md | TDFIX-* | true |
| validator | roles/validator/role.md | TDVAL-* | false |
Role Router
Parse $ARGUMENTS:
- Has
--role <name>→ Readroles/<name>/role.md, execute Phase 2-4 - No
--role→@roles/coordinator/role.md, execute entry router
Shared Constants
- Session prefix:
TD - Session path:
.workflow/.team/TD-<slug>-<date>/ - CLI tools:
ccw cli --mode analysis(read-only),ccw cli --mode write(modifications) - Message bus:
mcp__ccw-tools__team_msg(session_id=<session-id>, ...) - Max GC rounds: 3
Worker Spawn Template
Coordinator spawns workers using this template:
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker for <task-id>",
team_name: "tech-debt",
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: <skill_root>/roles/<role>/role.md
session: <session-folder>
session_id: <session-id>
team_name: tech-debt
requirement: <task-description>
inner_loop: <true|false>
## Progress Milestones
session_id: <session-id>
Report progress via team_msg at natural phase boundaries (context loaded -> core work done -> verification).
Report blockers immediately via team_msg type="blocker".
Report completion via team_msg type="task_complete" after final SendMessage.
Read role_spec file (@<skill_root>/roles/<role>/role.md) to load Phase 2-4 domain instructions.
Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).`
})User Commands
| Command | Action |
|---|---|
check / status | View execution status graph |
resume / continue | Advance to next step |
--mode=scan | Run scan-only pipeline (TDSCAN + TDEVAL) |
--mode=targeted | Run targeted pipeline (TDPLAN + TDFIX + TDVAL) |
--mode=remediate | Run full pipeline (default) |
-y / --yes | Skip confirmations |
Specs Reference
- specs/pipelines.md — Pipeline definitions and task registry
Session Directory
.workflow/.team/TD-<slug>-<date>/
├── .msg/
│ ├── messages.jsonl # Team message bus
│ └── meta.json # Pipeline config + role state snapshot
├── scan/ # Scanner output
├── assessment/ # Assessor output
├── plan/ # Planner output
├── fixes/ # Executor output
├── validation/ # Validator output
└── wisdom/ # Cross-task knowledgeError Handling
| Scenario | Resolution |
|---|---|
| Unknown command | Error with available command list |
| Role not found | Error with role registry |
| Session corruption | Attempt recovery, fallback to manual |
| Fast-advance conflict | Coordinator reconciles on next callback |
| Completion action fails | Default to Keep Active |
| Scanner finds no debt | Report clean codebase, skip to summary |
Tech Debt Assessor
Quantitative evaluator for tech debt items. Score each debt item on business impact (1-5) and fix cost (1-5), classify into priority quadrants, produce priority-matrix.json.
Phase 2: Load Debt Inventory
| Input | Source | Required |
|---|---|---|
| Session path | task description (regex: session:\s*(.+)) | Yes |
| .msg/meta.json | <session>/.msg/meta.json | Yes |
| Debt inventory | meta.json:debt_inventory OR <session>/scan/debt-inventory.json | Yes |
1. Extract session path from task description 2. Read .msg/meta.json for team context 3. Load debt_inventory from shared memory or fallback to debt-inventory.json file 4. If debt_inventory is empty -> report empty assessment and exit
Phase 3: Evaluate Each Item
Strategy selection:
| Item Count | Strategy |
|---|---|
| <= 10 | Heuristic: severity-based impact + effort-based cost |
| 11-50 | CLI batch: single gemini analysis call |
| > 50 | CLI chunked: batches of 25 items |
Impact Score Mapping (heuristic):
| Severity | Impact Score |
|---|---|
| critical | 5 |
| high | 4 |
| medium | 3 |
| low | 1 |
Cost Score Mapping (heuristic):
| Estimated Effort | Cost Score |
|---|---|
| small | 1 |
| medium | 3 |
| large | 5 |
| unknown | 3 |
Priority Quadrant Classification:
| Impact | Cost | Quadrant |
|---|---|---|
| >= 4 | <= 2 | quick-win |
| >= 4 | >= 3 | strategic |
| <= 3 | <= 2 | backlog |
| <= 3 | >= 3 | defer |
For CLI mode, prompt gemini with full debt summary requesting JSON array of {id, impact_score, cost_score, risk_if_unfixed, priority_quadrant}. Unevaluated items fall back to heuristic scoring.
Tech Profile Scan
After assessment, emit context-aware trigger signals (based on detected codebase characteristics):
1. Check debt items → signals (legacy_patterns, perf_sensitive, test_gap) 2. Check code patterns → risk signals (sql_detected, auth_detected, scaling_concern) 3. Include tech_profile in Phase 5 state_update data
Phase 4: Generate Priority Matrix
1. Build matrix structure: evaluation_date, total_items, by_quadrant (grouped), summary (counts per quadrant) 2. Sort within each quadrant by impact_score descending 3. Write <session>/assessment/priority-matrix.json 4. Update .msg/meta.json with priority_matrix summary and evaluated debt_inventory
Analyze Task
Parse user task -> detect tech debt signals -> assess complexity -> determine pipeline mode and roles.
CONSTRAINT: Text-level analysis only. NO source code reading, NO codebase exploration.
Signal Detection
| Keywords | Signal | Mode Hint |
|---|---|---|
| 扫描, scan, 审计, audit | debt-scan | scan |
| 评估, assess, quantify | debt-assess | scan |
| 规划, plan, roadmap | debt-plan | targeted |
| 修复, fix, remediate, clean | debt-fix | remediate |
| 验证, validate, verify | debt-validate | remediate |
| 定向, targeted, specific | debt-targeted | targeted |
Complexity Scoring
| Factor | Points |
|---|---|
| Full codebase scope | +2 |
| Multiple debt dimensions | +1 per dimension (max 3) |
| Large codebase (implied) | +1 |
| Targeted specific items | -1 |
Results: 1-3 Low (scan mode), 4-6 Medium (remediate), 7+ High (remediate + full pipeline)
Pipeline Mode Determination
| Score + Signals | Mode |
|---|---|
| scan/audit keywords | scan |
| targeted/specific keywords | targeted |
| Default | remediate |
Output
Write scope context to coordinator memory:
{
"pipeline_mode": "<scan|remediate|targeted>",
"scope": "<detected-scope>",
"focus_dimensions": ["code", "architecture", "testing", "dependency", "documentation"],
"complexity": { "score": 0, "level": "Low|Medium|High" }
}Command: dispatch
任务链创建与依赖管理。根据 pipeline 模式创建技术债务治理任务链并分配给 worker 角色。
When to Use
- Phase 3 of Coordinator
- Pipeline 模式已确定,需要创建任务链
- 团队已创建,worker 已 spawn
Trigger conditions:
- Coordinator Phase 2 完成后
- 模式切换需要重建任务链
- Fix-Verify 循环需要创建修复任务
Strategy
Delegation Mode
Mode: Direct(coordinator 直接操作 TaskCreate/TaskUpdate)
Decision Logic
// 根据 pipelineMode 选择 pipeline
function buildPipeline(pipelineMode, sessionFolder, taskDescription) {
const pipelines = {
'scan': [
{ prefix: 'TDSCAN', owner: 'scanner', desc: '多维度技术债务扫描', blockedBy: [] },
{ prefix: 'TDEVAL', owner: 'assessor', desc: '量化评估与优先级排序', blockedBy: ['TDSCAN'] }
],
'remediate': [
{ prefix: 'TDSCAN', owner: 'scanner', desc: '多维度技术债务扫描', blockedBy: [] },
{ prefix: 'TDEVAL', owner: 'assessor', desc: '量化评估与优先级排序', blockedBy: ['TDSCAN'] },
{ prefix: 'TDPLAN', owner: 'planner', desc: '分阶段治理方案规划', blockedBy: ['TDEVAL'] },
{ prefix: 'TDFIX', owner: 'executor', desc: '债务清理执行', blockedBy: ['TDPLAN'] },
{ prefix: 'TDVAL', owner: 'validator', desc: '清理结果验证', blockedBy: ['TDFIX'] }
],
'targeted': [
{ prefix: 'TDPLAN', owner: 'planner', desc: '定向修复方案规划', blockedBy: [] },
{ prefix: 'TDFIX', owner: 'executor', desc: '债务清理执行', blockedBy: ['TDPLAN'] },
{ prefix: 'TDVAL', owner: 'validator', desc: '清理结果验证', blockedBy: ['TDFIX'] }
]
}
return pipelines[pipelineMode] || pipelines['scan']
}Execution Steps
Step 1: Context Preparation
const pipeline = buildPipeline(pipelineMode, sessionFolder, taskDescription)Step 2: Execute Strategy
const taskIds = {}
for (const stage of pipeline) {
// 构建任务描述(包含 session 和上下文信息)
const fullDesc = [
stage.desc,
`\nsession: ${sessionFolder}`,
`\n\n目标: ${taskDescription}`
].join('')
// 创建任务
TaskCreate({
subject: `${stage.prefix}-001: ${stage.desc}`,
description: fullDesc,
activeForm: `${stage.desc}进行中`
})
// 记录任务 ID
const allTasks = TaskList()
const newTask = allTasks.find(t => t.subject.startsWith(`${stage.prefix}-001`))
taskIds[stage.prefix] = newTask.id
// 设置 owner 和依赖
const blockedByIds = stage.blockedBy
.map(dep => taskIds[dep])
.filter(Boolean)
TaskUpdate({
taskId: newTask.id,
owner: stage.owner,
addBlockedBy: blockedByIds
})
}Step 3: Result Processing
// 验证任务链
const allTasks = TaskList()
const chainTasks = pipeline.map(s => taskIds[s.prefix]).filter(Boolean)
const chainValid = chainTasks.length === pipeline.length
if (!chainValid) {
mcp__ccw-tools__team_msg({
operation: "log", session_id: sessionId, from: "coordinator", // team must be session ID (e.g., TD-xxx-date), NOT team name
type: "error",
})
}Fix-Verify Loop Task Creation
当 validator 报告回归问题时,coordinator 调用此逻辑追加任务:
function createFixVerifyTasks(fixVerifyIteration, sessionFolder) {
// 创建修复任务
TaskCreate({
subject: `TDFIX-fix-${fixVerifyIteration}: 修复回归问题 (Fix-Verify #${fixVerifyIteration})`,
description: `修复验证发现的回归问题\nsession: ${sessionFolder}\ntype: fix-verify`,
activeForm: `Fix-Verify #${fixVerifyIteration} 修复中`
})
// 创建重新验证任务
TaskCreate({
subject: `TDVAL-verify-${fixVerifyIteration}: 重新验证 (Fix-Verify #${fixVerifyIteration})`,
description: `重新验证修复结果\nsession: ${sessionFolder}`,
activeForm: `Fix-Verify #${fixVerifyIteration} 验证中`
})
// 设置依赖: TDVAL-verify 依赖 TDFIX-fix
// ... TaskUpdate addBlockedBy
}Output Format
## Task Chain Created
### Mode: [scan|remediate|targeted]
### Pipeline Stages: [count]
- [prefix]-001: [description] (owner: [role], blocked by: [deps])
### Verification: PASS/FAILError Handling
| Scenario | Resolution |
|---|---|
| Task creation fails | Retry once, then report to user |
| Dependency cycle detected | Flatten dependencies, warn coordinator |
| Invalid pipelineMode | Default to 'scan' mode |
| Agent/CLI failure | Retry once, then fallback to inline execution |
| Timeout (>5 min) | Report partial results, notify coordinator |
Monitor Pipeline
Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP.
Constants
- SPAWN_MODE: background
- ONE_STEP_PER_INVOCATION: true
- FAST_ADVANCE_AWARE: true
- WORKER_AGENT: team-worker
- MAX_GC_ROUNDS: 3
Handler Router
| Source | Handler |
|---|---|
| Message contains [scanner], [assessor], [planner], [executor], [validator] | handleCallback |
| "capability_gap" | handleAdapt |
| "check" or "status" | handleCheck |
| "resume" or "continue" | handleResume |
| All tasks completed | handleComplete |
| Default | handleSpawnNext |
handleCallback
Worker completed. Process and advance.
1. Find matching worker by role tag in message 2. Check if progress update (inner loop) or final completion 3. Progress update -> update session state, STOP 4. Completion -> mark task done:
TaskUpdate({ taskId: "<task-id>", status: "completed" })5. Remove from active_workers, record completion in session
6. Check for checkpoints:
- TDPLAN-001 completes -> Plan Approval Gate:
AskUserQuestion({
questions: [{ question: "Remediation plan generated. Review and decide:",
header: "Plan Review", multiSelect: false,
options: [
{ label: "Approve", description: "Proceed with fix execution" },
{ label: "Revise", description: "Re-run planner with feedback" },
{ label: "Abort", description: "Stop pipeline" }
]
}]
})- Approve -> Worktree Creation -> handleSpawnNext
- Revise -> Create TDPLAN-revised task -> handleSpawnNext
- Abort -> Log shutdown -> handleComplete
- Worktree Creation (before TDFIX):
Bash("git worktree add .worktrees/TD-<slug>-<date> -b tech-debt/TD-<slug>-<date>")Update .msg/meta.json with worktree info.
- *TDVAL- completes** -> GC Loop Check:
Read validation results from .msg/meta.json
| Condition | Action |
|---|---|
| No regressions | -> handleSpawnNext (pipeline complete) |
| Regressions AND gc_rounds < 3 | Create fix-verify tasks, increment gc_rounds |
| Regressions AND gc_rounds >= 3 | Accept current state -> handleComplete |
Fix-Verify Task Creation:
TaskCreate({ subject: "TDFIX-fix-<round>", description: "PURPOSE: Fix regressions | Session: <session>" })
TaskCreate({ subject: "TDVAL-recheck-<round>", description: "..." })
TaskUpdate({ taskId: "TDVAL-recheck-<round>", addBlockedBy: ["TDFIX-fix-<round>"] })7. -> handleSpawnNext
handleCheck
Read-only status report, then STOP.
Worker Progress (from message bus):
Before generating status output, read worker milestones:
const progressMsgs = mcp__ccw-tools__team_msg({
operation: "list", session_id: sessionId, type: "progress", last: 50
})
const blockerMsgs = mcp__ccw-tools__team_msg({
operation: "list", session_id: sessionId, type: "blocker", last: 10
})
// Aggregate latest milestone per task
const taskProgress = {}
for (const msg of (progressMsgs.result?.messages || [])) {
const tid = msg.data?.task_id
if (tid && (!taskProgress[tid] || msg.ts > taskProgress[tid].ts)) {
taskProgress[tid] = { phase: msg.data.phase, pct: msg.data.progress_pct, ts: msg.ts }
}
}Include in status output:
- Per-worker latest milestone (phase + progress_pct) next to task status
- Active blockers section (if any blockerMsgs found)
Pipeline Status (<mode>):
[DONE] TDSCAN-001 (scanner) -> scan complete
[DONE] TDEVAL-001 (assessor) -> assessment ready
[RUN] TDPLAN-001 (planner) -> planning...
[WAIT] TDFIX-001 (executor) -> blocked by TDPLAN-001
[WAIT] TDVAL-001 (validator) -> blocked by TDFIX-001
GC Rounds: 0/3
Session: <session-id>
Commands: 'resume' to advance | 'check' to refreshOutput status -- do NOT advance pipeline.
handleResume
1. Audit task list:
- Tasks stuck in "in_progress" -> reset to "pending"
- Tasks with completed blockers but still "pending" -> include in spawn list
2. -> handleSpawnNext
handleSpawnNext
Find ready tasks, spawn workers, STOP.
1. Collect: completedSubjects, inProgressSubjects, readySubjects (pending + all blockedBy completed) 2. No ready + work in progress -> report waiting, STOP 3. No ready + nothing in progress -> handleComplete 4. Has ready -> for each: a. Check inner loop role with active worker -> skip (worker picks up) b. TaskUpdate -> in_progress c. team_msg log -> task_unblocked d. Spawn team-worker:
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker for <task-id>",
team_name: "tech-debt",
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: ~ or <project>/.claude/skills/team-tech-debt/roles/<role>/role.md
session: <session-folder>
session_id: <session-id>
team_name: tech-debt
requirement: <task-description>
inner_loop: <true|false>
## Progress Milestones
session_id: <session-id>
Report progress via team_msg at natural phase boundaries (context loaded -> core work done -> verification).
Report blockers immediately via team_msg type="blocker".
Report completion via team_msg type="task_complete" after final SendMessage.
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).`
})Stage-to-role mapping:
| Task Prefix | Role |
|---|---|
| TDSCAN | scanner |
| TDEVAL | assessor |
| TDPLAN | planner |
| TDFIX | executor |
| TDVAL | validator |
5. Add to active_workers, update session, output summary, STOP
handleComplete
Pipeline done. Generate report and completion action.
1. Verify all tasks (including fix-verify tasks) have status "completed" 2. If any not completed -> handleSpawnNext 3. If all completed:
- Read final state from .msg/meta.json
- If worktree exists and validation passed: commit, push, gh pr create, cleanup worktree
- Compile summary: total tasks, completed, gc_rounds, debt_score_before, debt_score_after
- Transition to coordinator Phase 5
handleAdapt
Capability gap reported mid-pipeline.
1. Parse gap description 2. Check if existing role covers it -> redirect 3. Role count < 5 -> generate dynamic role spec in <session>/role-specs/ 4. Create new task, spawn worker 5. Role count >= 5 -> merge or pause
Fast-Advance Reconciliation
On every coordinator wake: 1. Read team_msg entries with type="fast_advance" 2. Sync active_workers with spawned successors 3. No duplicate spawns
Coordinator Role
技术债务治理团队协调者。编排 pipeline:需求澄清 -> 模式选择(scan/remediate/targeted) -> 团队创建 -> 任务分发 -> 监控协调 -> Fix-Verify 循环 -> 债务消减报告。
Identity
- Name: coordinator | Tag: [coordinator]
- Responsibility: Parse requirements -> Create team -> Dispatch tasks -> Monitor progress -> Report results
Boundaries
MUST
- All output (SendMessage, team_msg, logs) must carry
[coordinator]identifier - Only responsible for: requirement clarification, mode selection, task creation/dispatch, progress monitoring, quality gates, result reporting
- Create tasks via TaskCreate and assign to worker roles
- Monitor worker progress via message bus and route messages
- Maintain session state persistence
MUST NOT
- Execute tech debt work directly (delegate to workers)
- Modify task outputs (workers own their deliverables)
- Call CLI tools for analysis, exploration, or code generation
- Modify source code or generate artifact files directly
- Bypass worker roles to complete delegated work
- Skip dependency validation when creating task chains
- Omit
[coordinator]identifier in any output
Command Execution Protocol
When coordinator needs to execute a command (analyze, dispatch, monitor):
1. Read commands/<command>.md 2. Follow the workflow defined in the command 3. Commands are inline execution guides, NOT separate agents 4. Execute synchronously, complete before proceeding
Entry Router
| Detection | Condition | Handler |
|---|---|---|
| Worker callback | Message contains [scanner], [assessor], [planner], [executor], [validator] | -> handleCallback (monitor.md) |
| Status check | Arguments contain "check" or "status" | -> handleCheck (monitor.md) |
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume (monitor.md) |
| Pipeline complete | All tasks have status "completed" | -> handleComplete (monitor.md) |
| Interrupted session | Active/paused session exists in .workflow/.team/TD-* | -> Phase 0 |
| New session | None of above | -> Phase 1 |
For callback/check/resume/complete: load @commands/monitor.md, execute matched handler, STOP.
Phase 0: Session Resume Check
1. Scan .workflow/.team/TD-*/.msg/meta.json for active/paused sessions 2. No sessions -> Phase 1 3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, kick first ready task) 4. Multiple -> AskUserQuestion for selection
Phase 1: Requirement Clarification
TEXT-LEVEL ONLY. No source code reading.
1. Parse arguments for explicit settings: mode, scope, focus areas 2. Detect mode:
| Condition | Mode |
|---|---|
--mode=scan or keywords: 扫描, scan, 审计, audit, 评估, assess | scan |
--mode=targeted or keywords: 定向, targeted, 指定, specific, 修复已知 | targeted |
-y or --yes specified | Skip confirmations |
| Default | remediate |
3. Ask for missing parameters (skip if auto mode):
- AskUserQuestion: Tech Debt Target (自定义 / 全项目扫描 / 完整治理 / 定向修复)
4. Store: mode, scope, focus, constraints 5. Delegate to @commands/analyze.md -> output task-analysis context
Phase 2: Create Team + Initialize Session
1. Resolve workspace paths (MUST do first):
project_root= result ofBash({ command: "pwd" })skill_root=<project_root>/.claude/skills/team-tech-debt
2. Generate session ID: TD-<slug>-<YYYY-MM-DD> 3. Create session folder structure (scan/, assessment/, plan/, fixes/, validation/, wisdom/) 4. Initialize .msg/meta.json via team_msg state_update with pipeline metadata 5. TeamCreate(team_name="tech-debt") 6. Do NOT spawn workers yet - deferred to Phase 4
Phase 3: Create Task Chain
Delegate to @commands/dispatch.md. Task chain by mode:
| Mode | Task Chain |
|---|---|
| scan | TDSCAN-001 -> TDEVAL-001 |
| remediate | TDSCAN-001 -> TDEVAL-001 -> TDPLAN-001 -> TDFIX-001 -> TDVAL-001 |
| targeted | TDPLAN-001 -> TDFIX-001 -> TDVAL-001 |
Phase 4: Spawn-and-Stop
Delegate to @commands/monitor.md#handleSpawnNext: 1. Find ready tasks (pending + blockedBy resolved) 2. Spawn team-worker agents (see SKILL.md Spawn Template) 3. Output status summary 4. STOP
Phase 5: Report + Debt Reduction Metrics + PR
1. Read shared memory -> collect all results 2. PR Creation (worktree mode, validation passed): commit, push, gh pr create, cleanup worktree 3. Calculate: debt_items_found, items_fixed, reduction_rate 4. Generate report with mode, debt scores, validation status 5. Output with [coordinator] prefix 6. Execute completion action (AskUserQuestion: 新目标 / 深度修复 / 关闭团队)
Error Handling
| Error | Resolution |
|---|---|
| Task timeout | Log, mark failed, ask user to retry or skip |
| Worker crash | Respawn worker, reassign task |
| Dependency cycle | Detect, report to user, halt |
| Invalid mode | Reject with error, ask to clarify |
| Session corruption | Attempt recovery, fallback to manual reconciliation |
| Scanner finds no debt | Report clean codebase, skip to summary |
| Fix-Verify loop stuck >3 iterations | Accept current state, continue pipeline |
Tech Debt Executor
Debt cleanup executor. Apply remediation plan actions in worktree: refactor code, update dependencies, add tests, add documentation. Batch-delegate to CLI tools, self-validate after each batch.
Phase 2: Load Remediation Plan
| Input | Source | Required |
|---|---|---|
| Session path | task description (regex: session:\s*(.+)) | Yes |
| .msg/meta.json | <session>/.msg/meta.json | Yes |
| Remediation plan | <session>/plan/remediation-plan.json | Yes |
| Worktree info | meta.json:worktree.path, worktree.branch | Yes |
| Context accumulator | From prior TDFIX tasks (inner loop) | Yes (inner loop) |
1. Extract session path from task description 2. Read .msg/meta.json for worktree path and branch 3. Read remediation-plan.json, extract all actions from plan phases 4. Group actions by type: refactor, restructure, add-tests, update-deps, add-docs 5. Split large groups (> 10 items) into sub-batches of 10 6. For inner loop (fix-verify cycle): load context_accumulator from prior TDFIX tasks, parse review/validation feedback for specific issues
Batch order: refactor -> update-deps -> add-tests -> add-docs -> restructure
Phase 3: Execute Fixes
For each batch, use CLI tool for implementation:
Worktree constraint: ALL file operations and commands must execute within worktree path. Use cd "<worktree-path>" && ... prefix for all Bash commands.
Per-batch delegation:
ccw cli -p "PURPOSE: Apply tech debt fixes in batch; success = all items fixed without breaking changes
TASK: <batch-type-specific-tasks>
MODE: write
CONTEXT: @<worktree-path>/**/* | Memory: Remediation plan context
EXPECTED: Code changes that fix debt items, maintain backward compatibility, pass existing tests
CONSTRAINTS: Minimal changes only | No new features | No suppressions | Read files before modifying
Batch type: <refactor|update-deps|add-tests|add-docs|restructure>
Items: <list-of-items-with-file-paths-and-descriptions>" --tool gemini --mode write --cd "<worktree-path>"Wait for CLI completion before proceeding to next batch.
Fix Results Tracking:
| Field | Description |
|---|---|
| items_fixed | Count of successfully fixed items |
| items_failed | Count of failed items |
| items_remaining | Remaining items count |
| batches_completed | Completed batch count |
| files_modified | Array of modified file paths |
| errors | Array of error messages |
After each batch, verify file modifications via git diff --name-only in worktree.
Phase 4: Self-Validation
All commands in worktree:
| Check | Command | Pass Criteria |
|---|---|---|
| Syntax | tsc --noEmit or python -m py_compile | No new errors |
| Lint | eslint --no-error-on-unmatched-pattern | No new errors |
Write <session>/fixes/fix-log.json with fix results. Update .msg/meta.json with fix_results.
Append to context_accumulator for next TDFIX task (inner loop): files modified, fixes applied, validation results, discovered caveats.
Tech Debt Planner
Remediation plan designer. Create phased remediation plan from priority matrix: Phase 1 quick-wins (immediate), Phase 2 systematic (medium-term), Phase 3 prevention (long-term). Produce remediation-plan.md.
Phase 2: Load Assessment Data
| Input | Source | Required |
|---|---|---|
| Session path | task description (regex: session:\s*(.+)) | Yes |
| .msg/meta.json | <session>/.msg/meta.json | Yes |
| Priority matrix | <session>/assessment/priority-matrix.json | Yes |
1. Extract session path from task description 2. Read .msg/meta.json for debt_inventory 3. Read priority-matrix.json for quadrant groupings 4. Group items: quickWins (quick-win), strategic (strategic), backlog (backlog), deferred (defer)
Phase 3: Create Remediation Plan
Strategy selection:
| Item Count (quick-win + strategic) | Strategy |
|---|---|
| <= 5 | Inline: generate steps from item data |
| > 5 | CLI-assisted: gemini generates detailed remediation steps |
3-Phase Plan Structure:
| Phase | Name | Source Items | Focus |
|---|---|---|---|
| 1 | Quick Wins | quick-win quadrant | High impact, low cost -- immediate execution |
| 2 | Systematic | strategic quadrant | High impact, high cost -- structured refactoring |
| 3 | Prevention | Generated from dimension patterns | Long-term prevention mechanisms |
Action Type Mapping:
| Dimension | Action Type |
|---|---|
| code | refactor |
| architecture | restructure |
| testing | add-tests |
| dependency | update-deps |
| documentation | add-docs |
Prevention Actions (generated when dimension has >= 3 items):
| Dimension | Prevention Action |
|---|---|
| code | Add linting rules for complexity thresholds and code smell detection |
| architecture | Introduce module boundary checks in CI pipeline |
| testing | Set minimum coverage thresholds in CI and add pre-commit test hooks |
| dependency | Configure automated dependency update bot (Renovate/Dependabot) |
| documentation | Add JSDoc/docstring enforcement in linting rules |
For CLI-assisted mode, prompt gemini with debt summary requesting specific fix steps per item, grouped into phases, with dependencies and estimated time.
Phase 4: Validate & Save
1. Calculate validation metrics: total_actions, total_effort, files_affected, has_quick_wins, has_prevention 2. Write <session>/plan/remediation-plan.md (markdown with per-item checklists) 3. Write <session>/plan/remediation-plan.json (machine-readable) 4. Update .msg/meta.json with remediation_plan summary
Tech Debt Scanner
Multi-dimension tech debt scanner. Scan codebase across 5 dimensions (code, architecture, testing, dependency, documentation), produce structured debt inventory with severity rankings.
Phase 2: Context & Environment Detection
| Input | Source | Required |
|---|---|---|
| Scan scope | task description (regex: scope:\s*(.+)) | No (default: **/*) |
| Session path | task description (regex: session:\s*(.+)) | Yes |
| .msg/meta.json | <session>/.msg/meta.json | Yes |
1. Extract session path and scan scope from task description 2. Load debug specs: Run ccw spec load --category debug for known issues, workarounds, and root-cause notes 3. Read .msg/meta.json for team context 3. Detect project type and framework:
| Signal File | Project Type |
|---|---|
| package.json + React/Vue/Angular | Frontend Node |
| package.json + Express/Fastify/NestJS | Backend Node |
| pyproject.toml / requirements.txt | Python |
| go.mod | Go |
| No detection | Generic |
4. Determine scan dimensions (default: code, architecture, testing, dependency, documentation) 5. Detect perspectives from task description:
| Condition | Perspective |
|---|---|
| `security\ | auth\ |
| `performance\ | speed\ |
| `quality\ | clean\ |
| `architect\ | pattern\ |
| Default | code-quality + architecture |
6. Assess complexity:
| Score | Complexity | Strategy |
|---|---|---|
| >= 4 | High | Triple Fan-out: CLI explore + CLI 5 dimensions + multi-perspective Gemini |
| 2-3 | Medium | Dual Fan-out: CLI explore + CLI 3 dimensions |
| 0-1 | Low | Inline: ACE search + Grep |
Phase 3: Multi-Dimension Scan
Low Complexity (inline):
- Use
mcp__ace-tool__search_contextfor code smells, TODO/FIXME, deprecated APIs, complex functions, dead code, missing tests - Classify findings into dimensions
Medium/High Complexity (Fan-out):
- Fan-out A: CLI exploration (structure, patterns, dependencies angles) via
ccw cli --tool gemini --mode analysis - Fan-out B: CLI dimension analysis (parallel gemini per dimension -- code, architecture, testing, dependency, documentation)
- Fan-out C (High only): Multi-perspective Gemini analysis (security, performance, code-quality, architecture)
- Fan-in: Merge results, cross-deduplicate by file:line, boost severity for multi-source findings
Standardize each finding:
| Field | Description |
|---|---|
id | TD-NNN (sequential) |
dimension | code, architecture, testing, dependency, documentation |
severity | critical, high, medium, low |
file | File path |
line | Line number |
description | Issue description |
suggestion | Fix suggestion |
estimated_effort | small, medium, large, unknown |
Phase 4: Aggregate & Save
1. Deduplicate findings across Fan-out layers (file:line key), merge cross-references 2. Sort by severity (cross-referenced items boosted) 3. Write <session>/scan/debt-inventory.json with scan_date, dimensions, total_items, by_dimension, by_severity, items 4. Update .msg/meta.json with debt_inventory array and debt_score_before count
Tech Debt Validator
Cleanup result validator. Run test suite, type checks, lint checks, and quality analysis to verify debt cleanup introduced no regressions. Compare before/after debt scores, produce validation-report.json.
Phase 2: Load Context
| Input | Source | Required |
|---|---|---|
| Session path | task description (regex: session:\s*(.+)) | Yes |
| .msg/meta.json | <session>/.msg/meta.json | Yes |
| Fix log | <session>/fixes/fix-log.json | No |
1. Extract session path from task description 2. Read .msg/meta.json for: worktree.path, debt_inventory, fix_results, debt_score_before 3. Determine command prefix: cd "<worktree-path>" && if worktree exists 4. Read fix-log.json for modified files list 5. Detect available validation tools in worktree:
| Signal | Tool | Method |
|---|---|---|
| package.json + npm | npm test | Test suite |
| pytest available | python -m pytest | Test suite |
| npx tsc available | npx tsc --noEmit | Type check |
| npx eslint available | npx eslint | Lint check |
Phase 3: Run Validation Checks
Execute 4-layer validation (all commands in worktree):
1. Test Suite:
- Run
npm testorpython -m pytestin worktree - PASS if no FAIL/error/failed keywords; FAIL with regression count otherwise
- Skip with "no-tests" if no test runner available
2. Type Check:
- Run
npx tsc --noEmitin worktree - Count
error TSoccurrences for error count
3. Lint Check:
- Run
npx eslint --no-error-on-unmatched-pattern <modified-files>in worktree - Count error occurrences
4. Quality Analysis (optional, when > 5 modified files):
- Use gemini CLI to compare code quality before/after
- Assess complexity, duplication, naming quality improvements
Debt Score Calculation:
- debt_score_after = debt items NOT in modified files (remaining unfixed items)
- improvement_percentage = ((before - after) / before) * 100
Auto-fix attempt (when total_regressions <= 3):
- Use CLI tool to fix regressions in worktree:
Bash({
command: `cd "${worktreePath}" && ccw cli -p "PURPOSE: Fix regressions found in validation
TASK: ${regressionDetails}
MODE: write
CONTEXT: @${modifiedFiles.join(' @')}
EXPECTED: Fixed regressions
CONSTRAINTS: Fix only regressions | Preserve debt cleanup changes | No suppressions" --tool gemini --mode write`,
run_in_background: false
})- Re-run validation checks after fix attempt
Phase 4: Compare & Report
1. Calculate: total_regressions = test_regressions + type_errors + lint_errors; passed = (total_regressions === 0) 2. Write <session>/validation/validation-report.json with: validation_date, passed, regressions, checks (per-check status), debt_score_before, debt_score_after, improvement_percentage 3. Update .msg/meta.json with validation_results and debt_score_after 4. Select message type: validation_complete if passed, regression_found if not
Pipeline Definitions
Tech debt pipeline modes and task registry.
Pipeline Modes
| Mode | Description | Task Chain |
|---|---|---|
| scan | Scan and assess only, no fixes | TDSCAN-001 -> TDEVAL-001 |
| remediate | Full pipeline: scan -> assess -> plan -> fix -> validate | TDSCAN-001 -> TDEVAL-001 -> TDPLAN-001 -> TDFIX-001 -> TDVAL-001 |
| targeted | Skip scan/assess, direct fix path | TDPLAN-001 -> TDFIX-001 -> TDVAL-001 |
Task Registry
| Task ID | Role | Prefix | blockedBy | Description |
|---|---|---|---|---|
| TDSCAN-001 | scanner | TDSCAN | [] | Fan-out multi-dimension codebase scan (code, architecture, testing, dependency, documentation) |
| TDEVAL-001 | assessor | TDEVAL | [TDSCAN-001] | Severity assessment with priority quadrant matrix |
| TDPLAN-001 | planner | TDPLAN | [TDEVAL-001] | 3-phase remediation plan with effort estimates |
| TDFIX-001 | executor | TDFIX | [TDPLAN-001] | Worktree-based incremental fixes (inner_loop: true) |
| TDVAL-001 | validator | TDVAL | [TDFIX-001] | 4-layer validation: syntax, tests, integration, regression |
Checkpoints
| Checkpoint | Trigger | Condition | Action |
|---|---|---|---|
| Plan Approval Gate | TDPLAN-001 completes | Always | AskUserQuestion: Approve / Revise / Abort |
| Worktree Creation | Plan approved | Before TDFIX | git worktree add .worktrees/TD-<slug>-<date> |
| Fix-Verify GC Loop | TDVAL-* completes | Regressions found | Create TDFIX-fix-<round> + TDVAL-recheck-<round> (max 3 rounds) |
GC Loop Behavior
| Condition | Action |
|---|---|
| No regressions | Pipeline complete |
| Regressions AND gc_rounds < 3 | Create fix-verify tasks, increment gc_rounds |
| Regressions AND gc_rounds >= 3 | Accept current state, handleComplete |
Output Artifacts
| Task | Output Path |
|---|---|
| TDSCAN-001 | <session>/scan/scan-report.json |
| TDEVAL-001 | <session>/assessment/debt-assessment.json |
| TDPLAN-001 | <session>/plan/remediation-plan.md |
| TDFIX-001 | <session>/fixes/ (worktree) |
| TDVAL-001 | <session>/validation/validation-report.md |
{
"team_name": "tech-debt",
"version": "1.0.0",
"description": "技术债务识别与清理团队 - 融合\"债务扫描\"、\"量化评估\"、\"治理规划\"、\"清理执行\"、\"验证回归\"五大能力域,形成扫描→评估→规划→清理→验证的闭环",
"skill_entry": "team-tech-debt",
"invocation": "Skill(skill=\"team-tech-debt\", args=\"--role=coordinator ...\")",
"roles": {
"coordinator": {
"name": "coordinator",
"responsibility": "Orchestration",
"task_prefix": null,
"description": "技术债务治理协调者。编排 pipeline:需求澄清 → 模式选择 → 团队创建 → 任务分发 → 监控协调 → 质量门控 → 结果汇报",
"message_types_sent": ["mode_selected", "quality_gate", "task_unblocked", "error", "shutdown"],
"message_types_received": ["scan_complete", "assessment_complete", "plan_ready", "fix_complete", "validation_complete", "regression_found", "error"],
"commands": ["dispatch", "monitor"]
},
"scanner": {
"name": "scanner",
"responsibility": "Orchestration (多维度债务扫描)",
"task_prefix": "TDSCAN",
"description": "技术债务扫描员。多维度扫描代码库:代码债务、架构债务、测试债务、依赖债务、文档债务,生成债务清单",
"message_types_sent": ["scan_complete", "debt_items_found", "error"],
"message_types_received": [],
"commands": ["scan-debt"],
"cli_tools": ["gemini"]
},
"assessor": {
"name": "assessor",
"responsibility": "Read-only analysis (量化评估)",
"task_prefix": "TDEVAL",
"description": "技术债务评估师。量化评估债务项的影响和修复成本,按优先级矩阵排序,生成评估报告",
"message_types_sent": ["assessment_complete", "error"],
"message_types_received": [],
"commands": ["evaluate"],
"cli_tools": ["gemini"]
},
"planner": {
"name": "planner",
"responsibility": "Orchestration (治理规划)",
"task_prefix": "TDPLAN",
"description": "技术债务治理规划师。制定分阶段治理方案:短期速赢、中期系统性治理、长期预防机制",
"message_types_sent": ["plan_ready", "plan_revision", "error"],
"message_types_received": [],
"commands": ["create-plan"],
"cli_tools": ["gemini"]
},
"executor": {
"name": "executor",
"responsibility": "Code generation (债务清理执行)",
"task_prefix": "TDFIX",
"description": "技术债务清理执行者。按优先级执行重构、依赖更新、代码清理、测试补充等治理动作",
"message_types_sent": ["fix_complete", "fix_progress", "error"],
"message_types_received": [],
"commands": ["remediate"],
"cli_tools": [{"tool": "gemini", "mode": "write"}]
},
"validator": {
"name": "validator",
"responsibility": "Validation (清理验证)",
"task_prefix": "TDVAL",
"description": "技术债务清理验证者。验证清理后无回归、质量指标提升、债务确实消除",
"message_types_sent": ["validation_complete", "regression_found", "error"],
"message_types_received": [],
"commands": ["verify"],
"cli_tools": [{"tool": "gemini", "mode": "write"}]
}
},
"pipeline_modes": {
"scan": {
"description": "仅扫描评估,不执行修复(审计模式)",
"stages": ["TDSCAN", "TDEVAL"],
"entry_role": "scanner"
},
"remediate": {
"description": "完整闭环:扫描 → 评估 → 规划 → 修复 → 验证",
"stages": ["TDSCAN", "TDEVAL", "TDPLAN", "TDFIX", "TDVAL"],
"entry_role": "scanner"
},
"targeted": {
"description": "定向修复:用户已知债务项,直接规划执行",
"stages": ["TDPLAN", "TDFIX", "TDVAL"],
"entry_role": "planner"
}
},
"fix_verify_loop": {
"max_iterations": 3,
"trigger": "validation fails or regression found",
"participants": ["executor", "validator"],
"flow": "TDFIX-fix → TDVAL-verify → evaluate"
},
"shared_memory": {
"file": ".msg/meta.json",
"fields": {
"debt_inventory": { "owner": "scanner", "type": "array" },
"assessment_matrix": { "owner": "assessor", "type": "object" },
"remediation_plan": { "owner": "planner", "type": "object" },
"fix_results": { "owner": "executor", "type": "object" },
"validation_results": { "owner": "validator", "type": "object" },
"debt_score_before": { "owner": "assessor", "type": "number" },
"debt_score_after": { "owner": "validator", "type": "number" }
}
},
"collaboration_patterns": [
"CP-1: Linear Pipeline (scan/remediate/targeted mode)",
"CP-2: Review-Fix Cycle (Executor ↔ Validator loop)",
"CP-3: Fan-out (Scanner multi-dimension scan)",
"CP-5: Escalation (Worker → Coordinator → User)",
"CP-6: Incremental Delivery (batch remediation)",
"CP-10: Post-Mortem (debt reduction report)"
],
"debt_dimensions": {
"code": { "name": "代码债务", "tools": ["static-analysis", "complexity-metrics"] },
"architecture": { "name": "架构债务", "tools": ["dependency-graph", "coupling-analysis"] },
"testing": { "name": "测试债务", "tools": ["coverage-analysis", "test-quality"] },
"dependency": { "name": "依赖债务", "tools": ["outdated-check", "vulnerability-scan"] },
"documentation": { "name": "文档债务", "tools": ["doc-coverage", "api-doc-check"] }
},
"session_directory": {
"pattern": ".workflow/.team/TD-{slug}-{date}",
"subdirectories": ["scan", "assessment", "plan", "fixes", "validation"]
}
}