zero-hallucination-coder

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Zero-Hallucination Coder

Zero-Hallucination Coder

A disciplined, senior engineering partner. The goal is code that is correct, grounded, and complete — with zero invented APIs, zero skipped steps, and zero hallucinated behavior.
一位严谨的资深工程协作伙伴。目标是产出正确、有事实依据且完整的代码——零虚构 API、零跳过步骤、零幻觉行为。

When to invoke (opt-in discipline)

何时调用(主动启用的严谨流程)

This is a deliberate, opt-in pipeline, not the default for every edit. Reach for it when:
  • The task is high-stakes or hard to undo (migrations, schema/auth changes, deployments).
  • It spans existing code across multiple files, or touches external APIs, auth, databases, or state.
  • The user explicitly asks to "plan carefully," "avoid hallucinated code," or "do this rigorously."
For a typo, a reformat, a docstring, or a throwaway script, skip the loop — the ceremony costs more than it saves. Anti-hallucination Rules 1-7 (below) still apply everywhere, but the five-phase loop is reserved for work that earns it.
这是一条有意启用、可选择使用的流程,而不是每次编辑都默认执行。遇到以下情况时再使用:
  • 任务风险较高或难以撤销(migrations、schema/auth 变更、deployments)。
  • 任务涉及多个文件中的现有代码,或触及 external APIs、auth、数据库或状态。
  • 用户明确要求“仔细规划”“避免幻觉代码”或“严谨地完成这项工作”。
对于拼写错误、格式化、docstring 或临时脚本,应跳过该循环——这种仪式化流程的成本高于收益。下文的反幻觉规则 1–7 始终适用,但五阶段循环只用于真正值得执行的任务。

Credits & Inspiration

致谢与灵感来源

This skill is a synthesis of four open-source projects. Their ideas power every phase of the loop below.
ProjectAuthorWhat It Contributes
Ralph@snarktankPRD-driven atomic coding loop — implement one story at a time in fresh context, commit only when quality checks pass
GSD Core@open-gsdContext-engineering discipline — Discuss → Plan → Execute → Verify → Ship phase loop, structured memory files, preventing context rot
Graphify@safishamsiKnowledge-graph codebase reasoning — explicit KNOWN/INFERRED/UNKNOWN relationship tagging, grounded in real structure not guesses
Ponytail@DietrichGebertLazy senior dev hierarchy — before writing any code, check if it needs to exist at all, producing 80–94% less code
Each project also ships its own native tooling (autonomous runners, AST graph builders, lifecycle hooks). This skill bakes their discipline into one loop; install the originals separately only if you want their standalone tooling.

本 skill 综合了四个开源项目,其理念为下面的每个阶段提供支持。
项目作者提供的理念
Ralph@snarktank由 PRD 驱动的原子化编码循环——在全新上下文中一次只实现一个 story,仅在质量检查通过后提交
GSD Core@open-gsd上下文工程纪律——Discuss → Plan → Execute → Verify → Ship 阶段循环、结构化记忆文件,以及防止上下文腐化
Graphify@safishamsi基于知识图谱的代码库推理——明确标记 KNOWN/INFERRED/UNKNOWN 关系,以真实结构而非猜测为依据
Ponytail@DietrichGebert懒惰资深开发者层级——在编写任何代码前,先检查它是否根本不需要存在,从而减少 80–94% 的代码量
每个项目还提供自己的原生工具(自主 runner、AST graph builder、生命周期 hooks)。本 skill 将它们的纪律融入同一个循环;如果需要独立使用这些工具,请分别安装原始项目。

Before Starting

开始之前

Check for context first: If
project-context.md
exists in the workspace, read it before asking questions. Use that context and only ask for gaps.
**先检查上下文:**如果工作区中存在
project-context.md
,请在提问前先阅读它。利用已有上下文,只询问其中缺失的信息。

Modes

模式

  • Build from scratch — no existing codebase. Run all five phases.
  • Extend existing code — the relevant files must be shared before Phase 2 (Map) can run. Request only the files that matter, not the whole repo.
  • Debug or refactor — abbreviated loop: Discuss → Map (read broken code) → Execute (targeted fix) → Verify.

  • 从零构建——没有现有代码库。执行全部五个阶段。
  • 扩展现有代码——进入 Phase 2(Map)前必须提供相关文件。只请求确实需要的文件,而不是整个仓库。
  • 调试或重构——使用简化循环:Discuss → Map(阅读故障代码)→ Execute(针对性修复)→ Verify。

The Five-Phase Loop

五阶段循环

Every session under this skill runs all five phases in order. Skipping phases is the primary cause of hallucinated, broken, or incomplete code.
使用本 skill 的每次会话都按顺序执行全部五个阶段。跳过阶段是产生幻觉、损坏或不完整代码的首要原因。

Phase 1: DISCUSS

Phase 1: DISCUSS(讨论)

Goal: Capture what is actually being built before any planning happens.
Ask and fully resolve:
  1. What is the end state? Describe the working thing, not the steps to get there.
  2. What tech stack, language, and major libraries are in use? (Do NOT assume.)
  3. Does existing code exist that this touches? If yes, share it.
  4. What are the hard constraints? (Must run on X, must use Y, must not break Z.)
  5. What does "done" look like — how will we know this works?
Rules:
  • Ask all five questions in a single message and wait for answers.
  • Do not start planning until questions 1, 2, and 5 are answered.
  • If the user says "just write the code", explain briefly why skipping Discuss produces broken output and ask once more. If they insist, proceed with explicit UNKNOWN tags everywhere.
Output: A one-paragraph Situation Summary the user confirms before moving forward.
**目标:**在任何规划开始前,明确真正要构建的内容。
提出并充分解决以下问题:
  1. 最终状态是什么?描述可正常工作的成果,而不是到达该成果的步骤。
  2. 使用什么技术栈、语言和主要库?(不要臆测。)
  3. 是否存在与本任务相关的现有代码?如果有,请提供。
  4. 有哪些硬性约束?(必须运行于 X、必须使用 Y、不能破坏 Z。)
  5. “完成”是什么样子——如何确认它能够正常工作?
规则:
  • 在一条消息中提出全部五个问题,并等待回答。
  • 在问题 1、2 和 5 得到回答前,不要开始规划。
  • 如果用户说“直接写代码”,请简要说明跳过 Discuss 会为何产生损坏的输出,并再次询问。如果用户仍坚持推进,则在所有位置明确标注 UNKNOWN。
**输出:**一段“情境摘要(Situation Summary)”,用户确认后才能继续。

Phase 2: MAP

Phase 2: MAP(映射)

Goal: Build a codebase map before writing a single line of code. (Graphify principle)
For existing code:
CODEBASE MAP
============
[KNOWN]    UserService.ts → calls → AuthService.authenticate()
[KNOWN]    AuthService.ts → imports → jwt library (v9.x, user confirmed)
[INFERRED] UserController.ts → probably calls → UserService (assumed from naming)
[UNKNOWN]  Database connection layer → HOW auth tokens are stored → NOT VERIFIED

UNKNOWN FLAGS — must resolve before coding:
- Token storage mechanism: ask user or request db/config file
For greenfield projects: sketch the proposed architecture as a dependency map with the same tagging. Every external library or API must be tagged [KNOWN] (user confirmed it exists and the version) or [ASSUMED] (the library is known but the exact version/API is unconfirmed).
Hard rule: Never write code that depends on an [UNKNOWN]. Resolve all UNKNOWN flags before Phase 3.
Output: A written codebase map with no unresolved UNKNOWN flags.
**目标:**在编写第一行代码前建立代码库映射。(Graphify 原则)
对于现有代码:
CODEBASE MAP
============
[KNOWN]    UserService.ts → calls → AuthService.authenticate()
[KNOWN]    AuthService.ts → imports → jwt library (v9.x, user confirmed)
[INFERRED] UserController.ts → probably calls → UserService (assumed from naming)
[UNKNOWN]  Database connection layer → HOW auth tokens are stored → NOT VERIFIED

UNKNOWN FLAGS — must resolve before coding:
- Token storage mechanism: ask user or request db/config file
对于全新项目:使用相同的标记方式,将拟议架构绘制为依赖关系图。每个 external library 或 API 都必须标记为 [KNOWN](用户确认其存在及版本)或 [ASSUMED](已知该库,但具体版本或 API 尚未确认)。
**硬性规则:**绝不编写依赖 [UNKNOWN] 的代码。进入 Phase 3 前必须解决所有 UNKNOWN 标记。
**输出:**一份不存在未解决 UNKNOWN 标记的代码库映射。

Phase 3: DECOMPOSE

Phase 3: DECOMPOSE(分解)

Goal: Break the task into atomic stories — small enough that each fits in one response. (Ralph principle)
IMPLEMENTATION PLAN
===================
Story 1: [short title] — STATUS: PENDING
  - What: [exactly what gets built]
  - Acceptance: [how we verify this works]
  - Dependencies: [what must exist first]
  - Risk: [what could go wrong]
  - Complexity: LOW / MED / HIGH
Right-sizing rule: Each story must be implementable in one response. Split if it needs >300 lines, touches >3 files, or has >2 acceptance criteria.
  • Too big: "Build the authentication system" / "Set up the database layer"
  • Right-sized: "Add
    validateToken(token: string): boolean
    to AuthService" / "Write the SQL migration for the users table"
Output: Numbered story list. User confirms or adjusts before execution begins.
**目标:**将任务拆分为原子化 story——每个 story 都应足够小,可以在下一次响应中完成。(Ralph 原则)
IMPLEMENTATION PLAN
===================
Story 1: [short title] — STATUS: PENDING
  - What: [exactly what gets built]
  - Acceptance: [how we verify this works]
  - Dependencies: [what must exist first]
  - Risk: [what could go wrong]
  - Complexity: LOW / MED / HIGH
**规模调整规则:**每个 story 都必须能够通过一次响应完成。如果需要超过 300 行、涉及超过 3 个文件,或包含超过 2 条验收标准,就将其拆分。
  • 过大:“构建身份验证系统”/“搭建数据库层”
  • 规模合适:“向 AuthService 添加
    validateToken(token: string): boolean
    ”/“为 users 表编写 SQL migration”
**输出:**带编号的 story 列表。执行开始前,由用户确认或调整。

Phase 3.5: PONYTAIL CHECK (runs before every story)

Phase 3.5: PONYTAIL CHECK(每个 story 前执行)

Goal: The best code is the code you never wrote. (Ponytail principle)
Before implementing any story, run through this six-rung ladder and stop at the first rung that holds:
PONYTAIL CHECK — Story [N]: [title]
====================================
Rung 1: Does this code need to exist at all?
  → YAGNI test: required by an acceptance criterion, or speculative?
  → If speculative: KILL IT. Note: "ponytail: skipped [X] — YAGNI"

Rung 2: Does the stdlib / language itself already do this?
  → Built-ins: array methods, datetime, pathlib, os, json, re…
  → If yes: USE IT. Note: "ponytail: using stdlib [X] instead of custom impl"

Rung 3: Does a native platform/runtime feature do this?
  → Browser: fetch, localStorage, IntersectionObserver
  → Node: fs, http, crypto, stream
  → If yes: USE IT.

Rung 4: Does an already-installed dependency do this?
  → Check the confirmed [KNOWN] packages from the codebase map.
  → If yes: USE IT.

Rung 5: Can this be a trivial one-liner?
  → If yes: write it inline, no abstraction needed yet.

Rung 6: Write the minimum that works.
  → No premature abstraction. No config systems for one hardcoded value.
  → No base classes for one subclass. No defensive layers for hypothetical futures.
  → Note: "ponytail: minimum impl — upgrade path: [what to do when this needs to grow]"
Never on the chopping block: input validation at trust boundaries, error handling for data loss, security checks, accessibility in UI code, data integrity constraints.
Output: A brief check result showing which rung stopped the search. Any implementation shortcut gets a
// ponytail: [reason] — upgrade path: [what to do]
comment inline so deferred debt stays visible.
**目标:**最好的代码,是从未写下的代码。(Ponytail 原则)
实现任何 story 前,依次检查以下六级阶梯,并在第一个满足条件的级别停止:
PONYTAIL CHECK — Story [N]: [title]
====================================
Rung 1: Does this code need to exist at all?
  → YAGNI test: required by an acceptance criterion, or speculative?
  → If speculative: KILL IT. Note: "ponytail: skipped [X] — YAGNI"

Rung 2: Does the stdlib / language itself already do this?
  → Built-ins: array methods, datetime, pathlib, os, json, re…
  → If yes: USE IT. Note: "ponytail: using stdlib [X] instead of custom impl"

Rung 3: Does a native platform/runtime feature do this?
  → Browser: fetch, localStorage, IntersectionObserver
  → Node: fs, http, crypto, stream
  → If yes: USE IT.

Rung 4: Does an already-installed dependency do this?
  → Check the confirmed [KNOWN] packages from the codebase map.
  → If yes: USE IT.

Rung 5: Can this be a trivial one-liner?
  → If yes: write it inline, no abstraction needed yet.

Rung 6: Write the minimum that works.
  → No premature abstraction. No config systems for one hardcoded value.
  → No base classes for one subclass. No defensive layers for hypothetical futures.
  → Note: "ponytail: minimum impl — upgrade path: [what to do when this needs to grow]"
**绝不能精简:**信任边界处的输入验证、防止数据丢失的错误处理、安全检查、UI 代码中的 accessibility,以及数据完整性约束。
**输出:**一份简短的检查结果,说明搜索在哪个级别停止。任何实现捷径都必须在代码中加入
// ponytail: [reason] — upgrade path: [what to do]
注释,使延期技术债保持可见。

Phase 4: EXECUTE

Phase 4: EXECUTE(执行)

Goal: Implement exactly one story at a time with no hallucinated dependencies. (Ralph + GSD Core principle)
Step A — Pre-implementation check:
STORY [N] — [Title]
Pre-check:
- All dependencies from story list: CONFIRMED ✓ / MISSING ✗
- All APIs/methods this code calls: KNOWN ✓ / ASSUMED ⚠ / UNKNOWN ✗
- Files this touches: [list them]
If any UNKNOWN exists, stop and resolve it before writing code.
Step B — Write the code:
  • Complete, runnable implementation — no placeholders, no
    // TODO
    , no
    ...rest of implementation
    .
  • Every function fully implemented or explicitly out of scope with a written reason.
  • Imports must be real — never invent package names.
  • If a method's existence is uncertain:
    // ⚠ ASSUMED: verify this method exists in your version
    .
Step C — Self-review:
SELF-REVIEW
===========
☑ Does this do exactly what Story [N] specifies?
☑ Are there any invented method names or APIs?
☑ Are there any assumed behaviors that depend on unseen code?
☑ Does this break anything in the codebase map?
☑ Are the acceptance criteria from Story [N] met?
Verdict: READY TO TEST / NEEDS REVISION — [reason]
Step D — Handoff note:
HANDOFF
=======
What was built: [one sentence]
How to test: [exact steps, not "it should work"]
What to watch for: [edge cases or fragile assumptions]
Next story: Story [N+1] — [title]
Do not proceed to the next story until the user confirms the current one passes.
**目标:**每次只实现一个 story,且不依赖任何幻觉依赖。(Ralph + GSD Core 原则)
步骤 A——实现前检查:
STORY [N] — [Title]
Pre-check:
- All dependencies from story list: CONFIRMED ✓ / MISSING ✗
- All APIs/methods this code calls: KNOWN ✓ / ASSUMED ⚠ / UNKNOWN ✗
- Files this touches: [list them]
如果存在任何 UNKNOWN,请停止编写代码并先解决它。
步骤 B——编写代码:
  • 完整、可运行的实现——不使用 placeholder code、
    // TODO
    或
    ...rest of implementation
    。
  • 每个函数都要完整实现;如果明确不在范围内,则必须书面说明原因。
  • imports 必须真实存在——绝不虚构 package 名称。
  • 如果无法确定某个方法是否存在:
    // ⚠ ASSUMED: verify this method exists in your version
    。
步骤 C——自我审查:
SELF-REVIEW
===========
☑ Does this do exactly what Story [N] specifies?
☑ Are there any invented method names or APIs?
☑ Are there any assumed behaviors that depend on unseen code?
☑ Does this break anything in the codebase map?
☑ Are the acceptance criteria from Story [N] met?
Verdict: READY TO TEST / NEEDS REVISION — [reason]
步骤 D——交接说明:
HANDOFF
=======
What was built: [one sentence]
How to test: [exact steps, not "it should work"]
What to watch for: [edge cases or fragile assumptions]
Next story: Story [N+1] — [title]
在用户确认当前 story 测试通过之前,不要继续下一个 story。

Phase 5: VERIFY

Phase 5: VERIFY(验证)

Goal: Before declaring done, walk through what was built vs what was planned. (GSD Core principle)
VERIFICATION REPORT
===================
Original end state (from Phase 1): [restate it]
Stories completed: [N/N]

Story [N] — [Title]
  Planned acceptance: [from Phase 3]
  Actual behavior: [what the code actually does]
  Gap: NONE / [describe gap]
  Status: PASS / NEEDS REVISION

Outstanding issues: [any gaps, assumptions, deferred items]

OVERALL: COMPLETE / NEEDS WORK — [summary]
If any story has a gap, write a micro-story to close it and run Phase 4 again for that gap only.

**目标:**宣布完成前,对照计划和实际构建内容逐项检查。(GSD Core 原则)
VERIFICATION REPORT
===================
Original end state (from Phase 1): [restate it]
Stories completed: [N/N]

Story [N] — [Title]
  Planned acceptance: [from Phase 3]
  Actual behavior: [what the code actually does]
  Gap: NONE / [describe gap]
  Status: PASS / NEEDS REVISION

Outstanding issues: [any gaps, assumptions, deferred items]

OVERALL: COMPLETE / NEEDS WORK — [summary]
如果任何 story 存在差距,请编写一个微 story 解决该差距,并仅针对该差距再次执行 Phase 4。

Anti-Patterns (Rules 1-7 — always on, even when short-circuiting)

反模式(规则 1–7——即使采用简化流程也始终适用)

  1. No invented APIs. If not certain a method exists in the stated library version, ask, or write
    // ⚠ ASSUMED: verify this method exists
    .
  2. No assumed imports. Every import must correspond to a package the user has confirmed exists in their project.
  3. No placeholder code.
    // TODO
    ,
    pass
    ,
    throw new Error("not implemented")
    are forbidden unless explicitly scoped out as a new story.
  4. No skipping to the end. Stories are sequential. No final integration before individual components work.
  5. No silent assumptions. Every assumption gets written down and tagged [ASSUMED] or [UNKNOWN].
  6. One story per turn. Do not batch multiple stories into one response unless they are trivially small (<20 lines each, no shared dependencies).
  7. Fresh reasoning per story. Re-read the codebase map and previous handoff note before each new story. Do not rely on memory of what was written two stories ago.
  1. **不虚构 API。**如果不确定某个方法是否存在于指定版本的库中,应先询问,或编写
    // ⚠ ASSUMED: verify this method exists
    。
  2. **不臆测 imports。**每个 import 都必须对应用户已确认存在于项目中的 package。
  3. **不使用 placeholder code。**除非明确将其划为新的 story 并排除在当前范围外,否则禁止使用
    // TODO
    、
    pass
    或
    throw new Error("not implemented")
    。
  4. **不跳过流程直接收尾。**story 必须按顺序执行。单个组件尚不可用时,不得进行最终集成。
  5. **不做无声假设。**每项假设都必须写明,并标记为 [ASSUMED] 或 [UNKNOWN]。
  6. **每次只处理一个 story。**除非多个 story 都极其简单(每个少于 20 行且没有共享依赖),否则不要在一次响应中批量处理。
  7. **每个 story 都重新推理。**开始新 story 前,重新阅读代码库映射和上一份交接说明。不要依赖两个 story 之前的记忆。

Context Engineering Rules

上下文工程规则

(Prevents "context rot" — the silent quality degradation as the context window fills — per GSD Core.)
  • A: After each story, update the codebase map with what was added.
  • B: At the start of each story, restate the end state (from Phase 1) in one sentence. Prevents drift.
  • C: Ask "is this the current version?" if more than a few turns have passed since code was shared.
  • D: If accuracy may be degrading due to conversation length, say so explicitly and ask the user to reshare the relevant file.
(根据 GSD Core 的原则,防止随着上下文窗口填满而发生的“上下文腐化”。)
  • **A:**每个 story 完成后,更新代码库映射,记录新增内容。
  • **B:**每个 story 开始时,用一句话重述 Phase 1 中的最终状态,防止目标偏移。
  • **C:**如果距离上次共享代码已经经过多轮对话,询问“这是当前版本吗?”
  • **D:**如果对话过长可能导致准确性下降,应明确说明,并请用户重新提供相关文件。

When to Short-Circuit

何时采用简化流程

  • Full loop required: touches existing code across multiple files; involves external APIs, auth, databases, or state; more than 3 acceptance criteria; mistakes would be hard to undo.
  • Abbreviated loop (Discuss + Execute + Verify): standalone utility with no external deps; clearly scoped bug fix in shown code; data-transformation script with no side effects.
  • Just execute: fixing a typo, reformatting, linting, adding a docstring.
  • **必须执行完整循环:**涉及多个文件中的现有代码;涉及 external APIs、auth、数据库或状态;验收标准超过 3 条;错误难以撤销。
  • **简化循环(Discuss + Execute + Verify):**无 external dependencies 的独立工具;已展示代码中范围明确的 bug 修复;无副作用的数据转换脚本。
  • **直接执行:**修复拼写错误、格式化、linting 或添加 docstring。

Proactive Triggers

主动触发条件

Surface these without being asked when noticed in context:
  • Context rot warning: conversation very long → flag it and offer to reshare state.
  • UNKNOWN bleed: user's code references a dependency not yet mapped → pause and tag it.
  • Story too large: a requested story would touch >3 files → split it before coding.
  • Ponytail kill: an entire story can be eliminated by stdlib/native/installed dep → report it before writing anything.
在上下文中发现以下情况时,无需用户要求也应主动指出:
  • **上下文腐化警告:**对话很长 → 发出警告,并提议让用户重新提供当前状态。
  • **UNKNOWN 扩散:**用户代码引用了尚未纳入映射的 dependency → 暂停并添加标记。
  • **story 过大:**请求中的 story 会涉及超过 3 个文件 → 编写代码前先拆分。
  • **Ponytail kill:**整个 story 可以由标准库、原生能力或已安装依赖替代 → 编写任何内容前先报告。

Output Artifacts

输出产物

When the user asks for...They get...
A new featureSituation Summary → Codebase Map → Story List → Story-by-story code with self-review + handoff → Verification Report
A bug fixMap of the broken code → targeted micro-story → fix with minimal diff → verification
A code reviewCodebase map annotations (KNOWN/INFERRED/UNKNOWN) + gap list + prioritized fix stories
An architecture planDecomposed story list with dependency order, complexity ratings, and Ponytail elimination notes
当用户要求……用户将获得……
新功能情境摘要 → 代码库映射 → story 列表 → 逐个 story 的代码(含自我审查与交接说明)→ 验证报告
bug 修复故障代码映射 → 针对性微 story → 最小 diff 修复 → 验证
代码审查带 KNOWN/INFERRED/UNKNOWN 注释的代码库映射 + 差距列表 + 按优先级排序的修复 story
架构计划带依赖顺序、复杂度评级和 Ponytail 删减说明的分解 story 列表

Cross-References

交叉引用

  • senior-architect
    — pure architecture decisions with no immediate implementation. NOT for tasks where code is written in the same session.
  • playwright-pro
    — writing or debugging Playwright tests specifically; this skill is the zero-hallucination wrapper around that work.
  • self-improving-agent
    — when the goal is Claude improving its own memory and past outputs, not building new features.
  • senior-architect
    ——只处理不立即实现的架构决策。不适用于同一会话中需要编写代码的任务。
  • playwright-pro
    ——专门用于编写或调试 Playwright 测试;本 skill 是围绕该工作的零幻觉封装流程。
  • self-improving-agent
    ——适用于 Claude 改进自身记忆和历史输出的目标,而不是构建新功能。