Task Master Loop - Default Task Completion
【免费下载链接】claude-task-masterAn AI-powered task-management system you can drop into Cursor, Lovable, Windsurf, Roo, and others.项目地址: https://gitcode.com/GitHub_Trending/cl/claude-task-master
You are completing tasks from a Task Master backlog. Complete ONE task per session.
Files Available
- @.taskmaster/tasks/tasks.json - Your task backlog
- @.taskmaster/loop-progress.txt - Progress log from previous iterations
Process
- Run
task-master nextto get the highest priority available task - Read the task details carefully with
task-master show <id> - Implement the task, focusing on the smallest possible change
- Ensure quality:
- Run tests if they exist
- Run type check if applicable
- Verify the implementation works as expected
- Update the task status:
task-master set-status --id=<id> --status=done - Commit your work with a descriptive message referencing the task ID
- Append a brief note to the progress file about what was done
Important
- Complete ONLY ONE task per session
- Keep changes small and focused
- Do NOT start another task after completing one
- If all tasks are complete, output: ALL_TASKS_DONE
- If you cannot complete the task, output: REASON
### 5.2 预设:`test-coverage`(测试覆盖) ```markdown # Task Master Loop - Test Coverage Find uncovered code and write meaningful tests. ONE test per session. ## Files Available - @.taskmaster/loop-progress.txt - Progress log (coverage %, what was tested) ## What Makes a Great Test A great test covers behavior users depend on. It tests a feature that, if broken, would frustrate or block users. It validates real workflows - not implementation details. Do NOT write tests just to increase coverage. Use coverage as a guide to find UNTESTED USER-FACING BEHAVIOR. If code is not worth testing (boilerplate, unreachable branches, internal plumbing), add ignore comments instead of low-value tests. ## Process 1. Run coverage command (`pnpm coverage`, `npm run coverage`, etc.) 2. Identify the most important USER-FACING FEATURE that lacks tests - Prioritize: error handling users hit, CLI commands, API endpoints, file parsing - Deprioritize: internal utilities, edge cases users won't encounter, boilerplate 3. Write ONE meaningful test that validates the feature works correctly 4. Run coverage again - it should increase as a side effect of testing real behavior 5. Commit with message: `test(<file>): <describe the user behavior being tested>` 6. Append to progress file: what you tested, new coverage %, learnings ## Completion Criteria - If coverage reaches target (or 100%), output: <loop-complete>COVERAGE_TARGET</loop-complete> - Only write ONE test per iteration5.3 预设:linting(Lint 与类型错误修复)
# Task Master Loop - Linting Fix lint errors and type errors one by one. ONE fix per session. ## Files Available - @.taskmaster/loop-progress.txt - Progress log (errors fixed, remaining count) ## Process 1. Run lint command (`pnpm lint`, `npm run lint`, `eslint .`, etc.) 2. Run type check (`pnpm typecheck`, `tsc --noEmit`, etc.) 3. Pick ONE error to fix - prioritize: - Type errors (breaks builds) - Security-related lint errors - Errors in frequently-changed files 4. Fix the error with minimal changes - don't refactor surrounding code 5. Run lint/typecheck again to verify the fix doesn't introduce new errors 6. Commit with message: `fix(<file>): <describe the lint/type error fixed>` 7. Append to progress file: error fixed, remaining error count ## Completion Criteria - If zero lint errors and zero type errors, output: <loop-complete>ZERO_ERRORS</loop-complete> - Only fix ONE error per iteration5.4 预设:duplication(重复代码重构)
# Task Master Loop - Duplication Find duplicated code and refactor into shared utilities. ONE refactor per session. ## Files Available - @.taskmaster/loop-progress.txt - Progress log (clones refactored, duplication %) ## Process 1. Run duplication detection (`npx jscpd .`, or similar tool) 2. Review the report and pick ONE clone to refactor - prioritize: - Larger clones (more lines = more maintenance burden) - Clones in frequently-changed files - Clones with slight variations (consolidate logic) 3. Extract the duplicated code into a shared utility/function 4. Update all clone locations to use the shared utility 5. Run tests to ensure behavior is preserved 6. Commit with message: `refactor(<file>): extract <utility> to reduce duplication` 7. Append to progress file: what was refactored, new duplication % ## Completion Criteria - If duplication below threshold (e.g., <3%), output: <loop-complete>LOW_DUPLICATION</loop-complete> - Only refactor ONE clone per iteration5.5 预设:entropy(代码坏味道清理)
# Task Master Loop - Entropy (Code Smells) Find code smells and clean them up. ONE cleanup per session. ## Files Available - @.taskmaster/loop-progress.txt - Progress log (smells fixed, areas cleaned) ## Code Smells to Target - Long functions (>60 lines) - extract into smaller functions - Deep nesting (>3 levels) - use early returns, extract conditions - Large files (>500 lines) - split into focused modules - Magic numbers - extract into named constants - Complex conditionals - extract into well-named functions - God classes - split responsibilities ## Process 1. Scan the codebase for code smells (use your judgment or tools like `complexity-report`) 2. Pick ONE smell to fix - prioritize: - Smells in frequently-changed files - Smells that hurt readability the most - Smells in critical paths (authentication, payments, etc.) 3. Refactor with minimal changes - don't over-engineer 4. Run tests to ensure behavior is preserved 5. Commit with message: `refactor(<file>): <describe the cleanup>` 6. Append to progress file: what was cleaned, smell type ## Completion Criteria - If no significant smells remain, output: <loop-complete>LOW_ENTROPY</loop-complete> - Only fix ONE smell per iteration所有预设遵循同一哲学:一次迭代只做一件事(一个任务 / 一个测试 / 一个修复 / 一次重构 / 一处清理),并通过统一的<loop-complete>/<loop-blocked>标记向宿主进程汇报完成或受阻状态。
六、架构与核心逻辑:薄 CLI 与厚领域层
6.1 分层架构
PRD 将 loop 划分为两层,实际实现与此一致:
- CLI 命令层(apps/cli/src/commands/loop.command.ts)——薄展示层:解析参数、显示头部信息与实时输出、打印最终结果;
- 核心逻辑层(packages/tm-core/src/modules/loop/)——任务选择、进度追踪、prompt 生成、预设解析等全部业务逻辑。
领域层采用与 tm-core 其他模块一致的Domain Facade 模式:loop-domain.ts 对外提供统一 API,内部懒加载LoopService;LoopDomain.run()会先检查是否已有循环在运行,若有则先stop()防止遗留孤儿进程,再构建完整配置执行。
6.2 核心类型设计
types.ts 定义了完整的类型体系,相比 PRD 有所增强:
export type LoopPreset = | 'default' | 'test-coverage' | 'linting' | 'duplication' | 'entropy';LoopConfig:除 PRD 中的iterations / prompt / progressFile / sleepSeconds / tag外,实际实现新增了sandbox、includeOutput、verbose、brief、callbacks五个字段。其中brief会写入进度文件头部,给 Claude 提供跨迭代的"大局观";includeOutput控制是否在LoopIteration.output中携带完整 Claude 输出(单次迭代输出可能高达 50MB,默认关闭以省内存);LoopIteration:单次迭代结果,状态取值为success | blocked | error | complete;LoopResult:整体结果,finalStatus取值为all_complete | max_iterations | blocked | error;LoopOutputCallbacks:展示层回调,让 CLI/MCP 负责呈现、服务层专注业务逻辑。回调分三档:onIterationStart/End/onError/onStderr两种模式都触发;onText/onToolUse仅verbose模式触发;onOutput仅非 verbose 模式触发。
CLI 侧通过createOutputCallbacks()将这些回调渲染为终端输出——每次迭代以━━━ Iteration X of Y ━━━分隔,verbose模式下实时打印 Claude 的文本与工具调用(→ toolName),迭代结束按状态着色(成功绿色 / 错误红色 / 其余黄色),见 loop.command.ts。
6.3 预设解析
presets/index.ts 通过PRESETS记录表将预设名映射到内容,并提供三个辅助函数:
getPreset(name):按名取内容;isPreset(value):类型守卫,判断字符串是否为合法预设名;PRESET_NAMES:全部预设名数组(CLI 帮助文本直接引用它生成--prompt的候选列表)。
LoopDomain.resolvePrompt()实现了 PRD 的"预设或文件路径"判定:预设名直接返回内嵌内容;否则视为文件路径,通过注入的readFile回调读取(无回调时抛出明确错误)。LoopService.resolvePrompt()则进一步校验自定义 prompt 文件不得为空,空文件直接报错。
6.4 LoopService:循环执行引擎
services/loop.service.ts 是执行核心,其run()流程严格对应 PRD 的 CLI 伪代码:
- 前置校验:
verbose && sandbox互斥,同时开启直接返回error结果(避免每次迭代重复失败); - 初始化进度文件:
initProgressFile()自动mkdir父目录,以追加方式写入会话头(开始时间、可选 brief、预设名、最大迭代数、可选 tag),保留历史进度而非覆盖; - 主循环:
for (let i = 1; i <= config.iterations && this._isRunning; i++)——每轮构建 prompt → 执行迭代 → 推送结果:status === 'complete'→ 立即以all_complete收尾;status === 'blocked'→ 立即以blocked收尾;status === 'success'→tasksCompleted++;
- 迭代间休眠:除最后一次外,
sleepSeconds * 1000毫秒; - 收尾:
finalize()写入最终摘要(总迭代数、完成任务数、最终状态)到进度文件,返回LoopResult。
完成标记解析(parseCompletion())是循环退出的关键机制:
const completeMatch = output.match(/<loop-complete>([^<]*)<\/loop-complete>/i); if (completeMatch) return { status: 'complete', message: completeMatch[1].trim() }; const blockedMatch = output.match(/<loop-blocked>([^<]*)<\/loop-blocked>/i); if (blockedMatch) return { status: 'blocked', message: blockedMatch[1].trim() }; if (exitCode !== 0) return { status: 'error', message: `Exit code ${exitCode}` }; return { status: 'success' };即:Agent 在 prompt 中按要求输出<loop-complete>...</loop-complete>时循环提前结束;输出<loop-blocked>REASON</loop-blocked>时以阻塞状态结束;非零退出码记为 error。
七、Claude Code 集成:命令构造与上下文注入
Loop 通过 CLI 调用 Claude Code。实际实现的命令构造(buildCommandArgs())为:
# 普通模式(非 verbose) claude -p "<prompt>" --dangerously-skip-permissions # verbose 模式:stream-json 实时流 claude -p "<prompt>" --dangerously-skip-permissions --output-format stream-json --verbose # Docker sandbox 模式(--sandbox) docker sandbox run claude -p "<prompt>"要点:
- prompt 用
@语法引用文件:buildContextHeader()生成@<progressFile> @CLAUDE.md头 +Loop iteration X of Y (tag: ...)上下文,让 Claude Code 将进度文件与项目级 CLAUDE.md 加载进上下文(PRD 中引用.taskmaster/loop-progress.txt,实际实现按配置的progressFile动态注入); - verbose 模式:采用 Claude 的
stream-json输出格式,executeVerboseIteration()逐行解析 JSON 事件流——assistant事件中的text块实时打印(onText),tool_use块显示工具名(onToolUse),并做防御性解析(isValidStreamEvent校验结构、缓冲行拼接处理跨 chunk 的 JSON 行、resolveOnce防止 error/close 竞态重复 resolve); - 错误处理:Claude CLI 未安装(
ENOENT)时给出安装指引(npm install -g @anthropic-ai/claude-code);Docker 未安装时提示安装 Docker Desktop;无权限(EACCES)等错误均有对应中文友好的提示文案(见formatCommandError())。
sandbox 认证流程(--sandbox时触发,见 loop.command.ts 的handleSandboxAuth()):先执行docker sandbox run claude -p "Say OK"探测认证状态,未就绪则进入交互式会话让用户完成认证(提示Please complete auth, then Ctrl+C to continue.),成功后继续循环。
八、进度持久化:Agent 的跨迭代记忆
进度文件是 loop"每轮全新上下文"设计的关键配套:虽然每次迭代的上下文窗口是全新的,但通过追加写的进度文件,后一轮 Agent 可以读到前几轮做了什么。
initProgressFile()写入的会话头格式:
# Taskmaster Loop Progress # Started: <ISO 时间戳> # Brief: <可选,来自 --brief 上下文或 auth 的 briefName> # Preset: <预设名> # Max Iterations: <迭代数> # Tag: <可选 tag> ---【免费下载链接】claude-task-masterAn AI-powered task-management system you can drop into Cursor, Lovable, Windsurf, Roo, and others.项目地址: https://gitcode.com/GitHub_Trending/cl/claude-task-master
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考