diagnose-bug

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Diagnose Bug

Bug诊断

Use this skill to diagnose backend and algorithmic failures from evidence inward: reproduce with concrete inputs, establish the intended invariant or contract, correlate runtime signals, then inspect code. Keep it globally usable; discover the project's actual runtimes, test harnesses, and observability instead of assuming a stack.
This skill is for non-UI surfaces: APIs, services, CLIs, libraries, workers/queues, ETL/pipelines, compilers/analyzers, and algorithms (correctness, complexity, numeric stability). This is quality regime A (deterministic compute).
  • Live browser/product UI failures →
    troubleshoot-app
    (regime B)
  • Agent loops / stochastic LLM quality →
    agents analyze
    (+ Langfuse traces/evals), not this skill as the primary cut (regime C)
Use existing specs, types, contracts, property tests, unit/integration tests, DocSlime/TESTING, and docs as the definition of correct behavior (
handbook/concepts/13-quality-trace.md
). Prefer refining an existing definition over inventing a parallel one. If none fits, propose a concise contract or Given/When/Then scenario and say where it should live. Wrong answers, broken invariants, and silent data lies are bugs — including data/test/observability debt labels when those name the interest (
handbook/concepts/12-bugs-and-debt.md
).
使用此技能从证据出发向内诊断后端和算法故障:通过具体输入复现问题,明确预期的不变量或契约,关联运行时信号,然后审查代码。保持全局通用性;要去发现项目实际的运行时、测试框架和可观测性体系,而非假设技术栈。
此技能适用于非UI层面:API、服务、CLI、库、worker/队列、ETL/管道、编译器/分析器,以及算法(正确性、复杂度、数值稳定性)。属于质量体系A(确定性计算)。
  • 实时浏览器/产品UI故障 →
    troubleshoot-app
    (体系B)
  • Agent循环/随机LLM质量问题 →
    agents analyze
    (+ Langfuse 链路追踪/评估),不将此技能作为首选(体系C)
使用现有规范、类型、契约、属性测试、单元/集成测试、DocSlime/TESTING 以及文档作为正确行为的定义(
handbook/concepts/13-quality-trace.md
)。优先完善现有定义,而非创建一套平行的定义。如果没有合适的定义,提出简洁的契约或Given/When/Then场景,并说明应存放的位置。错误输出、违反不变量、静默数据错误都属于bug——当数据/测试/可观测性债务的标签明确对应问题时,也包含在内(
handbook/concepts/12-bugs-and-debt.md
)。

Operating contract

操作契约

Shared by every DecisionNerd/dev-skills skill. Canonical copy:
handbook/concepts/14-operating-contract.md
.
  • Define done first. Before using tools, write the finish line in one or two lines: the acceptance criteria (existing issue AC, BDD scenarios, tests, or contract when they exist; otherwise propose them and say where they should live) and the evidence that will prove them. Re-check it before reporting done. Never report done on work you did not verify.
  • Requested scope sets the finish line. A question ("is it ready?", "why is it broken?", "what next?") ends with the answer and a
    Next:
    line naming the exact next invoke. An outcome request ("fix", "finish", "land", "#42") continues through the chain (diagnose → fix → test → check-readiness → merge-it) until the outcome or a real blocker. Do not end a turn with "Do you want me to…?" for in-scope, in-repo work.
  • Stop only for real blockers. Stop and ask only when you cannot continue without the user, or before: deleting data or unmerged work, force-push or history rewrite, changing anything outside this repository (GitHub objects, deployments, live data, production or paid resources, external services), or leaving the requested scope, unless the user's request already named that exact action. Keep the harness's permission prompts for risky commands. Otherwise keep going and put status notes in the same message as the next action.
  • Ask well, once. For a genuine question use the harness's structured question tool when it has one (Claude Code:
    AskUserQuestion
    ; Codex:
    request_user_input
    when the current mode supports it) with concrete options; otherwise plain text with numbered options. Treat the answer as settled; do not re-open earlier verdicts, plans, or answers unless asked.
  • Fan out when work is parallel. Use subagents for independent reads (repo survey, evidence gathering, per-option research, per-area audits) and for independent verification (a reviewer that did not write the change). Writes stay single-owner per path set and sequential. Brief every child with goal, done-when, constraints, must-not, and return shape; verify each child's result before consolidating. Use Claude Code's
    Workflow
    tool only for orchestration across many subagents that truly needs it; it is expensive.
  • Pick the model tier per child; defer to routing config. If the harness or user config already routes subagents (Claude Code
    CLAUDE_CODE_SUBAGENT_MODEL
    or a CLAUDE.md rule; Codex
    agents.default_subagent_model
    or a role's
    agents.<name>.config_file
    ; Cursor a custom subagent's
    model:
    frontmatter), follow it and do not pass a model. Otherwise: mechanical search or inventory → fast/cheap (Claude Code
    haiku
    ); implementation and evidence gathering → mid (
    sonnet
    ); planning, review, adversarial verification → top (
    opus
    or
    fable
    ). In Claude Code set it with the
    Agent
    tool
    model
    param or agent frontmatter
    model:
    ; in Codex pass a spawn model or set
    model
    in the role's config file; in Cursor set
    model:
    (default
    inherit
    ) in
    .cursor/agents/*.md
    . Where the harness cannot choose, children inherit the parent model or the harness picks one (Cursor's built-in Explore/Bash/Browser subagents pick per subtask); say which in the status note.
  • Keep a checklist on long runs. For more than about five steps or work that crosses skills, keep
    TASKS.md
    at the repo root and tick items as they finish. Do not commit it unless the repo already tracks one.
  • Close every run with three headings.
    Blocked on me
    (the one genuine question or blocker, else "none");
    Changed
    (files, commits, GitHub objects, deploys, else "nothing");
    Found
    (evidence, verdict, and
    Next: <exact invoke>
    ).
所有DecisionNerd/dev-skills技能通用。标准副本:
handbook/concepts/14-operating-contract.md
。
  • 先定义完成标准。 使用工具前,用一两行写明完成线:验收标准(现有issue的AC、BDD场景、测试或契约,如果存在的话;否则提出并说明存放位置)以及证明达标的证据。报告完成前重新检查。永远不要对未验证的工作宣称完成。
  • 请求范围决定完成线。 问题类请求(“准备好了吗?”、“为什么坏了?”、“下一步是什么?”)以答案和明确下一步调用的
    Next:
    行结束。结果类请求(“修复”、“完成”、“上线”、“#42”)会贯穿整个链条(诊断→修复→测试→就绪检查→合并)直到达成结果或遇到真正的阻塞。对于范围内、仓库内的工作,不要以“你需要我…吗?”结束一轮对话。
  • 仅因真正的阻塞停止。 仅当没有用户参与就无法继续,或在执行以下操作前才停止并询问:删除数据或未合并的工作、强制推送或历史重写、修改此仓库外的任何内容(GitHub对象、部署、实时数据、生产或付费资源、外部服务),或超出请求范围——除非用户的请求已经明确指定了该操作。对于风险命令,保留框架的权限提示。否则继续推进,并在同一条消息中附上状态说明和下一步操作。
  • 一次问清楚。 对于真正的问题,如果框架有结构化提问工具(Claude Code:
    AskUserQuestion
    ;Codex:当前模式支持时使用
    request_user_input
    ),则使用该工具并提供具体选项;否则使用带编号选项的纯文本。将答案视为最终结论;除非被要求,否则不要重新讨论之前的结论、计划或答案。
  • 并行工作时拆分任务。 使用子agent执行独立读取任务(仓库调研、证据收集、各选项研究、各领域审计)和独立验证(由未编写变更的评审者进行)。写入操作按路径集保持单一负责人且顺序执行。向每个子agent说明目标、完成条件、约束、禁止事项和返回格式;合并前验证每个子agent的结果。仅当确实需要编排大量子agent时才使用Claude Code的
    Workflow
    工具;该工具成本较高。
  • 为每个子agent选择模型等级;遵循路由配置。 如果框架或用户配置已经设置了子agent路由(Claude Code的
    CLAUDE_CODE_SUBAGENT_MODEL
    或CLAUDE.md规则;Codex的
    agents.default_subagent_model
    或角色的
    agents.<name>.config_file
    ;Cursor自定义子agent的
    model:
    前置元数据),则遵循该配置,不要传递模型参数。否则:机械搜索或盘点→快速/低成本(Claude Code
    haiku
    );实现和证据收集→中等(
    sonnet
    );规划、评审、对抗性验证→顶级(
    opus
    或
    fable
    )。在Claude Code中,通过
    Agent
    工具的
    model
    参数或agent前置元数据的
    model:
    设置;在Codex中,传递生成模型或在角色配置文件中设置
    model
    ;在Cursor中,在
    .cursor/agents/*.md
    中设置
    model:
    (默认
    inherit
    )。如果框架无法选择,子agent继承父模型或由框架选择(Cursor内置的Explore/Bash/Browser子agent会按子任务选择);在状态说明中说明使用的模型。
  • 长时间运行时保留检查清单。 对于超过约五个步骤或跨技能的工作,在仓库根目录维护
    TASKS.md
    ,完成一项就勾选一项。除非仓库已经跟踪该文件,否则不要提交它。
  • 每次运行结束时附上三个标题。
    Blocked on me
    (一个真正的问题或阻塞,否则为“none”);
    Changed
    (文件、提交、GitHub对象、部署,否则为“nothing”);
    Found
    (证据、结论和
    Next: <具体调用>
    )。

Core Rule

核心规则

Do not jump straight from stack trace to a speculative rewrite. Establish the failing input, the expected contract, and what runtime evidence shows. Treat logs and metrics as evidence, not authority.
Done when: the named contract or test passes, a regression test is added, and no new failures appear in the narrowest suite.
A bug report is a fix request. After diagnosis, implement the smallest fix and add a regression test in the same run — report the diagnosis as a status note before coding. Stop before implementing only when:
  • the user asked for diagnosis or explanation only, or said "don't change code";
  • the fix requires a production config change; or
  • the fix requires a live-data or queue mutation or a change outside this repository that the user's request did not name exactly; or
  • two materially different fixes are viable and the choice changes product behavior — then ask one structured question with the options (
    <option A> / <option B> / stop
    ).
不要直接从堆栈跟踪跳到推测性重写。先明确失败的输入、预期的契约,以及运行时证据显示的情况。将日志和指标视为证据,而非绝对权威。
完成条件: 指定的契约或测试通过,添加了回归测试,且最小范围的测试套件中没有出现新的失败。
Bug报告就是修复请求。诊断后,在同一次运行中实现最小修复并添加回归测试——编码前将诊断结果作为状态说明报告。仅在以下情况时,在实现前停止:
  • 用户仅要求诊断或解释,或表示“不要修改代码”;
  • 修复需要修改生产环境配置;或
  • 修复需要修改实时数据或队列,或变更此仓库外的内容,且用户的请求未明确指定该操作;或
  • 存在两种本质不同的可行修复方案,且选择会改变产品行为——此时提出一个结构化问题,给出选项(
    <选项A> / <选项B> / 停止
    )。

Workflow

工作流程

  1. Capture the failing case.
    • Collect the exact input, command, request, fixture, seed, or test name that fails.
    • Record expected vs actual output, exit code, status, error message, and whether it is flaky.
    • Prefer a minimal reproducible example: shrink inputs, freeze seeds/time, isolate the failing test or request.
    • Avoid mutating production data or queues during diagnosis unless the user explicitly asked for a live repair.
  2. Identify the intended contract.
    • Search docs, ADRs, OpenAPI/GraphQL schemas, type definitions, comments, issues, PRs, and existing tests for the expected behavior.
    • Name the invariant that appears violated, for example "idempotent retry must not double-charge," "sort must be stable," "handler must fail closed on missing tenant," or "algorithm is O(n log n) on n ≤ 1e5."
    • For algorithm bugs, state preconditions, postconditions, complexity/space bounds, and edge cases (empty, single element, duplicates, overflow, NaN, concurrency).
    • If an existing definition is close but incomplete, say how to refine it. If none fits, draft a proposed contract or BDD scenario and where it should live.
  3. Discover runtime and evidence sources.
    • Read project docs, scripts, package files, CI config, and deployment metadata.
    • Look for: test runners, profilers, debuggers, tracing (OpenTelemetry), APM, structured logs, metrics, queue dashboards, DB read paths, feature flags, and load/bench harnesses.
    • Use only available credentials/tools. Redact secrets and personal data in summaries.
    • If a signal source is unavailable, say exactly which source and why.
    • Fan out evidence gathering to parallel read-only subagents (fast tier) when more than one source is available — repro/test-runner, logs/traces, and code-path reads can run concurrently; verify each result before diagnosing.
  4. Reproduce and gather signals.
    • Run the smallest failing test or local invocation first when possible.
    • Capture stack traces, assertion diffs, request/response payloads (redacted), job IDs, trace/span IDs, and timing.
    • Compare at least two layers when possible: input → code path → durable state or output; or unit result vs integration vs production log.
    • Check for races, retries without idempotency, cache staleness, clock skew, partial writes, off-by-one, wrong comparator, mutable shared state, incorrect big-O assumptions under real input size, and numeric/precision issues.
  5. Inspect code only after evidence.
    • Locate the function, handler, worker, query, or algorithm that should enforce the contract.
    • Find tests that should already cover the case. Missing coverage is part of the recommended fix.
    • Prefer reading the hot path and invariants over broad refactors. For algorithms, verify loop bounds, termination, data-structure choices, and complexity against measured sizes.
  6. Diagnose.
    • State the observed symptom and minimal repro.
    • State the intended contract used: existing spec/test, refined definition, or newly proposed scenario.
    • State runtime/test evidence.
    • State the likely root cause and confidence level.
    • Distinguish confirmed facts from inference.
  7. Recommend.
    • Recommend the smallest fix that restores the contract while preserving safety boundaries (authz, tenancy, idempotency, data integrity).
    • Include tests (unit/property/integration), logging/metrics if needed, and any migration or backfill as explicit steps.
    • Make verification explicit: the linked or proposed contract/test must pass; for performance bugs, state the target metric and input size.
    • Identify a safe workaround only when appropriate (feature flag, circuit breaker, temporary guard).
  8. Fix and prove.
    • If the fix requires a live-data mutation or a change outside this repository that the user's request did not name exactly, state the proposed action and ask one structured question:
      <do it> / revise / stop
      . If two materially different fixes exist and the choice changes product behavior, ask the same structured question with the options named.
    • Implement the smallest fix identified in step 7.
    • Add a regression test that would have caught this bug.
    • Run the narrowest test suite that covers the fix; confirm it is green.
    • Re-check the contract from step 2: the named invariant or scenario must now pass.
  1. 捕获失败案例。
    • 收集导致失败的确切输入、命令、请求、测试固件、种子或测试名称。
    • 记录预期输出与实际输出、退出码、状态、错误消息,以及是否为偶发(flaky)。
    • 优先使用最小可复现示例:精简输入、固定种子/时间、隔离失败的测试或请求。
    • 诊断期间避免修改生产数据或队列,除非用户明确要求实时修复。
  2. 明确预期契约。
    • 搜索文档、ADR、OpenAPI/GraphQL schema、类型定义、注释、issue、PR和现有测试,查找预期行为。
    • 指出看似被违反的不变量,例如“幂等重试不得重复收费”、“排序必须稳定”、“租户缺失时处理器必须故障关闭(fail closed)”、“算法在n ≤ 1e5时的时间复杂度为O(n log n)”。
    • 对于算法bug,说明前置条件、后置条件、复杂度/空间限制和边界情况(空、单元素、重复、溢出、NaN、并发)。
    • 如果现有定义接近但不完整,说明如何完善。如果没有合适的定义,起草拟议的契约或BDD场景,并说明存放位置。
  3. 发现运行时和证据来源。
    • 阅读项目文档、脚本、包文件、CI配置和部署元数据。
    • 查找:测试运行器、性能分析器、调试器、链路追踪(OpenTelemetry)、APM、结构化日志、指标、队列仪表盘、数据库读取路径、功能开关、压测/基准测试框架。
    • 仅使用可用的凭证/工具。在摘要中脱敏密钥和个人数据。
    • 如果某个信号源不可用,明确说明是哪个源以及原因。
    • 当有多个可用来源时,将证据收集工作分发给并行的只读子agent(快速等级)——复现/测试运行、日志/链路追踪、代码路径读取可以并发执行;诊断前验证每个结果。
  4. 复现并收集信号。
    • 尽可能先运行最小的失败测试或本地调用。
    • 捕获堆栈跟踪、断言差异、请求/响应载荷(脱敏后)、作业ID、trace/span ID和耗时。
    • 尽可能对比至少两个层面:输入→代码路径→持久化状态或输出;或单元测试结果 vs 集成测试 vs 生产日志。
    • 检查竞态条件、非幂等重试、缓存过期、时钟偏移、部分写入、差一(off-by-one)错误、比较器错误、可变共享状态、真实输入规模下的大O假设错误,以及数值/精度问题。
  5. 仅在掌握证据后审查代码。
    • 定位应执行契约的函数、处理器、worker、查询或算法。
    • 查找本应覆盖该场景的测试。缺失的测试覆盖是推荐修复方案的一部分。
    • 优先阅读热路径和不变量,而非大规模重构。对于算法,根据实际测量的规模验证循环边界、终止条件、数据结构选择和复杂度。
  6. 诊断。
    • 说明观察到的症状和最小复现步骤。
    • 说明使用的预期契约:现有规范/测试、完善后的定义,或新提出的场景。
    • 说明运行时/测试证据。
    • 说明可能的根本原因和置信度。
    • 区分已确认的事实和推断。
  7. 推荐方案。
    • 推荐最小的修复方案,既能恢复契约,又能保留安全边界(授权、租户隔离、幂等性、数据完整性)。
    • 明确包含测试(单元/属性/集成)、必要的日志/指标,以及任何迁移或数据回填步骤。
    • 明确验证方式:关联的或拟议的契约/测试必须通过;对于性能bug,说明目标指标和输入规模。
    • 仅在合适时提供安全的临时解决方案(功能开关、断路器、临时防护)。
  8. 修复并验证。
    • 如果修复需要修改实时数据或变更此仓库外的内容,且用户的请求未明确指定该操作,说明拟议的操作并提出一个结构化问题:
      <执行> / 修改 / 停止
      。如果存在两种本质不同的修复方案且选择会改变产品行为,提出同样的结构化问题并列出选项。
    • 实现步骤7中确定的最小修复。
    • 添加一个本可捕获此bug的回归测试。
    • 运行覆盖该修复的最小范围测试套件;确认测试通过(绿色)。
    • 重新检查步骤2中的契约:指定的不变量或场景现在必须通过。

Backend And Algo Focus

后端与算法重点

Prefer these investigation angles:
  • APIs / services: status codes, validation, authz, idempotency, retries, timeouts, schema drift.
  • Workers / queues: at-least-once delivery, poison messages, ordering, visibility timeouts, dead-letter.
  • Data / pipelines: nulls, duplicates, late data, partition skew, migration mismatch.
  • Algorithms: correctness proofs via invariants, edge cases, complexity vs measured n, numeric stability.
  • Concurrency: shared mutation, lock ordering, async races, TOCTOU.
Use
references/backend-evidence.md
for discovery patterns and safe reproduction tips.
优先从以下角度调查:
  • API / 服务: 状态码、校验、授权、幂等性、重试、超时、schema漂移。
  • Worker / 队列: 至少一次投递、毒消息、顺序性、可见性超时、死信队列。
  • 数据 / 管道: 空值、重复、延迟数据、分区倾斜、迁移不匹配。
  • 算法: 通过不变量证明正确性、边界情况、复杂度与实际测量n的对比、数值稳定性。
  • 并发: 共享修改、锁顺序、异步竞态、TOCTOU。
参考
references/backend-evidence.md
了解发现模式和安全复现技巧。

Response Shape

响应格式

Keep the diagnosis concise and evidence-led. Report diagnosis as a status note before coding:
markdown
I reproduced the bug: ...

Expected contract:
- Source: <spec/test/docs/issue/PR or "No suitable existing definition found">
- Invariant / scenario: <existing/refined/proposed summary>

Evidence:
- Repro / test: ...
- Logs / traces / metrics: ...
- State / output: ...

Diagnosis: ...

Recommended fix: ...
保持诊断简洁且以证据为导向。编码前将诊断结果作为状态说明报告:
markdown
我已复现该bug:...

预期契约:
- 来源:<spec/test/docs/issue/PR 或 “未找到合适的现有定义”>
- 不变量/场景:<现有/完善后/拟议的摘要>

证据:
- 复现/测试:...
- 日志/链路追踪/指标:...
- 状态/输出:...

诊断:...

推荐修复方案:...

Blocked on me

Blocked on me

<the one genuine question or blocker, else "none">
<一个真正的问题或阻塞,否则为 “none”>

Changed

Changed

<files changed by the fix, else "nothing">
<修复修改的文件,否则为 “nothing”>

Found

Found

Diagnosis: <root cause>. Fix: <what changed>. Verification: <test name(s) and result>.
Next: <check-readiness after a verified fix; otherwise the step that unblocks, e.g. fix-it or the named blocker>
undefined
诊断:<根本原因>。修复:<变更内容>。验证:<测试名称及结果>。
Next:<验证修复后的就绪检查;否则为解除阻塞的步骤,例如 fix-it 或指定的阻塞项>
undefined

Grounding

基础依据

This skill's TTPs are grounded in current engineering baselines (DORA, GitHub Docs, Fowler/Beck, Google SRE & SWE book, OpenTelemetry, OWASP LLM / NIST AI RMF, Diátaxis — see handbook
sources.md
).
Reproduce → isolate → falsifiable hypothesis before coding (SRE troubleshooting). Regime A (
handbook/concepts/11-quality-regimes.md
);
troubleshoot-app
for product UI (B);
agents analyze
+ Langfuse for generative (C). Prefer golden signals / data correctness SLIs over random restarts. Close against the quality trace (
13-quality-trace.md
).
Handbook card:
handbook/practices/diagnose-bug.md
.
此技能的TTP(战术、技术与流程)基于当前工程基准(DORA、GitHub Docs、Fowler/Beck、Google SRE与SWE书籍、OpenTelemetry、OWASP LLM / NIST AI RMF、Diátaxis——参见手册
sources.md
)。
编码前遵循“复现→隔离→可证伪假设”的流程(SRE故障排查方法)。属于体系A(
handbook/concepts/11-quality-regimes.md
);产品UI问题使用
troubleshoot-app
(体系B);生成式AI问题使用
agents analyze
+ Langfuse(体系C)。优先关注黄金信号/数据正确性SLI,而非随机重启。对照质量追踪闭环(
13-quality-trace.md
)。
手册卡片:
handbook/practices/diagnose-bug.md
。