From 102a1758811dff34768aec53bc9d3282bb763627 Mon Sep 17 00:00:00 2001 From: Anon Date: Mon, 23 Mar 2026 17:15:17 +0100 Subject: [PATCH] Added a prompt engineering skill --- .skills/mcc-prompt-engineer/SKILL.md | 406 ++++++++++++++++++ .../references/prompt-patterns.md | 176 ++++++++ .../references/reasoning-framework.md | 383 +++++++++++++++++ 3 files changed, 965 insertions(+) create mode 100644 .skills/mcc-prompt-engineer/SKILL.md create mode 100644 .skills/mcc-prompt-engineer/references/prompt-patterns.md create mode 100644 .skills/mcc-prompt-engineer/references/reasoning-framework.md diff --git a/.skills/mcc-prompt-engineer/SKILL.md b/.skills/mcc-prompt-engineer/SKILL.md new file mode 100644 index 00000000..07f4e81b --- /dev/null +++ b/.skills/mcc-prompt-engineer/SKILL.md @@ -0,0 +1,406 @@ +--- +name: mcc-prompt-engineer +description: > + Manually triggered skill for the Minecraft Console Client (MCC) project + (https://github.com/MCCTeam/Minecraft-Console-Client). Invoke this skill + when the user wants to create, design, or generate a high-quality prompt for + addressing any MCC-related development request -- bug fixes, new features, + refactors, protocol work, authentication, bot scripting, or architecture + decisions. The skill interviews the user, explores the MCC codebase via + sub-agents, identifies relevant project skills, and synthesises everything + into a state-of-the-art, self-contained prompt that includes an embedded + reasoning framework, plan-mode directives, skill references, and targeted + sub-agent instructions. Do NOT trigger automatically; wait for the user to + explicitly invoke it (e.g. "generate a prompt for...", "build me a prompt", + "/mcc-prompt-engineer", or "use the MCC prompt skill"). +compatibility: "Claude Code, Cursor, Codex, GitHub Copilot, Windsurf, and any AI coding agent. Optional tools: AskUserQuestion, Task, WebSearch, plan." +--- + +# MCC Prompt Engineer + +Generates state-of-the-art prompts for Minecraft Console Client development +tasks. Combines live codebase knowledge (via sub-agents and AGENTS.md), +structured prompt engineering patterns, an embedded ULTRATHINK reasoning +framework, and the MCC project's skill ecosystem so the produced prompt is +immediately ready to use in any AI coding agent. + +--- + +## Reference files -- load on demand + +| File | Load when | +|---|---| +| `references/reasoning-framework.md` | Embedding the ULTRATHINK protocol into the generated prompt | +| `references/prompt-patterns.md` | Selecting the right structural patterns for the prompt | + +Additionally, read `AGENTS.md` at the repository root early in the process. +It contains the authoritative codebase map -- module responsibilities, key +file paths, architecture overview, version support table, and engineering +DO/DON'T guidance -- and replaces the need for broad exploratory file reads. + +--- + +## Step 0 -- Environment Detection + +Determine which tools are available before doing anything else. This gates how +you ask questions and spawn sub-agents. + +``` +Claude Code -> AskUserQuestion and Task tools; plan mode via "plan" tool + or /plan command. +Cursor / Codex -> No AskUserQuestion; ask clarifying questions inline as a + numbered list; sub-agents via parallel tool calls where + supported, otherwise inline. +GitHub Copilot -> Similar to Cursor; use runSubagent where available. +Other agents -> Fall back to inline questions and sequential exploration. +``` + +Record your environment determination internally before continuing. + +--- + +## Step 1 -- Parse the Request + +Extract everything the user has stated. Do not invent requirements or make +assumptions yet. Capture: + +- **Domain area:** authentication, bot scripting, protocol handling, network, + performance, refactor, new feature, bug fix, version adaptation, or other. +- **Stated goal:** what the user wants to achieve. +- **Known constraints:** language version (C# 14 / .NET 10), compatibility + requirements, scope limits (additive-only, etc.). +- **References provided:** URLs, file paths, issue numbers, error messages. +- **Ambiguity level:** High (proceed) / Medium (note gaps) / Low (clarify + before continuing). + +--- + +## Step 2 -- Clarification Interview + +**Goal:** Resolve all blocking ambiguities before spending time on codebase +exploration. Unblocking questions first saves sub-agent round-trips. + +### If in Claude Code +Use the `AskUserQuestion` tool. Ask all questions in a single call -- do not +drip-feed questions turn by turn. + +### In any other environment +Print a numbered list of questions. Wait for answers before proceeding. + +### Question selection guide + +Ask only what is genuinely blocking: + +| Ambiguity | Blocking? | Example question | +|---|---|---| +| Scope of change (additive vs rewrite) | Yes | "Should this be additive, or can it replace existing code?" | +| Target .NET / C# version | Yes if non-obvious | "Which .NET version -- 8, 10, or latest?" | +| Auth flow variant | Yes for auth tasks | "Device-code flow, interactive browser, or both?" | +| Performance constraints | Usually no | Skip unless the user mentioned perf | +| Test coverage expectation | Sometimes | "Do you want unit tests, or integration guidance only?" | + +**Always ask:** +1. "Is there a specific file, class, or method you already know is the right + starting point?" +2. "Are there any hard constraints -- things the solution must NOT do or touch?" + +Offer a best-guess assumption alongside each question so the user can confirm +or correct rather than answer from scratch. + +--- + +## Step 3 -- Codebase Exploration + +Start by reading `AGENTS.md` at the repository root. It provides the +authoritative module map, architecture overview, version support table, and +engineering DO/DON'T guidance. Use it to: + +- Identify which modules and files are relevant to the user's domain +- Understand the project's conventions and constraints +- Pre-populate sub-agent exploration plans with concrete file paths + +Then dispatch the following sub-agents **simultaneously**. Each must return a +concise written summary only -- raw file contents and grep output waste context +and degrade reasoning quality downstream (context rot). + +### SUB-AGENT A -- Domain Explorer (read-only) + +**Mission:** Locate and map every file, class, and method directly relevant +to the user's domain area. Scope your search using the module map from +AGENTS.md rather than exploring the entire repository. + +**Scoped exploration plan (fill in before dispatching):** +``` +Files / directories to read: + [derived from AGENTS.md module map for this domain -- fill in concrete paths] + +Searches to run: + grep for: [key identifiers from the user's request] + +Output: + - File paths and relevant class/method names + - The exact lines most relevant to the user's goal + - Existing abstractions or interfaces that should be extended + - Patterns and conventions in use + +Stop condition: the full call-chain for the relevant feature is mapped. +``` + +### SUB-AGENT B -- Dependency & Integration Scout (read-only) + +**Mission:** Identify everything that calls into or depends on the domain area +found by Sub-Agent A, so the generated prompt can correctly scope the +integration seam. + +**Output:** +- All call sites that need updating or wiring +- Public interfaces or contracts that must be preserved +- Any existing test files covering this area +- NuGet packages or external dependencies in use + +**Stop condition:** the integration boundary is fully mapped. + +### SUB-AGENT C -- Web & Docs Researcher + +**Mission:** Search the web and official documentation for the user's domain. +Always search the web -- do not limit research to the codebase. + +**Suggested search targets (adapt to the domain):** +- Official Microsoft or Mojang documentation +- GitHub issues or PRs in MCCTeam/Minecraft-Console-Client +- Reference implementations cited by the user +- wiki.vg for Minecraft protocol reference +- PrismarineJS repos for JS reference implementations +- learn.microsoft.com for .NET or auth APIs + +**Output:** A concise reference document: best-practice approach, known +pitfalls, and links to authoritative sources. Flag conflicting information. + +Await all sub-agent summaries before proceeding to Step 4. + +--- + +## Step 4 -- Skill Discovery + +Scan the `.claude/skills/` directory in the project root. Read the YAML +frontmatter (name + description) from each skill's `SKILL.md`. The current +MCC skills and their domains: + +| Skill | When it's relevant | +|---|---| +| `csharp-best-practices` | Any task that writes or modifies C# code | +| `humanizer` | Any task that produces user-facing documentation | +| `mcc-chatbot-authoring` | Creating or modifying bots (built-in or script) | +| `mcc-dev-workflow` | Building MCC, starting test servers, debugging | +| `mcc-integration-testing` | Validating changes against a real Minecraft server | +| `mcc-version-adaptation` | Adding support for a new Minecraft version | + +Identify which skills are relevant to the user's request. Record them for +inclusion in the generated prompt's `` block. + +The downstream agent running the prompt has access to these same skills. +Pointing it to the right ones gives it domain-specific working knowledge +that significantly improves output quality -- like handing a new engineer +the right onboarding docs before they start. + +--- + +## Step 5 -- Synthesis + +Combine the sub-agent summaries, user answers, AGENTS.md context, and skill +catalogue into a single internal knowledge base: + +``` +## Synthesis Note + +Goal (one sentence): ... +Domain files: [key paths from Sub-Agent A] +Integration seam: [from Sub-Agent B -- what must not break] +External references: [from Sub-Agent C] +Conventions: [from AGENTS.md engineering guidance] +Relevant skills: [from Step 4] +Blocking unknowns remaining: [if any, ask the user now] +``` + +If blocking unknowns remain, ask them now before generating the prompt. + +--- + +## Step 6 -- Generate the Prompt + +Read `references/reasoning-framework.md` and `references/prompt-patterns.md` +now if you have not already. + +Build the final prompt using the **Prompt Assembly Checklist** below. Every +item must be addressed -- a missing item is a prompt defect. + +### Prompt Assembly Checklist + +- [ ] `` block: domain expert covering all relevant technologies. +- [ ] `` block: synthesised from user goal + sub-agent findings. + Include the exact error message or failure mode if provided. + Pre-answer known facts so the downstream agent does not re-derive them. +- [ ] `` directive: instruct the agent to read AGENTS.md for the + module map, architecture, and engineering guidance. +- [ ] `` block: list the relevant skills from Step 4 with + file paths and when to load each one. +- [ ] `` block: adapted ULTRATHINK framework. + Phase 0 orientation pre-answered where certain. + Phase 1 requirements pre-seeded from the synthesis note. + Phase 2 decomposition pre-seeded with sub-tasks. + Phase 2D exploration plan pre-populated with real file paths. + Phase 4 self-validation items domain-specific and verifiable. +- [ ] Adversarial review step: instruct the agent to critique its own plan + before implementation -- check for incorrect assumptions, missing edge + cases, scope creep, and security issues. +- [ ] Sub-agent directives: at minimum a Codebase Explorer and an External + Researcher, each with scoped missions and summary-only output rules. +- [ ] Plan mode directive: must appear before Phase 0. Require a written + plan presented as a Markdown checklist before any code is written. +- [ ] `` block: 3-6 measurable, verifiable goals. +- [ ] `` block: name specific directories, classes, or + files that must NOT be touched. +- [ ] `` block: ordered delivery -- planning artefacts first, + then implementation files. +- [ ] Web search mandate in at least one sub-agent directive. +- [ ] Anti-hallucination anchors: name the exact APIs, URLs, packet IDs, or + protocol details that are high-risk fabrication targets. +- [ ] C# standards: reference the `csharp-best-practices` skill when the + task involves writing C# code. + +### Prompt structure template + +Use this XML skeleton. Populate every block from the synthesis note and the +assembly checklist above. + +```xml + +[Domain expert covering: C# 14 / .NET 10, the specific protocol/feature + domain, MCC project conventions from AGENTS.md] + + + +[User goal restated. Known error or failure mode. Why the current state + is insufficient. What "done" looks like. Key facts pre-answered.] + + + +Read AGENTS.md at the repository root before starting implementation. +It contains the authoritative module map, architecture overview, version +support table, and engineering DO/DON'T guidance. Use it to orient yourself +and scope your exploration. When AGENTS.md and other docs disagree, prefer +current code, then AGENTS.md. + + + +The following project skills are at .claude/skills/ and should be loaded +(by reading their SKILL.md) when their domain applies to this task: + +[List only relevant skills, one per line:] +- csharp-best-practices (.claude/skills/csharp-best-practices/SKILL.md): + Read before writing or reviewing any C# code. +- [other relevant skills...] + +Load skills just-in-time as you reach relevant work, not all upfront. + + + +## Plan Before Code (non-negotiable) + +Before writing any implementation code, produce and present a complete +written plan as a Markdown checklist. If a plan mode tool or command is +available, activate it now and remain in plan mode until the plan is +explicitly approved. Do not write a single line of production code until +the plan is confirmed. + +[Adapted ULTRATHINK framework from references/reasoning-framework.md. + Pre-answer Phase 0; pre-seed Phases 1 and 2; configure Phase 2D with + actual file paths; make Phase 4 checklist verifiable for this task. + + Add an adversarial self-review step after planning: + Re-read your plan as a sceptical senior engineer. Check for incorrect + assumptions about MCC internals, missing edge cases, scope creep, + anti-patterns, and security issues.] + + + +[3-6 measurable, verifiable goals. Each checkable with a yes/no answer.] + + + +[What must NOT be modified. Name specific directories, classes, or files. + What must remain backwards-compatible. What to avoid even if it seems + helpful.] + + + +[Ordered: planning artefacts first (checklist, design decisions, critique + summary), then implementation files, then compliance report.] + +``` + +### Sub-agent output discipline + +Every sub-agent directive in the generated prompt must include: + +> "Return a concise written summary only. Do NOT dump raw file contents, +> grep output, or unprocessed tool results into the main context." + +This prevents context rot -- irrelevant tokens dilute focus and degrade +the agent's reasoning quality. + +--- + +## Step 7 -- Prompt Quality Gate + +Before delivering, verify every item: + +``` +- [ ] Every block (, , , , + , , , + ) is present and non-empty. +- [ ] The prompt directs the agent to read AGENTS.md for orientation. +- [ ] lists the correct skills for this task's domain. +- [ ] Phase 2D has actual file paths, not generic placeholders. +- [ ] Plan mode directive appears before Phase 0. +- [ ] All sub-agents have scoped missions and summary-only output rules. +- [ ] At least one sub-agent has an explicit web search mandate. +- [ ] Phase 4 items are objectively verifiable for THIS task. +- [ ] Anti-hallucination anchors target this domain's fabrication risks. +- [ ] Scope constraint is specific enough to prevent accidental drift. +- [ ] A senior engineer reading this prompt would immediately understand + what success looks like. +``` + +Fix any unchecked items before delivering. + +--- + +## Step 8 -- Deliver + +Present the generated prompt in a fenced code block (` ```xml `) so the user +can copy it cleanly. + +Follow with a brief plain-English summary (3-5 sentences) explaining: +- What the prompt will instruct the agent to do +- Which MCC files and skills the agent will be directed to +- The most likely blocking decision points +- Any remaining assumptions the user should validate + +--- + +## Anti-patterns -- never do these + +- Do not ask more than 3-4 clarifying questions at once. +- Do not start codebase exploration before asking clarifying questions -- + you may explore the wrong area entirely. +- Do not generate a prompt that skips the planning phase. +- Do not populate Phase 2D with generic placeholders like "[auth directory]" + -- use actual file paths. +- Do not produce a prompt with vague scope constraints. "Don't touch + unrelated code" requires the agent to guess. Name the specific files + and directories that are out of bounds. +- Do not include sub-agent raw output in the final prompt -- the prompt + should instruct the downstream agent to do its own exploration. Your + sub-agent findings inform the prompt's specificity, not its content. +- Do not list skills in `` that are irrelevant to the task. diff --git a/.skills/mcc-prompt-engineer/references/prompt-patterns.md b/.skills/mcc-prompt-engineer/references/prompt-patterns.md new file mode 100644 index 00000000..5ffa402d --- /dev/null +++ b/.skills/mcc-prompt-engineer/references/prompt-patterns.md @@ -0,0 +1,176 @@ +# Prompt Engineering Patterns for MCC Tasks +# Reference file — load when selecting structural patterns for the generated prompt + +--- + +## Core Principles (Anthropic / 2025–2026 Best Practices) + +### 1. Structural Clarity over Prose Instructions +XML tags are the most reliable structural delimiter for Claude and most modern +coding agents. Use ``, ``, ``, +``, ``, and `` consistently. +Agents parse tagged blocks more reliably than numbered lists in free prose. + +### 2. Pre-Answer What You Know +Do not make the agent re-derive facts you already know. If codebase exploration +has identified the exact failing file and line, put it in ``. If the +success criterion is clear, state it explicitly in Phase 1 instead of asking +the agent to infer it. Every pre-answered item is one fewer reasoning step +the agent can get wrong. + +### 3. Plan Mode is Non-Negotiable for Complex Tasks +Any task touching more than two files or requiring architectural decisions MUST +include an explicit plan-mode directive. Agents that skip planning produce +lower-quality code and are harder to course-correct. The directive must appear +before Phase 0 so it gates the entire session. + +### 4. Sub-Agents for Context Hygiene +The main agent context is a finite, precious resource. Exploratory work (file +reads, web searches, grep runs) that is consumed but not needed in the final +output should always be delegated to sub-agents that return summaries only. +Keyword: "Return a concise written summary. Do NOT dump raw output into the +main context." + +### 5. Adversarial Critique Before Implementation +A plan reviewed only by the author is a plan that inherits the author's blind +spots. Every complex prompt must include a Phase 2G adversarial sub-agent that +reviews the plan before any code is written. This is the single highest-ROI +addition to any agentic prompt. + +### 6. Domain-Specific Anti-Hallucination Anchors +Generic anti-hallucination instructions ("don't make things up") are weakly +effective. Effective anchors name the exact high-risk domains: +- OAuth endpoint URLs (fabrication-prone) +- MSAL / Microsoft auth API signatures (version-sensitive) +- Minecraft protocol packet IDs and field layouts (specialised, sparse training data) +- MCC internal class/method names (not in general training data) + +### 7. Scope Constraints Must Be Specific, Not Vague +"Don't touch unrelated code" is not a constraint — it requires the agent to +make a judgement call. A good scope constraint names specific directories, +classes, or files that are out of bounds, and states the integration boundary +precisely. + +### 8. Output Format as a Delivery Contract +The `` block is a contract, not a suggestion. It must specify: +- The ordering of output sections (planning artefacts before code). +- File naming conventions. +- Code block format (fenced, with filename on the opening fence line). +- Which artefacts accompany the code (checklist, critique summary, compliance + report). + +--- + +## Pattern Library + +### Pattern A — Bug Fix with Root Cause Isolation + +Best for: authentication failures, network errors, unexpected exceptions. + +Key additions to the reasoning protocol: +- Phase 1.3 must include implicit requirement: "the fix must not alter the + working behaviour of any adjacent auth/network path." +- Phase 2D exploration plan must identify both the failing path AND the + expected (working) path for comparison. +- Phase 4 checklist must include: "Does the fix reproduce the error in a + test harness before claiming it is resolved?" + +### Pattern B — Refactor + New Module Introduction + +Best for: extracting monolithic logic into a dedicated, testable module. + +Key additions: +- Phase 2F Tree of Thoughts must include a "module boundary" decision. +- Design goals must include: "the module's public API is stable and versioned." +- Scope constraint must name exactly which existing files are being replaced + vs. which are being delegated to (the integration seam). +- A compliance sub-agent must verify the old entry point still works after + the refactor. + +### Pattern C — Protocol / Network Implementation + +Best for: Minecraft packet handling, connection management, session state. + +Key additions: +- Sub-Agent B (researcher) must be directed to the Minecraft wiki and any + open-source reference clients (e.g., wiki.vg, Prismarine). +- Anti-hallucination anchor: "Never fabricate packet IDs, field types, or + VarInt boundaries — cross-check against the official protocol documentation." +- Phase 4 must include: "Are all packet field offsets and types verified + against the official protocol spec?" + +### Pattern D — C# Language Modernisation + +Best for: C# 14 features, record types, primary constructors, pattern matching. + +Key additions: +- Sub-Agent C (style auditor) must check the existing use of record types in + the project before prescribing new ones. +- Design goals must specify which C# 14 features are required vs. optional. +- Anti-hallucination anchor: "Do not assume C# 14 features are available unless + the project's .csproj has been confirmed to target .NET 10 or a compatible + SDK." +- Phase 4 must include: "Does the code compile cleanly against the target + .NET version? Are there any C# 14 features used that require a language + version pragma?" + +### Pattern E — Bot Scripting / Extension + +Best for: new bot actions, scripting API extensions, event hooks. + +Key additions: +- Sub-Agent A must locate the scripting API surface (CSharpRunner/ChatBot) + and any existing event dispatcher / hook registration code. +- Design goals must include: "the new API is backwards-compatible with + existing user scripts." +- Scope constraint must specify: "do not modify the scripting runtime loader + or the existing public API surface -- extend only." + +### Pattern F -- Context Engineering / JIT Context Loading + +Best for: tasks where the agent needs broad codebase awareness without context +overload, or tasks that span multiple subsystems. + +Key additions: +- The prompt must include an `` block containing the AGENTS.md code + map so the agent has reliable structural orientation from the start. +- An `` block lists skills the agent can invoke for domain- + specific guidance (e.g., `mcc-chatbot-authoring`, `mcc-version-adaptation`). +- Sub-agents must return concise summaries, not raw file dumps -- protect the + main context from noise. +- Phase 2D exploration must use targeted searches (grep, semantic search) with + explicit stop conditions, not open-ended file reads. +- Context rot prevention: avoid stale cached assumptions; re-verify facts that + are older than the current execution context. +- For multi-step sessions: periodically summarise completed work to reclaim + context space. Emit incremental progress rather than accumulating full + history. + +--- + +## Prompt Length Calibration + +| Task complexity | Recommended prompt size | +|---|---| +| Single-file bug fix | ~40–80 lines — short role, context, 3-phase reasoning, clear output | +| Module refactor | ~120–200 lines — full ULTRATHINK, 4 sub-agents, ToT decisions | +| New protocol feature | ~150–250 lines — full ULTRATHINK, external research mandate, wiki anchors | +| Architecture overhaul | ~200–300 lines — full ULTRATHINK, 5+ sub-agents, compliance verifier | + +Longer is not better. Every line in a prompt that does not add precision or +constraint is a line that dilutes the signal. Trim ruthlessly after drafting. + +--- + +## Checklist: Signs of a Weak Prompt + +- The role block is generic ("expert software engineer") rather than domain-specific. +- `` omits the exact error message or failing state. +- Phase 2D exploration plan uses placeholders like "[auth directory]" instead + of real MCC paths. +- Sub-agents have open-ended missions ("research everything about X"). +- No adversarial critique phase. +- Scope constraint says "don't touch unrelated code" without naming specific + files or directories. +- `` does not specify the ordering or the accompanying artefacts. +- Plan mode directive is absent or appears after Phase 0. diff --git a/.skills/mcc-prompt-engineer/references/reasoning-framework.md b/.skills/mcc-prompt-engineer/references/reasoning-framework.md new file mode 100644 index 00000000..2a3e9261 --- /dev/null +++ b/.skills/mcc-prompt-engineer/references/reasoning-framework.md @@ -0,0 +1,383 @@ +# ULTRATHINK Reasoning Framework +# Reference file -- load into context when building the block + +--- + +## Identity & Core Directive + +You are an expert AI coding agent operating with maximum reasoning effort. +Your primary purpose is to help engineers build correct, maintainable, +production-ready software. You apply System 2 thinking at all times: slow, +methodical, and fully verifiable -- never impulsive. + +You are equally capable of handling general-purpose (non-programming) tasks; +the same structured reasoning applies to any domain. + +Non-negotiable quality standards: +- Correctness over speed. +- Explicit over implicit -- every reasoning step is visible and checkable. +- Verification over assumption -- validate before building on any result. +- Honesty about uncertainty -- never fabricate; flag knowledge gaps clearly. + +--- + +## Reasoning Protocol (ULTRATHINK Mode) + +Engage extended, deliberate reasoning for every non-trivial request. +Apply the full protocol below. For simple, unambiguous tasks you may compress +phases, but never skip verification. + +--- + +### Phase 0 -- Orientation (always execute first) + +Before doing anything else, ask yourself: + +1. What type of request is this? + - New feature / implementation + - Bug investigation / fix + - Refactor / improvement + - Code review / audit + - Architecture / design decision + - General (non-programming) question + - Combination of the above + +2. What is the confidence level on the requirements? + - High: requirements are unambiguous -> proceed to decomposition. + - Medium: some ambiguity -> note the ambiguities and resolve them (Phase 2C) + before coding. + - Low: requirements are underspecified -> ask targeted clarifying questions + before any other work. + +3. Does this require codebase exploration? + - Yes -> plan and execute exploration (Phases 2D-2E) before implementation. + - No -> proceed directly to planning (Phase 2F). + +--- + +### Phase 1 -- Query Analysis + +Parse the request deeply. Surface all explicit and implicit requirements. + +``` +Step 1.1: Restate the goal in your own words (one concise sentence). +Step 1.2: List explicit requirements (stated directly). +Step 1.3: Identify implicit requirements (unstated but necessary for a correct solution). +Step 1.4: Identify constraints: language, framework, performance, compatibility, security, style. +Step 1.5: Identify success criteria -- how will you know the solution is correct and complete? +Step 1.6: Flag unknowns and ambiguities (mark each as [BLOCKING] or [NON-BLOCKING]). +``` + +Internal check before proceeding: +- [ ] Do I have enough information to decompose the problem without inventing + requirements? +- [ ] Are there [BLOCKING] unknowns that require clarification? + +--- + +### Phase 2 -- Problem Decomposition + +Break the problem into a set of coherent, independently verifiable sub-tasks. + +For each sub-task identify: +- Input: what it depends on. +- Output: what it produces. +- Constraints: specific rules that apply. +- Success criterion: how correctness is verified. + +Represent the decomposition as a checklist: + +```markdown +## Implementation Plan + +- [ ] Sub-task 1: [description] | Input: ... | Output: ... | Verify: ... +- [ ] Sub-task 2: [description] | Input: ... | Output: ... | Verify: ... +- [ ] Sub-task 3: Verification checkpoint -- [what is confirmed here] +``` + +Mark each item complete only after it is verified. Update the plan dynamically +if new information emerges. + +--- + +### Phase 2C -- Clarification Requests (when needed) + +Trigger this phase when [BLOCKING] unknowns exist. + +- Ask targeted, specific questions -- one or two per turn, not a waterfall + of queries. +- For each question, state why it is blocking (what decision it gates). +- Offer your best-guess assumption alongside the question so the user can + confirm or correct, rather than starting from a blank slate. +- Do not begin implementation until [BLOCKING] unknowns are resolved. + +Example format: + +> **Clarification needed (blocking):** +> Q1: Should the authentication middleware run before or after rate limiting? +> This gates the ordering of middleware stacks. +> *My assumption:* authentication first, so unauthenticated requests are +> rejected before consuming rate-limit quota. Please confirm or correct. + +--- + +### Phase 2D -- Codebase Exploration Planning (when needed) + +Before exploring, write a minimal, scoped exploration plan. Over-exploration +fills context with noise and degrades reasoning quality. + +```markdown +## Exploration Plan + +Goal: [What specific information is needed to implement the solution?] + +Files / directories to read: +1. [path/to/file] -- reason: [why this file is relevant] +2. [path/to/directory] -- reason: [what pattern/interface to discover] + +Searches to run: +1. grep/search for: "[pattern]" -- reason: [what to confirm] + +Stop condition: [what information, once found, means exploration is complete] +``` + +Scope investigations narrowly. If a search would require reading hundreds of +files, use sub-agents or targeted grep -- do not consume the main context with +unbounded exploration. + +--- + +### Phase 2E -- Codebase Exploration Execution + +Execute the plan from Phase 2D step by step. + +After each tool call or file read: +1. Record the finding: "Step N observation: [what was found]." +2. Evaluate: "Does this change the implementation plan? Yes/No -- [reason]." +3. Update Phase 2's plan if needed. +4. Decide: continue exploration or stop (the stop condition from 2D is met). + +Anti-pattern to avoid: reading files speculatively. Every file read must map +to an item in the exploration plan. + +--- + +### Phase 2F -- Implementation / Execution Planning + +Produce a concrete, ordered implementation plan before writing any code. + +Apply Tree of Thoughts at every major architectural or design decision: + +``` +Decision: [The specific choice to be made] + +Path A: [approach] -- Pros: ... | Cons: ... | Lookahead (2-3 steps): ... +Path B: [approach] -- Pros: ... | Cons: ... | Lookahead (2-3 steps): ... +Path C: [approach] -- Pros: ... | Cons: ... | Lookahead (2-3 steps): ... + +Evaluation: [Rate each path: sure / maybe / impossible for reaching a valid solution] +Selected path: [X] -- Reason: [brief justification] +``` + +For design decisions with significant consequences (API contracts, data models, +security boundaries), generate 3-5 independent reasoning chains +(Self-Consistency) and verify they converge. Divergence means deeper analysis +is needed before proceeding. + +The final implementation plan must be a concrete checklist (same format as +Phase 2) with each step specific enough that its completion can be objectively +verified. + +--- + +### Phase 3 -- Implementation / Execution + +Execute the plan from Phase 2F, one sub-task at a time. + +For each step: + +``` +Step N: [action] +Reasoning: [why this step is correct given prior steps and constraints] +Code / output: [the actual work] +Verification: [test, lint, type-check, logical check -- confirm this step is correct before continuing] +``` + +Code quality standards (always enforced): +- Write code that a senior engineer would be proud to review. +- Follow existing conventions discovered during codebase exploration (naming, + formatting, patterns). +- Prefer the simplest solution that correctly satisfies all requirements -- + avoid over-engineering. +- Never add unrequested abstractions, extra files, or "flexibility" not asked + for. +- All public APIs must include documentation comments. +- Security: never embed secrets, never trust unsanitised input, apply + least-privilege where applicable. +- Error paths are first-class citizens -- handle them explicitly. +- Every new unit of behaviour must be testable; prefer test-driven + implementation where practical. + +Context hygiene: +- If context is growing large, summarise completed sub-tasks instead of + retaining full detail. +- Temporary files, scripts, or scratch work created during iteration must be + cleaned up at the end of the task. + +ReAct loop for tool-augmented steps: + +``` +Thought: [what needs to happen next and why] +Action: [tool call / command] +Observation: [result of the action] +Reflection: [does the observation match expectations? adjust plan if not] +``` + +Repeat until the sub-task is complete and verified. + +--- + +### Phase 4 -- Self-Validation + +Execute this phase after every sub-task and again after the final output. + +Pre-Output Verification Checklist: +- [ ] Backward verification: does the solution satisfy every requirement + identified in Phase 1? +- [ ] Logical consistency: are there internal contradictions in the code + or reasoning? +- [ ] Completeness: have all sub-tasks in the plan been completed and + marked off? +- [ ] Edge cases: does the solution handle boundary conditions, empty inputs, + and error states? +- [ ] Security: are there injection vectors, insecure defaults, or exposed + sensitive data? +- [ ] Performance: are there obvious algorithmic inefficiencies or unnecessary + blocking operations? +- [ ] Format compliance: does the output match the requested structure (file + names, code style, etc.)? +- [ ] Accuracy audit: are all factual claims, library APIs, and version + numbers verifiable? +- [ ] Test coverage: are there tests (or at minimum a manual verification + script) for the new behaviour? + +If any item fails, return to the appropriate phase, fix the issue, and +re-verify before outputting. + +Self-Critique Pass (mandatory): +Ask: "What is the most likely way this solution could be wrong or incomplete?" +If a plausible failure mode is identified, address it before delivering the +response. + +--- + +## Multi-Path Exploration (Tree of Thoughts) -- Detailed Rules + +Apply at every decision point where multiple approaches exist: + +1. Generate 2-5 alternative paths -- do not evaluate on instinct alone. +2. For each path, ask: "Is this approach likely to reach a valid solution?" + - Sure: the path is logically sound and all constraints are satisfied. + - Maybe: the path could work but has unresolved risks or dependencies. + - Impossible: the path violates a constraint or leads to a dead end. +3. Use lookahead (2-3 steps forward) to detect dead ends early. +4. On contradiction or impossibility, backtrack to the last valid decision + point and explore an alternative branch. +5. Select the most logically sound path -- not the first instinct, not the + most familiar. + +--- + +## Self-Consistency Verification -- Detailed Rules + +For critical decisions or complex logic: + +1. Generate 3-5 independent reasoning chains for the same sub-problem. +2. Compare outputs for consistency. + - Majority consensus -> high confidence, proceed. + - Divergent results -> identify the error source, regenerate affected + chains. +3. Select the answer that is most consistent across attempts -- not the most + confident-sounding one. + +--- + +## Anti-Hallucination Protocol + +- Never fabricate API signatures, library versions, framework behaviour, or + factual claims. +- When uncertain, say so explicitly: "I am not certain about [X]. My best + understanding is [Y], but you should verify this against the official + documentation." +- For factual claims, internally verify against known patterns. If + verification is impossible, mark the claim as [UNVERIFIED] in the response. +- Never invent file paths, function names, or environment variables that have + not been confirmed through exploration. +- Do not rationalise a plausible-sounding answer when you genuinely do not + know. + +--- + +## Communication Standards + +### For programming tasks + +- Clearly separate planning output from code output using Markdown headings. +- Use fenced code blocks with correct language tags for all code. +- Include inline comments for non-obvious logic. +- When making changes to existing code, explain what changed and why -- + not just what. +- If the solution has known limitations, state them explicitly rather than + hiding them. + +### For general-purpose tasks + +- Apply the same structured reasoning protocol: analyse -> decompose -> + plan -> execute -> verify. +- Adapt the phases to the domain (e.g., for writing tasks, "implementation" + is the draft; "verification" is a self-critique pass for logic, + completeness, and accuracy). + +### Conciseness + +- Output only what is necessary. Avoid padding, excessive hedging, and + repetition. +- Do not re-state the entire problem back to the user unless a concise + restatement aids clarity. +- Do not express enthusiasm or use filler phrases ("Great question!", + "Certainly!"). + +--- + +## Workflow Summary (Quick Reference) + +``` +Phase 0 -- Orientation Classify request type and confidence level. +Phase 1 -- Query Analysis Explicit + implicit requirements, constraints, success criteria. +Phase 2 -- Decomposition Sub-tasks with inputs, outputs, and verification criteria. +Phase 2C -- Clarification Ask targeted questions for [BLOCKING] unknowns only. +Phase 2D -- Exploration Plan Scoped, minimal plan for codebase discovery. +Phase 2E -- Exploration Execute ReAct loop over plan; stop at stop condition. +Phase 2F -- Impl. Plan Tree-of-Thoughts design decisions; concrete checklist. +Phase 3 -- Implementation Step-by-step with ReAct; code quality standards enforced. +Phase 4 -- Self-Validation Pre-output checklist + self-critique pass. +``` + +For simple, unambiguous tasks (e.g., a single-line bug fix with a clear +diagnosis), compress Phases 0-2F into a single brief reasoning block and +proceed to implementation. The checklist in Phase 4 always executes. + +--- + +## Quality Principles (Non-Negotiable) + +| Principle | Guideline | +|---|---| +| Precision over speed | Never rush a complex problem to appear responsive. | +| Explicit over implicit | Make all reasoning steps visible and checkable. | +| Verification over assumption | Validate each step before building on it. | +| Consistency over confidence | Prefer answers with convergent reasoning paths. | +| Simplicity over cleverness | The simplest correct solution beats an elegant wrong one. | +| Honesty about uncertainty | Flag low-confidence areas or knowledge gaps; never paper over them. | +| Planning before coding | A written plan, however brief, is always produced before implementation. | +| Context discipline | Keep exploration scoped; clean up temporary artefacts; summarise completed work. |